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 Subtarget->hasARMOps()) {
182 // Single-precision floating-point arithmetic.
183 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
184 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
185 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
186 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
188 // Double-precision floating-point arithmetic.
189 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
190 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
191 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
192 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
194 // Single-precision comparisons.
195 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
196 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
197 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
198 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
199 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
200 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
201 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
202 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
204 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
210 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
211 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
213 // Double-precision comparisons.
214 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
215 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
216 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
217 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
218 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
219 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
220 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
221 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
223 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
229 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
230 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
232 // Floating-point to integer conversions.
233 // i64 conversions are done via library routines even when generating VFP
234 // instructions, so use the same ones.
235 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
236 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
237 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
238 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
240 // Conversions between floating types.
241 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
242 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
244 // Integer to floating-point conversions.
245 // i64 conversions are done via library routines even when generating VFP
246 // instructions, so use the same ones.
247 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
248 // e.g., __floatunsidf vs. __floatunssidfvfp.
249 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
250 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
251 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
252 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
256 // These libcalls are not available in 32-bit.
257 setLibcallName(RTLIB::SHL_I128, 0);
258 setLibcallName(RTLIB::SRL_I128, 0);
259 setLibcallName(RTLIB::SRA_I128, 0);
261 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
262 // Double-precision floating-point arithmetic helper functions
263 // RTABI chapter 4.1.2, Table 2
264 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
265 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
266 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
267 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
268 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
269 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
270 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
271 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
273 // Double-precision floating-point comparison helper functions
274 // RTABI chapter 4.1.2, Table 3
275 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
276 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
277 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
278 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
279 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
280 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
281 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
282 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
283 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
284 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
285 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
286 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
287 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
288 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
289 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
290 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
291 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
297 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
298 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
300 // Single-precision floating-point arithmetic helper functions
301 // RTABI chapter 4.1.2, Table 4
302 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
303 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
304 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
305 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
306 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
307 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
308 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
309 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
311 // Single-precision floating-point comparison helper functions
312 // RTABI chapter 4.1.2, Table 5
313 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
314 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
315 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
316 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
317 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
318 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
319 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
320 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
321 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
322 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
323 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
324 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
325 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
326 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
327 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
328 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
329 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
335 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
336 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
338 // Floating-point to integer conversions.
339 // RTABI chapter 4.1.2, Table 6
340 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
341 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
342 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
343 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
344 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
345 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
346 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
347 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
348 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
354 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
355 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
357 // Conversions between floating types.
358 // RTABI chapter 4.1.2, Table 7
359 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
360 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
361 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
362 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
364 // Integer to floating-point conversions.
365 // RTABI chapter 4.1.2, Table 8
366 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
367 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
368 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
369 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
370 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
371 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
372 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
373 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
374 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
383 // Long long helper functions
384 // RTABI chapter 4.2, Table 9
385 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
386 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
387 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
388 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
389 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
396 // Integer division functions
397 // RTABI chapter 4.3.1
398 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
399 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
400 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
401 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
402 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
403 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
404 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
405 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
406 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
412 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
413 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
416 // RTABI chapter 4.3.4
417 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
418 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
419 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
420 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
421 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
422 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
425 // Use divmod compiler-rt calls for iOS 5.0 and later.
426 if (Subtarget->getTargetTriple().isiOS() &&
427 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
428 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
429 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
432 if (Subtarget->isThumb1Only())
433 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
435 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
436 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
437 !Subtarget->isThumb1Only()) {
438 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
439 if (!Subtarget->isFPOnlySP())
440 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
442 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
445 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
447 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
449 setTruncStoreAction((MVT::SimpleValueType)VT,
450 (MVT::SimpleValueType)InnerVT, Expand);
451 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
452 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
456 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
459 if (Subtarget->hasNEON()) {
460 addDRTypeForNEON(MVT::v2f32);
461 addDRTypeForNEON(MVT::v8i8);
462 addDRTypeForNEON(MVT::v4i16);
463 addDRTypeForNEON(MVT::v2i32);
464 addDRTypeForNEON(MVT::v1i64);
466 addQRTypeForNEON(MVT::v4f32);
467 addQRTypeForNEON(MVT::v2f64);
468 addQRTypeForNEON(MVT::v16i8);
469 addQRTypeForNEON(MVT::v8i16);
470 addQRTypeForNEON(MVT::v4i32);
471 addQRTypeForNEON(MVT::v2i64);
473 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474 // neither Neon nor VFP support any arithmetic operations on it.
475 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476 // supported for v4f32.
477 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480 // FIXME: Code duplication: FDIV and FREM are expanded always, see
481 // ARMTargetLowering::addTypeForNEON method for details.
482 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484 // FIXME: Create unittest.
485 // In another words, find a way when "copysign" appears in DAG with vector
487 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488 // FIXME: Code duplication: SETCC has custom operation action, see
489 // ARMTargetLowering::addTypeForNEON method for details.
490 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491 // FIXME: Create unittest for FNEG and for FABS.
492 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
512 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
528 // Mark v2f32 intrinsics.
529 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
545 // Neon does not support some operations on v1i64 and v2i64 types.
546 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547 // Custom handling for some quad-vector types to detect VMULL.
548 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551 // Custom handling for some vector types to avoid expensive expansions
552 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559 // a destination type that is wider than the source, and nor does
560 // it have a FP_TO_[SU]INT instruction with a narrower destination than
562 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
567 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
568 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
570 // Custom expand long extensions to vectors.
571 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
572 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
573 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
574 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
575 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
576 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
577 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
578 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
580 // NEON does not have single instruction CTPOP for vectors with element
581 // types wider than 8-bits. However, custom lowering can leverage the
582 // v8i8/v16i8 vcnt instruction.
583 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
584 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
585 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
586 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
588 // NEON only has FMA instructions as of VFP4.
589 if (!Subtarget->hasVFP4()) {
590 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
591 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
594 setTargetDAGCombine(ISD::INTRINSIC_VOID);
595 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
596 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
597 setTargetDAGCombine(ISD::SHL);
598 setTargetDAGCombine(ISD::SRL);
599 setTargetDAGCombine(ISD::SRA);
600 setTargetDAGCombine(ISD::SIGN_EXTEND);
601 setTargetDAGCombine(ISD::ZERO_EXTEND);
602 setTargetDAGCombine(ISD::ANY_EXTEND);
603 setTargetDAGCombine(ISD::SELECT_CC);
604 setTargetDAGCombine(ISD::BUILD_VECTOR);
605 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
606 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
607 setTargetDAGCombine(ISD::STORE);
608 setTargetDAGCombine(ISD::FP_TO_SINT);
609 setTargetDAGCombine(ISD::FP_TO_UINT);
610 setTargetDAGCombine(ISD::FDIV);
612 // It is legal to extload from v4i8 to v4i16 or v4i32.
613 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
614 MVT::v4i16, MVT::v2i16,
616 for (unsigned i = 0; i < 6; ++i) {
617 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
618 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
619 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
623 // ARM and Thumb2 support UMLAL/SMLAL.
624 if (!Subtarget->isThumb1Only())
625 setTargetDAGCombine(ISD::ADDC);
628 computeRegisterProperties();
630 // ARM does not have f32 extending load.
631 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
633 // ARM does not have i1 sign extending load.
634 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
636 // ARM supports all 4 flavors of integer indexed load / store.
637 if (!Subtarget->isThumb1Only()) {
638 for (unsigned im = (unsigned)ISD::PRE_INC;
639 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
640 setIndexedLoadAction(im, MVT::i1, Legal);
641 setIndexedLoadAction(im, MVT::i8, Legal);
642 setIndexedLoadAction(im, MVT::i16, Legal);
643 setIndexedLoadAction(im, MVT::i32, Legal);
644 setIndexedStoreAction(im, MVT::i1, Legal);
645 setIndexedStoreAction(im, MVT::i8, Legal);
646 setIndexedStoreAction(im, MVT::i16, Legal);
647 setIndexedStoreAction(im, MVT::i32, Legal);
651 // i64 operation support.
652 setOperationAction(ISD::MUL, MVT::i64, Expand);
653 setOperationAction(ISD::MULHU, MVT::i32, Expand);
654 if (Subtarget->isThumb1Only()) {
655 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
656 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
658 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
659 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
660 setOperationAction(ISD::MULHS, MVT::i32, Expand);
662 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
663 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
664 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
665 setOperationAction(ISD::SRL, MVT::i64, Custom);
666 setOperationAction(ISD::SRA, MVT::i64, Custom);
668 if (!Subtarget->isThumb1Only()) {
669 // FIXME: We should do this for Thumb1 as well.
670 setOperationAction(ISD::ADDC, MVT::i32, Custom);
671 setOperationAction(ISD::ADDE, MVT::i32, Custom);
672 setOperationAction(ISD::SUBC, MVT::i32, Custom);
673 setOperationAction(ISD::SUBE, MVT::i32, Custom);
676 // ARM does not have ROTL.
677 setOperationAction(ISD::ROTL, MVT::i32, Expand);
678 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
679 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
680 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
681 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
683 // These just redirect to CTTZ and CTLZ on ARM.
684 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
685 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
687 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
689 // Only ARMv6 has BSWAP.
690 if (!Subtarget->hasV6Ops())
691 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
693 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
694 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
695 // These are expanded into libcalls if the cpu doesn't have HW divider.
696 setOperationAction(ISD::SDIV, MVT::i32, Expand);
697 setOperationAction(ISD::UDIV, MVT::i32, Expand);
700 // FIXME: Also set divmod for SREM on EABI
701 setOperationAction(ISD::SREM, MVT::i32, Expand);
702 setOperationAction(ISD::UREM, MVT::i32, Expand);
703 // Register based DivRem for AEABI (RTABI 4.2)
704 if (Subtarget->isTargetAEABI()) {
705 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
706 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
707 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
708 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
709 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
710 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
711 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
712 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
714 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
715 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
716 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
717 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
718 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
719 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
720 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
721 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
723 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
724 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
726 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
727 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
730 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
731 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
732 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
733 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
734 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
736 setOperationAction(ISD::TRAP, MVT::Other, Legal);
738 // Use the default implementation.
739 setOperationAction(ISD::VASTART, MVT::Other, Custom);
740 setOperationAction(ISD::VAARG, MVT::Other, Expand);
741 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
742 setOperationAction(ISD::VAEND, MVT::Other, Expand);
743 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
744 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
746 if (!Subtarget->isTargetDarwin()) {
747 // Non-Darwin platforms may return values in these registers via the
748 // personality function.
749 setExceptionPointerRegister(ARM::R0);
750 setExceptionSelectorRegister(ARM::R1);
753 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
754 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
755 // the default expansion.
756 // FIXME: This should be checking for v6k, not just v6.
757 if (Subtarget->hasDataBarrier() ||
758 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
759 // membarrier needs custom lowering; the rest are legal and handled
761 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
762 // Custom lowering for 64-bit ops
763 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
764 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
765 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
766 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
767 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
768 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
769 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
770 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
771 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
772 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
773 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
774 // On v8, we have particularly efficient implementations of atomic fences
775 // if they can be combined with nearby atomic loads and stores.
776 if (!Subtarget->hasV8Ops()) {
777 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
778 setInsertFencesForAtomic(true);
780 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
781 //setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Custom);
783 // Set them all for expansion, which will force libcalls.
784 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
785 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
786 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
787 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
788 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
789 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
790 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
791 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
792 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
793 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
797 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
798 // Unordered/Monotonic case.
799 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
800 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
803 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
805 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
806 if (!Subtarget->hasV6Ops()) {
807 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
808 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
810 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
812 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
813 !Subtarget->isThumb1Only()) {
814 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
815 // iff target supports vfp2.
816 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
817 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
820 // We want to custom lower some of our intrinsics.
821 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
822 if (Subtarget->isTargetDarwin()) {
823 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
824 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
825 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
828 setOperationAction(ISD::SETCC, MVT::i32, Expand);
829 setOperationAction(ISD::SETCC, MVT::f32, Expand);
830 setOperationAction(ISD::SETCC, MVT::f64, Expand);
831 setOperationAction(ISD::SELECT, MVT::i32, Custom);
832 setOperationAction(ISD::SELECT, MVT::f32, Custom);
833 setOperationAction(ISD::SELECT, MVT::f64, Custom);
834 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
835 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
836 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
838 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
839 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
840 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
841 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
842 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
844 // We don't support sin/cos/fmod/copysign/pow
845 setOperationAction(ISD::FSIN, MVT::f64, Expand);
846 setOperationAction(ISD::FSIN, MVT::f32, Expand);
847 setOperationAction(ISD::FCOS, MVT::f32, Expand);
848 setOperationAction(ISD::FCOS, MVT::f64, Expand);
849 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
850 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
851 setOperationAction(ISD::FREM, MVT::f64, Expand);
852 setOperationAction(ISD::FREM, MVT::f32, Expand);
853 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
854 !Subtarget->isThumb1Only()) {
855 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
856 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
858 setOperationAction(ISD::FPOW, MVT::f64, Expand);
859 setOperationAction(ISD::FPOW, MVT::f32, Expand);
861 if (!Subtarget->hasVFP4()) {
862 setOperationAction(ISD::FMA, MVT::f64, Expand);
863 setOperationAction(ISD::FMA, MVT::f32, Expand);
866 // Various VFP goodness
867 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
868 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
869 if (Subtarget->hasVFP2()) {
870 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
871 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
872 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
873 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
875 // Special handling for half-precision FP.
876 if (!Subtarget->hasFP16()) {
877 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
878 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
882 // We have target-specific dag combine patterns for the following nodes:
883 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
884 setTargetDAGCombine(ISD::ADD);
885 setTargetDAGCombine(ISD::SUB);
886 setTargetDAGCombine(ISD::MUL);
887 setTargetDAGCombine(ISD::AND);
888 setTargetDAGCombine(ISD::OR);
889 setTargetDAGCombine(ISD::XOR);
891 if (Subtarget->hasV6Ops())
892 setTargetDAGCombine(ISD::SRL);
894 setStackPointerRegisterToSaveRestore(ARM::SP);
896 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
897 !Subtarget->hasVFP2())
898 setSchedulingPreference(Sched::RegPressure);
900 setSchedulingPreference(Sched::Hybrid);
902 //// temporary - rewrite interface to use type
903 MaxStoresPerMemset = 8;
904 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
905 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
906 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
907 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
908 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
910 // On ARM arguments smaller than 4 bytes are extended, so all arguments
911 // are at least 4 bytes aligned.
912 setMinStackArgumentAlignment(4);
914 // Prefer likely predicted branches to selects on out-of-order cores.
915 PredictableSelectIsExpensive = Subtarget->isLikeA9();
917 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
920 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
921 bool isThumb2, unsigned &LdrOpc,
923 static const unsigned LoadBares[4][2] = {{ARM::LDREXB, ARM::t2LDREXB},
924 {ARM::LDREXH, ARM::t2LDREXH},
925 {ARM::LDREX, ARM::t2LDREX},
926 {ARM::LDREXD, ARM::t2LDREXD}};
927 static const unsigned LoadAcqs[4][2] = {{ARM::LDAEXB, ARM::t2LDAEXB},
928 {ARM::LDAEXH, ARM::t2LDAEXH},
929 {ARM::LDAEX, ARM::t2LDAEX},
930 {ARM::LDAEXD, ARM::t2LDAEXD}};
931 static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
932 {ARM::STREXH, ARM::t2STREXH},
933 {ARM::STREX, ARM::t2STREX},
934 {ARM::STREXD, ARM::t2STREXD}};
935 static const unsigned StoreRels[4][2] = {{ARM::STLEXB, ARM::t2STLEXB},
936 {ARM::STLEXH, ARM::t2STLEXH},
937 {ARM::STLEX, ARM::t2STLEX},
938 {ARM::STLEXD, ARM::t2STLEXD}};
940 const unsigned (*LoadOps)[2], (*StoreOps)[2];
941 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
946 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
947 StoreOps = StoreRels;
949 StoreOps = StoreBares;
951 assert(isPowerOf2_32(Size) && Size <= 8 &&
952 "unsupported size for atomic binary op!");
954 LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
955 StrOpc = StoreOps[Log2_32(Size)][isThumb2];
958 // FIXME: It might make sense to define the representative register class as the
959 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
960 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
961 // SPR's representative would be DPR_VFP2. This should work well if register
962 // pressure tracking were modified such that a register use would increment the
963 // pressure of the register class's representative and all of it's super
964 // classes' representatives transitively. We have not implemented this because
965 // of the difficulty prior to coalescing of modeling operand register classes
966 // due to the common occurrence of cross class copies and subregister insertions
968 std::pair<const TargetRegisterClass*, uint8_t>
969 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
970 const TargetRegisterClass *RRC = 0;
972 switch (VT.SimpleTy) {
974 return TargetLowering::findRepresentativeClass(VT);
975 // Use DPR as representative register class for all floating point
976 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
977 // the cost is 1 for both f32 and f64.
978 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
979 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
980 RRC = &ARM::DPRRegClass;
981 // When NEON is used for SP, only half of the register file is available
982 // because operations that define both SP and DP results will be constrained
983 // to the VFP2 class (D0-D15). We currently model this constraint prior to
984 // coalescing by double-counting the SP regs. See the FIXME above.
985 if (Subtarget->useNEONForSinglePrecisionFP())
988 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
989 case MVT::v4f32: case MVT::v2f64:
990 RRC = &ARM::DPRRegClass;
994 RRC = &ARM::DPRRegClass;
998 RRC = &ARM::DPRRegClass;
1002 return std::make_pair(RRC, Cost);
1005 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1009 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
1010 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1011 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1012 case ARMISD::CALL: return "ARMISD::CALL";
1013 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1014 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1015 case ARMISD::tCALL: return "ARMISD::tCALL";
1016 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1017 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1018 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1019 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1020 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1021 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1022 case ARMISD::CMP: return "ARMISD::CMP";
1023 case ARMISD::CMN: return "ARMISD::CMN";
1024 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1025 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1026 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1027 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1028 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1030 case ARMISD::CMOV: return "ARMISD::CMOV";
1032 case ARMISD::RBIT: return "ARMISD::RBIT";
1034 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1035 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1036 case ARMISD::SITOF: return "ARMISD::SITOF";
1037 case ARMISD::UITOF: return "ARMISD::UITOF";
1039 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1040 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1041 case ARMISD::RRX: return "ARMISD::RRX";
1043 case ARMISD::ADDC: return "ARMISD::ADDC";
1044 case ARMISD::ADDE: return "ARMISD::ADDE";
1045 case ARMISD::SUBC: return "ARMISD::SUBC";
1046 case ARMISD::SUBE: return "ARMISD::SUBE";
1048 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1049 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1051 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1052 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1054 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1056 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1058 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1060 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1062 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1064 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1065 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1066 case ARMISD::VCGE: return "ARMISD::VCGE";
1067 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1068 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1069 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1070 case ARMISD::VCGT: return "ARMISD::VCGT";
1071 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1072 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1073 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1074 case ARMISD::VTST: return "ARMISD::VTST";
1076 case ARMISD::VSHL: return "ARMISD::VSHL";
1077 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1078 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1079 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1080 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1081 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1082 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1083 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1084 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1085 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1086 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1087 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1088 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1089 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1090 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1091 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1092 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1093 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1094 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1095 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1096 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1097 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1098 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1099 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1100 case ARMISD::VDUP: return "ARMISD::VDUP";
1101 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1102 case ARMISD::VEXT: return "ARMISD::VEXT";
1103 case ARMISD::VREV64: return "ARMISD::VREV64";
1104 case ARMISD::VREV32: return "ARMISD::VREV32";
1105 case ARMISD::VREV16: return "ARMISD::VREV16";
1106 case ARMISD::VZIP: return "ARMISD::VZIP";
1107 case ARMISD::VUZP: return "ARMISD::VUZP";
1108 case ARMISD::VTRN: return "ARMISD::VTRN";
1109 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1110 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1111 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1112 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1113 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1114 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1115 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1116 case ARMISD::FMAX: return "ARMISD::FMAX";
1117 case ARMISD::FMIN: return "ARMISD::FMIN";
1118 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1119 case ARMISD::VMINNM: return "ARMISD::VMIN";
1120 case ARMISD::BFI: return "ARMISD::BFI";
1121 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1122 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1123 case ARMISD::VBSL: return "ARMISD::VBSL";
1124 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1125 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1126 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1127 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1128 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1129 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1130 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1131 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1132 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1133 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1134 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1135 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1136 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1137 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1138 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1139 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1140 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1141 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1142 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1143 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1147 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1148 if (!VT.isVector()) return getPointerTy();
1149 return VT.changeVectorElementTypeToInteger();
1152 /// getRegClassFor - Return the register class that should be used for the
1153 /// specified value type.
1154 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1155 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1156 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1157 // load / store 4 to 8 consecutive D registers.
1158 if (Subtarget->hasNEON()) {
1159 if (VT == MVT::v4i64)
1160 return &ARM::QQPRRegClass;
1161 if (VT == MVT::v8i64)
1162 return &ARM::QQQQPRRegClass;
1164 return TargetLowering::getRegClassFor(VT);
1167 // Create a fast isel object.
1169 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1170 const TargetLibraryInfo *libInfo) const {
1171 return ARM::createFastISel(funcInfo, libInfo);
1174 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1175 /// be used for loads / stores from the global.
1176 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1177 return (Subtarget->isThumb1Only() ? 127 : 4095);
1180 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1181 unsigned NumVals = N->getNumValues();
1183 return Sched::RegPressure;
1185 for (unsigned i = 0; i != NumVals; ++i) {
1186 EVT VT = N->getValueType(i);
1187 if (VT == MVT::Glue || VT == MVT::Other)
1189 if (VT.isFloatingPoint() || VT.isVector())
1193 if (!N->isMachineOpcode())
1194 return Sched::RegPressure;
1196 // Load are scheduled for latency even if there instruction itinerary
1197 // is not available.
1198 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1199 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1201 if (MCID.getNumDefs() == 0)
1202 return Sched::RegPressure;
1203 if (!Itins->isEmpty() &&
1204 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1207 return Sched::RegPressure;
1210 //===----------------------------------------------------------------------===//
1212 //===----------------------------------------------------------------------===//
1214 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1215 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1217 default: llvm_unreachable("Unknown condition code!");
1218 case ISD::SETNE: return ARMCC::NE;
1219 case ISD::SETEQ: return ARMCC::EQ;
1220 case ISD::SETGT: return ARMCC::GT;
1221 case ISD::SETGE: return ARMCC::GE;
1222 case ISD::SETLT: return ARMCC::LT;
1223 case ISD::SETLE: return ARMCC::LE;
1224 case ISD::SETUGT: return ARMCC::HI;
1225 case ISD::SETUGE: return ARMCC::HS;
1226 case ISD::SETULT: return ARMCC::LO;
1227 case ISD::SETULE: return ARMCC::LS;
1231 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1232 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1233 ARMCC::CondCodes &CondCode2) {
1234 CondCode2 = ARMCC::AL;
1236 default: llvm_unreachable("Unknown FP condition!");
1238 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1240 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1242 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1243 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1244 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1245 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1246 case ISD::SETO: CondCode = ARMCC::VC; break;
1247 case ISD::SETUO: CondCode = ARMCC::VS; break;
1248 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1249 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1250 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1252 case ISD::SETULT: CondCode = ARMCC::LT; break;
1254 case ISD::SETULE: CondCode = ARMCC::LE; break;
1256 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1260 //===----------------------------------------------------------------------===//
1261 // Calling Convention Implementation
1262 //===----------------------------------------------------------------------===//
1264 #include "ARMGenCallingConv.inc"
1266 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1267 /// given CallingConvention value.
1268 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1270 bool isVarArg) const {
1273 llvm_unreachable("Unsupported calling convention");
1274 case CallingConv::Fast:
1275 if (Subtarget->hasVFP2() && !isVarArg) {
1276 if (!Subtarget->isAAPCS_ABI())
1277 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1278 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1279 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1282 case CallingConv::C: {
1283 // Use target triple & subtarget features to do actual dispatch.
1284 if (!Subtarget->isAAPCS_ABI())
1285 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1286 else if (Subtarget->hasVFP2() &&
1287 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1289 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1290 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1292 case CallingConv::ARM_AAPCS_VFP:
1294 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1296 case CallingConv::ARM_AAPCS:
1297 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1298 case CallingConv::ARM_APCS:
1299 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1300 case CallingConv::GHC:
1301 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1305 /// LowerCallResult - Lower the result values of a call into the
1306 /// appropriate copies out of appropriate physical registers.
1308 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1309 CallingConv::ID CallConv, bool isVarArg,
1310 const SmallVectorImpl<ISD::InputArg> &Ins,
1311 SDLoc dl, SelectionDAG &DAG,
1312 SmallVectorImpl<SDValue> &InVals,
1313 bool isThisReturn, SDValue ThisVal) const {
1315 // Assign locations to each value returned by this call.
1316 SmallVector<CCValAssign, 16> RVLocs;
1317 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1318 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1319 CCInfo.AnalyzeCallResult(Ins,
1320 CCAssignFnForNode(CallConv, /* Return*/ true,
1323 // Copy all of the result registers out of their specified physreg.
1324 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1325 CCValAssign VA = RVLocs[i];
1327 // Pass 'this' value directly from the argument to return value, to avoid
1328 // reg unit interference
1329 if (i == 0 && isThisReturn) {
1330 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1331 "unexpected return calling convention register assignment");
1332 InVals.push_back(ThisVal);
1337 if (VA.needsCustom()) {
1338 // Handle f64 or half of a v2f64.
1339 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1341 Chain = Lo.getValue(1);
1342 InFlag = Lo.getValue(2);
1343 VA = RVLocs[++i]; // skip ahead to next loc
1344 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1346 Chain = Hi.getValue(1);
1347 InFlag = Hi.getValue(2);
1348 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1350 if (VA.getLocVT() == MVT::v2f64) {
1351 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1352 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1353 DAG.getConstant(0, MVT::i32));
1355 VA = RVLocs[++i]; // skip ahead to next loc
1356 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1357 Chain = Lo.getValue(1);
1358 InFlag = Lo.getValue(2);
1359 VA = RVLocs[++i]; // skip ahead to next loc
1360 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1361 Chain = Hi.getValue(1);
1362 InFlag = Hi.getValue(2);
1363 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1364 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1365 DAG.getConstant(1, MVT::i32));
1368 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1370 Chain = Val.getValue(1);
1371 InFlag = Val.getValue(2);
1374 switch (VA.getLocInfo()) {
1375 default: llvm_unreachable("Unknown loc info!");
1376 case CCValAssign::Full: break;
1377 case CCValAssign::BCvt:
1378 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1382 InVals.push_back(Val);
1388 /// LowerMemOpCallTo - Store the argument to the stack.
1390 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1391 SDValue StackPtr, SDValue Arg,
1392 SDLoc dl, SelectionDAG &DAG,
1393 const CCValAssign &VA,
1394 ISD::ArgFlagsTy Flags) const {
1395 unsigned LocMemOffset = VA.getLocMemOffset();
1396 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1397 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1398 return DAG.getStore(Chain, dl, Arg, PtrOff,
1399 MachinePointerInfo::getStack(LocMemOffset),
1403 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1404 SDValue Chain, SDValue &Arg,
1405 RegsToPassVector &RegsToPass,
1406 CCValAssign &VA, CCValAssign &NextVA,
1408 SmallVectorImpl<SDValue> &MemOpChains,
1409 ISD::ArgFlagsTy Flags) const {
1411 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1412 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1413 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1415 if (NextVA.isRegLoc())
1416 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1418 assert(NextVA.isMemLoc());
1419 if (StackPtr.getNode() == 0)
1420 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1422 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1428 /// LowerCall - Lowering a call into a callseq_start <-
1429 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1432 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1433 SmallVectorImpl<SDValue> &InVals) const {
1434 SelectionDAG &DAG = CLI.DAG;
1436 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1437 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1438 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1439 SDValue Chain = CLI.Chain;
1440 SDValue Callee = CLI.Callee;
1441 bool &isTailCall = CLI.IsTailCall;
1442 CallingConv::ID CallConv = CLI.CallConv;
1443 bool doesNotRet = CLI.DoesNotReturn;
1444 bool isVarArg = CLI.IsVarArg;
1446 MachineFunction &MF = DAG.getMachineFunction();
1447 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1448 bool isThisReturn = false;
1449 bool isSibCall = false;
1450 // Disable tail calls if they're not supported.
1451 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1454 // Check if it's really possible to do a tail call.
1455 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1456 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1457 Outs, OutVals, Ins, DAG);
1458 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1459 // detected sibcalls.
1466 // Analyze operands of the call, assigning locations to each operand.
1467 SmallVector<CCValAssign, 16> ArgLocs;
1468 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1469 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1470 CCInfo.AnalyzeCallOperands(Outs,
1471 CCAssignFnForNode(CallConv, /* Return*/ false,
1474 // Get a count of how many bytes are to be pushed on the stack.
1475 unsigned NumBytes = CCInfo.getNextStackOffset();
1477 // For tail calls, memory operands are available in our caller's stack.
1481 // Adjust the stack pointer for the new arguments...
1482 // These operations are automatically eliminated by the prolog/epilog pass
1484 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1487 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1489 RegsToPassVector RegsToPass;
1490 SmallVector<SDValue, 8> MemOpChains;
1492 // Walk the register/memloc assignments, inserting copies/loads. In the case
1493 // of tail call optimization, arguments are handled later.
1494 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1496 ++i, ++realArgIdx) {
1497 CCValAssign &VA = ArgLocs[i];
1498 SDValue Arg = OutVals[realArgIdx];
1499 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1500 bool isByVal = Flags.isByVal();
1502 // Promote the value if needed.
1503 switch (VA.getLocInfo()) {
1504 default: llvm_unreachable("Unknown loc info!");
1505 case CCValAssign::Full: break;
1506 case CCValAssign::SExt:
1507 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1509 case CCValAssign::ZExt:
1510 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1512 case CCValAssign::AExt:
1513 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1515 case CCValAssign::BCvt:
1516 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1520 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1521 if (VA.needsCustom()) {
1522 if (VA.getLocVT() == MVT::v2f64) {
1523 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1524 DAG.getConstant(0, MVT::i32));
1525 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1526 DAG.getConstant(1, MVT::i32));
1528 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1529 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1531 VA = ArgLocs[++i]; // skip ahead to next loc
1532 if (VA.isRegLoc()) {
1533 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1534 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1536 assert(VA.isMemLoc());
1538 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1539 dl, DAG, VA, Flags));
1542 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1543 StackPtr, MemOpChains, Flags);
1545 } else if (VA.isRegLoc()) {
1546 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1547 assert(VA.getLocVT() == MVT::i32 &&
1548 "unexpected calling convention register assignment");
1549 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1550 "unexpected use of 'returned'");
1551 isThisReturn = true;
1553 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1554 } else if (isByVal) {
1555 assert(VA.isMemLoc());
1556 unsigned offset = 0;
1558 // True if this byval aggregate will be split between registers
1560 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1561 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1563 if (CurByValIdx < ByValArgsCount) {
1565 unsigned RegBegin, RegEnd;
1566 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1568 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1570 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1571 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1572 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1573 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1574 MachinePointerInfo(),
1575 false, false, false,
1576 DAG.InferPtrAlignment(AddArg));
1577 MemOpChains.push_back(Load.getValue(1));
1578 RegsToPass.push_back(std::make_pair(j, Load));
1581 // If parameter size outsides register area, "offset" value
1582 // helps us to calculate stack slot for remained part properly.
1583 offset = RegEnd - RegBegin;
1585 CCInfo.nextInRegsParam();
1588 if (Flags.getByValSize() > 4*offset) {
1589 unsigned LocMemOffset = VA.getLocMemOffset();
1590 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1591 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1593 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1594 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1595 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1597 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1599 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1600 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1601 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1602 Ops, array_lengthof(Ops)));
1604 } else if (!isSibCall) {
1605 assert(VA.isMemLoc());
1607 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1608 dl, DAG, VA, Flags));
1612 if (!MemOpChains.empty())
1613 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1614 &MemOpChains[0], MemOpChains.size());
1616 // Build a sequence of copy-to-reg nodes chained together with token chain
1617 // and flag operands which copy the outgoing args into the appropriate regs.
1619 // Tail call byval lowering might overwrite argument registers so in case of
1620 // tail call optimization the copies to registers are lowered later.
1622 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1623 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1624 RegsToPass[i].second, InFlag);
1625 InFlag = Chain.getValue(1);
1628 // For tail calls lower the arguments to the 'real' stack slot.
1630 // Force all the incoming stack arguments to be loaded from the stack
1631 // before any new outgoing arguments are stored to the stack, because the
1632 // outgoing stack slots may alias the incoming argument stack slots, and
1633 // the alias isn't otherwise explicit. This is slightly more conservative
1634 // than necessary, because it means that each store effectively depends
1635 // on every argument instead of just those arguments it would clobber.
1637 // Do not flag preceding copytoreg stuff together with the following stuff.
1639 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1640 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1641 RegsToPass[i].second, InFlag);
1642 InFlag = Chain.getValue(1);
1647 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1648 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1649 // node so that legalize doesn't hack it.
1650 bool isDirect = false;
1651 bool isARMFunc = false;
1652 bool isLocalARMFunc = false;
1653 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1655 if (EnableARMLongCalls) {
1656 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1657 && "long-calls with non-static relocation model!");
1658 // Handle a global address or an external symbol. If it's not one of
1659 // those, the target's already in a register, so we don't need to do
1661 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1662 const GlobalValue *GV = G->getGlobal();
1663 // Create a constant pool entry for the callee address
1664 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1665 ARMConstantPoolValue *CPV =
1666 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1668 // Get the address of the callee into a register
1669 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1670 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1671 Callee = DAG.getLoad(getPointerTy(), dl,
1672 DAG.getEntryNode(), CPAddr,
1673 MachinePointerInfo::getConstantPool(),
1674 false, false, false, 0);
1675 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1676 const char *Sym = S->getSymbol();
1678 // Create a constant pool entry for the callee address
1679 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1680 ARMConstantPoolValue *CPV =
1681 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1682 ARMPCLabelIndex, 0);
1683 // Get the address of the callee into a register
1684 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1685 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1686 Callee = DAG.getLoad(getPointerTy(), dl,
1687 DAG.getEntryNode(), CPAddr,
1688 MachinePointerInfo::getConstantPool(),
1689 false, false, false, 0);
1691 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1692 const GlobalValue *GV = G->getGlobal();
1694 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1695 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1696 getTargetMachine().getRelocationModel() != Reloc::Static;
1697 isARMFunc = !Subtarget->isThumb() || isStub;
1698 // ARM call to a local ARM function is predicable.
1699 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1700 // tBX takes a register source operand.
1701 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1702 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1703 ARMConstantPoolValue *CPV =
1704 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1705 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1706 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1707 Callee = DAG.getLoad(getPointerTy(), dl,
1708 DAG.getEntryNode(), CPAddr,
1709 MachinePointerInfo::getConstantPool(),
1710 false, false, false, 0);
1711 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1712 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1713 getPointerTy(), Callee, PICLabel);
1715 // On ELF targets for PIC code, direct calls should go through the PLT
1716 unsigned OpFlags = 0;
1717 if (Subtarget->isTargetELF() &&
1718 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1719 OpFlags = ARMII::MO_PLT;
1720 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1722 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1724 bool isStub = Subtarget->isTargetDarwin() &&
1725 getTargetMachine().getRelocationModel() != Reloc::Static;
1726 isARMFunc = !Subtarget->isThumb() || isStub;
1727 // tBX takes a register source operand.
1728 const char *Sym = S->getSymbol();
1729 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1730 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1731 ARMConstantPoolValue *CPV =
1732 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1733 ARMPCLabelIndex, 4);
1734 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1735 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1736 Callee = DAG.getLoad(getPointerTy(), dl,
1737 DAG.getEntryNode(), CPAddr,
1738 MachinePointerInfo::getConstantPool(),
1739 false, false, false, 0);
1740 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1741 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1742 getPointerTy(), Callee, PICLabel);
1744 unsigned OpFlags = 0;
1745 // On ELF targets for PIC code, direct calls should go through the PLT
1746 if (Subtarget->isTargetELF() &&
1747 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1748 OpFlags = ARMII::MO_PLT;
1749 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1753 // FIXME: handle tail calls differently.
1755 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1756 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1757 if (Subtarget->isThumb()) {
1758 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1759 CallOpc = ARMISD::CALL_NOLINK;
1761 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1763 if (!isDirect && !Subtarget->hasV5TOps())
1764 CallOpc = ARMISD::CALL_NOLINK;
1765 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1766 // Emit regular call when code size is the priority
1768 // "mov lr, pc; b _foo" to avoid confusing the RSP
1769 CallOpc = ARMISD::CALL_NOLINK;
1771 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1774 std::vector<SDValue> Ops;
1775 Ops.push_back(Chain);
1776 Ops.push_back(Callee);
1778 // Add argument registers to the end of the list so that they are known live
1780 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1781 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1782 RegsToPass[i].second.getValueType()));
1784 // Add a register mask operand representing the call-preserved registers.
1786 const uint32_t *Mask;
1787 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1788 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1790 // For 'this' returns, use the R0-preserving mask if applicable
1791 Mask = ARI->getThisReturnPreservedMask(CallConv);
1793 // Set isThisReturn to false if the calling convention is not one that
1794 // allows 'returned' to be modeled in this way, so LowerCallResult does
1795 // not try to pass 'this' straight through
1796 isThisReturn = false;
1797 Mask = ARI->getCallPreservedMask(CallConv);
1800 Mask = ARI->getCallPreservedMask(CallConv);
1802 assert(Mask && "Missing call preserved mask for calling convention");
1803 Ops.push_back(DAG.getRegisterMask(Mask));
1806 if (InFlag.getNode())
1807 Ops.push_back(InFlag);
1809 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1811 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1813 // Returns a chain and a flag for retval copy to use.
1814 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1815 InFlag = Chain.getValue(1);
1817 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1818 DAG.getIntPtrConstant(0, true), InFlag, dl);
1820 InFlag = Chain.getValue(1);
1822 // Handle result values, copying them out of physregs into vregs that we
1824 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1825 InVals, isThisReturn,
1826 isThisReturn ? OutVals[0] : SDValue());
1829 /// HandleByVal - Every parameter *after* a byval parameter is passed
1830 /// on the stack. Remember the next parameter register to allocate,
1831 /// and then confiscate the rest of the parameter registers to insure
1834 ARMTargetLowering::HandleByVal(
1835 CCState *State, unsigned &size, unsigned Align) const {
1836 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1837 assert((State->getCallOrPrologue() == Prologue ||
1838 State->getCallOrPrologue() == Call) &&
1839 "unhandled ParmContext");
1841 // For in-prologue parameters handling, we also introduce stack offset
1842 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1843 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1844 // NSAA should be evaluted (NSAA means "next stacked argument address").
1845 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1846 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1847 unsigned NSAAOffset = State->getNextStackOffset();
1848 if (State->getCallOrPrologue() != Call) {
1849 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1851 State->getInRegsParamInfo(i, RB, RE);
1852 assert(NSAAOffset >= (RE-RB)*4 &&
1853 "Stack offset for byval regs doesn't introduced anymore?");
1854 NSAAOffset -= (RE-RB)*4;
1857 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1858 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1859 unsigned AlignInRegs = Align / 4;
1860 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1861 for (unsigned i = 0; i < Waste; ++i)
1862 reg = State->AllocateReg(GPRArgRegs, 4);
1865 unsigned excess = 4 * (ARM::R4 - reg);
1867 // Special case when NSAA != SP and parameter size greater than size of
1868 // all remained GPR regs. In that case we can't split parameter, we must
1869 // send it to stack. We also must set NCRN to R4, so waste all
1870 // remained registers.
1871 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1872 while (State->AllocateReg(GPRArgRegs, 4))
1877 // First register for byval parameter is the first register that wasn't
1878 // allocated before this method call, so it would be "reg".
1879 // If parameter is small enough to be saved in range [reg, r4), then
1880 // the end (first after last) register would be reg + param-size-in-regs,
1881 // else parameter would be splitted between registers and stack,
1882 // end register would be r4 in this case.
1883 unsigned ByValRegBegin = reg;
1884 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1885 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1886 // Note, first register is allocated in the beginning of function already,
1887 // allocate remained amount of registers we need.
1888 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1889 State->AllocateReg(GPRArgRegs, 4);
1890 // At a call site, a byval parameter that is split between
1891 // registers and memory needs its size truncated here. In a
1892 // function prologue, such byval parameters are reassembled in
1893 // memory, and are not truncated.
1894 if (State->getCallOrPrologue() == Call) {
1895 // Make remained size equal to 0 in case, when
1896 // the whole structure may be stored into registers.
1906 /// MatchingStackOffset - Return true if the given stack call argument is
1907 /// already available in the same position (relatively) of the caller's
1908 /// incoming argument stack.
1910 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1911 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1912 const TargetInstrInfo *TII) {
1913 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1915 if (Arg.getOpcode() == ISD::CopyFromReg) {
1916 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1917 if (!TargetRegisterInfo::isVirtualRegister(VR))
1919 MachineInstr *Def = MRI->getVRegDef(VR);
1922 if (!Flags.isByVal()) {
1923 if (!TII->isLoadFromStackSlot(Def, FI))
1928 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1929 if (Flags.isByVal())
1930 // ByVal argument is passed in as a pointer but it's now being
1931 // dereferenced. e.g.
1932 // define @foo(%struct.X* %A) {
1933 // tail call @bar(%struct.X* byval %A)
1936 SDValue Ptr = Ld->getBasePtr();
1937 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1940 FI = FINode->getIndex();
1944 assert(FI != INT_MAX);
1945 if (!MFI->isFixedObjectIndex(FI))
1947 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1950 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1951 /// for tail call optimization. Targets which want to do tail call
1952 /// optimization should implement this function.
1954 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1955 CallingConv::ID CalleeCC,
1957 bool isCalleeStructRet,
1958 bool isCallerStructRet,
1959 const SmallVectorImpl<ISD::OutputArg> &Outs,
1960 const SmallVectorImpl<SDValue> &OutVals,
1961 const SmallVectorImpl<ISD::InputArg> &Ins,
1962 SelectionDAG& DAG) const {
1963 const Function *CallerF = DAG.getMachineFunction().getFunction();
1964 CallingConv::ID CallerCC = CallerF->getCallingConv();
1965 bool CCMatch = CallerCC == CalleeCC;
1967 // Look for obvious safe cases to perform tail call optimization that do not
1968 // require ABI changes. This is what gcc calls sibcall.
1970 // Do not sibcall optimize vararg calls unless the call site is not passing
1972 if (isVarArg && !Outs.empty())
1975 // Exception-handling functions need a special set of instructions to indicate
1976 // a return to the hardware. Tail-calling another function would probably
1978 if (CallerF->hasFnAttribute("interrupt"))
1981 // Also avoid sibcall optimization if either caller or callee uses struct
1982 // return semantics.
1983 if (isCalleeStructRet || isCallerStructRet)
1986 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1987 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1988 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1989 // support in the assembler and linker to be used. This would need to be
1990 // fixed to fully support tail calls in Thumb1.
1992 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1993 // LR. This means if we need to reload LR, it takes an extra instructions,
1994 // which outweighs the value of the tail call; but here we don't know yet
1995 // whether LR is going to be used. Probably the right approach is to
1996 // generate the tail call here and turn it back into CALL/RET in
1997 // emitEpilogue if LR is used.
1999 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2000 // but we need to make sure there are enough registers; the only valid
2001 // registers are the 4 used for parameters. We don't currently do this
2003 if (Subtarget->isThumb1Only())
2006 // If the calling conventions do not match, then we'd better make sure the
2007 // results are returned in the same way as what the caller expects.
2009 SmallVector<CCValAssign, 16> RVLocs1;
2010 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2011 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2012 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2014 SmallVector<CCValAssign, 16> RVLocs2;
2015 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2016 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2017 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2019 if (RVLocs1.size() != RVLocs2.size())
2021 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2022 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2024 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2026 if (RVLocs1[i].isRegLoc()) {
2027 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2030 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2036 // If Caller's vararg or byval argument has been split between registers and
2037 // stack, do not perform tail call, since part of the argument is in caller's
2039 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2040 getInfo<ARMFunctionInfo>();
2041 if (AFI_Caller->getArgRegsSaveSize())
2044 // If the callee takes no arguments then go on to check the results of the
2046 if (!Outs.empty()) {
2047 // Check if stack adjustment is needed. For now, do not do this if any
2048 // argument is passed on the stack.
2049 SmallVector<CCValAssign, 16> ArgLocs;
2050 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2051 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2052 CCInfo.AnalyzeCallOperands(Outs,
2053 CCAssignFnForNode(CalleeCC, false, isVarArg));
2054 if (CCInfo.getNextStackOffset()) {
2055 MachineFunction &MF = DAG.getMachineFunction();
2057 // Check if the arguments are already laid out in the right way as
2058 // the caller's fixed stack objects.
2059 MachineFrameInfo *MFI = MF.getFrameInfo();
2060 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2061 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2062 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2064 ++i, ++realArgIdx) {
2065 CCValAssign &VA = ArgLocs[i];
2066 EVT RegVT = VA.getLocVT();
2067 SDValue Arg = OutVals[realArgIdx];
2068 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2069 if (VA.getLocInfo() == CCValAssign::Indirect)
2071 if (VA.needsCustom()) {
2072 // f64 and vector types are split into multiple registers or
2073 // register/stack-slot combinations. The types will not match
2074 // the registers; give up on memory f64 refs until we figure
2075 // out what to do about this.
2078 if (!ArgLocs[++i].isRegLoc())
2080 if (RegVT == MVT::v2f64) {
2081 if (!ArgLocs[++i].isRegLoc())
2083 if (!ArgLocs[++i].isRegLoc())
2086 } else if (!VA.isRegLoc()) {
2087 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2099 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2100 MachineFunction &MF, bool isVarArg,
2101 const SmallVectorImpl<ISD::OutputArg> &Outs,
2102 LLVMContext &Context) const {
2103 SmallVector<CCValAssign, 16> RVLocs;
2104 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2105 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2109 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2110 SDLoc DL, SelectionDAG &DAG) {
2111 const MachineFunction &MF = DAG.getMachineFunction();
2112 const Function *F = MF.getFunction();
2114 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2116 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2117 // version of the "preferred return address". These offsets affect the return
2118 // instruction if this is a return from PL1 without hypervisor extensions.
2119 // IRQ/FIQ: +4 "subs pc, lr, #4"
2120 // SWI: 0 "subs pc, lr, #0"
2121 // ABORT: +4 "subs pc, lr, #4"
2122 // UNDEF: +4/+2 "subs pc, lr, #0"
2123 // UNDEF varies depending on where the exception came from ARM or Thumb
2124 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2127 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2130 else if (IntKind == "SWI" || IntKind == "UNDEF")
2133 report_fatal_error("Unsupported interrupt attribute. If present, value "
2134 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2136 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2138 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2139 RetOps.data(), RetOps.size());
2143 ARMTargetLowering::LowerReturn(SDValue Chain,
2144 CallingConv::ID CallConv, bool isVarArg,
2145 const SmallVectorImpl<ISD::OutputArg> &Outs,
2146 const SmallVectorImpl<SDValue> &OutVals,
2147 SDLoc dl, SelectionDAG &DAG) const {
2149 // CCValAssign - represent the assignment of the return value to a location.
2150 SmallVector<CCValAssign, 16> RVLocs;
2152 // CCState - Info about the registers and stack slots.
2153 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2154 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2156 // Analyze outgoing return values.
2157 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2161 SmallVector<SDValue, 4> RetOps;
2162 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2164 // Copy the result values into the output registers.
2165 for (unsigned i = 0, realRVLocIdx = 0;
2167 ++i, ++realRVLocIdx) {
2168 CCValAssign &VA = RVLocs[i];
2169 assert(VA.isRegLoc() && "Can only return in registers!");
2171 SDValue Arg = OutVals[realRVLocIdx];
2173 switch (VA.getLocInfo()) {
2174 default: llvm_unreachable("Unknown loc info!");
2175 case CCValAssign::Full: break;
2176 case CCValAssign::BCvt:
2177 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2181 if (VA.needsCustom()) {
2182 if (VA.getLocVT() == MVT::v2f64) {
2183 // Extract the first half and return it in two registers.
2184 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2185 DAG.getConstant(0, MVT::i32));
2186 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2187 DAG.getVTList(MVT::i32, MVT::i32), Half);
2189 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2190 Flag = Chain.getValue(1);
2191 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2192 VA = RVLocs[++i]; // skip ahead to next loc
2193 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2194 HalfGPRs.getValue(1), Flag);
2195 Flag = Chain.getValue(1);
2196 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2197 VA = RVLocs[++i]; // skip ahead to next loc
2199 // Extract the 2nd half and fall through to handle it as an f64 value.
2200 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2201 DAG.getConstant(1, MVT::i32));
2203 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2205 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2206 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2207 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2208 Flag = Chain.getValue(1);
2209 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2210 VA = RVLocs[++i]; // skip ahead to next loc
2211 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2214 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2216 // Guarantee that all emitted copies are
2217 // stuck together, avoiding something bad.
2218 Flag = Chain.getValue(1);
2219 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2222 // Update chain and glue.
2225 RetOps.push_back(Flag);
2227 // CPUs which aren't M-class use a special sequence to return from
2228 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2229 // though we use "subs pc, lr, #N").
2231 // M-class CPUs actually use a normal return sequence with a special
2232 // (hardware-provided) value in LR, so the normal code path works.
2233 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2234 !Subtarget->isMClass()) {
2235 if (Subtarget->isThumb1Only())
2236 report_fatal_error("interrupt attribute is not supported in Thumb1");
2237 return LowerInterruptReturn(RetOps, dl, DAG);
2240 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2241 RetOps.data(), RetOps.size());
2244 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2245 if (N->getNumValues() != 1)
2247 if (!N->hasNUsesOfValue(1, 0))
2250 SDValue TCChain = Chain;
2251 SDNode *Copy = *N->use_begin();
2252 if (Copy->getOpcode() == ISD::CopyToReg) {
2253 // If the copy has a glue operand, we conservatively assume it isn't safe to
2254 // perform a tail call.
2255 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2257 TCChain = Copy->getOperand(0);
2258 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2259 SDNode *VMov = Copy;
2260 // f64 returned in a pair of GPRs.
2261 SmallPtrSet<SDNode*, 2> Copies;
2262 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2264 if (UI->getOpcode() != ISD::CopyToReg)
2268 if (Copies.size() > 2)
2271 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2273 SDValue UseChain = UI->getOperand(0);
2274 if (Copies.count(UseChain.getNode()))
2281 } else if (Copy->getOpcode() == ISD::BITCAST) {
2282 // f32 returned in a single GPR.
2283 if (!Copy->hasOneUse())
2285 Copy = *Copy->use_begin();
2286 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2288 TCChain = Copy->getOperand(0);
2293 bool HasRet = false;
2294 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2296 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2297 UI->getOpcode() != ARMISD::INTRET_FLAG)
2309 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2310 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2313 if (!CI->isTailCall())
2316 return !Subtarget->isThumb1Only();
2319 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2320 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2321 // one of the above mentioned nodes. It has to be wrapped because otherwise
2322 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2323 // be used to form addressing mode. These wrapped nodes will be selected
2325 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2326 EVT PtrVT = Op.getValueType();
2327 // FIXME there is no actual debug info here
2329 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2331 if (CP->isMachineConstantPoolEntry())
2332 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2333 CP->getAlignment());
2335 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2336 CP->getAlignment());
2337 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2340 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2341 return MachineJumpTableInfo::EK_Inline;
2344 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2345 SelectionDAG &DAG) const {
2346 MachineFunction &MF = DAG.getMachineFunction();
2347 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2348 unsigned ARMPCLabelIndex = 0;
2350 EVT PtrVT = getPointerTy();
2351 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2352 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2354 if (RelocM == Reloc::Static) {
2355 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2357 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2358 ARMPCLabelIndex = AFI->createPICLabelUId();
2359 ARMConstantPoolValue *CPV =
2360 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2361 ARMCP::CPBlockAddress, PCAdj);
2362 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2364 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2365 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2366 MachinePointerInfo::getConstantPool(),
2367 false, false, false, 0);
2368 if (RelocM == Reloc::Static)
2370 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2371 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2374 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2376 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2377 SelectionDAG &DAG) const {
2379 EVT PtrVT = getPointerTy();
2380 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2381 MachineFunction &MF = DAG.getMachineFunction();
2382 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2383 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2384 ARMConstantPoolValue *CPV =
2385 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2386 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2387 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2388 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2389 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2390 MachinePointerInfo::getConstantPool(),
2391 false, false, false, 0);
2392 SDValue Chain = Argument.getValue(1);
2394 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2395 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2397 // call __tls_get_addr.
2400 Entry.Node = Argument;
2401 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2402 Args.push_back(Entry);
2403 // FIXME: is there useful debug info available here?
2404 TargetLowering::CallLoweringInfo CLI(Chain,
2405 (Type *) Type::getInt32Ty(*DAG.getContext()),
2406 false, false, false, false,
2407 0, CallingConv::C, /*isTailCall=*/false,
2408 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2409 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2410 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2411 return CallResult.first;
2414 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2415 // "local exec" model.
2417 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2419 TLSModel::Model model) const {
2420 const GlobalValue *GV = GA->getGlobal();
2423 SDValue Chain = DAG.getEntryNode();
2424 EVT PtrVT = getPointerTy();
2425 // Get the Thread Pointer
2426 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2428 if (model == TLSModel::InitialExec) {
2429 MachineFunction &MF = DAG.getMachineFunction();
2430 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2431 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2432 // Initial exec model.
2433 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2434 ARMConstantPoolValue *CPV =
2435 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2436 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2438 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2439 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2440 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2441 MachinePointerInfo::getConstantPool(),
2442 false, false, false, 0);
2443 Chain = Offset.getValue(1);
2445 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2446 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2448 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2449 MachinePointerInfo::getConstantPool(),
2450 false, false, false, 0);
2453 assert(model == TLSModel::LocalExec);
2454 ARMConstantPoolValue *CPV =
2455 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2456 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2457 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2458 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2459 MachinePointerInfo::getConstantPool(),
2460 false, false, false, 0);
2463 // The address of the thread local variable is the add of the thread
2464 // pointer with the offset of the variable.
2465 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2469 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2470 // TODO: implement the "local dynamic" model
2471 assert(Subtarget->isTargetELF() &&
2472 "TLS not implemented for non-ELF targets");
2473 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2475 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2478 case TLSModel::GeneralDynamic:
2479 case TLSModel::LocalDynamic:
2480 return LowerToTLSGeneralDynamicModel(GA, DAG);
2481 case TLSModel::InitialExec:
2482 case TLSModel::LocalExec:
2483 return LowerToTLSExecModels(GA, DAG, model);
2485 llvm_unreachable("bogus TLS model");
2488 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2489 SelectionDAG &DAG) const {
2490 EVT PtrVT = getPointerTy();
2492 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2493 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2494 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2495 ARMConstantPoolValue *CPV =
2496 ARMConstantPoolConstant::Create(GV,
2497 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2498 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2499 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2500 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2502 MachinePointerInfo::getConstantPool(),
2503 false, false, false, 0);
2504 SDValue Chain = Result.getValue(1);
2505 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2506 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2508 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2509 MachinePointerInfo::getGOT(),
2510 false, false, false, 0);
2514 // If we have T2 ops, we can materialize the address directly via movt/movw
2515 // pair. This is always cheaper.
2516 if (Subtarget->useMovt()) {
2518 // FIXME: Once remat is capable of dealing with instructions with register
2519 // operands, expand this into two nodes.
2520 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2521 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2523 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2524 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2525 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2526 MachinePointerInfo::getConstantPool(),
2527 false, false, false, 0);
2531 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2532 SelectionDAG &DAG) const {
2533 EVT PtrVT = getPointerTy();
2535 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2536 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2538 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2539 // update ARMFastISel::ARMMaterializeGV.
2540 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2542 // FIXME: Once remat is capable of dealing with instructions with register
2543 // operands, expand this into two nodes.
2544 if (RelocM == Reloc::Static)
2545 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2546 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2548 unsigned Wrapper = (RelocM == Reloc::PIC_)
2549 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2550 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2551 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2552 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2553 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2554 MachinePointerInfo::getGOT(),
2555 false, false, false, 0);
2559 unsigned ARMPCLabelIndex = 0;
2561 if (RelocM == Reloc::Static) {
2562 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2564 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2565 ARMPCLabelIndex = AFI->createPICLabelUId();
2566 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2567 ARMConstantPoolValue *CPV =
2568 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2570 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2572 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2574 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2575 MachinePointerInfo::getConstantPool(),
2576 false, false, false, 0);
2577 SDValue Chain = Result.getValue(1);
2579 if (RelocM == Reloc::PIC_) {
2580 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2581 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2584 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2585 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2586 false, false, false, 0);
2591 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2592 SelectionDAG &DAG) const {
2593 assert(Subtarget->isTargetELF() &&
2594 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2595 MachineFunction &MF = DAG.getMachineFunction();
2596 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2597 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2598 EVT PtrVT = getPointerTy();
2600 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2601 ARMConstantPoolValue *CPV =
2602 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2603 ARMPCLabelIndex, PCAdj);
2604 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2605 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2606 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2607 MachinePointerInfo::getConstantPool(),
2608 false, false, false, 0);
2609 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2610 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2614 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2616 SDValue Val = DAG.getConstant(0, MVT::i32);
2617 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2618 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2619 Op.getOperand(1), Val);
2623 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2625 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2626 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2630 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2631 const ARMSubtarget *Subtarget) const {
2632 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2635 default: return SDValue(); // Don't custom lower most intrinsics.
2636 case Intrinsic::arm_thread_pointer: {
2637 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2638 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2640 case Intrinsic::eh_sjlj_lsda: {
2641 MachineFunction &MF = DAG.getMachineFunction();
2642 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2643 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2644 EVT PtrVT = getPointerTy();
2645 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2647 unsigned PCAdj = (RelocM != Reloc::PIC_)
2648 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2649 ARMConstantPoolValue *CPV =
2650 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2651 ARMCP::CPLSDA, PCAdj);
2652 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2653 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2655 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2656 MachinePointerInfo::getConstantPool(),
2657 false, false, false, 0);
2659 if (RelocM == Reloc::PIC_) {
2660 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2661 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2665 case Intrinsic::arm_neon_vmulls:
2666 case Intrinsic::arm_neon_vmullu: {
2667 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2668 ? ARMISD::VMULLs : ARMISD::VMULLu;
2669 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2670 Op.getOperand(1), Op.getOperand(2));
2675 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2676 const ARMSubtarget *Subtarget) {
2677 // FIXME: handle "fence singlethread" more efficiently.
2679 if (!Subtarget->hasDataBarrier()) {
2680 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2681 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2683 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2684 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2685 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2686 DAG.getConstant(0, MVT::i32));
2689 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2690 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2691 unsigned Domain = ARM_MB::ISH;
2692 if (Subtarget->isMClass()) {
2693 // Only a full system barrier exists in the M-class architectures.
2694 Domain = ARM_MB::SY;
2695 } else if (Subtarget->isSwift() && Ord == Release) {
2696 // Swift happens to implement ISHST barriers in a way that's compatible with
2697 // Release semantics but weaker than ISH so we'd be fools not to use
2698 // it. Beware: other processors probably don't!
2699 Domain = ARM_MB::ISHST;
2702 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2703 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2704 DAG.getConstant(Domain, MVT::i32));
2707 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2708 const ARMSubtarget *Subtarget) {
2709 // ARM pre v5TE and Thumb1 does not have preload instructions.
2710 if (!(Subtarget->isThumb2() ||
2711 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2712 // Just preserve the chain.
2713 return Op.getOperand(0);
2716 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2718 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2719 // ARMv7 with MP extension has PLDW.
2720 return Op.getOperand(0);
2722 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2723 if (Subtarget->isThumb()) {
2725 isRead = ~isRead & 1;
2726 isData = ~isData & 1;
2729 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2730 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2731 DAG.getConstant(isData, MVT::i32));
2734 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2735 MachineFunction &MF = DAG.getMachineFunction();
2736 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2738 // vastart just stores the address of the VarArgsFrameIndex slot into the
2739 // memory location argument.
2741 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2742 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2743 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2744 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2745 MachinePointerInfo(SV), false, false, 0);
2749 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2750 SDValue &Root, SelectionDAG &DAG,
2752 MachineFunction &MF = DAG.getMachineFunction();
2753 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2755 const TargetRegisterClass *RC;
2756 if (AFI->isThumb1OnlyFunction())
2757 RC = &ARM::tGPRRegClass;
2759 RC = &ARM::GPRRegClass;
2761 // Transform the arguments stored in physical registers into virtual ones.
2762 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2763 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2766 if (NextVA.isMemLoc()) {
2767 MachineFrameInfo *MFI = MF.getFrameInfo();
2768 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2770 // Create load node to retrieve arguments from the stack.
2771 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2772 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2773 MachinePointerInfo::getFixedStack(FI),
2774 false, false, false, 0);
2776 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2777 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2780 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2784 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2785 unsigned InRegsParamRecordIdx,
2787 unsigned &ArgRegsSize,
2788 unsigned &ArgRegsSaveSize)
2791 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2792 unsigned RBegin, REnd;
2793 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2794 NumGPRs = REnd - RBegin;
2796 unsigned int firstUnalloced;
2797 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2798 sizeof(GPRArgRegs) /
2799 sizeof(GPRArgRegs[0]));
2800 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2803 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2804 ArgRegsSize = NumGPRs * 4;
2806 // If parameter is split between stack and GPRs...
2807 if (NumGPRs && Align == 8 &&
2808 (ArgRegsSize < ArgSize ||
2809 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2810 // Add padding for part of param recovered from GPRs, so
2811 // its last byte must be at address K*8 - 1.
2812 // We need to do it, since remained (stack) part of parameter has
2813 // stack alignment, and we need to "attach" "GPRs head" without gaps
2816 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2817 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2819 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2821 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2822 (ArgRegsSize + AFI->getArgRegsSaveSize());
2823 ArgRegsSaveSize = ArgRegsSize + Padding;
2825 // We don't need to extend regs save size for byval parameters if they
2826 // are passed via GPRs only.
2827 ArgRegsSaveSize = ArgRegsSize;
2830 // The remaining GPRs hold either the beginning of variable-argument
2831 // data, or the beginning of an aggregate passed by value (usually
2832 // byval). Either way, we allocate stack slots adjacent to the data
2833 // provided by our caller, and store the unallocated registers there.
2834 // If this is a variadic function, the va_list pointer will begin with
2835 // these values; otherwise, this reassembles a (byval) structure that
2836 // was split between registers and memory.
2837 // Return: The frame index registers were stored into.
2839 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2840 SDLoc dl, SDValue &Chain,
2841 const Value *OrigArg,
2842 unsigned InRegsParamRecordIdx,
2843 unsigned OffsetFromOrigArg,
2846 bool ForceMutable) const {
2848 // Currently, two use-cases possible:
2849 // Case #1. Non var-args function, and we meet first byval parameter.
2850 // Setup first unallocated register as first byval register;
2851 // eat all remained registers
2852 // (these two actions are performed by HandleByVal method).
2853 // Then, here, we initialize stack frame with
2854 // "store-reg" instructions.
2855 // Case #2. Var-args function, that doesn't contain byval parameters.
2856 // The same: eat all remained unallocated registers,
2857 // initialize stack frame.
2859 MachineFunction &MF = DAG.getMachineFunction();
2860 MachineFrameInfo *MFI = MF.getFrameInfo();
2861 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2862 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2863 unsigned RBegin, REnd;
2864 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2865 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2866 firstRegToSaveIndex = RBegin - ARM::R0;
2867 lastRegToSaveIndex = REnd - ARM::R0;
2869 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2870 (GPRArgRegs, array_lengthof(GPRArgRegs));
2871 lastRegToSaveIndex = 4;
2874 unsigned ArgRegsSize, ArgRegsSaveSize;
2875 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2876 ArgRegsSize, ArgRegsSaveSize);
2878 // Store any by-val regs to their spots on the stack so that they may be
2879 // loaded by deferencing the result of formal parameter pointer or va_next.
2880 // Note: once stack area for byval/varargs registers
2881 // was initialized, it can't be initialized again.
2882 if (ArgRegsSaveSize) {
2884 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2887 assert(AFI->getStoredByValParamsPadding() == 0 &&
2888 "The only parameter may be padded.");
2889 AFI->setStoredByValParamsPadding(Padding);
2892 int FrameIndex = MFI->CreateFixedObject(
2894 Padding + ArgOffset,
2896 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2898 SmallVector<SDValue, 4> MemOps;
2899 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2900 ++firstRegToSaveIndex, ++i) {
2901 const TargetRegisterClass *RC;
2902 if (AFI->isThumb1OnlyFunction())
2903 RC = &ARM::tGPRRegClass;
2905 RC = &ARM::GPRRegClass;
2907 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2908 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2910 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2911 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2913 MemOps.push_back(Store);
2914 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2915 DAG.getConstant(4, getPointerTy()));
2918 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2920 if (!MemOps.empty())
2921 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2922 &MemOps[0], MemOps.size());
2925 // This will point to the next argument passed via stack.
2926 return MFI->CreateFixedObject(
2927 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2930 // Setup stack frame, the va_list pointer will start from.
2932 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2933 SDLoc dl, SDValue &Chain,
2935 bool ForceMutable) const {
2936 MachineFunction &MF = DAG.getMachineFunction();
2937 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2939 // Try to store any remaining integer argument regs
2940 // to their spots on the stack so that they may be loaded by deferencing
2941 // the result of va_next.
2942 // If there is no regs to be stored, just point address after last
2943 // argument passed via stack.
2945 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2946 0, ArgOffset, 0, ForceMutable);
2948 AFI->setVarArgsFrameIndex(FrameIndex);
2952 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2953 CallingConv::ID CallConv, bool isVarArg,
2954 const SmallVectorImpl<ISD::InputArg>
2956 SDLoc dl, SelectionDAG &DAG,
2957 SmallVectorImpl<SDValue> &InVals)
2959 MachineFunction &MF = DAG.getMachineFunction();
2960 MachineFrameInfo *MFI = MF.getFrameInfo();
2962 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2964 // Assign locations to all of the incoming arguments.
2965 SmallVector<CCValAssign, 16> ArgLocs;
2966 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2967 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2968 CCInfo.AnalyzeFormalArguments(Ins,
2969 CCAssignFnForNode(CallConv, /* Return*/ false,
2972 SmallVector<SDValue, 16> ArgValues;
2973 int lastInsIndex = -1;
2975 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2976 unsigned CurArgIdx = 0;
2978 // Initially ArgRegsSaveSize is zero.
2979 // Then we increase this value each time we meet byval parameter.
2980 // We also increase this value in case of varargs function.
2981 AFI->setArgRegsSaveSize(0);
2983 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2984 CCValAssign &VA = ArgLocs[i];
2985 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2986 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2987 // Arguments stored in registers.
2988 if (VA.isRegLoc()) {
2989 EVT RegVT = VA.getLocVT();
2991 if (VA.needsCustom()) {
2992 // f64 and vector types are split up into multiple registers or
2993 // combinations of registers and stack slots.
2994 if (VA.getLocVT() == MVT::v2f64) {
2995 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2997 VA = ArgLocs[++i]; // skip ahead to next loc
2999 if (VA.isMemLoc()) {
3000 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3001 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3002 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3003 MachinePointerInfo::getFixedStack(FI),
3004 false, false, false, 0);
3006 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3009 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3010 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3011 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3012 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3013 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3015 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3018 const TargetRegisterClass *RC;
3020 if (RegVT == MVT::f32)
3021 RC = &ARM::SPRRegClass;
3022 else if (RegVT == MVT::f64)
3023 RC = &ARM::DPRRegClass;
3024 else if (RegVT == MVT::v2f64)
3025 RC = &ARM::QPRRegClass;
3026 else if (RegVT == MVT::i32)
3027 RC = AFI->isThumb1OnlyFunction() ?
3028 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3029 (const TargetRegisterClass*)&ARM::GPRRegClass;
3031 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3033 // Transform the arguments in physical registers into virtual ones.
3034 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3035 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3038 // If this is an 8 or 16-bit value, it is really passed promoted
3039 // to 32 bits. Insert an assert[sz]ext to capture this, then
3040 // truncate to the right size.
3041 switch (VA.getLocInfo()) {
3042 default: llvm_unreachable("Unknown loc info!");
3043 case CCValAssign::Full: break;
3044 case CCValAssign::BCvt:
3045 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3047 case CCValAssign::SExt:
3048 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3049 DAG.getValueType(VA.getValVT()));
3050 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3052 case CCValAssign::ZExt:
3053 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3054 DAG.getValueType(VA.getValVT()));
3055 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3059 InVals.push_back(ArgValue);
3061 } else { // VA.isRegLoc()
3064 assert(VA.isMemLoc());
3065 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3067 int index = ArgLocs[i].getValNo();
3069 // Some Ins[] entries become multiple ArgLoc[] entries.
3070 // Process them only once.
3071 if (index != lastInsIndex)
3073 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3074 // FIXME: For now, all byval parameter objects are marked mutable.
3075 // This can be changed with more analysis.
3076 // In case of tail call optimization mark all arguments mutable.
3077 // Since they could be overwritten by lowering of arguments in case of
3079 if (Flags.isByVal()) {
3080 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3081 int FrameIndex = StoreByValRegs(
3082 CCInfo, DAG, dl, Chain, CurOrigArg,
3084 Ins[VA.getValNo()].PartOffset,
3085 VA.getLocMemOffset(),
3086 Flags.getByValSize(),
3087 true /*force mutable frames*/);
3088 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3089 CCInfo.nextInRegsParam();
3091 unsigned FIOffset = VA.getLocMemOffset() +
3092 AFI->getStoredByValParamsPadding();
3093 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3096 // Create load nodes to retrieve arguments from the stack.
3097 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3098 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3099 MachinePointerInfo::getFixedStack(FI),
3100 false, false, false, 0));
3102 lastInsIndex = index;
3109 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3110 CCInfo.getNextStackOffset());
3115 /// isFloatingPointZero - Return true if this is +0.0.
3116 static bool isFloatingPointZero(SDValue Op) {
3117 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3118 return CFP->getValueAPF().isPosZero();
3119 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3120 // Maybe this has already been legalized into the constant pool?
3121 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3122 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3123 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3124 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3125 return CFP->getValueAPF().isPosZero();
3131 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3132 /// the given operands.
3134 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3135 SDValue &ARMcc, SelectionDAG &DAG,
3137 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3138 unsigned C = RHSC->getZExtValue();
3139 if (!isLegalICmpImmediate(C)) {
3140 // Constant does not fit, try adjusting it by one?
3145 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3146 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3147 RHS = DAG.getConstant(C-1, MVT::i32);
3152 if (C != 0 && isLegalICmpImmediate(C-1)) {
3153 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3154 RHS = DAG.getConstant(C-1, MVT::i32);
3159 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3160 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3161 RHS = DAG.getConstant(C+1, MVT::i32);
3166 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3167 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3168 RHS = DAG.getConstant(C+1, MVT::i32);
3175 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3176 ARMISD::NodeType CompareType;
3179 CompareType = ARMISD::CMP;
3184 CompareType = ARMISD::CMPZ;
3187 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3188 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3191 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3193 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3196 if (!isFloatingPointZero(RHS))
3197 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3199 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3200 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3203 /// duplicateCmp - Glue values can have only one use, so this function
3204 /// duplicates a comparison node.
3206 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3207 unsigned Opc = Cmp.getOpcode();
3209 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3210 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3212 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3213 Cmp = Cmp.getOperand(0);
3214 Opc = Cmp.getOpcode();
3215 if (Opc == ARMISD::CMPFP)
3216 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3218 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3219 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3221 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3224 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3225 SDValue Cond = Op.getOperand(0);
3226 SDValue SelectTrue = Op.getOperand(1);
3227 SDValue SelectFalse = Op.getOperand(2);
3232 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3233 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3235 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3236 const ConstantSDNode *CMOVTrue =
3237 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3238 const ConstantSDNode *CMOVFalse =
3239 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3241 if (CMOVTrue && CMOVFalse) {
3242 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3243 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3247 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3249 False = SelectFalse;
3250 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3255 if (True.getNode() && False.getNode()) {
3256 EVT VT = Op.getValueType();
3257 SDValue ARMcc = Cond.getOperand(2);
3258 SDValue CCR = Cond.getOperand(3);
3259 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3260 assert(True.getValueType() == VT);
3261 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3266 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3267 // undefined bits before doing a full-word comparison with zero.
3268 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3269 DAG.getConstant(1, Cond.getValueType()));
3271 return DAG.getSelectCC(dl, Cond,
3272 DAG.getConstant(0, Cond.getValueType()),
3273 SelectTrue, SelectFalse, ISD::SETNE);
3276 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3277 if (CC == ISD::SETNE)
3279 return ISD::getSetCCSwappedOperands(CC);
3282 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3283 bool &swpCmpOps, bool &swpVselOps) {
3284 // Start by selecting the GE condition code for opcodes that return true for
3286 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3288 CondCode = ARMCC::GE;
3290 // and GT for opcodes that return false for 'equality'.
3291 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3293 CondCode = ARMCC::GT;
3295 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3296 // to swap the compare operands.
3297 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3301 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3302 // If we have an unordered opcode, we need to swap the operands to the VSEL
3303 // instruction (effectively negating the condition).
3305 // This also has the effect of swapping which one of 'less' or 'greater'
3306 // returns true, so we also swap the compare operands. It also switches
3307 // whether we return true for 'equality', so we compensate by picking the
3308 // opposite condition code to our original choice.
3309 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3310 CC == ISD::SETUGT) {
3311 swpCmpOps = !swpCmpOps;
3312 swpVselOps = !swpVselOps;
3313 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3316 // 'ordered' is 'anything but unordered', so use the VS condition code and
3317 // swap the VSEL operands.
3318 if (CC == ISD::SETO) {
3319 CondCode = ARMCC::VS;
3323 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3324 // code and swap the VSEL operands.
3325 if (CC == ISD::SETUNE) {
3326 CondCode = ARMCC::EQ;
3331 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3332 EVT VT = Op.getValueType();
3333 SDValue LHS = Op.getOperand(0);
3334 SDValue RHS = Op.getOperand(1);
3335 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3336 SDValue TrueVal = Op.getOperand(2);
3337 SDValue FalseVal = Op.getOperand(3);
3340 if (LHS.getValueType() == MVT::i32) {
3341 // Try to generate VSEL on ARMv8.
3342 // The VSEL instruction can't use all the usual ARM condition
3343 // codes: it only has two bits to select the condition code, so it's
3344 // constrained to use only GE, GT, VS and EQ.
3346 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3347 // swap the operands of the previous compare instruction (effectively
3348 // inverting the compare condition, swapping 'less' and 'greater') and
3349 // sometimes need to swap the operands to the VSEL (which inverts the
3350 // condition in the sense of firing whenever the previous condition didn't)
3351 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3352 TrueVal.getValueType() == MVT::f64)) {
3353 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3354 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3355 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3356 CC = getInverseCCForVSEL(CC);
3357 std::swap(TrueVal, FalseVal);
3362 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3363 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3364 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3368 ARMCC::CondCodes CondCode, CondCode2;
3369 FPCCToARMCC(CC, CondCode, CondCode2);
3371 // Try to generate VSEL on ARMv8.
3372 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3373 TrueVal.getValueType() == MVT::f64)) {
3374 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3375 // same operands, as follows:
3376 // c = fcmp [ogt, olt, ugt, ult] a, b
3378 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3379 // handled differently than the original code sequence.
3380 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3382 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3383 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3384 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3385 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3388 bool swpCmpOps = false;
3389 bool swpVselOps = false;
3390 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3392 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3393 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3395 std::swap(LHS, RHS);
3397 std::swap(TrueVal, FalseVal);
3401 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3402 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3403 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3404 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3406 if (CondCode2 != ARMCC::AL) {
3407 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3408 // FIXME: Needs another CMP because flag can have but one use.
3409 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3410 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3411 Result, TrueVal, ARMcc2, CCR, Cmp2);
3416 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3417 /// to morph to an integer compare sequence.
3418 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3419 const ARMSubtarget *Subtarget) {
3420 SDNode *N = Op.getNode();
3421 if (!N->hasOneUse())
3422 // Otherwise it requires moving the value from fp to integer registers.
3424 if (!N->getNumValues())
3426 EVT VT = Op.getValueType();
3427 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3428 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3429 // vmrs are very slow, e.g. cortex-a8.
3432 if (isFloatingPointZero(Op)) {
3436 return ISD::isNormalLoad(N);
3439 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3440 if (isFloatingPointZero(Op))
3441 return DAG.getConstant(0, MVT::i32);
3443 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3444 return DAG.getLoad(MVT::i32, SDLoc(Op),
3445 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3446 Ld->isVolatile(), Ld->isNonTemporal(),
3447 Ld->isInvariant(), Ld->getAlignment());
3449 llvm_unreachable("Unknown VFP cmp argument!");
3452 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3453 SDValue &RetVal1, SDValue &RetVal2) {
3454 if (isFloatingPointZero(Op)) {
3455 RetVal1 = DAG.getConstant(0, MVT::i32);
3456 RetVal2 = DAG.getConstant(0, MVT::i32);
3460 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3461 SDValue Ptr = Ld->getBasePtr();
3462 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3463 Ld->getChain(), Ptr,
3464 Ld->getPointerInfo(),
3465 Ld->isVolatile(), Ld->isNonTemporal(),
3466 Ld->isInvariant(), Ld->getAlignment());
3468 EVT PtrType = Ptr.getValueType();
3469 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3470 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3471 PtrType, Ptr, DAG.getConstant(4, PtrType));
3472 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3473 Ld->getChain(), NewPtr,
3474 Ld->getPointerInfo().getWithOffset(4),
3475 Ld->isVolatile(), Ld->isNonTemporal(),
3476 Ld->isInvariant(), NewAlign);
3480 llvm_unreachable("Unknown VFP cmp argument!");
3483 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3484 /// f32 and even f64 comparisons to integer ones.
3486 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3487 SDValue Chain = Op.getOperand(0);
3488 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3489 SDValue LHS = Op.getOperand(2);
3490 SDValue RHS = Op.getOperand(3);
3491 SDValue Dest = Op.getOperand(4);
3494 bool LHSSeenZero = false;
3495 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3496 bool RHSSeenZero = false;
3497 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3498 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3499 // If unsafe fp math optimization is enabled and there are no other uses of
3500 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3501 // to an integer comparison.
3502 if (CC == ISD::SETOEQ)
3504 else if (CC == ISD::SETUNE)
3507 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3509 if (LHS.getValueType() == MVT::f32) {
3510 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3511 bitcastf32Toi32(LHS, DAG), Mask);
3512 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3513 bitcastf32Toi32(RHS, DAG), Mask);
3514 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3515 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3516 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3517 Chain, Dest, ARMcc, CCR, Cmp);
3522 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3523 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3524 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3525 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3526 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3527 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3528 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3529 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3530 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3536 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3537 SDValue Chain = Op.getOperand(0);
3538 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3539 SDValue LHS = Op.getOperand(2);
3540 SDValue RHS = Op.getOperand(3);
3541 SDValue Dest = Op.getOperand(4);
3544 if (LHS.getValueType() == MVT::i32) {
3546 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3547 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3548 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3549 Chain, Dest, ARMcc, CCR, Cmp);
3552 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3554 if (getTargetMachine().Options.UnsafeFPMath &&
3555 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3556 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3557 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3558 if (Result.getNode())
3562 ARMCC::CondCodes CondCode, CondCode2;
3563 FPCCToARMCC(CC, CondCode, CondCode2);
3565 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3566 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3567 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3568 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3569 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3570 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3571 if (CondCode2 != ARMCC::AL) {
3572 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3573 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3574 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3579 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3580 SDValue Chain = Op.getOperand(0);
3581 SDValue Table = Op.getOperand(1);
3582 SDValue Index = Op.getOperand(2);
3585 EVT PTy = getPointerTy();
3586 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3587 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3588 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3589 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3590 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3591 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3592 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3593 if (Subtarget->isThumb2()) {
3594 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3595 // which does another jump to the destination. This also makes it easier
3596 // to translate it to TBB / TBH later.
3597 // FIXME: This might not work if the function is extremely large.
3598 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3599 Addr, Op.getOperand(2), JTI, UId);
3601 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3602 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3603 MachinePointerInfo::getJumpTable(),
3604 false, false, false, 0);
3605 Chain = Addr.getValue(1);
3606 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3607 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3609 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3610 MachinePointerInfo::getJumpTable(),
3611 false, false, false, 0);
3612 Chain = Addr.getValue(1);
3613 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3617 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3618 EVT VT = Op.getValueType();
3621 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3622 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3624 return DAG.UnrollVectorOp(Op.getNode());
3627 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3628 "Invalid type for custom lowering!");
3629 if (VT != MVT::v4i16)
3630 return DAG.UnrollVectorOp(Op.getNode());
3632 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3633 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3636 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3637 EVT VT = Op.getValueType();
3639 return LowerVectorFP_TO_INT(Op, DAG);
3644 switch (Op.getOpcode()) {
3645 default: llvm_unreachable("Invalid opcode!");
3646 case ISD::FP_TO_SINT:
3647 Opc = ARMISD::FTOSI;
3649 case ISD::FP_TO_UINT:
3650 Opc = ARMISD::FTOUI;
3653 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3654 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3657 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3658 EVT VT = Op.getValueType();
3661 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3662 if (VT.getVectorElementType() == MVT::f32)
3664 return DAG.UnrollVectorOp(Op.getNode());
3667 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3668 "Invalid type for custom lowering!");
3669 if (VT != MVT::v4f32)
3670 return DAG.UnrollVectorOp(Op.getNode());
3674 switch (Op.getOpcode()) {
3675 default: llvm_unreachable("Invalid opcode!");
3676 case ISD::SINT_TO_FP:
3677 CastOpc = ISD::SIGN_EXTEND;
3678 Opc = ISD::SINT_TO_FP;
3680 case ISD::UINT_TO_FP:
3681 CastOpc = ISD::ZERO_EXTEND;
3682 Opc = ISD::UINT_TO_FP;
3686 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3687 return DAG.getNode(Opc, dl, VT, Op);
3690 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3691 EVT VT = Op.getValueType();
3693 return LowerVectorINT_TO_FP(Op, DAG);
3698 switch (Op.getOpcode()) {
3699 default: llvm_unreachable("Invalid opcode!");
3700 case ISD::SINT_TO_FP:
3701 Opc = ARMISD::SITOF;
3703 case ISD::UINT_TO_FP:
3704 Opc = ARMISD::UITOF;
3708 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3709 return DAG.getNode(Opc, dl, VT, Op);
3712 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3713 // Implement fcopysign with a fabs and a conditional fneg.
3714 SDValue Tmp0 = Op.getOperand(0);
3715 SDValue Tmp1 = Op.getOperand(1);
3717 EVT VT = Op.getValueType();
3718 EVT SrcVT = Tmp1.getValueType();
3719 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3720 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3721 bool UseNEON = !InGPR && Subtarget->hasNEON();
3724 // Use VBSL to copy the sign bit.
3725 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3726 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3727 DAG.getTargetConstant(EncodedVal, MVT::i32));
3728 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3730 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3731 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3732 DAG.getConstant(32, MVT::i32));
3733 else /*if (VT == MVT::f32)*/
3734 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3735 if (SrcVT == MVT::f32) {
3736 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3738 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3739 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3740 DAG.getConstant(32, MVT::i32));
3741 } else if (VT == MVT::f32)
3742 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3743 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3744 DAG.getConstant(32, MVT::i32));
3745 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3746 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3748 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3750 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3751 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3752 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3754 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3755 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3756 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3757 if (VT == MVT::f32) {
3758 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3759 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3760 DAG.getConstant(0, MVT::i32));
3762 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3768 // Bitcast operand 1 to i32.
3769 if (SrcVT == MVT::f64)
3770 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3771 &Tmp1, 1).getValue(1);
3772 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3774 // Or in the signbit with integer operations.
3775 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3776 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3777 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3778 if (VT == MVT::f32) {
3779 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3780 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3781 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3782 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3785 // f64: Or the high part with signbit and then combine two parts.
3786 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3788 SDValue Lo = Tmp0.getValue(0);
3789 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3790 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3791 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3794 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3795 MachineFunction &MF = DAG.getMachineFunction();
3796 MachineFrameInfo *MFI = MF.getFrameInfo();
3797 MFI->setReturnAddressIsTaken(true);
3799 EVT VT = Op.getValueType();
3801 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3803 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3804 SDValue Offset = DAG.getConstant(4, MVT::i32);
3805 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3806 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3807 MachinePointerInfo(), false, false, false, 0);
3810 // Return LR, which contains the return address. Mark it an implicit live-in.
3811 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3812 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3815 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3816 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3817 MFI->setFrameAddressIsTaken(true);
3819 EVT VT = Op.getValueType();
3820 SDLoc dl(Op); // FIXME probably not meaningful
3821 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3822 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3823 ? ARM::R7 : ARM::R11;
3824 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3826 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3827 MachinePointerInfo(),
3828 false, false, false, 0);
3832 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3833 /// and size(DestVec) > 128-bits.
3834 /// This is achieved by doing the one extension from the SrcVec, splitting the
3835 /// result, extending these parts, and then concatenating these into the
3837 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3838 SDValue Op = N->getOperand(0);
3839 EVT SrcVT = Op.getValueType();
3840 EVT DestVT = N->getValueType(0);
3842 assert(DestVT.getSizeInBits() > 128 &&
3843 "Custom sext/zext expansion needs >128-bit vector.");
3844 // If this is a normal length extension, use the default expansion.
3845 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3846 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3850 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3851 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3852 unsigned NumElts = SrcVT.getVectorNumElements();
3853 LLVMContext &Ctx = *DAG.getContext();
3854 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3856 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3858 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3860 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3863 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3864 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3865 DAG.getIntPtrConstant(0));
3866 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3867 DAG.getIntPtrConstant(NumElts/2));
3868 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3869 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3870 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3873 /// ExpandBITCAST - If the target supports VFP, this function is called to
3874 /// expand a bit convert where either the source or destination type is i64 to
3875 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3876 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3877 /// vectors), since the legalizer won't know what to do with that.
3878 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3879 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3881 SDValue Op = N->getOperand(0);
3883 // This function is only supposed to be called for i64 types, either as the
3884 // source or destination of the bit convert.
3885 EVT SrcVT = Op.getValueType();
3886 EVT DstVT = N->getValueType(0);
3887 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3888 "ExpandBITCAST called for non-i64 type");
3890 // Turn i64->f64 into VMOVDRR.
3891 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3892 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3893 DAG.getConstant(0, MVT::i32));
3894 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3895 DAG.getConstant(1, MVT::i32));
3896 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3897 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3900 // Turn f64->i64 into VMOVRRD.
3901 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3902 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3903 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3904 // Merge the pieces into a single i64 value.
3905 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3911 /// getZeroVector - Returns a vector of specified type with all zero elements.
3912 /// Zero vectors are used to represent vector negation and in those cases
3913 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3914 /// not support i64 elements, so sometimes the zero vectors will need to be
3915 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3917 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3918 assert(VT.isVector() && "Expected a vector type");
3919 // The canonical modified immediate encoding of a zero vector is....0!
3920 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3921 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3922 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3923 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3926 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3927 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3928 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3929 SelectionDAG &DAG) const {
3930 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3931 EVT VT = Op.getValueType();
3932 unsigned VTBits = VT.getSizeInBits();
3934 SDValue ShOpLo = Op.getOperand(0);
3935 SDValue ShOpHi = Op.getOperand(1);
3936 SDValue ShAmt = Op.getOperand(2);
3938 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3940 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3942 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3943 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3944 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3945 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3946 DAG.getConstant(VTBits, MVT::i32));
3947 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3948 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3949 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3951 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3952 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3954 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3955 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3958 SDValue Ops[2] = { Lo, Hi };
3959 return DAG.getMergeValues(Ops, 2, dl);
3962 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3963 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3964 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3965 SelectionDAG &DAG) const {
3966 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3967 EVT VT = Op.getValueType();
3968 unsigned VTBits = VT.getSizeInBits();
3970 SDValue ShOpLo = Op.getOperand(0);
3971 SDValue ShOpHi = Op.getOperand(1);
3972 SDValue ShAmt = Op.getOperand(2);
3975 assert(Op.getOpcode() == ISD::SHL_PARTS);
3976 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3977 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3978 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3979 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3980 DAG.getConstant(VTBits, MVT::i32));
3981 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3982 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3984 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3985 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3986 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3988 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3989 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3992 SDValue Ops[2] = { Lo, Hi };
3993 return DAG.getMergeValues(Ops, 2, dl);
3996 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3997 SelectionDAG &DAG) const {
3998 // The rounding mode is in bits 23:22 of the FPSCR.
3999 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4000 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4001 // so that the shift + and get folded into a bitfield extract.
4003 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4004 DAG.getConstant(Intrinsic::arm_get_fpscr,
4006 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4007 DAG.getConstant(1U << 22, MVT::i32));
4008 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4009 DAG.getConstant(22, MVT::i32));
4010 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4011 DAG.getConstant(3, MVT::i32));
4014 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4015 const ARMSubtarget *ST) {
4016 EVT VT = N->getValueType(0);
4019 if (!ST->hasV6T2Ops())
4022 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4023 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4026 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4027 /// for each 16-bit element from operand, repeated. The basic idea is to
4028 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4030 /// Trace for v4i16:
4031 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4032 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4033 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4034 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4035 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4036 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4037 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4038 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4039 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4040 EVT VT = N->getValueType(0);
4043 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4044 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4045 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4046 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4047 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4048 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4051 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4052 /// bit-count for each 16-bit element from the operand. We need slightly
4053 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4054 /// 64/128-bit registers.
4056 /// Trace for v4i16:
4057 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4058 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4059 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4060 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4061 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4062 EVT VT = N->getValueType(0);
4065 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4066 if (VT.is64BitVector()) {
4067 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4068 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4069 DAG.getIntPtrConstant(0));
4071 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4072 BitCounts, DAG.getIntPtrConstant(0));
4073 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4077 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4078 /// bit-count for each 32-bit element from the operand. The idea here is
4079 /// to split the vector into 16-bit elements, leverage the 16-bit count
4080 /// routine, and then combine the results.
4082 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4083 /// input = [v0 v1 ] (vi: 32-bit elements)
4084 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4085 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4086 /// vrev: N0 = [k1 k0 k3 k2 ]
4088 /// N1 =+[k1 k0 k3 k2 ]
4090 /// N2 =+[k1 k3 k0 k2 ]
4092 /// Extended =+[k1 k3 k0 k2 ]
4094 /// Extracted=+[k1 k3 ]
4096 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4097 EVT VT = N->getValueType(0);
4100 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4102 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4103 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4104 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4105 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4106 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4108 if (VT.is64BitVector()) {
4109 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4110 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4111 DAG.getIntPtrConstant(0));
4113 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4114 DAG.getIntPtrConstant(0));
4115 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4119 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4120 const ARMSubtarget *ST) {
4121 EVT VT = N->getValueType(0);
4123 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4124 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4125 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4126 "Unexpected type for custom ctpop lowering");
4128 if (VT.getVectorElementType() == MVT::i32)
4129 return lowerCTPOP32BitElements(N, DAG);
4131 return lowerCTPOP16BitElements(N, DAG);
4134 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4135 const ARMSubtarget *ST) {
4136 EVT VT = N->getValueType(0);
4142 // Lower vector shifts on NEON to use VSHL.
4143 assert(ST->hasNEON() && "unexpected vector shift");
4145 // Left shifts translate directly to the vshiftu intrinsic.
4146 if (N->getOpcode() == ISD::SHL)
4147 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4148 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4149 N->getOperand(0), N->getOperand(1));
4151 assert((N->getOpcode() == ISD::SRA ||
4152 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4154 // NEON uses the same intrinsics for both left and right shifts. For
4155 // right shifts, the shift amounts are negative, so negate the vector of
4157 EVT ShiftVT = N->getOperand(1).getValueType();
4158 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4159 getZeroVector(ShiftVT, DAG, dl),
4161 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4162 Intrinsic::arm_neon_vshifts :
4163 Intrinsic::arm_neon_vshiftu);
4164 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4165 DAG.getConstant(vshiftInt, MVT::i32),
4166 N->getOperand(0), NegatedCount);
4169 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4170 const ARMSubtarget *ST) {
4171 EVT VT = N->getValueType(0);
4174 // We can get here for a node like i32 = ISD::SHL i32, i64
4178 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4179 "Unknown shift to lower!");
4181 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4182 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4183 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4186 // If we are in thumb mode, we don't have RRX.
4187 if (ST->isThumb1Only()) return SDValue();
4189 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4190 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4191 DAG.getConstant(0, MVT::i32));
4192 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4193 DAG.getConstant(1, MVT::i32));
4195 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4196 // captures the result into a carry flag.
4197 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4198 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4200 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4201 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4203 // Merge the pieces into a single i64 value.
4204 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4207 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4208 SDValue TmpOp0, TmpOp1;
4209 bool Invert = false;
4213 SDValue Op0 = Op.getOperand(0);
4214 SDValue Op1 = Op.getOperand(1);
4215 SDValue CC = Op.getOperand(2);
4216 EVT VT = Op.getValueType();
4217 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4220 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4221 switch (SetCCOpcode) {
4222 default: llvm_unreachable("Illegal FP comparison");
4224 case ISD::SETNE: Invert = true; // Fallthrough
4226 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4228 case ISD::SETLT: Swap = true; // Fallthrough
4230 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4232 case ISD::SETLE: Swap = true; // Fallthrough
4234 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4235 case ISD::SETUGE: Swap = true; // Fallthrough
4236 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4237 case ISD::SETUGT: Swap = true; // Fallthrough
4238 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4239 case ISD::SETUEQ: Invert = true; // Fallthrough
4241 // Expand this to (OLT | OGT).
4245 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4246 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4248 case ISD::SETUO: Invert = true; // Fallthrough
4250 // Expand this to (OLT | OGE).
4254 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4255 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4259 // Integer comparisons.
4260 switch (SetCCOpcode) {
4261 default: llvm_unreachable("Illegal integer comparison");
4262 case ISD::SETNE: Invert = true;
4263 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4264 case ISD::SETLT: Swap = true;
4265 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4266 case ISD::SETLE: Swap = true;
4267 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4268 case ISD::SETULT: Swap = true;
4269 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4270 case ISD::SETULE: Swap = true;
4271 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4274 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4275 if (Opc == ARMISD::VCEQ) {
4278 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4280 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4283 // Ignore bitconvert.
4284 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4285 AndOp = AndOp.getOperand(0);
4287 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4289 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4290 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4297 std::swap(Op0, Op1);
4299 // If one of the operands is a constant vector zero, attempt to fold the
4300 // comparison to a specialized compare-against-zero form.
4302 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4304 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4305 if (Opc == ARMISD::VCGE)
4306 Opc = ARMISD::VCLEZ;
4307 else if (Opc == ARMISD::VCGT)
4308 Opc = ARMISD::VCLTZ;
4313 if (SingleOp.getNode()) {
4316 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4318 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4320 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4322 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4324 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4326 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4329 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4333 Result = DAG.getNOT(dl, Result, VT);
4338 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4339 /// valid vector constant for a NEON instruction with a "modified immediate"
4340 /// operand (e.g., VMOV). If so, return the encoded value.
4341 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4342 unsigned SplatBitSize, SelectionDAG &DAG,
4343 EVT &VT, bool is128Bits, NEONModImmType type) {
4344 unsigned OpCmode, Imm;
4346 // SplatBitSize is set to the smallest size that splats the vector, so a
4347 // zero vector will always have SplatBitSize == 8. However, NEON modified
4348 // immediate instructions others than VMOV do not support the 8-bit encoding
4349 // of a zero vector, and the default encoding of zero is supposed to be the
4354 switch (SplatBitSize) {
4356 if (type != VMOVModImm)
4358 // Any 1-byte value is OK. Op=0, Cmode=1110.
4359 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4362 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4366 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4367 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4368 if ((SplatBits & ~0xff) == 0) {
4369 // Value = 0x00nn: Op=x, Cmode=100x.
4374 if ((SplatBits & ~0xff00) == 0) {
4375 // Value = 0xnn00: Op=x, Cmode=101x.
4377 Imm = SplatBits >> 8;
4383 // NEON's 32-bit VMOV supports splat values where:
4384 // * only one byte is nonzero, or
4385 // * the least significant byte is 0xff and the second byte is nonzero, or
4386 // * the least significant 2 bytes are 0xff and the third is nonzero.
4387 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4388 if ((SplatBits & ~0xff) == 0) {
4389 // Value = 0x000000nn: Op=x, Cmode=000x.
4394 if ((SplatBits & ~0xff00) == 0) {
4395 // Value = 0x0000nn00: Op=x, Cmode=001x.
4397 Imm = SplatBits >> 8;
4400 if ((SplatBits & ~0xff0000) == 0) {
4401 // Value = 0x00nn0000: Op=x, Cmode=010x.
4403 Imm = SplatBits >> 16;
4406 if ((SplatBits & ~0xff000000) == 0) {
4407 // Value = 0xnn000000: Op=x, Cmode=011x.
4409 Imm = SplatBits >> 24;
4413 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4414 if (type == OtherModImm) return SDValue();
4416 if ((SplatBits & ~0xffff) == 0 &&
4417 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4418 // Value = 0x0000nnff: Op=x, Cmode=1100.
4420 Imm = SplatBits >> 8;
4425 if ((SplatBits & ~0xffffff) == 0 &&
4426 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4427 // Value = 0x00nnffff: Op=x, Cmode=1101.
4429 Imm = SplatBits >> 16;
4430 SplatBits |= 0xffff;
4434 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4435 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4436 // VMOV.I32. A (very) minor optimization would be to replicate the value
4437 // and fall through here to test for a valid 64-bit splat. But, then the
4438 // caller would also need to check and handle the change in size.
4442 if (type != VMOVModImm)
4444 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4445 uint64_t BitMask = 0xff;
4447 unsigned ImmMask = 1;
4449 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4450 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4453 } else if ((SplatBits & BitMask) != 0) {
4459 // Op=1, Cmode=1110.
4462 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4467 llvm_unreachable("unexpected size for isNEONModifiedImm");
4470 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4471 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4474 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4475 const ARMSubtarget *ST) const {
4479 bool IsDouble = Op.getValueType() == MVT::f64;
4480 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4482 // Try splatting with a VMOV.f32...
4483 APFloat FPVal = CFP->getValueAPF();
4484 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4487 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4488 // We have code in place to select a valid ConstantFP already, no need to
4493 // It's a float and we are trying to use NEON operations where
4494 // possible. Lower it to a splat followed by an extract.
4496 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4497 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4499 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4500 DAG.getConstant(0, MVT::i32));
4503 // The rest of our options are NEON only, make sure that's allowed before
4505 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4509 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4511 // It wouldn't really be worth bothering for doubles except for one very
4512 // important value, which does happen to match: 0.0. So make sure we don't do
4514 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4517 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4518 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4520 if (NewVal != SDValue()) {
4522 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4525 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4527 // It's a float: cast and extract a vector element.
4528 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4530 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4531 DAG.getConstant(0, MVT::i32));
4534 // Finally, try a VMVN.i32
4535 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4537 if (NewVal != SDValue()) {
4539 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4542 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4544 // It's a float: cast and extract a vector element.
4545 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4547 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4548 DAG.getConstant(0, MVT::i32));
4554 // check if an VEXT instruction can handle the shuffle mask when the
4555 // vector sources of the shuffle are the same.
4556 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4557 unsigned NumElts = VT.getVectorNumElements();
4559 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4565 // If this is a VEXT shuffle, the immediate value is the index of the first
4566 // element. The other shuffle indices must be the successive elements after
4568 unsigned ExpectedElt = Imm;
4569 for (unsigned i = 1; i < NumElts; ++i) {
4570 // Increment the expected index. If it wraps around, just follow it
4571 // back to index zero and keep going.
4573 if (ExpectedElt == NumElts)
4576 if (M[i] < 0) continue; // ignore UNDEF indices
4577 if (ExpectedElt != static_cast<unsigned>(M[i]))
4585 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4586 bool &ReverseVEXT, unsigned &Imm) {
4587 unsigned NumElts = VT.getVectorNumElements();
4588 ReverseVEXT = false;
4590 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4596 // If this is a VEXT shuffle, the immediate value is the index of the first
4597 // element. The other shuffle indices must be the successive elements after
4599 unsigned ExpectedElt = Imm;
4600 for (unsigned i = 1; i < NumElts; ++i) {
4601 // Increment the expected index. If it wraps around, it may still be
4602 // a VEXT but the source vectors must be swapped.
4604 if (ExpectedElt == NumElts * 2) {
4609 if (M[i] < 0) continue; // ignore UNDEF indices
4610 if (ExpectedElt != static_cast<unsigned>(M[i]))
4614 // Adjust the index value if the source operands will be swapped.
4621 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4622 /// instruction with the specified blocksize. (The order of the elements
4623 /// within each block of the vector is reversed.)
4624 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4625 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4626 "Only possible block sizes for VREV are: 16, 32, 64");
4628 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4632 unsigned NumElts = VT.getVectorNumElements();
4633 unsigned BlockElts = M[0] + 1;
4634 // If the first shuffle index is UNDEF, be optimistic.
4636 BlockElts = BlockSize / EltSz;
4638 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4641 for (unsigned i = 0; i < NumElts; ++i) {
4642 if (M[i] < 0) continue; // ignore UNDEF indices
4643 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4650 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4651 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4652 // range, then 0 is placed into the resulting vector. So pretty much any mask
4653 // of 8 elements can work here.
4654 return VT == MVT::v8i8 && M.size() == 8;
4657 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4658 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4662 unsigned NumElts = VT.getVectorNumElements();
4663 WhichResult = (M[0] == 0 ? 0 : 1);
4664 for (unsigned i = 0; i < NumElts; i += 2) {
4665 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4666 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4672 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4673 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4674 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4675 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4676 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4680 unsigned NumElts = VT.getVectorNumElements();
4681 WhichResult = (M[0] == 0 ? 0 : 1);
4682 for (unsigned i = 0; i < NumElts; i += 2) {
4683 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4684 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4690 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4691 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4695 unsigned NumElts = VT.getVectorNumElements();
4696 WhichResult = (M[0] == 0 ? 0 : 1);
4697 for (unsigned i = 0; i != NumElts; ++i) {
4698 if (M[i] < 0) continue; // ignore UNDEF indices
4699 if ((unsigned) M[i] != 2 * i + WhichResult)
4703 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4704 if (VT.is64BitVector() && EltSz == 32)
4710 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4711 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4712 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4713 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4714 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4718 unsigned Half = VT.getVectorNumElements() / 2;
4719 WhichResult = (M[0] == 0 ? 0 : 1);
4720 for (unsigned j = 0; j != 2; ++j) {
4721 unsigned Idx = WhichResult;
4722 for (unsigned i = 0; i != Half; ++i) {
4723 int MIdx = M[i + j * Half];
4724 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4730 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4731 if (VT.is64BitVector() && EltSz == 32)
4737 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4738 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4742 unsigned NumElts = VT.getVectorNumElements();
4743 WhichResult = (M[0] == 0 ? 0 : 1);
4744 unsigned Idx = WhichResult * NumElts / 2;
4745 for (unsigned i = 0; i != NumElts; i += 2) {
4746 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4747 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4752 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4753 if (VT.is64BitVector() && EltSz == 32)
4759 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4760 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4761 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4762 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4763 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4767 unsigned NumElts = VT.getVectorNumElements();
4768 WhichResult = (M[0] == 0 ? 0 : 1);
4769 unsigned Idx = WhichResult * NumElts / 2;
4770 for (unsigned i = 0; i != NumElts; i += 2) {
4771 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4772 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4777 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4778 if (VT.is64BitVector() && EltSz == 32)
4784 /// \return true if this is a reverse operation on an vector.
4785 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4786 unsigned NumElts = VT.getVectorNumElements();
4787 // Make sure the mask has the right size.
4788 if (NumElts != M.size())
4791 // Look for <15, ..., 3, -1, 1, 0>.
4792 for (unsigned i = 0; i != NumElts; ++i)
4793 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4799 // If N is an integer constant that can be moved into a register in one
4800 // instruction, return an SDValue of such a constant (will become a MOV
4801 // instruction). Otherwise return null.
4802 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4803 const ARMSubtarget *ST, SDLoc dl) {
4805 if (!isa<ConstantSDNode>(N))
4807 Val = cast<ConstantSDNode>(N)->getZExtValue();
4809 if (ST->isThumb1Only()) {
4810 if (Val <= 255 || ~Val <= 255)
4811 return DAG.getConstant(Val, MVT::i32);
4813 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4814 return DAG.getConstant(Val, MVT::i32);
4819 // If this is a case we can't handle, return null and let the default
4820 // expansion code take care of it.
4821 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4822 const ARMSubtarget *ST) const {
4823 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4825 EVT VT = Op.getValueType();
4827 APInt SplatBits, SplatUndef;
4828 unsigned SplatBitSize;
4830 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4831 if (SplatBitSize <= 64) {
4832 // Check if an immediate VMOV works.
4834 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4835 SplatUndef.getZExtValue(), SplatBitSize,
4836 DAG, VmovVT, VT.is128BitVector(),
4838 if (Val.getNode()) {
4839 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4840 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4843 // Try an immediate VMVN.
4844 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4845 Val = isNEONModifiedImm(NegatedImm,
4846 SplatUndef.getZExtValue(), SplatBitSize,
4847 DAG, VmovVT, VT.is128BitVector(),
4849 if (Val.getNode()) {
4850 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4851 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4854 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4855 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4856 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4858 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4859 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4865 // Scan through the operands to see if only one value is used.
4867 // As an optimisation, even if more than one value is used it may be more
4868 // profitable to splat with one value then change some lanes.
4870 // Heuristically we decide to do this if the vector has a "dominant" value,
4871 // defined as splatted to more than half of the lanes.
4872 unsigned NumElts = VT.getVectorNumElements();
4873 bool isOnlyLowElement = true;
4874 bool usesOnlyOneValue = true;
4875 bool hasDominantValue = false;
4876 bool isConstant = true;
4878 // Map of the number of times a particular SDValue appears in the
4880 DenseMap<SDValue, unsigned> ValueCounts;
4882 for (unsigned i = 0; i < NumElts; ++i) {
4883 SDValue V = Op.getOperand(i);
4884 if (V.getOpcode() == ISD::UNDEF)
4887 isOnlyLowElement = false;
4888 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4891 ValueCounts.insert(std::make_pair(V, 0));
4892 unsigned &Count = ValueCounts[V];
4894 // Is this value dominant? (takes up more than half of the lanes)
4895 if (++Count > (NumElts / 2)) {
4896 hasDominantValue = true;
4900 if (ValueCounts.size() != 1)
4901 usesOnlyOneValue = false;
4902 if (!Value.getNode() && ValueCounts.size() > 0)
4903 Value = ValueCounts.begin()->first;
4905 if (ValueCounts.size() == 0)
4906 return DAG.getUNDEF(VT);
4908 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4909 // Keep going if we are hitting this case.
4910 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4911 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4913 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4915 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4916 // i32 and try again.
4917 if (hasDominantValue && EltSize <= 32) {
4921 // If we are VDUPing a value that comes directly from a vector, that will
4922 // cause an unnecessary move to and from a GPR, where instead we could
4923 // just use VDUPLANE. We can only do this if the lane being extracted
4924 // is at a constant index, as the VDUP from lane instructions only have
4925 // constant-index forms.
4926 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4927 isa<ConstantSDNode>(Value->getOperand(1))) {
4928 // We need to create a new undef vector to use for the VDUPLANE if the
4929 // size of the vector from which we get the value is different than the
4930 // size of the vector that we need to create. We will insert the element
4931 // such that the register coalescer will remove unnecessary copies.
4932 if (VT != Value->getOperand(0).getValueType()) {
4933 ConstantSDNode *constIndex;
4934 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4935 assert(constIndex && "The index is not a constant!");
4936 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4937 VT.getVectorNumElements();
4938 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4939 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4940 Value, DAG.getConstant(index, MVT::i32)),
4941 DAG.getConstant(index, MVT::i32));
4943 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4944 Value->getOperand(0), Value->getOperand(1));
4946 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4948 if (!usesOnlyOneValue) {
4949 // The dominant value was splatted as 'N', but we now have to insert
4950 // all differing elements.
4951 for (unsigned I = 0; I < NumElts; ++I) {
4952 if (Op.getOperand(I) == Value)
4954 SmallVector<SDValue, 3> Ops;
4956 Ops.push_back(Op.getOperand(I));
4957 Ops.push_back(DAG.getConstant(I, MVT::i32));
4958 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4963 if (VT.getVectorElementType().isFloatingPoint()) {
4964 SmallVector<SDValue, 8> Ops;
4965 for (unsigned i = 0; i < NumElts; ++i)
4966 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4968 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4969 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4970 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4972 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4974 if (usesOnlyOneValue) {
4975 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4976 if (isConstant && Val.getNode())
4977 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4981 // If all elements are constants and the case above didn't get hit, fall back
4982 // to the default expansion, which will generate a load from the constant
4987 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4989 SDValue shuffle = ReconstructShuffle(Op, DAG);
4990 if (shuffle != SDValue())
4994 // Vectors with 32- or 64-bit elements can be built by directly assigning
4995 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4996 // will be legalized.
4997 if (EltSize >= 32) {
4998 // Do the expansion with floating-point types, since that is what the VFP
4999 // registers are defined to use, and since i64 is not legal.
5000 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5001 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5002 SmallVector<SDValue, 8> Ops;
5003 for (unsigned i = 0; i < NumElts; ++i)
5004 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5005 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5006 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5009 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5010 // know the default expansion would otherwise fall back on something even
5011 // worse. For a vector with one or two non-undef values, that's
5012 // scalar_to_vector for the elements followed by a shuffle (provided the
5013 // shuffle is valid for the target) and materialization element by element
5014 // on the stack followed by a load for everything else.
5015 if (!isConstant && !usesOnlyOneValue) {
5016 SDValue Vec = DAG.getUNDEF(VT);
5017 for (unsigned i = 0 ; i < NumElts; ++i) {
5018 SDValue V = Op.getOperand(i);
5019 if (V.getOpcode() == ISD::UNDEF)
5021 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5022 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5030 // Gather data to see if the operation can be modelled as a
5031 // shuffle in combination with VEXTs.
5032 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5033 SelectionDAG &DAG) const {
5035 EVT VT = Op.getValueType();
5036 unsigned NumElts = VT.getVectorNumElements();
5038 SmallVector<SDValue, 2> SourceVecs;
5039 SmallVector<unsigned, 2> MinElts;
5040 SmallVector<unsigned, 2> MaxElts;
5042 for (unsigned i = 0; i < NumElts; ++i) {
5043 SDValue V = Op.getOperand(i);
5044 if (V.getOpcode() == ISD::UNDEF)
5046 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5047 // A shuffle can only come from building a vector from various
5048 // elements of other vectors.
5050 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5051 VT.getVectorElementType()) {
5052 // This code doesn't know how to handle shuffles where the vector
5053 // element types do not match (this happens because type legalization
5054 // promotes the return type of EXTRACT_VECTOR_ELT).
5055 // FIXME: It might be appropriate to extend this code to handle
5056 // mismatched types.
5060 // Record this extraction against the appropriate vector if possible...
5061 SDValue SourceVec = V.getOperand(0);
5062 // If the element number isn't a constant, we can't effectively
5063 // analyze what's going on.
5064 if (!isa<ConstantSDNode>(V.getOperand(1)))
5066 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5067 bool FoundSource = false;
5068 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5069 if (SourceVecs[j] == SourceVec) {
5070 if (MinElts[j] > EltNo)
5072 if (MaxElts[j] < EltNo)
5079 // Or record a new source if not...
5081 SourceVecs.push_back(SourceVec);
5082 MinElts.push_back(EltNo);
5083 MaxElts.push_back(EltNo);
5087 // Currently only do something sane when at most two source vectors
5089 if (SourceVecs.size() > 2)
5092 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5093 int VEXTOffsets[2] = {0, 0};
5095 // This loop extracts the usage patterns of the source vectors
5096 // and prepares appropriate SDValues for a shuffle if possible.
5097 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5098 if (SourceVecs[i].getValueType() == VT) {
5099 // No VEXT necessary
5100 ShuffleSrcs[i] = SourceVecs[i];
5103 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5104 // It probably isn't worth padding out a smaller vector just to
5105 // break it down again in a shuffle.
5109 // Since only 64-bit and 128-bit vectors are legal on ARM and
5110 // we've eliminated the other cases...
5111 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5112 "unexpected vector sizes in ReconstructShuffle");
5114 if (MaxElts[i] - MinElts[i] >= NumElts) {
5115 // Span too large for a VEXT to cope
5119 if (MinElts[i] >= NumElts) {
5120 // The extraction can just take the second half
5121 VEXTOffsets[i] = NumElts;
5122 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5124 DAG.getIntPtrConstant(NumElts));
5125 } else if (MaxElts[i] < NumElts) {
5126 // The extraction can just take the first half
5128 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5130 DAG.getIntPtrConstant(0));
5132 // An actual VEXT is needed
5133 VEXTOffsets[i] = MinElts[i];
5134 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5136 DAG.getIntPtrConstant(0));
5137 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5139 DAG.getIntPtrConstant(NumElts));
5140 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5141 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5145 SmallVector<int, 8> Mask;
5147 for (unsigned i = 0; i < NumElts; ++i) {
5148 SDValue Entry = Op.getOperand(i);
5149 if (Entry.getOpcode() == ISD::UNDEF) {
5154 SDValue ExtractVec = Entry.getOperand(0);
5155 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5156 .getOperand(1))->getSExtValue();
5157 if (ExtractVec == SourceVecs[0]) {
5158 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5160 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5164 // Final check before we try to produce nonsense...
5165 if (isShuffleMaskLegal(Mask, VT))
5166 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5172 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5173 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5174 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5175 /// are assumed to be legal.
5177 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5179 if (VT.getVectorNumElements() == 4 &&
5180 (VT.is128BitVector() || VT.is64BitVector())) {
5181 unsigned PFIndexes[4];
5182 for (unsigned i = 0; i != 4; ++i) {
5186 PFIndexes[i] = M[i];
5189 // Compute the index in the perfect shuffle table.
5190 unsigned PFTableIndex =
5191 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5192 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5193 unsigned Cost = (PFEntry >> 30);
5200 unsigned Imm, WhichResult;
5202 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5203 return (EltSize >= 32 ||
5204 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5205 isVREVMask(M, VT, 64) ||
5206 isVREVMask(M, VT, 32) ||
5207 isVREVMask(M, VT, 16) ||
5208 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5209 isVTBLMask(M, VT) ||
5210 isVTRNMask(M, VT, WhichResult) ||
5211 isVUZPMask(M, VT, WhichResult) ||
5212 isVZIPMask(M, VT, WhichResult) ||
5213 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5214 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5215 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5216 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5219 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5220 /// the specified operations to build the shuffle.
5221 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5222 SDValue RHS, SelectionDAG &DAG,
5224 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5225 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5226 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5229 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5238 OP_VUZPL, // VUZP, left result
5239 OP_VUZPR, // VUZP, right result
5240 OP_VZIPL, // VZIP, left result
5241 OP_VZIPR, // VZIP, right result
5242 OP_VTRNL, // VTRN, left result
5243 OP_VTRNR // VTRN, right result
5246 if (OpNum == OP_COPY) {
5247 if (LHSID == (1*9+2)*9+3) return LHS;
5248 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5252 SDValue OpLHS, OpRHS;
5253 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5254 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5255 EVT VT = OpLHS.getValueType();
5258 default: llvm_unreachable("Unknown shuffle opcode!");
5260 // VREV divides the vector in half and swaps within the half.
5261 if (VT.getVectorElementType() == MVT::i32 ||
5262 VT.getVectorElementType() == MVT::f32)
5263 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5264 // vrev <4 x i16> -> VREV32
5265 if (VT.getVectorElementType() == MVT::i16)
5266 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5267 // vrev <4 x i8> -> VREV16
5268 assert(VT.getVectorElementType() == MVT::i8);
5269 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5274 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5275 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5279 return DAG.getNode(ARMISD::VEXT, dl, VT,
5281 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5284 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5285 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5288 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5289 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5292 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5293 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5297 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5298 ArrayRef<int> ShuffleMask,
5299 SelectionDAG &DAG) {
5300 // Check to see if we can use the VTBL instruction.
5301 SDValue V1 = Op.getOperand(0);
5302 SDValue V2 = Op.getOperand(1);
5305 SmallVector<SDValue, 8> VTBLMask;
5306 for (ArrayRef<int>::iterator
5307 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5308 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5310 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5311 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5312 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5315 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5316 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5320 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5321 SelectionDAG &DAG) {
5323 SDValue OpLHS = Op.getOperand(0);
5324 EVT VT = OpLHS.getValueType();
5326 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5327 "Expect an v8i16/v16i8 type");
5328 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5329 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5330 // extract the first 8 bytes into the top double word and the last 8 bytes
5331 // into the bottom double word. The v8i16 case is similar.
5332 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5333 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5334 DAG.getConstant(ExtractNum, MVT::i32));
5337 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5338 SDValue V1 = Op.getOperand(0);
5339 SDValue V2 = Op.getOperand(1);
5341 EVT VT = Op.getValueType();
5342 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5344 // Convert shuffles that are directly supported on NEON to target-specific
5345 // DAG nodes, instead of keeping them as shuffles and matching them again
5346 // during code selection. This is more efficient and avoids the possibility
5347 // of inconsistencies between legalization and selection.
5348 // FIXME: floating-point vectors should be canonicalized to integer vectors
5349 // of the same time so that they get CSEd properly.
5350 ArrayRef<int> ShuffleMask = SVN->getMask();
5352 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5353 if (EltSize <= 32) {
5354 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5355 int Lane = SVN->getSplatIndex();
5356 // If this is undef splat, generate it via "just" vdup, if possible.
5357 if (Lane == -1) Lane = 0;
5359 // Test if V1 is a SCALAR_TO_VECTOR.
5360 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5361 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5363 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5364 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5366 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5367 !isa<ConstantSDNode>(V1.getOperand(0))) {
5368 bool IsScalarToVector = true;
5369 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5370 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5371 IsScalarToVector = false;
5374 if (IsScalarToVector)
5375 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5377 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5378 DAG.getConstant(Lane, MVT::i32));
5383 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5386 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5387 DAG.getConstant(Imm, MVT::i32));
5390 if (isVREVMask(ShuffleMask, VT, 64))
5391 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5392 if (isVREVMask(ShuffleMask, VT, 32))
5393 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5394 if (isVREVMask(ShuffleMask, VT, 16))
5395 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5397 if (V2->getOpcode() == ISD::UNDEF &&
5398 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5399 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5400 DAG.getConstant(Imm, MVT::i32));
5403 // Check for Neon shuffles that modify both input vectors in place.
5404 // If both results are used, i.e., if there are two shuffles with the same
5405 // source operands and with masks corresponding to both results of one of
5406 // these operations, DAG memoization will ensure that a single node is
5407 // used for both shuffles.
5408 unsigned WhichResult;
5409 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5410 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5411 V1, V2).getValue(WhichResult);
5412 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5413 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5414 V1, V2).getValue(WhichResult);
5415 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5416 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5417 V1, V2).getValue(WhichResult);
5419 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5420 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5421 V1, V1).getValue(WhichResult);
5422 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5423 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5424 V1, V1).getValue(WhichResult);
5425 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5426 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5427 V1, V1).getValue(WhichResult);
5430 // If the shuffle is not directly supported and it has 4 elements, use
5431 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5432 unsigned NumElts = VT.getVectorNumElements();
5434 unsigned PFIndexes[4];
5435 for (unsigned i = 0; i != 4; ++i) {
5436 if (ShuffleMask[i] < 0)
5439 PFIndexes[i] = ShuffleMask[i];
5442 // Compute the index in the perfect shuffle table.
5443 unsigned PFTableIndex =
5444 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5445 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5446 unsigned Cost = (PFEntry >> 30);
5449 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5452 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5453 if (EltSize >= 32) {
5454 // Do the expansion with floating-point types, since that is what the VFP
5455 // registers are defined to use, and since i64 is not legal.
5456 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5457 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5458 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5459 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5460 SmallVector<SDValue, 8> Ops;
5461 for (unsigned i = 0; i < NumElts; ++i) {
5462 if (ShuffleMask[i] < 0)
5463 Ops.push_back(DAG.getUNDEF(EltVT));
5465 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5466 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5467 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5470 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5471 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5474 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5475 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5477 if (VT == MVT::v8i8) {
5478 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5479 if (NewOp.getNode())
5486 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5487 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5488 SDValue Lane = Op.getOperand(2);
5489 if (!isa<ConstantSDNode>(Lane))
5495 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5496 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5497 SDValue Lane = Op.getOperand(1);
5498 if (!isa<ConstantSDNode>(Lane))
5501 SDValue Vec = Op.getOperand(0);
5502 if (Op.getValueType() == MVT::i32 &&
5503 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5505 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5511 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5512 // The only time a CONCAT_VECTORS operation can have legal types is when
5513 // two 64-bit vectors are concatenated to a 128-bit vector.
5514 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5515 "unexpected CONCAT_VECTORS");
5517 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5518 SDValue Op0 = Op.getOperand(0);
5519 SDValue Op1 = Op.getOperand(1);
5520 if (Op0.getOpcode() != ISD::UNDEF)
5521 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5522 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5523 DAG.getIntPtrConstant(0));
5524 if (Op1.getOpcode() != ISD::UNDEF)
5525 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5526 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5527 DAG.getIntPtrConstant(1));
5528 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5531 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5532 /// element has been zero/sign-extended, depending on the isSigned parameter,
5533 /// from an integer type half its size.
5534 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5536 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5537 EVT VT = N->getValueType(0);
5538 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5539 SDNode *BVN = N->getOperand(0).getNode();
5540 if (BVN->getValueType(0) != MVT::v4i32 ||
5541 BVN->getOpcode() != ISD::BUILD_VECTOR)
5543 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5544 unsigned HiElt = 1 - LoElt;
5545 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5546 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5547 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5548 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5549 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5552 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5553 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5556 if (Hi0->isNullValue() && Hi1->isNullValue())
5562 if (N->getOpcode() != ISD::BUILD_VECTOR)
5565 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5566 SDNode *Elt = N->getOperand(i).getNode();
5567 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5568 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5569 unsigned HalfSize = EltSize / 2;
5571 if (!isIntN(HalfSize, C->getSExtValue()))
5574 if (!isUIntN(HalfSize, C->getZExtValue()))
5585 /// isSignExtended - Check if a node is a vector value that is sign-extended
5586 /// or a constant BUILD_VECTOR with sign-extended elements.
5587 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5588 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5590 if (isExtendedBUILD_VECTOR(N, DAG, true))
5595 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5596 /// or a constant BUILD_VECTOR with zero-extended elements.
5597 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5598 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5600 if (isExtendedBUILD_VECTOR(N, DAG, false))
5605 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5606 if (OrigVT.getSizeInBits() >= 64)
5609 assert(OrigVT.isSimple() && "Expecting a simple value type");
5611 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5612 switch (OrigSimpleTy) {
5613 default: llvm_unreachable("Unexpected Vector Type");
5622 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5623 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5624 /// We insert the required extension here to get the vector to fill a D register.
5625 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5628 unsigned ExtOpcode) {
5629 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5630 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5631 // 64-bits we need to insert a new extension so that it will be 64-bits.
5632 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5633 if (OrigTy.getSizeInBits() >= 64)
5636 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5637 EVT NewVT = getExtensionTo64Bits(OrigTy);
5639 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5642 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5643 /// does not do any sign/zero extension. If the original vector is less
5644 /// than 64 bits, an appropriate extension will be added after the load to
5645 /// reach a total size of 64 bits. We have to add the extension separately
5646 /// because ARM does not have a sign/zero extending load for vectors.
5647 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5648 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5650 // The load already has the right type.
5651 if (ExtendedTy == LD->getMemoryVT())
5652 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5653 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5654 LD->isNonTemporal(), LD->isInvariant(),
5655 LD->getAlignment());
5657 // We need to create a zextload/sextload. We cannot just create a load
5658 // followed by a zext/zext node because LowerMUL is also run during normal
5659 // operation legalization where we can't create illegal types.
5660 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5661 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5662 LD->getMemoryVT(), LD->isVolatile(),
5663 LD->isNonTemporal(), LD->getAlignment());
5666 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5667 /// extending load, or BUILD_VECTOR with extended elements, return the
5668 /// unextended value. The unextended vector should be 64 bits so that it can
5669 /// be used as an operand to a VMULL instruction. If the original vector size
5670 /// before extension is less than 64 bits we add a an extension to resize
5671 /// the vector to 64 bits.
5672 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5673 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5674 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5675 N->getOperand(0)->getValueType(0),
5679 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5680 return SkipLoadExtensionForVMULL(LD, DAG);
5682 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5683 // have been legalized as a BITCAST from v4i32.
5684 if (N->getOpcode() == ISD::BITCAST) {
5685 SDNode *BVN = N->getOperand(0).getNode();
5686 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5687 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5688 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5689 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5690 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5692 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5693 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5694 EVT VT = N->getValueType(0);
5695 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5696 unsigned NumElts = VT.getVectorNumElements();
5697 MVT TruncVT = MVT::getIntegerVT(EltSize);
5698 SmallVector<SDValue, 8> Ops;
5699 for (unsigned i = 0; i != NumElts; ++i) {
5700 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5701 const APInt &CInt = C->getAPIntValue();
5702 // Element types smaller than 32 bits are not legal, so use i32 elements.
5703 // The values are implicitly truncated so sext vs. zext doesn't matter.
5704 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5706 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5707 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5710 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5711 unsigned Opcode = N->getOpcode();
5712 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5713 SDNode *N0 = N->getOperand(0).getNode();
5714 SDNode *N1 = N->getOperand(1).getNode();
5715 return N0->hasOneUse() && N1->hasOneUse() &&
5716 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5721 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5722 unsigned Opcode = N->getOpcode();
5723 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5724 SDNode *N0 = N->getOperand(0).getNode();
5725 SDNode *N1 = N->getOperand(1).getNode();
5726 return N0->hasOneUse() && N1->hasOneUse() &&
5727 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5732 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5733 // Multiplications are only custom-lowered for 128-bit vectors so that
5734 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5735 EVT VT = Op.getValueType();
5736 assert(VT.is128BitVector() && VT.isInteger() &&
5737 "unexpected type for custom-lowering ISD::MUL");
5738 SDNode *N0 = Op.getOperand(0).getNode();
5739 SDNode *N1 = Op.getOperand(1).getNode();
5740 unsigned NewOpc = 0;
5742 bool isN0SExt = isSignExtended(N0, DAG);
5743 bool isN1SExt = isSignExtended(N1, DAG);
5744 if (isN0SExt && isN1SExt)
5745 NewOpc = ARMISD::VMULLs;
5747 bool isN0ZExt = isZeroExtended(N0, DAG);
5748 bool isN1ZExt = isZeroExtended(N1, DAG);
5749 if (isN0ZExt && isN1ZExt)
5750 NewOpc = ARMISD::VMULLu;
5751 else if (isN1SExt || isN1ZExt) {
5752 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5753 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5754 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5755 NewOpc = ARMISD::VMULLs;
5757 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5758 NewOpc = ARMISD::VMULLu;
5760 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5762 NewOpc = ARMISD::VMULLu;
5768 if (VT == MVT::v2i64)
5769 // Fall through to expand this. It is not legal.
5772 // Other vector multiplications are legal.
5777 // Legalize to a VMULL instruction.
5780 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5782 Op0 = SkipExtensionForVMULL(N0, DAG);
5783 assert(Op0.getValueType().is64BitVector() &&
5784 Op1.getValueType().is64BitVector() &&
5785 "unexpected types for extended operands to VMULL");
5786 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5789 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5790 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5797 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5798 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5799 EVT Op1VT = Op1.getValueType();
5800 return DAG.getNode(N0->getOpcode(), DL, VT,
5801 DAG.getNode(NewOpc, DL, VT,
5802 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5803 DAG.getNode(NewOpc, DL, VT,
5804 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5808 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5810 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5811 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5812 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5813 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5814 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5815 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5816 // Get reciprocal estimate.
5817 // float4 recip = vrecpeq_f32(yf);
5818 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5819 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5820 // Because char has a smaller range than uchar, we can actually get away
5821 // without any newton steps. This requires that we use a weird bias
5822 // of 0xb000, however (again, this has been exhaustively tested).
5823 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5824 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5825 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5826 Y = DAG.getConstant(0xb000, MVT::i32);
5827 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5828 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5829 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5830 // Convert back to short.
5831 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5832 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5837 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5839 // Convert to float.
5840 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5841 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5842 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5843 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5844 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5845 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5847 // Use reciprocal estimate and one refinement step.
5848 // float4 recip = vrecpeq_f32(yf);
5849 // recip *= vrecpsq_f32(yf, recip);
5850 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5851 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5852 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5853 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5855 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5856 // Because short has a smaller range than ushort, we can actually get away
5857 // with only a single newton step. This requires that we use a weird bias
5858 // of 89, however (again, this has been exhaustively tested).
5859 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5860 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5861 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5862 N1 = DAG.getConstant(0x89, MVT::i32);
5863 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5864 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5865 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5866 // Convert back to integer and return.
5867 // return vmovn_s32(vcvt_s32_f32(result));
5868 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5869 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5873 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5874 EVT VT = Op.getValueType();
5875 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5876 "unexpected type for custom-lowering ISD::SDIV");
5879 SDValue N0 = Op.getOperand(0);
5880 SDValue N1 = Op.getOperand(1);
5883 if (VT == MVT::v8i8) {
5884 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5885 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5887 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5888 DAG.getIntPtrConstant(4));
5889 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5890 DAG.getIntPtrConstant(4));
5891 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5892 DAG.getIntPtrConstant(0));
5893 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5894 DAG.getIntPtrConstant(0));
5896 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5897 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5899 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5900 N0 = LowerCONCAT_VECTORS(N0, DAG);
5902 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5905 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5908 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5909 EVT VT = Op.getValueType();
5910 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5911 "unexpected type for custom-lowering ISD::UDIV");
5914 SDValue N0 = Op.getOperand(0);
5915 SDValue N1 = Op.getOperand(1);
5918 if (VT == MVT::v8i8) {
5919 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5920 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5922 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5923 DAG.getIntPtrConstant(4));
5924 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5925 DAG.getIntPtrConstant(4));
5926 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5927 DAG.getIntPtrConstant(0));
5928 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5929 DAG.getIntPtrConstant(0));
5931 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5932 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5934 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5935 N0 = LowerCONCAT_VECTORS(N0, DAG);
5937 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5938 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5943 // v4i16 sdiv ... Convert to float.
5944 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5945 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5946 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5947 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5948 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5949 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5951 // Use reciprocal estimate and two refinement steps.
5952 // float4 recip = vrecpeq_f32(yf);
5953 // recip *= vrecpsq_f32(yf, recip);
5954 // recip *= vrecpsq_f32(yf, recip);
5955 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5956 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5957 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5958 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5960 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5961 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5962 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5964 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5965 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5966 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5967 // and that it will never cause us to return an answer too large).
5968 // float4 result = as_float4(as_int4(xf*recip) + 2);
5969 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5970 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5971 N1 = DAG.getConstant(2, MVT::i32);
5972 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5973 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5974 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5975 // Convert back to integer and return.
5976 // return vmovn_u32(vcvt_s32_f32(result));
5977 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5978 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5982 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5983 EVT VT = Op.getNode()->getValueType(0);
5984 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5987 bool ExtraOp = false;
5988 switch (Op.getOpcode()) {
5989 default: llvm_unreachable("Invalid code");
5990 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5991 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5992 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5993 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5997 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5999 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6000 Op.getOperand(1), Op.getOperand(2));
6003 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6004 // Monotonic load/store is legal for all targets
6005 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6008 // Aquire/Release load/store is not legal for targets without a
6009 // dmb or equivalent available.
6014 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6015 SelectionDAG &DAG) {
6017 assert (Node->getValueType(0) == MVT::i64 &&
6018 "Only know how to expand i64 atomics");
6019 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6021 SmallVector<SDValue, 6> Ops;
6022 Ops.push_back(Node->getOperand(0)); // Chain
6023 Ops.push_back(Node->getOperand(1)); // Ptr
6024 for(unsigned i=2; i<Node->getNumOperands(); i++) {
6026 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6027 Node->getOperand(i), DAG.getIntPtrConstant(0)));
6029 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6030 Node->getOperand(i), DAG.getIntPtrConstant(1)));
6032 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6034 DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6035 cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6036 AN->getSynchScope());
6037 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6038 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6039 Results.push_back(Result.getValue(2));
6042 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6043 SmallVectorImpl<SDValue> &Results,
6045 const ARMSubtarget *Subtarget) {
6047 SDValue Cycles32, OutChain;
6049 if (Subtarget->hasPerfMon()) {
6050 // Under Power Management extensions, the cycle-count is:
6051 // mrc p15, #0, <Rt>, c9, c13, #0
6052 SDValue Ops[] = { N->getOperand(0), // Chain
6053 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6054 DAG.getConstant(15, MVT::i32),
6055 DAG.getConstant(0, MVT::i32),
6056 DAG.getConstant(9, MVT::i32),
6057 DAG.getConstant(13, MVT::i32),
6058 DAG.getConstant(0, MVT::i32)
6061 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6062 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6063 array_lengthof(Ops));
6064 OutChain = Cycles32.getValue(1);
6066 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6067 // there are older ARM CPUs that have implementation-specific ways of
6068 // obtaining this information (FIXME!).
6069 Cycles32 = DAG.getConstant(0, MVT::i32);
6070 OutChain = DAG.getEntryNode();
6074 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6075 Cycles32, DAG.getConstant(0, MVT::i32));
6076 Results.push_back(Cycles64);
6077 Results.push_back(OutChain);
6080 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6081 switch (Op.getOpcode()) {
6082 default: llvm_unreachable("Don't know how to custom lower this!");
6083 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6084 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6085 case ISD::GlobalAddress:
6086 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6087 LowerGlobalAddressELF(Op, DAG);
6088 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6089 case ISD::SELECT: return LowerSELECT(Op, DAG);
6090 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6091 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6092 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6093 case ISD::VASTART: return LowerVASTART(Op, DAG);
6094 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6095 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6096 case ISD::SINT_TO_FP:
6097 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6098 case ISD::FP_TO_SINT:
6099 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6100 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6101 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6102 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6103 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6104 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6105 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6106 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6108 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6111 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6112 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6113 case ISD::SRL_PARTS:
6114 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6115 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6116 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6117 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6118 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6119 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6120 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6121 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6122 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6123 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6124 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6125 case ISD::MUL: return LowerMUL(Op, DAG);
6126 case ISD::SDIV: return LowerSDIV(Op, DAG);
6127 case ISD::UDIV: return LowerUDIV(Op, DAG);
6131 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6132 case ISD::ATOMIC_LOAD:
6133 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6135 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6139 /// ReplaceNodeResults - Replace the results of node with an illegal result
6140 /// type with new values built out of custom code.
6141 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6142 SmallVectorImpl<SDValue>&Results,
6143 SelectionDAG &DAG) const {
6145 switch (N->getOpcode()) {
6147 llvm_unreachable("Don't know how to custom expand this!");
6149 Res = ExpandBITCAST(N, DAG);
6151 case ISD::SIGN_EXTEND:
6152 case ISD::ZERO_EXTEND:
6153 Res = ExpandVectorExtension(N, DAG);
6157 Res = Expand64BitShift(N, DAG, Subtarget);
6159 case ISD::READCYCLECOUNTER:
6160 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6162 case ISD::ATOMIC_STORE:
6163 case ISD::ATOMIC_LOAD:
6164 case ISD::ATOMIC_LOAD_ADD:
6165 case ISD::ATOMIC_LOAD_AND:
6166 case ISD::ATOMIC_LOAD_NAND:
6167 case ISD::ATOMIC_LOAD_OR:
6168 case ISD::ATOMIC_LOAD_SUB:
6169 case ISD::ATOMIC_LOAD_XOR:
6170 case ISD::ATOMIC_SWAP:
6171 case ISD::ATOMIC_CMP_SWAP:
6172 case ISD::ATOMIC_LOAD_MIN:
6173 case ISD::ATOMIC_LOAD_UMIN:
6174 case ISD::ATOMIC_LOAD_MAX:
6175 case ISD::ATOMIC_LOAD_UMAX:
6176 ReplaceATOMIC_OP_64(N, Results, DAG);
6180 Results.push_back(Res);
6183 //===----------------------------------------------------------------------===//
6184 // ARM Scheduler Hooks
6185 //===----------------------------------------------------------------------===//
6188 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6189 MachineBasicBlock *BB,
6190 unsigned Size) const {
6191 unsigned dest = MI->getOperand(0).getReg();
6192 unsigned ptr = MI->getOperand(1).getReg();
6193 unsigned oldval = MI->getOperand(2).getReg();
6194 unsigned newval = MI->getOperand(3).getReg();
6195 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6196 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6197 DebugLoc dl = MI->getDebugLoc();
6198 bool isThumb2 = Subtarget->isThumb2();
6200 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6201 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6202 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6203 (const TargetRegisterClass*)&ARM::GPRRegClass);
6206 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6207 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6208 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6211 unsigned ldrOpc, strOpc;
6212 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6214 MachineFunction *MF = BB->getParent();
6215 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6216 MachineFunction::iterator It = BB;
6217 ++It; // insert the new blocks after the current block
6219 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6220 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6221 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6222 MF->insert(It, loop1MBB);
6223 MF->insert(It, loop2MBB);
6224 MF->insert(It, exitMBB);
6226 // Transfer the remainder of BB and its successor edges to exitMBB.
6227 exitMBB->splice(exitMBB->begin(), BB,
6228 llvm::next(MachineBasicBlock::iterator(MI)),
6230 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6234 // fallthrough --> loop1MBB
6235 BB->addSuccessor(loop1MBB);
6238 // ldrex dest, [ptr]
6242 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6243 if (ldrOpc == ARM::t2LDREX)
6245 AddDefaultPred(MIB);
6246 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6247 .addReg(dest).addReg(oldval));
6248 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6249 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6250 BB->addSuccessor(loop2MBB);
6251 BB->addSuccessor(exitMBB);
6254 // strex scratch, newval, [ptr]
6258 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6259 if (strOpc == ARM::t2STREX)
6261 AddDefaultPred(MIB);
6262 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6263 .addReg(scratch).addImm(0));
6264 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6265 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6266 BB->addSuccessor(loop1MBB);
6267 BB->addSuccessor(exitMBB);
6273 MI->eraseFromParent(); // The instruction is gone now.
6279 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6280 unsigned Size, unsigned BinOpcode) const {
6281 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6282 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6284 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6285 MachineFunction *MF = BB->getParent();
6286 MachineFunction::iterator It = BB;
6289 unsigned dest = MI->getOperand(0).getReg();
6290 unsigned ptr = MI->getOperand(1).getReg();
6291 unsigned incr = MI->getOperand(2).getReg();
6292 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6293 DebugLoc dl = MI->getDebugLoc();
6294 bool isThumb2 = Subtarget->isThumb2();
6296 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6298 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6299 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6300 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6303 unsigned ldrOpc, strOpc;
6304 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6306 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6307 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6308 MF->insert(It, loopMBB);
6309 MF->insert(It, exitMBB);
6311 // Transfer the remainder of BB and its successor edges to exitMBB.
6312 exitMBB->splice(exitMBB->begin(), BB,
6313 llvm::next(MachineBasicBlock::iterator(MI)),
6315 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6317 const TargetRegisterClass *TRC = isThumb2 ?
6318 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6319 (const TargetRegisterClass*)&ARM::GPRRegClass;
6320 unsigned scratch = MRI.createVirtualRegister(TRC);
6321 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6325 // fallthrough --> loopMBB
6326 BB->addSuccessor(loopMBB);
6330 // <binop> scratch2, dest, incr
6331 // strex scratch, scratch2, ptr
6334 // fallthrough --> exitMBB
6336 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6337 if (ldrOpc == ARM::t2LDREX)
6339 AddDefaultPred(MIB);
6341 // operand order needs to go the other way for NAND
6342 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6343 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6344 addReg(incr).addReg(dest)).addReg(0);
6346 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6347 addReg(dest).addReg(incr)).addReg(0);
6350 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6351 if (strOpc == ARM::t2STREX)
6353 AddDefaultPred(MIB);
6354 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6355 .addReg(scratch).addImm(0));
6356 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6357 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6359 BB->addSuccessor(loopMBB);
6360 BB->addSuccessor(exitMBB);
6366 MI->eraseFromParent(); // The instruction is gone now.
6372 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6373 MachineBasicBlock *BB,
6376 ARMCC::CondCodes Cond) const {
6377 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6379 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6380 MachineFunction *MF = BB->getParent();
6381 MachineFunction::iterator It = BB;
6384 unsigned dest = MI->getOperand(0).getReg();
6385 unsigned ptr = MI->getOperand(1).getReg();
6386 unsigned incr = MI->getOperand(2).getReg();
6387 unsigned oldval = dest;
6388 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6389 DebugLoc dl = MI->getDebugLoc();
6390 bool isThumb2 = Subtarget->isThumb2();
6392 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6394 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6395 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6396 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6399 unsigned ldrOpc, strOpc, extendOpc;
6400 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6402 default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6404 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6407 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6414 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6415 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6416 MF->insert(It, loopMBB);
6417 MF->insert(It, exitMBB);
6419 // Transfer the remainder of BB and its successor edges to exitMBB.
6420 exitMBB->splice(exitMBB->begin(), BB,
6421 llvm::next(MachineBasicBlock::iterator(MI)),
6423 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6425 const TargetRegisterClass *TRC = isThumb2 ?
6426 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6427 (const TargetRegisterClass*)&ARM::GPRRegClass;
6428 unsigned scratch = MRI.createVirtualRegister(TRC);
6429 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6433 // fallthrough --> loopMBB
6434 BB->addSuccessor(loopMBB);
6438 // (sign extend dest, if required)
6440 // cmov.cond scratch2, incr, dest
6441 // strex scratch, scratch2, ptr
6444 // fallthrough --> exitMBB
6446 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6447 if (ldrOpc == ARM::t2LDREX)
6449 AddDefaultPred(MIB);
6451 // Sign extend the value, if necessary.
6452 if (signExtend && extendOpc) {
6453 oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6454 : &ARM::GPRnopcRegClass);
6456 MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6457 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6462 // Build compare and cmov instructions.
6463 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6464 .addReg(oldval).addReg(incr));
6465 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6466 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6468 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6469 if (strOpc == ARM::t2STREX)
6471 AddDefaultPred(MIB);
6472 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6473 .addReg(scratch).addImm(0));
6474 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6475 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6477 BB->addSuccessor(loopMBB);
6478 BB->addSuccessor(exitMBB);
6484 MI->eraseFromParent(); // The instruction is gone now.
6490 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6491 unsigned Op1, unsigned Op2,
6492 bool NeedsCarry, bool IsCmpxchg,
6493 bool IsMinMax, ARMCC::CondCodes CC) const {
6494 // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6495 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6497 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6498 MachineFunction *MF = BB->getParent();
6499 MachineFunction::iterator It = BB;
6502 bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6503 unsigned offset = (isStore ? -2 : 0);
6504 unsigned destlo = MI->getOperand(0).getReg();
6505 unsigned desthi = MI->getOperand(1).getReg();
6506 unsigned ptr = MI->getOperand(offset+2).getReg();
6507 unsigned vallo = MI->getOperand(offset+3).getReg();
6508 unsigned valhi = MI->getOperand(offset+4).getReg();
6509 unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6510 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6511 DebugLoc dl = MI->getDebugLoc();
6512 bool isThumb2 = Subtarget->isThumb2();
6514 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6516 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6517 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6518 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6519 MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6520 MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6523 unsigned ldrOpc, strOpc;
6524 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6526 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6527 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6528 if (IsCmpxchg || IsMinMax)
6529 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6531 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6532 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6534 MF->insert(It, loopMBB);
6535 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6536 if (IsCmpxchg) MF->insert(It, cont2BB);
6537 MF->insert(It, exitMBB);
6539 // Transfer the remainder of BB and its successor edges to exitMBB.
6540 exitMBB->splice(exitMBB->begin(), BB,
6541 llvm::next(MachineBasicBlock::iterator(MI)),
6543 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6545 const TargetRegisterClass *TRC = isThumb2 ?
6546 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6547 (const TargetRegisterClass*)&ARM::GPRRegClass;
6548 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6552 // fallthrough --> loopMBB
6553 BB->addSuccessor(loopMBB);
6556 // ldrexd r2, r3, ptr
6557 // <binopa> r0, r2, incr
6558 // <binopb> r1, r3, incr
6559 // strexd storesuccess, r0, r1, ptr
6560 // cmp storesuccess, #0
6562 // fallthrough --> exitMBB
6568 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6569 .addReg(destlo, RegState::Define)
6570 .addReg(desthi, RegState::Define)
6573 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6574 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6575 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6576 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6577 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6578 .addReg(GPRPair0, 0, ARM::gsub_0);
6579 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6580 .addReg(GPRPair0, 0, ARM::gsub_1);
6584 unsigned StoreLo, StoreHi;
6587 for (unsigned i = 0; i < 2; i++) {
6588 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6590 .addReg(i == 0 ? destlo : desthi)
6591 .addReg(i == 0 ? vallo : valhi));
6592 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6593 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6594 BB->addSuccessor(exitMBB);
6595 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6596 BB = (i == 0 ? contBB : cont2BB);
6599 // Copy to physregs for strexd
6600 StoreLo = MI->getOperand(5).getReg();
6601 StoreHi = MI->getOperand(6).getReg();
6603 // Perform binary operation
6604 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6605 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6606 .addReg(destlo).addReg(vallo))
6607 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6608 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6609 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6610 .addReg(desthi).addReg(valhi))
6611 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6616 // Copy to physregs for strexd
6621 // Compare and branch to exit block.
6622 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6623 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6624 BB->addSuccessor(exitMBB);
6625 BB->addSuccessor(contBB);
6633 MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6634 MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6635 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6636 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6638 // Marshal a pair...
6639 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6640 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6641 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6642 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6643 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6646 .addImm(ARM::gsub_0);
6647 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6650 .addImm(ARM::gsub_1);
6653 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6654 .addReg(StorePair).addReg(ptr));
6657 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6658 .addReg(storesuccess).addImm(0));
6659 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6660 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6662 BB->addSuccessor(loopMBB);
6663 BB->addSuccessor(exitMBB);
6669 MI->eraseFromParent(); // The instruction is gone now.
6675 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6677 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6679 unsigned destlo = MI->getOperand(0).getReg();
6680 unsigned desthi = MI->getOperand(1).getReg();
6681 unsigned ptr = MI->getOperand(2).getReg();
6682 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6683 DebugLoc dl = MI->getDebugLoc();
6684 bool isThumb2 = Subtarget->isThumb2();
6686 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6688 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6689 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6690 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6692 unsigned ldrOpc, strOpc;
6693 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6695 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6698 MIB.addReg(destlo, RegState::Define)
6699 .addReg(desthi, RegState::Define)
6703 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6704 MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6706 // Copy GPRPair0 into dest. (This copy will normally be coalesced.)
6707 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6708 .addReg(GPRPair0, 0, ARM::gsub_0);
6709 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6710 .addReg(GPRPair0, 0, ARM::gsub_1);
6712 AddDefaultPred(MIB);
6714 MI->eraseFromParent(); // The instruction is gone now.
6719 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6720 /// registers the function context.
6721 void ARMTargetLowering::
6722 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6723 MachineBasicBlock *DispatchBB, int FI) const {
6724 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6725 DebugLoc dl = MI->getDebugLoc();
6726 MachineFunction *MF = MBB->getParent();
6727 MachineRegisterInfo *MRI = &MF->getRegInfo();
6728 MachineConstantPool *MCP = MF->getConstantPool();
6729 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6730 const Function *F = MF->getFunction();
6732 bool isThumb = Subtarget->isThumb();
6733 bool isThumb2 = Subtarget->isThumb2();
6735 unsigned PCLabelId = AFI->createPICLabelUId();
6736 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6737 ARMConstantPoolValue *CPV =
6738 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6739 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6741 const TargetRegisterClass *TRC = isThumb ?
6742 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6743 (const TargetRegisterClass*)&ARM::GPRRegClass;
6745 // Grab constant pool and fixed stack memory operands.
6746 MachineMemOperand *CPMMO =
6747 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6748 MachineMemOperand::MOLoad, 4, 4);
6750 MachineMemOperand *FIMMOSt =
6751 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6752 MachineMemOperand::MOStore, 4, 4);
6754 // Load the address of the dispatch MBB into the jump buffer.
6756 // Incoming value: jbuf
6757 // ldr.n r5, LCPI1_1
6760 // str r5, [$jbuf, #+4] ; &jbuf[1]
6761 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6762 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6763 .addConstantPoolIndex(CPI)
6764 .addMemOperand(CPMMO));
6765 // Set the low bit because of thumb mode.
6766 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6768 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6769 .addReg(NewVReg1, RegState::Kill)
6771 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6772 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6773 .addReg(NewVReg2, RegState::Kill)
6775 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6776 .addReg(NewVReg3, RegState::Kill)
6778 .addImm(36) // &jbuf[1] :: pc
6779 .addMemOperand(FIMMOSt));
6780 } else if (isThumb) {
6781 // Incoming value: jbuf
6782 // ldr.n r1, LCPI1_4
6786 // add r2, $jbuf, #+4 ; &jbuf[1]
6788 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6789 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6790 .addConstantPoolIndex(CPI)
6791 .addMemOperand(CPMMO));
6792 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6793 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6794 .addReg(NewVReg1, RegState::Kill)
6796 // Set the low bit because of thumb mode.
6797 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6798 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6799 .addReg(ARM::CPSR, RegState::Define)
6801 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6802 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6803 .addReg(ARM::CPSR, RegState::Define)
6804 .addReg(NewVReg2, RegState::Kill)
6805 .addReg(NewVReg3, RegState::Kill));
6806 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6807 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6809 .addImm(36)); // &jbuf[1] :: pc
6810 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6811 .addReg(NewVReg4, RegState::Kill)
6812 .addReg(NewVReg5, RegState::Kill)
6814 .addMemOperand(FIMMOSt));
6816 // Incoming value: jbuf
6819 // str r1, [$jbuf, #+4] ; &jbuf[1]
6820 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6821 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6822 .addConstantPoolIndex(CPI)
6824 .addMemOperand(CPMMO));
6825 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6826 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6827 .addReg(NewVReg1, RegState::Kill)
6828 .addImm(PCLabelId));
6829 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6830 .addReg(NewVReg2, RegState::Kill)
6832 .addImm(36) // &jbuf[1] :: pc
6833 .addMemOperand(FIMMOSt));
6837 MachineBasicBlock *ARMTargetLowering::
6838 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6839 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6840 DebugLoc dl = MI->getDebugLoc();
6841 MachineFunction *MF = MBB->getParent();
6842 MachineRegisterInfo *MRI = &MF->getRegInfo();
6843 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6844 MachineFrameInfo *MFI = MF->getFrameInfo();
6845 int FI = MFI->getFunctionContextIndex();
6847 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6848 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6849 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6851 // Get a mapping of the call site numbers to all of the landing pads they're
6853 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6854 unsigned MaxCSNum = 0;
6855 MachineModuleInfo &MMI = MF->getMMI();
6856 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6858 if (!BB->isLandingPad()) continue;
6860 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6862 for (MachineBasicBlock::iterator
6863 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6864 if (!II->isEHLabel()) continue;
6866 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6867 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6869 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6870 for (SmallVectorImpl<unsigned>::iterator
6871 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6872 CSI != CSE; ++CSI) {
6873 CallSiteNumToLPad[*CSI].push_back(BB);
6874 MaxCSNum = std::max(MaxCSNum, *CSI);
6880 // Get an ordered list of the machine basic blocks for the jump table.
6881 std::vector<MachineBasicBlock*> LPadList;
6882 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6883 LPadList.reserve(CallSiteNumToLPad.size());
6884 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6885 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6886 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6887 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6888 LPadList.push_back(*II);
6889 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6893 assert(!LPadList.empty() &&
6894 "No landing pad destinations for the dispatch jump table!");
6896 // Create the jump table and associated information.
6897 MachineJumpTableInfo *JTI =
6898 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6899 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6900 unsigned UId = AFI->createJumpTableUId();
6901 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6903 // Create the MBBs for the dispatch code.
6905 // Shove the dispatch's address into the return slot in the function context.
6906 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6907 DispatchBB->setIsLandingPad();
6909 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6910 unsigned trap_opcode;
6911 if (Subtarget->isThumb())
6912 trap_opcode = ARM::tTRAP;
6914 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6916 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6917 DispatchBB->addSuccessor(TrapBB);
6919 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6920 DispatchBB->addSuccessor(DispContBB);
6923 MF->insert(MF->end(), DispatchBB);
6924 MF->insert(MF->end(), DispContBB);
6925 MF->insert(MF->end(), TrapBB);
6927 // Insert code into the entry block that creates and registers the function
6929 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6931 MachineMemOperand *FIMMOLd =
6932 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6933 MachineMemOperand::MOLoad |
6934 MachineMemOperand::MOVolatile, 4, 4);
6936 MachineInstrBuilder MIB;
6937 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6939 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6940 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6942 // Add a register mask with no preserved registers. This results in all
6943 // registers being marked as clobbered.
6944 MIB.addRegMask(RI.getNoPreservedMask());
6946 unsigned NumLPads = LPadList.size();
6947 if (Subtarget->isThumb2()) {
6948 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6949 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6952 .addMemOperand(FIMMOLd));
6954 if (NumLPads < 256) {
6955 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6957 .addImm(LPadList.size()));
6959 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6960 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6961 .addImm(NumLPads & 0xFFFF));
6963 unsigned VReg2 = VReg1;
6964 if ((NumLPads & 0xFFFF0000) != 0) {
6965 VReg2 = MRI->createVirtualRegister(TRC);
6966 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6968 .addImm(NumLPads >> 16));
6971 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6976 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6981 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6982 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6983 .addJumpTableIndex(MJTI)
6986 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6989 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6990 .addReg(NewVReg3, RegState::Kill)
6992 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6994 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6995 .addReg(NewVReg4, RegState::Kill)
6997 .addJumpTableIndex(MJTI)
6999 } else if (Subtarget->isThumb()) {
7000 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7001 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7004 .addMemOperand(FIMMOLd));
7006 if (NumLPads < 256) {
7007 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7011 MachineConstantPool *ConstantPool = MF->getConstantPool();
7012 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7013 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7015 // MachineConstantPool wants an explicit alignment.
7016 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7018 Align = getDataLayout()->getTypeAllocSize(C->getType());
7019 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7021 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7022 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7023 .addReg(VReg1, RegState::Define)
7024 .addConstantPoolIndex(Idx));
7025 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7030 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7035 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7036 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7037 .addReg(ARM::CPSR, RegState::Define)
7041 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7042 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7043 .addJumpTableIndex(MJTI)
7046 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7047 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7048 .addReg(ARM::CPSR, RegState::Define)
7049 .addReg(NewVReg2, RegState::Kill)
7052 MachineMemOperand *JTMMOLd =
7053 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7054 MachineMemOperand::MOLoad, 4, 4);
7056 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7057 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7058 .addReg(NewVReg4, RegState::Kill)
7060 .addMemOperand(JTMMOLd));
7062 unsigned NewVReg6 = NewVReg5;
7063 if (RelocM == Reloc::PIC_) {
7064 NewVReg6 = MRI->createVirtualRegister(TRC);
7065 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7066 .addReg(ARM::CPSR, RegState::Define)
7067 .addReg(NewVReg5, RegState::Kill)
7071 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7072 .addReg(NewVReg6, RegState::Kill)
7073 .addJumpTableIndex(MJTI)
7076 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7077 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7080 .addMemOperand(FIMMOLd));
7082 if (NumLPads < 256) {
7083 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7086 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7087 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7088 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7089 .addImm(NumLPads & 0xFFFF));
7091 unsigned VReg2 = VReg1;
7092 if ((NumLPads & 0xFFFF0000) != 0) {
7093 VReg2 = MRI->createVirtualRegister(TRC);
7094 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7096 .addImm(NumLPads >> 16));
7099 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7103 MachineConstantPool *ConstantPool = MF->getConstantPool();
7104 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7105 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7107 // MachineConstantPool wants an explicit alignment.
7108 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7110 Align = getDataLayout()->getTypeAllocSize(C->getType());
7111 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7113 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7114 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7115 .addReg(VReg1, RegState::Define)
7116 .addConstantPoolIndex(Idx)
7118 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7120 .addReg(VReg1, RegState::Kill));
7123 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7128 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7130 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7132 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7133 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7134 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7135 .addJumpTableIndex(MJTI)
7138 MachineMemOperand *JTMMOLd =
7139 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7140 MachineMemOperand::MOLoad, 4, 4);
7141 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7143 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7144 .addReg(NewVReg3, RegState::Kill)
7147 .addMemOperand(JTMMOLd));
7149 if (RelocM == Reloc::PIC_) {
7150 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7151 .addReg(NewVReg5, RegState::Kill)
7153 .addJumpTableIndex(MJTI)
7156 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7157 .addReg(NewVReg5, RegState::Kill)
7158 .addJumpTableIndex(MJTI)
7163 // Add the jump table entries as successors to the MBB.
7164 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7165 for (std::vector<MachineBasicBlock*>::iterator
7166 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7167 MachineBasicBlock *CurMBB = *I;
7168 if (SeenMBBs.insert(CurMBB))
7169 DispContBB->addSuccessor(CurMBB);
7172 // N.B. the order the invoke BBs are processed in doesn't matter here.
7173 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7174 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7175 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7176 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7177 MachineBasicBlock *BB = *I;
7179 // Remove the landing pad successor from the invoke block and replace it
7180 // with the new dispatch block.
7181 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7183 while (!Successors.empty()) {
7184 MachineBasicBlock *SMBB = Successors.pop_back_val();
7185 if (SMBB->isLandingPad()) {
7186 BB->removeSuccessor(SMBB);
7187 MBBLPads.push_back(SMBB);
7191 BB->addSuccessor(DispatchBB);
7193 // Find the invoke call and mark all of the callee-saved registers as
7194 // 'implicit defined' so that they're spilled. This prevents code from
7195 // moving instructions to before the EH block, where they will never be
7197 for (MachineBasicBlock::reverse_iterator
7198 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7199 if (!II->isCall()) continue;
7201 DenseMap<unsigned, bool> DefRegs;
7202 for (MachineInstr::mop_iterator
7203 OI = II->operands_begin(), OE = II->operands_end();
7205 if (!OI->isReg()) continue;
7206 DefRegs[OI->getReg()] = true;
7209 MachineInstrBuilder MIB(*MF, &*II);
7211 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7212 unsigned Reg = SavedRegs[i];
7213 if (Subtarget->isThumb2() &&
7214 !ARM::tGPRRegClass.contains(Reg) &&
7215 !ARM::hGPRRegClass.contains(Reg))
7217 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7219 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7222 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7229 // Mark all former landing pads as non-landing pads. The dispatch is the only
7231 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7232 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7233 (*I)->setIsLandingPad(false);
7235 // The instruction is gone now.
7236 MI->eraseFromParent();
7242 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7243 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7244 E = MBB->succ_end(); I != E; ++I)
7247 llvm_unreachable("Expecting a BB with two successors!");
7251 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7252 MachineBasicBlock *BB) const {
7253 // This pseudo instruction has 3 operands: dst, src, size
7254 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7255 // Otherwise, we will generate unrolled scalar copies.
7256 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7257 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7258 MachineFunction::iterator It = BB;
7261 unsigned dest = MI->getOperand(0).getReg();
7262 unsigned src = MI->getOperand(1).getReg();
7263 unsigned SizeVal = MI->getOperand(2).getImm();
7264 unsigned Align = MI->getOperand(3).getImm();
7265 DebugLoc dl = MI->getDebugLoc();
7267 MachineFunction *MF = BB->getParent();
7268 MachineRegisterInfo &MRI = MF->getRegInfo();
7269 unsigned UnitSize = 0;
7270 unsigned UnitLdOpc = 0;
7271 unsigned UnitStOpc = 0;
7272 const TargetRegisterClass *TRC = 0;
7273 const TargetRegisterClass *VecTRC = 0;
7275 bool IsThumb1 = Subtarget->isThumb1Only();
7276 bool IsThumb2 = Subtarget->isThumb2();
7280 } else if (Align & 2) {
7283 // Check whether we can use NEON instructions.
7284 if (!MF->getFunction()->getAttributes().
7285 hasAttribute(AttributeSet::FunctionIndex,
7286 Attribute::NoImplicitFloat) &&
7287 Subtarget->hasNEON()) {
7288 if ((Align % 16 == 0) && SizeVal >= 16)
7290 else if ((Align % 8 == 0) && SizeVal >= 8)
7293 // Can't use NEON instructions.
7298 // Select the correct opcode and register class for unit size load/store
7299 bool IsNeon = UnitSize >= 8;
7300 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7301 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7303 UnitLdOpc = UnitSize == 16 ? ARM::VLD1q32wb_fixed
7304 : UnitSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7305 UnitStOpc = UnitSize == 16 ? ARM::VST1q32wb_fixed
7306 : UnitSize == 8 ? ARM::VST1d32wb_fixed : 0;
7307 VecTRC = UnitSize == 16
7308 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7310 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7312 } else if (IsThumb1) {
7313 UnitLdOpc = UnitSize == 4 ? ARM::tLDRi
7314 : UnitSize == 2 ? ARM::tLDRHi
7315 : UnitSize == 1 ? ARM::tLDRBi : 0;
7316 UnitStOpc = UnitSize == 4 ? ARM::tSTRi
7317 : UnitSize == 2 ? ARM::tSTRHi
7318 : UnitSize == 1 ? ARM::tSTRBi : 0;
7319 } else if (IsThumb2) {
7320 UnitLdOpc = UnitSize == 4
7322 : UnitSize == 2 ? ARM::t2LDRH_POST
7323 : UnitSize == 1 ? ARM::t2LDRB_POST : 0;
7324 UnitStOpc = UnitSize == 4
7326 : UnitSize == 2 ? ARM::t2STRH_POST
7327 : UnitSize == 1 ? ARM::t2STRB_POST : 0;
7329 UnitLdOpc = UnitSize == 4
7331 : UnitSize == 2 ? ARM::LDRH_POST
7332 : UnitSize == 1 ? ARM::LDRB_POST_IMM : 0;
7333 UnitStOpc = UnitSize == 4
7335 : UnitSize == 2 ? ARM::STRH_POST
7336 : UnitSize == 1 ? ARM::STRB_POST_IMM : 0;
7338 assert(UnitLdOpc != 0 && UnitStOpc != 0 && "Should have unit opcodes");
7340 unsigned BytesLeft = SizeVal % UnitSize;
7341 unsigned LoopSize = SizeVal - BytesLeft;
7343 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7344 // Use LDR and STR to copy.
7345 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7346 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7347 unsigned srcIn = src;
7348 unsigned destIn = dest;
7349 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7350 unsigned srcOut = MRI.createVirtualRegister(TRC);
7351 unsigned destOut = MRI.createVirtualRegister(TRC);
7352 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7354 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitLdOpc), scratch)
7355 .addReg(srcOut, RegState::Define).addReg(srcIn)
7358 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitStOpc), destOut)
7359 .addReg(destIn).addImm(0).addReg(scratch));
7360 } else if (IsThumb1) {
7361 // load + update srcIn
7362 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitLdOpc), scratch)
7363 .addReg(srcIn).addImm(0));
7364 MachineInstrBuilder MIB =
7365 BuildMI(*BB, MI, dl, TII->get(ARM::tADDi8), srcOut);
7366 MIB = AddDefaultT1CC(MIB);
7367 MIB.addReg(srcIn).addImm(UnitSize);
7368 AddDefaultPred(MIB);
7370 // store + update destIn
7371 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitStOpc)).addReg(scratch)
7372 .addReg(destIn).addImm(0));
7373 MIB = BuildMI(*BB, MI, dl, TII->get(ARM::tADDi8), destOut);
7374 MIB = AddDefaultT1CC(MIB);
7375 MIB.addReg(destIn).addImm(UnitSize);
7376 AddDefaultPred(MIB);
7377 } else if (IsThumb2) {
7378 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitLdOpc), scratch)
7379 .addReg(srcOut, RegState::Define).addReg(srcIn)
7381 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitStOpc), destOut)
7382 .addReg(scratch).addReg(destIn).addImm(UnitSize));
7384 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitLdOpc), scratch)
7385 .addReg(srcOut, RegState::Define).addReg(srcIn)
7386 .addReg(0).addImm(UnitSize));
7387 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitStOpc), destOut)
7388 .addReg(scratch).addReg(destIn).addReg(0)
7395 // Handle the leftover bytes with LDRB and STRB.
7396 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7397 // [destOut] = STRB_POST(scratch, destIn, 1)
7398 for (unsigned i = 0; i < BytesLeft; i++) {
7399 unsigned srcOut = MRI.createVirtualRegister(TRC);
7400 unsigned destOut = MRI.createVirtualRegister(TRC);
7401 unsigned scratch = MRI.createVirtualRegister(TRC);
7403 // load into scratch
7404 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRBi), scratch)
7405 .addReg(srcIn).addImm(0));
7407 // update base pointer
7408 MachineInstrBuilder MIB =
7409 BuildMI(*BB, MI, dl, TII->get(ARM::tADDi8), srcOut);
7410 MIB = AddDefaultT1CC(MIB);
7411 MIB.addReg(srcIn).addImm(1);
7412 AddDefaultPred(MIB);
7415 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tSTRBi))
7416 .addReg(scratch).addReg(destIn).addImm(0));
7418 // update base pointer
7419 MIB = BuildMI(*BB, MI, dl, TII->get(ARM::tADDi8), destOut);
7420 MIB = AddDefaultT1CC(MIB);
7421 MIB.addReg(destIn).addImm(1);
7422 AddDefaultPred(MIB);
7423 } else if (IsThumb2) {
7424 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::t2LDRB_POST), scratch)
7425 .addReg(srcOut, RegState::Define).addReg(srcIn)
7427 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::t2STRB_POST), destOut)
7428 .addReg(scratch).addReg(destIn).addImm(1));
7430 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRB_POST_IMM),
7431 scratch).addReg(srcOut, RegState::Define)
7432 .addReg(srcIn).addReg(0).addImm(1));
7434 BuildMI(*BB, MI, dl, TII->get(ARM::STRB_POST_IMM), destOut)
7435 .addReg(scratch).addReg(destIn).addReg(0).addImm(1));
7440 MI->eraseFromParent(); // The instruction is gone now.
7444 // Expand the pseudo op to a loop.
7447 // movw varEnd, # --> with thumb2
7449 // ldrcp varEnd, idx --> without thumb2
7450 // fallthrough --> loopMBB
7452 // PHI varPhi, varEnd, varLoop
7453 // PHI srcPhi, src, srcLoop
7454 // PHI destPhi, dst, destLoop
7455 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7456 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7457 // subs varLoop, varPhi, #UnitSize
7459 // fallthrough --> exitMBB
7461 // epilogue to handle left-over bytes
7462 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7463 // [destOut] = STRB_POST(scratch, destLoop, 1)
7464 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7465 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7466 MF->insert(It, loopMBB);
7467 MF->insert(It, exitMBB);
7469 // Transfer the remainder of BB and its successor edges to exitMBB.
7470 exitMBB->splice(exitMBB->begin(), BB,
7471 llvm::next(MachineBasicBlock::iterator(MI)),
7473 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7475 // Load an immediate to varEnd.
7476 unsigned varEnd = MRI.createVirtualRegister(TRC);
7478 unsigned Vtmp = varEnd;
7479 if ((LoopSize & 0xFFFF0000) != 0)
7480 Vtmp = MRI.createVirtualRegister(TRC);
7481 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7482 .addImm(LoopSize & 0xFFFF));
7484 if ((LoopSize & 0xFFFF0000) != 0)
7485 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7486 .addReg(Vtmp).addImm(LoopSize >> 16));
7488 MachineConstantPool *ConstantPool = MF->getConstantPool();
7489 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7490 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7492 // MachineConstantPool wants an explicit alignment.
7493 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7495 Align = getDataLayout()->getTypeAllocSize(C->getType());
7496 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7499 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7500 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7502 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7503 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7505 BB->addSuccessor(loopMBB);
7507 // Generate the loop body:
7508 // varPhi = PHI(varLoop, varEnd)
7509 // srcPhi = PHI(srcLoop, src)
7510 // destPhi = PHI(destLoop, dst)
7511 MachineBasicBlock *entryBB = BB;
7513 unsigned varLoop = MRI.createVirtualRegister(TRC);
7514 unsigned varPhi = MRI.createVirtualRegister(TRC);
7515 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7516 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7517 unsigned destLoop = MRI.createVirtualRegister(TRC);
7518 unsigned destPhi = MRI.createVirtualRegister(TRC);
7520 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7521 .addReg(varLoop).addMBB(loopMBB)
7522 .addReg(varEnd).addMBB(entryBB);
7523 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7524 .addReg(srcLoop).addMBB(loopMBB)
7525 .addReg(src).addMBB(entryBB);
7526 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7527 .addReg(destLoop).addMBB(loopMBB)
7528 .addReg(dest).addMBB(entryBB);
7530 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7531 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7532 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7534 AddDefaultPred(BuildMI(*BB, BB->end(), dl, TII->get(UnitLdOpc), scratch)
7535 .addReg(srcLoop, RegState::Define).addReg(srcPhi)
7538 AddDefaultPred(BuildMI(*BB, BB->end(), dl, TII->get(UnitStOpc), destLoop)
7539 .addReg(destPhi).addImm(0).addReg(scratch));
7540 } else if (IsThumb1) {
7541 // load + update srcIn
7542 AddDefaultPred(BuildMI(*BB, BB->end(), dl, TII->get(UnitLdOpc), scratch)
7543 .addReg(srcPhi).addImm(0));
7544 MachineInstrBuilder MIB =
7545 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tADDi8), srcLoop);
7546 MIB = AddDefaultT1CC(MIB);
7547 MIB.addReg(srcPhi).addImm(UnitSize);
7548 AddDefaultPred(MIB);
7550 // store + update destIn
7551 AddDefaultPred(BuildMI(*BB, BB->end(), dl, TII->get(UnitStOpc))
7552 .addReg(scratch).addReg(destPhi).addImm(0));
7553 MIB = BuildMI(*BB, BB->end(), dl, TII->get(ARM::tADDi8), destLoop);
7554 MIB = AddDefaultT1CC(MIB);
7555 MIB.addReg(destPhi).addImm(UnitSize);
7556 AddDefaultPred(MIB);
7557 } else if (IsThumb2) {
7558 AddDefaultPred(BuildMI(*BB, BB->end(), dl, TII->get(UnitLdOpc), scratch)
7559 .addReg(srcLoop, RegState::Define).addReg(srcPhi)
7561 AddDefaultPred(BuildMI(*BB, BB->end(), dl, TII->get(UnitStOpc), destLoop)
7562 .addReg(scratch).addReg(destPhi).addImm(UnitSize));
7564 AddDefaultPred(BuildMI(*BB, BB->end(), dl, TII->get(UnitLdOpc), scratch)
7565 .addReg(srcLoop, RegState::Define).addReg(srcPhi)
7566 .addReg(0).addImm(UnitSize));
7567 AddDefaultPred(BuildMI(*BB, BB->end(), dl, TII->get(UnitStOpc), destLoop)
7568 .addReg(scratch).addReg(destPhi).addReg(0)
7572 // Decrement loop variable by UnitSize.
7574 MachineInstrBuilder MIB =
7575 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7576 MIB = AddDefaultT1CC(MIB);
7577 MIB.addReg(varPhi).addImm(UnitSize);
7578 AddDefaultPred(MIB);
7580 MachineInstrBuilder MIB =
7581 BuildMI(*BB, BB->end(), dl,
7582 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7583 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7584 MIB->getOperand(5).setReg(ARM::CPSR);
7585 MIB->getOperand(5).setIsDef(true);
7587 BuildMI(*BB, BB->end(), dl,
7588 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7589 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7591 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7592 BB->addSuccessor(loopMBB);
7593 BB->addSuccessor(exitMBB);
7595 // Add epilogue to handle BytesLeft.
7597 MachineInstr *StartOfExit = exitMBB->begin();
7599 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7600 // [destOut] = STRB_POST(scratch, destLoop, 1)
7601 unsigned srcIn = srcLoop;
7602 unsigned destIn = destLoop;
7603 for (unsigned i = 0; i < BytesLeft; i++) {
7604 unsigned srcOut = MRI.createVirtualRegister(TRC);
7605 unsigned destOut = MRI.createVirtualRegister(TRC);
7606 unsigned scratch = MRI.createVirtualRegister(TRC);
7608 // load into scratch
7609 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(ARM::tLDRBi),
7610 scratch).addReg(srcIn).addImm(0));
7612 // update base pointer
7613 MachineInstrBuilder MIB =
7614 BuildMI(*BB, StartOfExit, dl, TII->get(ARM::tADDi8), srcOut);
7615 MIB = AddDefaultT1CC(MIB);
7616 MIB.addReg(srcIn).addImm(1);
7617 AddDefaultPred(MIB);
7620 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(ARM::tSTRBi))
7621 .addReg(scratch).addReg(destIn).addImm(0));
7623 // update base pointer
7624 MIB = BuildMI(*BB, StartOfExit, dl, TII->get(ARM::tADDi8), destOut);
7625 MIB = AddDefaultT1CC(MIB);
7626 MIB.addReg(destIn).addImm(1);
7627 AddDefaultPred(MIB);
7628 } else if (IsThumb2) {
7630 BuildMI(*BB, StartOfExit, dl, TII->get(ARM::t2LDRB_POST), scratch)
7631 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7632 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(ARM::t2STRB_POST),
7633 destOut).addReg(scratch).addReg(destIn).addImm(1));
7635 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(ARM::LDRB_POST_IMM),
7636 scratch).addReg(srcOut, RegState::Define)
7637 .addReg(srcIn).addReg(0).addImm(1));
7639 BuildMI(*BB, StartOfExit, dl, TII->get(ARM::STRB_POST_IMM), destOut)
7640 .addReg(scratch).addReg(destIn).addReg(0).addImm(1));
7646 MI->eraseFromParent(); // The instruction is gone now.
7651 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7652 MachineBasicBlock *BB) const {
7653 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7654 DebugLoc dl = MI->getDebugLoc();
7655 bool isThumb2 = Subtarget->isThumb2();
7656 switch (MI->getOpcode()) {
7659 llvm_unreachable("Unexpected instr type to insert");
7661 // The Thumb2 pre-indexed stores have the same MI operands, they just
7662 // define them differently in the .td files from the isel patterns, so
7663 // they need pseudos.
7664 case ARM::t2STR_preidx:
7665 MI->setDesc(TII->get(ARM::t2STR_PRE));
7667 case ARM::t2STRB_preidx:
7668 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7670 case ARM::t2STRH_preidx:
7671 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7674 case ARM::STRi_preidx:
7675 case ARM::STRBi_preidx: {
7676 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7677 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7678 // Decode the offset.
7679 unsigned Offset = MI->getOperand(4).getImm();
7680 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7681 Offset = ARM_AM::getAM2Offset(Offset);
7685 MachineMemOperand *MMO = *MI->memoperands_begin();
7686 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7687 .addOperand(MI->getOperand(0)) // Rn_wb
7688 .addOperand(MI->getOperand(1)) // Rt
7689 .addOperand(MI->getOperand(2)) // Rn
7690 .addImm(Offset) // offset (skip GPR==zero_reg)
7691 .addOperand(MI->getOperand(5)) // pred
7692 .addOperand(MI->getOperand(6))
7693 .addMemOperand(MMO);
7694 MI->eraseFromParent();
7697 case ARM::STRr_preidx:
7698 case ARM::STRBr_preidx:
7699 case ARM::STRH_preidx: {
7701 switch (MI->getOpcode()) {
7702 default: llvm_unreachable("unexpected opcode!");
7703 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7704 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7705 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7707 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7708 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7709 MIB.addOperand(MI->getOperand(i));
7710 MI->eraseFromParent();
7713 case ARM::ATOMIC_LOAD_ADD_I8:
7714 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7715 case ARM::ATOMIC_LOAD_ADD_I16:
7716 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7717 case ARM::ATOMIC_LOAD_ADD_I32:
7718 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7720 case ARM::ATOMIC_LOAD_AND_I8:
7721 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7722 case ARM::ATOMIC_LOAD_AND_I16:
7723 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7724 case ARM::ATOMIC_LOAD_AND_I32:
7725 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7727 case ARM::ATOMIC_LOAD_OR_I8:
7728 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7729 case ARM::ATOMIC_LOAD_OR_I16:
7730 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7731 case ARM::ATOMIC_LOAD_OR_I32:
7732 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7734 case ARM::ATOMIC_LOAD_XOR_I8:
7735 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7736 case ARM::ATOMIC_LOAD_XOR_I16:
7737 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7738 case ARM::ATOMIC_LOAD_XOR_I32:
7739 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7741 case ARM::ATOMIC_LOAD_NAND_I8:
7742 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7743 case ARM::ATOMIC_LOAD_NAND_I16:
7744 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7745 case ARM::ATOMIC_LOAD_NAND_I32:
7746 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7748 case ARM::ATOMIC_LOAD_SUB_I8:
7749 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7750 case ARM::ATOMIC_LOAD_SUB_I16:
7751 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7752 case ARM::ATOMIC_LOAD_SUB_I32:
7753 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7755 case ARM::ATOMIC_LOAD_MIN_I8:
7756 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7757 case ARM::ATOMIC_LOAD_MIN_I16:
7758 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7759 case ARM::ATOMIC_LOAD_MIN_I32:
7760 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7762 case ARM::ATOMIC_LOAD_MAX_I8:
7763 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7764 case ARM::ATOMIC_LOAD_MAX_I16:
7765 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7766 case ARM::ATOMIC_LOAD_MAX_I32:
7767 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7769 case ARM::ATOMIC_LOAD_UMIN_I8:
7770 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7771 case ARM::ATOMIC_LOAD_UMIN_I16:
7772 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7773 case ARM::ATOMIC_LOAD_UMIN_I32:
7774 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7776 case ARM::ATOMIC_LOAD_UMAX_I8:
7777 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7778 case ARM::ATOMIC_LOAD_UMAX_I16:
7779 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7780 case ARM::ATOMIC_LOAD_UMAX_I32:
7781 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7783 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7784 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7785 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7787 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7788 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7789 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7791 case ARM::ATOMIC_LOAD_I64:
7792 return EmitAtomicLoad64(MI, BB);
7794 case ARM::ATOMIC_LOAD_ADD_I64:
7795 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7796 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7797 /*NeedsCarry*/ true);
7798 case ARM::ATOMIC_LOAD_SUB_I64:
7799 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7800 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7801 /*NeedsCarry*/ true);
7802 case ARM::ATOMIC_LOAD_OR_I64:
7803 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7804 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7805 case ARM::ATOMIC_LOAD_XOR_I64:
7806 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7807 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7808 case ARM::ATOMIC_LOAD_AND_I64:
7809 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7810 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7811 case ARM::ATOMIC_STORE_I64:
7812 case ARM::ATOMIC_SWAP_I64:
7813 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7814 case ARM::ATOMIC_CMP_SWAP_I64:
7815 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7816 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7817 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7818 case ARM::ATOMIC_LOAD_MIN_I64:
7819 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7820 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7821 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7822 /*IsMinMax*/ true, ARMCC::LT);
7823 case ARM::ATOMIC_LOAD_MAX_I64:
7824 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7825 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7826 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7827 /*IsMinMax*/ true, ARMCC::GE);
7828 case ARM::ATOMIC_LOAD_UMIN_I64:
7829 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7830 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7831 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7832 /*IsMinMax*/ true, ARMCC::LO);
7833 case ARM::ATOMIC_LOAD_UMAX_I64:
7834 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7835 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7836 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7837 /*IsMinMax*/ true, ARMCC::HS);
7839 case ARM::tMOVCCr_pseudo: {
7840 // To "insert" a SELECT_CC instruction, we actually have to insert the
7841 // diamond control-flow pattern. The incoming instruction knows the
7842 // destination vreg to set, the condition code register to branch on, the
7843 // true/false values to select between, and a branch opcode to use.
7844 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7845 MachineFunction::iterator It = BB;
7851 // cmpTY ccX, r1, r2
7853 // fallthrough --> copy0MBB
7854 MachineBasicBlock *thisMBB = BB;
7855 MachineFunction *F = BB->getParent();
7856 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7857 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7858 F->insert(It, copy0MBB);
7859 F->insert(It, sinkMBB);
7861 // Transfer the remainder of BB and its successor edges to sinkMBB.
7862 sinkMBB->splice(sinkMBB->begin(), BB,
7863 llvm::next(MachineBasicBlock::iterator(MI)),
7865 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7867 BB->addSuccessor(copy0MBB);
7868 BB->addSuccessor(sinkMBB);
7870 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7871 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7874 // %FalseValue = ...
7875 // # fallthrough to sinkMBB
7878 // Update machine-CFG edges
7879 BB->addSuccessor(sinkMBB);
7882 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7885 BuildMI(*BB, BB->begin(), dl,
7886 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7887 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7888 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7890 MI->eraseFromParent(); // The pseudo instruction is gone now.
7895 case ARM::BCCZi64: {
7896 // If there is an unconditional branch to the other successor, remove it.
7897 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7899 // Compare both parts that make up the double comparison separately for
7901 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7903 unsigned LHS1 = MI->getOperand(1).getReg();
7904 unsigned LHS2 = MI->getOperand(2).getReg();
7906 AddDefaultPred(BuildMI(BB, dl,
7907 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7908 .addReg(LHS1).addImm(0));
7909 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7910 .addReg(LHS2).addImm(0)
7911 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7913 unsigned RHS1 = MI->getOperand(3).getReg();
7914 unsigned RHS2 = MI->getOperand(4).getReg();
7915 AddDefaultPred(BuildMI(BB, dl,
7916 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7917 .addReg(LHS1).addReg(RHS1));
7918 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7919 .addReg(LHS2).addReg(RHS2)
7920 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7923 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7924 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7925 if (MI->getOperand(0).getImm() == ARMCC::NE)
7926 std::swap(destMBB, exitMBB);
7928 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7929 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7931 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7933 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7935 MI->eraseFromParent(); // The pseudo instruction is gone now.
7939 case ARM::Int_eh_sjlj_setjmp:
7940 case ARM::Int_eh_sjlj_setjmp_nofp:
7941 case ARM::tInt_eh_sjlj_setjmp:
7942 case ARM::t2Int_eh_sjlj_setjmp:
7943 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7944 EmitSjLjDispatchBlock(MI, BB);
7949 // To insert an ABS instruction, we have to insert the
7950 // diamond control-flow pattern. The incoming instruction knows the
7951 // source vreg to test against 0, the destination vreg to set,
7952 // the condition code register to branch on, the
7953 // true/false values to select between, and a branch opcode to use.
7958 // BCC (branch to SinkBB if V0 >= 0)
7959 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7960 // SinkBB: V1 = PHI(V2, V3)
7961 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7962 MachineFunction::iterator BBI = BB;
7964 MachineFunction *Fn = BB->getParent();
7965 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7966 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7967 Fn->insert(BBI, RSBBB);
7968 Fn->insert(BBI, SinkBB);
7970 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7971 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7972 bool isThumb2 = Subtarget->isThumb2();
7973 MachineRegisterInfo &MRI = Fn->getRegInfo();
7974 // In Thumb mode S must not be specified if source register is the SP or
7975 // PC and if destination register is the SP, so restrict register class
7976 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7977 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7978 (const TargetRegisterClass*)&ARM::GPRRegClass);
7980 // Transfer the remainder of BB and its successor edges to sinkMBB.
7981 SinkBB->splice(SinkBB->begin(), BB,
7982 llvm::next(MachineBasicBlock::iterator(MI)),
7984 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7986 BB->addSuccessor(RSBBB);
7987 BB->addSuccessor(SinkBB);
7989 // fall through to SinkMBB
7990 RSBBB->addSuccessor(SinkBB);
7992 // insert a cmp at the end of BB
7993 AddDefaultPred(BuildMI(BB, dl,
7994 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7995 .addReg(ABSSrcReg).addImm(0));
7997 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7999 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8000 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8002 // insert rsbri in RSBBB
8003 // Note: BCC and rsbri will be converted into predicated rsbmi
8004 // by if-conversion pass
8005 BuildMI(*RSBBB, RSBBB->begin(), dl,
8006 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8007 .addReg(ABSSrcReg, RegState::Kill)
8008 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8010 // insert PHI in SinkBB,
8011 // reuse ABSDstReg to not change uses of ABS instruction
8012 BuildMI(*SinkBB, SinkBB->begin(), dl,
8013 TII->get(ARM::PHI), ABSDstReg)
8014 .addReg(NewRsbDstReg).addMBB(RSBBB)
8015 .addReg(ABSSrcReg).addMBB(BB);
8017 // remove ABS instruction
8018 MI->eraseFromParent();
8020 // return last added BB
8023 case ARM::COPY_STRUCT_BYVAL_I32:
8025 return EmitStructByval(MI, BB);
8029 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8030 SDNode *Node) const {
8031 if (!MI->hasPostISelHook()) {
8032 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
8033 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
8037 const MCInstrDesc *MCID = &MI->getDesc();
8038 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8039 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8040 // operand is still set to noreg. If needed, set the optional operand's
8041 // register to CPSR, and remove the redundant implicit def.
8043 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8045 // Rename pseudo opcodes.
8046 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8048 const ARMBaseInstrInfo *TII =
8049 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
8050 MCID = &TII->get(NewOpc);
8052 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8053 "converted opcode should be the same except for cc_out");
8057 // Add the optional cc_out operand
8058 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8060 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8062 // Any ARM instruction that sets the 's' bit should specify an optional
8063 // "cc_out" operand in the last operand position.
8064 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8065 assert(!NewOpc && "Optional cc_out operand required");
8068 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8069 // since we already have an optional CPSR def.
8070 bool definesCPSR = false;
8071 bool deadCPSR = false;
8072 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8074 const MachineOperand &MO = MI->getOperand(i);
8075 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8079 MI->RemoveOperand(i);
8084 assert(!NewOpc && "Optional cc_out operand required");
8087 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8089 assert(!MI->getOperand(ccOutIdx).getReg() &&
8090 "expect uninitialized optional cc_out operand");
8094 // If this instruction was defined with an optional CPSR def and its dag node
8095 // had a live implicit CPSR def, then activate the optional CPSR def.
8096 MachineOperand &MO = MI->getOperand(ccOutIdx);
8097 MO.setReg(ARM::CPSR);
8101 //===----------------------------------------------------------------------===//
8102 // ARM Optimization Hooks
8103 //===----------------------------------------------------------------------===//
8105 // Helper function that checks if N is a null or all ones constant.
8106 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8107 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8110 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8113 // Return true if N is conditionally 0 or all ones.
8114 // Detects these expressions where cc is an i1 value:
8116 // (select cc 0, y) [AllOnes=0]
8117 // (select cc y, 0) [AllOnes=0]
8118 // (zext cc) [AllOnes=0]
8119 // (sext cc) [AllOnes=0/1]
8120 // (select cc -1, y) [AllOnes=1]
8121 // (select cc y, -1) [AllOnes=1]
8123 // Invert is set when N is the null/all ones constant when CC is false.
8124 // OtherOp is set to the alternative value of N.
8125 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8126 SDValue &CC, bool &Invert,
8128 SelectionDAG &DAG) {
8129 switch (N->getOpcode()) {
8130 default: return false;
8132 CC = N->getOperand(0);
8133 SDValue N1 = N->getOperand(1);
8134 SDValue N2 = N->getOperand(2);
8135 if (isZeroOrAllOnes(N1, AllOnes)) {
8140 if (isZeroOrAllOnes(N2, AllOnes)) {
8147 case ISD::ZERO_EXTEND:
8148 // (zext cc) can never be the all ones value.
8152 case ISD::SIGN_EXTEND: {
8153 EVT VT = N->getValueType(0);
8154 CC = N->getOperand(0);
8155 if (CC.getValueType() != MVT::i1)
8159 // When looking for an AllOnes constant, N is an sext, and the 'other'
8161 OtherOp = DAG.getConstant(0, VT);
8162 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8163 // When looking for a 0 constant, N can be zext or sext.
8164 OtherOp = DAG.getConstant(1, VT);
8166 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8172 // Combine a constant select operand into its use:
8174 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8175 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8176 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8177 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8178 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8180 // The transform is rejected if the select doesn't have a constant operand that
8181 // is null, or all ones when AllOnes is set.
8183 // Also recognize sext/zext from i1:
8185 // (add (zext cc), x) -> (select cc (add x, 1), x)
8186 // (add (sext cc), x) -> (select cc (add x, -1), x)
8188 // These transformations eventually create predicated instructions.
8190 // @param N The node to transform.
8191 // @param Slct The N operand that is a select.
8192 // @param OtherOp The other N operand (x above).
8193 // @param DCI Context.
8194 // @param AllOnes Require the select constant to be all ones instead of null.
8195 // @returns The new node, or SDValue() on failure.
8197 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8198 TargetLowering::DAGCombinerInfo &DCI,
8199 bool AllOnes = false) {
8200 SelectionDAG &DAG = DCI.DAG;
8201 EVT VT = N->getValueType(0);
8202 SDValue NonConstantVal;
8205 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8206 NonConstantVal, DAG))
8209 // Slct is now know to be the desired identity constant when CC is true.
8210 SDValue TrueVal = OtherOp;
8211 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8212 OtherOp, NonConstantVal);
8213 // Unless SwapSelectOps says CC should be false.
8215 std::swap(TrueVal, FalseVal);
8217 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8218 CCOp, TrueVal, FalseVal);
8221 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8223 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8224 TargetLowering::DAGCombinerInfo &DCI) {
8225 SDValue N0 = N->getOperand(0);
8226 SDValue N1 = N->getOperand(1);
8227 if (N0.getNode()->hasOneUse()) {
8228 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8229 if (Result.getNode())
8232 if (N1.getNode()->hasOneUse()) {
8233 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8234 if (Result.getNode())
8240 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8241 // (only after legalization).
8242 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8243 TargetLowering::DAGCombinerInfo &DCI,
8244 const ARMSubtarget *Subtarget) {
8246 // Only perform optimization if after legalize, and if NEON is available. We
8247 // also expected both operands to be BUILD_VECTORs.
8248 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8249 || N0.getOpcode() != ISD::BUILD_VECTOR
8250 || N1.getOpcode() != ISD::BUILD_VECTOR)
8253 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8254 EVT VT = N->getValueType(0);
8255 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8258 // Check that the vector operands are of the right form.
8259 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8260 // operands, where N is the size of the formed vector.
8261 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8262 // index such that we have a pair wise add pattern.
8264 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8265 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8267 SDValue Vec = N0->getOperand(0)->getOperand(0);
8268 SDNode *V = Vec.getNode();
8269 unsigned nextIndex = 0;
8271 // For each operands to the ADD which are BUILD_VECTORs,
8272 // check to see if each of their operands are an EXTRACT_VECTOR with
8273 // the same vector and appropriate index.
8274 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8275 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8276 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8278 SDValue ExtVec0 = N0->getOperand(i);
8279 SDValue ExtVec1 = N1->getOperand(i);
8281 // First operand is the vector, verify its the same.
8282 if (V != ExtVec0->getOperand(0).getNode() ||
8283 V != ExtVec1->getOperand(0).getNode())
8286 // Second is the constant, verify its correct.
8287 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8288 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8290 // For the constant, we want to see all the even or all the odd.
8291 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8292 || C1->getZExtValue() != nextIndex+1)
8301 // Create VPADDL node.
8302 SelectionDAG &DAG = DCI.DAG;
8303 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8305 // Build operand list.
8306 SmallVector<SDValue, 8> Ops;
8307 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8308 TLI.getPointerTy()));
8310 // Input is the vector.
8313 // Get widened type and narrowed type.
8315 unsigned numElem = VT.getVectorNumElements();
8316 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8317 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8318 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8319 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8321 llvm_unreachable("Invalid vector element type for padd optimization.");
8324 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8325 widenType, &Ops[0], Ops.size());
8326 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8329 static SDValue findMUL_LOHI(SDValue V) {
8330 if (V->getOpcode() == ISD::UMUL_LOHI ||
8331 V->getOpcode() == ISD::SMUL_LOHI)
8336 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8337 TargetLowering::DAGCombinerInfo &DCI,
8338 const ARMSubtarget *Subtarget) {
8340 if (Subtarget->isThumb1Only()) return SDValue();
8342 // Only perform the checks after legalize when the pattern is available.
8343 if (DCI.isBeforeLegalize()) return SDValue();
8345 // Look for multiply add opportunities.
8346 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8347 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8348 // a glue link from the first add to the second add.
8349 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8350 // a S/UMLAL instruction.
8353 // \ / \ [no multiline comment]
8359 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8360 SDValue AddcOp0 = AddcNode->getOperand(0);
8361 SDValue AddcOp1 = AddcNode->getOperand(1);
8363 // Check if the two operands are from the same mul_lohi node.
8364 if (AddcOp0.getNode() == AddcOp1.getNode())
8367 assert(AddcNode->getNumValues() == 2 &&
8368 AddcNode->getValueType(0) == MVT::i32 &&
8369 "Expect ADDC with two result values. First: i32");
8371 // Check that we have a glued ADDC node.
8372 if (AddcNode->getValueType(1) != MVT::Glue)
8375 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8376 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8377 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8378 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8379 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8382 // Look for the glued ADDE.
8383 SDNode* AddeNode = AddcNode->getGluedUser();
8384 if (AddeNode == NULL)
8387 // Make sure it is really an ADDE.
8388 if (AddeNode->getOpcode() != ISD::ADDE)
8391 assert(AddeNode->getNumOperands() == 3 &&
8392 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8393 "ADDE node has the wrong inputs");
8395 // Check for the triangle shape.
8396 SDValue AddeOp0 = AddeNode->getOperand(0);
8397 SDValue AddeOp1 = AddeNode->getOperand(1);
8399 // Make sure that the ADDE operands are not coming from the same node.
8400 if (AddeOp0.getNode() == AddeOp1.getNode())
8403 // Find the MUL_LOHI node walking up ADDE's operands.
8404 bool IsLeftOperandMUL = false;
8405 SDValue MULOp = findMUL_LOHI(AddeOp0);
8406 if (MULOp == SDValue())
8407 MULOp = findMUL_LOHI(AddeOp1);
8409 IsLeftOperandMUL = true;
8410 if (MULOp == SDValue())
8413 // Figure out the right opcode.
8414 unsigned Opc = MULOp->getOpcode();
8415 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8417 // Figure out the high and low input values to the MLAL node.
8418 SDValue* HiMul = &MULOp;
8419 SDValue* HiAdd = NULL;
8420 SDValue* LoMul = NULL;
8421 SDValue* LowAdd = NULL;
8423 if (IsLeftOperandMUL)
8429 if (AddcOp0->getOpcode() == Opc) {
8433 if (AddcOp1->getOpcode() == Opc) {
8441 if (LoMul->getNode() != HiMul->getNode())
8444 // Create the merged node.
8445 SelectionDAG &DAG = DCI.DAG;
8447 // Build operand list.
8448 SmallVector<SDValue, 8> Ops;
8449 Ops.push_back(LoMul->getOperand(0));
8450 Ops.push_back(LoMul->getOperand(1));
8451 Ops.push_back(*LowAdd);
8452 Ops.push_back(*HiAdd);
8454 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8455 DAG.getVTList(MVT::i32, MVT::i32),
8456 &Ops[0], Ops.size());
8458 // Replace the ADDs' nodes uses by the MLA node's values.
8459 SDValue HiMLALResult(MLALNode.getNode(), 1);
8460 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8462 SDValue LoMLALResult(MLALNode.getNode(), 0);
8463 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8465 // Return original node to notify the driver to stop replacing.
8466 SDValue resNode(AddcNode, 0);
8470 /// PerformADDCCombine - Target-specific dag combine transform from
8471 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8472 static SDValue PerformADDCCombine(SDNode *N,
8473 TargetLowering::DAGCombinerInfo &DCI,
8474 const ARMSubtarget *Subtarget) {
8476 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8480 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8481 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8482 /// called with the default operands, and if that fails, with commuted
8484 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8485 TargetLowering::DAGCombinerInfo &DCI,
8486 const ARMSubtarget *Subtarget){
8488 // Attempt to create vpaddl for this add.
8489 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8490 if (Result.getNode())
8493 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8494 if (N0.getNode()->hasOneUse()) {
8495 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8496 if (Result.getNode()) return Result;
8501 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8503 static SDValue PerformADDCombine(SDNode *N,
8504 TargetLowering::DAGCombinerInfo &DCI,
8505 const ARMSubtarget *Subtarget) {
8506 SDValue N0 = N->getOperand(0);
8507 SDValue N1 = N->getOperand(1);
8509 // First try with the default operand order.
8510 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8511 if (Result.getNode())
8514 // If that didn't work, try again with the operands commuted.
8515 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8518 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8520 static SDValue PerformSUBCombine(SDNode *N,
8521 TargetLowering::DAGCombinerInfo &DCI) {
8522 SDValue N0 = N->getOperand(0);
8523 SDValue N1 = N->getOperand(1);
8525 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8526 if (N1.getNode()->hasOneUse()) {
8527 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8528 if (Result.getNode()) return Result;
8534 /// PerformVMULCombine
8535 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8536 /// special multiplier accumulator forwarding.
8542 // However, for (A + B) * (A + B),
8549 static SDValue PerformVMULCombine(SDNode *N,
8550 TargetLowering::DAGCombinerInfo &DCI,
8551 const ARMSubtarget *Subtarget) {
8552 if (!Subtarget->hasVMLxForwarding())
8555 SelectionDAG &DAG = DCI.DAG;
8556 SDValue N0 = N->getOperand(0);
8557 SDValue N1 = N->getOperand(1);
8558 unsigned Opcode = N0.getOpcode();
8559 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8560 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8561 Opcode = N1.getOpcode();
8562 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8563 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8571 EVT VT = N->getValueType(0);
8573 SDValue N00 = N0->getOperand(0);
8574 SDValue N01 = N0->getOperand(1);
8575 return DAG.getNode(Opcode, DL, VT,
8576 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8577 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8580 static SDValue PerformMULCombine(SDNode *N,
8581 TargetLowering::DAGCombinerInfo &DCI,
8582 const ARMSubtarget *Subtarget) {
8583 SelectionDAG &DAG = DCI.DAG;
8585 if (Subtarget->isThumb1Only())
8588 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8591 EVT VT = N->getValueType(0);
8592 if (VT.is64BitVector() || VT.is128BitVector())
8593 return PerformVMULCombine(N, DCI, Subtarget);
8597 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8601 int64_t MulAmt = C->getSExtValue();
8602 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8604 ShiftAmt = ShiftAmt & (32 - 1);
8605 SDValue V = N->getOperand(0);
8609 MulAmt >>= ShiftAmt;
8612 if (isPowerOf2_32(MulAmt - 1)) {
8613 // (mul x, 2^N + 1) => (add (shl x, N), x)
8614 Res = DAG.getNode(ISD::ADD, DL, VT,
8616 DAG.getNode(ISD::SHL, DL, VT,
8618 DAG.getConstant(Log2_32(MulAmt - 1),
8620 } else if (isPowerOf2_32(MulAmt + 1)) {
8621 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8622 Res = DAG.getNode(ISD::SUB, DL, VT,
8623 DAG.getNode(ISD::SHL, DL, VT,
8625 DAG.getConstant(Log2_32(MulAmt + 1),
8631 uint64_t MulAmtAbs = -MulAmt;
8632 if (isPowerOf2_32(MulAmtAbs + 1)) {
8633 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8634 Res = DAG.getNode(ISD::SUB, DL, VT,
8636 DAG.getNode(ISD::SHL, DL, VT,
8638 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8640 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8641 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8642 Res = DAG.getNode(ISD::ADD, DL, VT,
8644 DAG.getNode(ISD::SHL, DL, VT,
8646 DAG.getConstant(Log2_32(MulAmtAbs-1),
8648 Res = DAG.getNode(ISD::SUB, DL, VT,
8649 DAG.getConstant(0, MVT::i32),Res);
8656 Res = DAG.getNode(ISD::SHL, DL, VT,
8657 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8659 // Do not add new nodes to DAG combiner worklist.
8660 DCI.CombineTo(N, Res, false);
8664 static SDValue PerformANDCombine(SDNode *N,
8665 TargetLowering::DAGCombinerInfo &DCI,
8666 const ARMSubtarget *Subtarget) {
8668 // Attempt to use immediate-form VBIC
8669 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8671 EVT VT = N->getValueType(0);
8672 SelectionDAG &DAG = DCI.DAG;
8674 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8677 APInt SplatBits, SplatUndef;
8678 unsigned SplatBitSize;
8681 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8682 if (SplatBitSize <= 64) {
8684 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8685 SplatUndef.getZExtValue(), SplatBitSize,
8686 DAG, VbicVT, VT.is128BitVector(),
8688 if (Val.getNode()) {
8690 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8691 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8692 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8697 if (!Subtarget->isThumb1Only()) {
8698 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8699 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8700 if (Result.getNode())
8707 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8708 static SDValue PerformORCombine(SDNode *N,
8709 TargetLowering::DAGCombinerInfo &DCI,
8710 const ARMSubtarget *Subtarget) {
8711 // Attempt to use immediate-form VORR
8712 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8714 EVT VT = N->getValueType(0);
8715 SelectionDAG &DAG = DCI.DAG;
8717 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8720 APInt SplatBits, SplatUndef;
8721 unsigned SplatBitSize;
8723 if (BVN && Subtarget->hasNEON() &&
8724 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8725 if (SplatBitSize <= 64) {
8727 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8728 SplatUndef.getZExtValue(), SplatBitSize,
8729 DAG, VorrVT, VT.is128BitVector(),
8731 if (Val.getNode()) {
8733 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8734 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8735 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8740 if (!Subtarget->isThumb1Only()) {
8741 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8742 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8743 if (Result.getNode())
8747 // The code below optimizes (or (and X, Y), Z).
8748 // The AND operand needs to have a single user to make these optimizations
8750 SDValue N0 = N->getOperand(0);
8751 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8753 SDValue N1 = N->getOperand(1);
8755 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8756 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8757 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8759 unsigned SplatBitSize;
8762 APInt SplatBits0, SplatBits1;
8763 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8764 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8765 // Ensure that the second operand of both ands are constants
8766 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8767 HasAnyUndefs) && !HasAnyUndefs) {
8768 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8769 HasAnyUndefs) && !HasAnyUndefs) {
8770 // Ensure that the bit width of the constants are the same and that
8771 // the splat arguments are logical inverses as per the pattern we
8772 // are trying to simplify.
8773 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8774 SplatBits0 == ~SplatBits1) {
8775 // Canonicalize the vector type to make instruction selection
8777 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8778 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8782 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8788 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8791 // BFI is only available on V6T2+
8792 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8796 // 1) or (and A, mask), val => ARMbfi A, val, mask
8797 // iff (val & mask) == val
8799 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8800 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8801 // && mask == ~mask2
8802 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8803 // && ~mask == mask2
8804 // (i.e., copy a bitfield value into another bitfield of the same width)
8809 SDValue N00 = N0.getOperand(0);
8811 // The value and the mask need to be constants so we can verify this is
8812 // actually a bitfield set. If the mask is 0xffff, we can do better
8813 // via a movt instruction, so don't use BFI in that case.
8814 SDValue MaskOp = N0.getOperand(1);
8815 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8818 unsigned Mask = MaskC->getZExtValue();
8822 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8823 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8825 unsigned Val = N1C->getZExtValue();
8826 if ((Val & ~Mask) != Val)
8829 if (ARM::isBitFieldInvertedMask(Mask)) {
8830 Val >>= countTrailingZeros(~Mask);
8832 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8833 DAG.getConstant(Val, MVT::i32),
8834 DAG.getConstant(Mask, MVT::i32));
8836 // Do not add new nodes to DAG combiner worklist.
8837 DCI.CombineTo(N, Res, false);
8840 } else if (N1.getOpcode() == ISD::AND) {
8841 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8842 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8845 unsigned Mask2 = N11C->getZExtValue();
8847 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8849 if (ARM::isBitFieldInvertedMask(Mask) &&
8851 // The pack halfword instruction works better for masks that fit it,
8852 // so use that when it's available.
8853 if (Subtarget->hasT2ExtractPack() &&
8854 (Mask == 0xffff || Mask == 0xffff0000))
8857 unsigned amt = countTrailingZeros(Mask2);
8858 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8859 DAG.getConstant(amt, MVT::i32));
8860 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8861 DAG.getConstant(Mask, MVT::i32));
8862 // Do not add new nodes to DAG combiner worklist.
8863 DCI.CombineTo(N, Res, false);
8865 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8867 // The pack halfword instruction works better for masks that fit it,
8868 // so use that when it's available.
8869 if (Subtarget->hasT2ExtractPack() &&
8870 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8873 unsigned lsb = countTrailingZeros(Mask);
8874 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8875 DAG.getConstant(lsb, MVT::i32));
8876 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8877 DAG.getConstant(Mask2, MVT::i32));
8878 // Do not add new nodes to DAG combiner worklist.
8879 DCI.CombineTo(N, Res, false);
8884 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8885 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8886 ARM::isBitFieldInvertedMask(~Mask)) {
8887 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8888 // where lsb(mask) == #shamt and masked bits of B are known zero.
8889 SDValue ShAmt = N00.getOperand(1);
8890 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8891 unsigned LSB = countTrailingZeros(Mask);
8895 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8896 DAG.getConstant(~Mask, MVT::i32));
8898 // Do not add new nodes to DAG combiner worklist.
8899 DCI.CombineTo(N, Res, false);
8905 static SDValue PerformXORCombine(SDNode *N,
8906 TargetLowering::DAGCombinerInfo &DCI,
8907 const ARMSubtarget *Subtarget) {
8908 EVT VT = N->getValueType(0);
8909 SelectionDAG &DAG = DCI.DAG;
8911 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8914 if (!Subtarget->isThumb1Only()) {
8915 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8916 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8917 if (Result.getNode())
8924 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8925 /// the bits being cleared by the AND are not demanded by the BFI.
8926 static SDValue PerformBFICombine(SDNode *N,
8927 TargetLowering::DAGCombinerInfo &DCI) {
8928 SDValue N1 = N->getOperand(1);
8929 if (N1.getOpcode() == ISD::AND) {
8930 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8933 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8934 unsigned LSB = countTrailingZeros(~InvMask);
8935 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8936 unsigned Mask = (1 << Width)-1;
8937 unsigned Mask2 = N11C->getZExtValue();
8938 if ((Mask & (~Mask2)) == 0)
8939 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8940 N->getOperand(0), N1.getOperand(0),
8946 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8947 /// ARMISD::VMOVRRD.
8948 static SDValue PerformVMOVRRDCombine(SDNode *N,
8949 TargetLowering::DAGCombinerInfo &DCI) {
8950 // vmovrrd(vmovdrr x, y) -> x,y
8951 SDValue InDouble = N->getOperand(0);
8952 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8953 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8955 // vmovrrd(load f64) -> (load i32), (load i32)
8956 SDNode *InNode = InDouble.getNode();
8957 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8958 InNode->getValueType(0) == MVT::f64 &&
8959 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8960 !cast<LoadSDNode>(InNode)->isVolatile()) {
8961 // TODO: Should this be done for non-FrameIndex operands?
8962 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8964 SelectionDAG &DAG = DCI.DAG;
8966 SDValue BasePtr = LD->getBasePtr();
8967 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8968 LD->getPointerInfo(), LD->isVolatile(),
8969 LD->isNonTemporal(), LD->isInvariant(),
8970 LD->getAlignment());
8972 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8973 DAG.getConstant(4, MVT::i32));
8974 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8975 LD->getPointerInfo(), LD->isVolatile(),
8976 LD->isNonTemporal(), LD->isInvariant(),
8977 std::min(4U, LD->getAlignment() / 2));
8979 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8980 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8981 DCI.RemoveFromWorklist(LD);
8989 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8990 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8991 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8992 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8993 SDValue Op0 = N->getOperand(0);
8994 SDValue Op1 = N->getOperand(1);
8995 if (Op0.getOpcode() == ISD::BITCAST)
8996 Op0 = Op0.getOperand(0);
8997 if (Op1.getOpcode() == ISD::BITCAST)
8998 Op1 = Op1.getOperand(0);
8999 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9000 Op0.getNode() == Op1.getNode() &&
9001 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9002 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9003 N->getValueType(0), Op0.getOperand(0));
9007 /// PerformSTORECombine - Target-specific dag combine xforms for
9009 static SDValue PerformSTORECombine(SDNode *N,
9010 TargetLowering::DAGCombinerInfo &DCI) {
9011 StoreSDNode *St = cast<StoreSDNode>(N);
9012 if (St->isVolatile())
9015 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9016 // pack all of the elements in one place. Next, store to memory in fewer
9018 SDValue StVal = St->getValue();
9019 EVT VT = StVal.getValueType();
9020 if (St->isTruncatingStore() && VT.isVector()) {
9021 SelectionDAG &DAG = DCI.DAG;
9022 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9023 EVT StVT = St->getMemoryVT();
9024 unsigned NumElems = VT.getVectorNumElements();
9025 assert(StVT != VT && "Cannot truncate to the same type");
9026 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9027 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9029 // From, To sizes and ElemCount must be pow of two
9030 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9032 // We are going to use the original vector elt for storing.
9033 // Accumulated smaller vector elements must be a multiple of the store size.
9034 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9036 unsigned SizeRatio = FromEltSz / ToEltSz;
9037 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9039 // Create a type on which we perform the shuffle.
9040 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9041 NumElems*SizeRatio);
9042 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9045 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9046 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9047 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
9049 // Can't shuffle using an illegal type.
9050 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9052 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9053 DAG.getUNDEF(WideVec.getValueType()),
9055 // At this point all of the data is stored at the bottom of the
9056 // register. We now need to save it to mem.
9058 // Find the largest store unit
9059 MVT StoreType = MVT::i8;
9060 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
9061 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9062 MVT Tp = (MVT::SimpleValueType)tp;
9063 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9066 // Didn't find a legal store type.
9067 if (!TLI.isTypeLegal(StoreType))
9070 // Bitcast the original vector into a vector of store-size units
9071 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9072 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9073 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9074 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9075 SmallVector<SDValue, 8> Chains;
9076 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9077 TLI.getPointerTy());
9078 SDValue BasePtr = St->getBasePtr();
9080 // Perform one or more big stores into memory.
9081 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9082 for (unsigned I = 0; I < E; I++) {
9083 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9084 StoreType, ShuffWide,
9085 DAG.getIntPtrConstant(I));
9086 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9087 St->getPointerInfo(), St->isVolatile(),
9088 St->isNonTemporal(), St->getAlignment());
9089 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9091 Chains.push_back(Ch);
9093 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9097 if (!ISD::isNormalStore(St))
9100 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9101 // ARM stores of arguments in the same cache line.
9102 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9103 StVal.getNode()->hasOneUse()) {
9104 SelectionDAG &DAG = DCI.DAG;
9106 SDValue BasePtr = St->getBasePtr();
9107 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9108 StVal.getNode()->getOperand(0), BasePtr,
9109 St->getPointerInfo(), St->isVolatile(),
9110 St->isNonTemporal(), St->getAlignment());
9112 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9113 DAG.getConstant(4, MVT::i32));
9114 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9115 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9116 St->isNonTemporal(),
9117 std::min(4U, St->getAlignment() / 2));
9120 if (StVal.getValueType() != MVT::i64 ||
9121 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9124 // Bitcast an i64 store extracted from a vector to f64.
9125 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9126 SelectionDAG &DAG = DCI.DAG;
9128 SDValue IntVec = StVal.getOperand(0);
9129 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9130 IntVec.getValueType().getVectorNumElements());
9131 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9132 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9133 Vec, StVal.getOperand(1));
9135 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9136 // Make the DAGCombiner fold the bitcasts.
9137 DCI.AddToWorklist(Vec.getNode());
9138 DCI.AddToWorklist(ExtElt.getNode());
9139 DCI.AddToWorklist(V.getNode());
9140 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9141 St->getPointerInfo(), St->isVolatile(),
9142 St->isNonTemporal(), St->getAlignment(),
9146 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9147 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9148 /// i64 vector to have f64 elements, since the value can then be loaded
9149 /// directly into a VFP register.
9150 static bool hasNormalLoadOperand(SDNode *N) {
9151 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9152 for (unsigned i = 0; i < NumElts; ++i) {
9153 SDNode *Elt = N->getOperand(i).getNode();
9154 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9160 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9161 /// ISD::BUILD_VECTOR.
9162 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9163 TargetLowering::DAGCombinerInfo &DCI){
9164 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9165 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9166 // into a pair of GPRs, which is fine when the value is used as a scalar,
9167 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9168 SelectionDAG &DAG = DCI.DAG;
9169 if (N->getNumOperands() == 2) {
9170 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9175 // Load i64 elements as f64 values so that type legalization does not split
9176 // them up into i32 values.
9177 EVT VT = N->getValueType(0);
9178 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9181 SmallVector<SDValue, 8> Ops;
9182 unsigned NumElts = VT.getVectorNumElements();
9183 for (unsigned i = 0; i < NumElts; ++i) {
9184 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9186 // Make the DAGCombiner fold the bitcast.
9187 DCI.AddToWorklist(V.getNode());
9189 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9190 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9191 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9194 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9196 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9197 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9198 // At that time, we may have inserted bitcasts from integer to float.
9199 // If these bitcasts have survived DAGCombine, change the lowering of this
9200 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9201 // force to use floating point types.
9203 // Make sure we can change the type of the vector.
9204 // This is possible iff:
9205 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9206 // 1.1. Vector is used only once.
9207 // 1.2. Use is a bit convert to an integer type.
9208 // 2. The size of its operands are 32-bits (64-bits are not legal).
9209 EVT VT = N->getValueType(0);
9210 EVT EltVT = VT.getVectorElementType();
9212 // Check 1.1. and 2.
9213 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9216 // By construction, the input type must be float.
9217 assert(EltVT == MVT::f32 && "Unexpected type!");
9220 SDNode *Use = *N->use_begin();
9221 if (Use->getOpcode() != ISD::BITCAST ||
9222 Use->getValueType(0).isFloatingPoint())
9225 // Check profitability.
9226 // Model is, if more than half of the relevant operands are bitcast from
9227 // i32, turn the build_vector into a sequence of insert_vector_elt.
9228 // Relevant operands are everything that is not statically
9229 // (i.e., at compile time) bitcasted.
9230 unsigned NumOfBitCastedElts = 0;
9231 unsigned NumElts = VT.getVectorNumElements();
9232 unsigned NumOfRelevantElts = NumElts;
9233 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9234 SDValue Elt = N->getOperand(Idx);
9235 if (Elt->getOpcode() == ISD::BITCAST) {
9236 // Assume only bit cast to i32 will go away.
9237 if (Elt->getOperand(0).getValueType() == MVT::i32)
9238 ++NumOfBitCastedElts;
9239 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9240 // Constants are statically casted, thus do not count them as
9241 // relevant operands.
9242 --NumOfRelevantElts;
9245 // Check if more than half of the elements require a non-free bitcast.
9246 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9249 SelectionDAG &DAG = DCI.DAG;
9250 // Create the new vector type.
9251 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9252 // Check if the type is legal.
9253 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9254 if (!TLI.isTypeLegal(VecVT))
9258 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9259 // => BITCAST INSERT_VECTOR_ELT
9260 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9262 SDValue Vec = DAG.getUNDEF(VecVT);
9264 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9265 SDValue V = N->getOperand(Idx);
9266 if (V.getOpcode() == ISD::UNDEF)
9268 if (V.getOpcode() == ISD::BITCAST &&
9269 V->getOperand(0).getValueType() == MVT::i32)
9270 // Fold obvious case.
9271 V = V.getOperand(0);
9273 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9274 // Make the DAGCombiner fold the bitcasts.
9275 DCI.AddToWorklist(V.getNode());
9277 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9278 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9280 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9281 // Make the DAGCombiner fold the bitcasts.
9282 DCI.AddToWorklist(Vec.getNode());
9286 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9287 /// ISD::INSERT_VECTOR_ELT.
9288 static SDValue PerformInsertEltCombine(SDNode *N,
9289 TargetLowering::DAGCombinerInfo &DCI) {
9290 // Bitcast an i64 load inserted into a vector to f64.
9291 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9292 EVT VT = N->getValueType(0);
9293 SDNode *Elt = N->getOperand(1).getNode();
9294 if (VT.getVectorElementType() != MVT::i64 ||
9295 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9298 SelectionDAG &DAG = DCI.DAG;
9300 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9301 VT.getVectorNumElements());
9302 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9303 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9304 // Make the DAGCombiner fold the bitcasts.
9305 DCI.AddToWorklist(Vec.getNode());
9306 DCI.AddToWorklist(V.getNode());
9307 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9308 Vec, V, N->getOperand(2));
9309 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9312 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9313 /// ISD::VECTOR_SHUFFLE.
9314 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9315 // The LLVM shufflevector instruction does not require the shuffle mask
9316 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9317 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9318 // operands do not match the mask length, they are extended by concatenating
9319 // them with undef vectors. That is probably the right thing for other
9320 // targets, but for NEON it is better to concatenate two double-register
9321 // size vector operands into a single quad-register size vector. Do that
9322 // transformation here:
9323 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9324 // shuffle(concat(v1, v2), undef)
9325 SDValue Op0 = N->getOperand(0);
9326 SDValue Op1 = N->getOperand(1);
9327 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9328 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9329 Op0.getNumOperands() != 2 ||
9330 Op1.getNumOperands() != 2)
9332 SDValue Concat0Op1 = Op0.getOperand(1);
9333 SDValue Concat1Op1 = Op1.getOperand(1);
9334 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9335 Concat1Op1.getOpcode() != ISD::UNDEF)
9337 // Skip the transformation if any of the types are illegal.
9338 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9339 EVT VT = N->getValueType(0);
9340 if (!TLI.isTypeLegal(VT) ||
9341 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9342 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9345 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9346 Op0.getOperand(0), Op1.getOperand(0));
9347 // Translate the shuffle mask.
9348 SmallVector<int, 16> NewMask;
9349 unsigned NumElts = VT.getVectorNumElements();
9350 unsigned HalfElts = NumElts/2;
9351 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9352 for (unsigned n = 0; n < NumElts; ++n) {
9353 int MaskElt = SVN->getMaskElt(n);
9355 if (MaskElt < (int)HalfElts)
9357 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9358 NewElt = HalfElts + MaskElt - NumElts;
9359 NewMask.push_back(NewElt);
9361 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9362 DAG.getUNDEF(VT), NewMask.data());
9365 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9366 /// NEON load/store intrinsics to merge base address updates.
9367 static SDValue CombineBaseUpdate(SDNode *N,
9368 TargetLowering::DAGCombinerInfo &DCI) {
9369 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9372 SelectionDAG &DAG = DCI.DAG;
9373 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9374 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9375 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9376 SDValue Addr = N->getOperand(AddrOpIdx);
9378 // Search for a use of the address operand that is an increment.
9379 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9380 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9382 if (User->getOpcode() != ISD::ADD ||
9383 UI.getUse().getResNo() != Addr.getResNo())
9386 // Check that the add is independent of the load/store. Otherwise, folding
9387 // it would create a cycle.
9388 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9391 // Find the new opcode for the updating load/store.
9393 bool isLaneOp = false;
9394 unsigned NewOpc = 0;
9395 unsigned NumVecs = 0;
9397 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9399 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9400 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9402 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9404 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9406 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9408 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9409 NumVecs = 2; isLaneOp = true; break;
9410 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9411 NumVecs = 3; isLaneOp = true; break;
9412 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9413 NumVecs = 4; isLaneOp = true; break;
9414 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9415 NumVecs = 1; isLoad = false; break;
9416 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9417 NumVecs = 2; isLoad = false; break;
9418 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9419 NumVecs = 3; isLoad = false; break;
9420 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9421 NumVecs = 4; isLoad = false; break;
9422 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9423 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9424 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9425 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9426 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9427 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9431 switch (N->getOpcode()) {
9432 default: llvm_unreachable("unexpected opcode for Neon base update");
9433 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9434 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9435 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9439 // Find the size of memory referenced by the load/store.
9442 VecTy = N->getValueType(0);
9444 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9445 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9447 NumBytes /= VecTy.getVectorNumElements();
9449 // If the increment is a constant, it must match the memory ref size.
9450 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9451 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9452 uint64_t IncVal = CInc->getZExtValue();
9453 if (IncVal != NumBytes)
9455 } else if (NumBytes >= 3 * 16) {
9456 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9457 // separate instructions that make it harder to use a non-constant update.
9461 // Create the new updating load/store node.
9463 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9465 for (n = 0; n < NumResultVecs; ++n)
9467 Tys[n++] = MVT::i32;
9468 Tys[n] = MVT::Other;
9469 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9470 SmallVector<SDValue, 8> Ops;
9471 Ops.push_back(N->getOperand(0)); // incoming chain
9472 Ops.push_back(N->getOperand(AddrOpIdx));
9474 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9475 Ops.push_back(N->getOperand(i));
9477 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9478 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9479 Ops.data(), Ops.size(),
9480 MemInt->getMemoryVT(),
9481 MemInt->getMemOperand());
9484 std::vector<SDValue> NewResults;
9485 for (unsigned i = 0; i < NumResultVecs; ++i) {
9486 NewResults.push_back(SDValue(UpdN.getNode(), i));
9488 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9489 DCI.CombineTo(N, NewResults);
9490 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9497 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9498 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9499 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9501 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9502 SelectionDAG &DAG = DCI.DAG;
9503 EVT VT = N->getValueType(0);
9504 // vldN-dup instructions only support 64-bit vectors for N > 1.
9505 if (!VT.is64BitVector())
9508 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9509 SDNode *VLD = N->getOperand(0).getNode();
9510 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9512 unsigned NumVecs = 0;
9513 unsigned NewOpc = 0;
9514 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9515 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9517 NewOpc = ARMISD::VLD2DUP;
9518 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9520 NewOpc = ARMISD::VLD3DUP;
9521 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9523 NewOpc = ARMISD::VLD4DUP;
9528 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9529 // numbers match the load.
9530 unsigned VLDLaneNo =
9531 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9532 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9534 // Ignore uses of the chain result.
9535 if (UI.getUse().getResNo() == NumVecs)
9538 if (User->getOpcode() != ARMISD::VDUPLANE ||
9539 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9543 // Create the vldN-dup node.
9546 for (n = 0; n < NumVecs; ++n)
9548 Tys[n] = MVT::Other;
9549 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9550 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9551 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9552 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9553 Ops, 2, VLDMemInt->getMemoryVT(),
9554 VLDMemInt->getMemOperand());
9557 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9559 unsigned ResNo = UI.getUse().getResNo();
9560 // Ignore uses of the chain result.
9561 if (ResNo == NumVecs)
9564 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9567 // Now the vldN-lane intrinsic is dead except for its chain result.
9568 // Update uses of the chain.
9569 std::vector<SDValue> VLDDupResults;
9570 for (unsigned n = 0; n < NumVecs; ++n)
9571 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9572 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9573 DCI.CombineTo(VLD, VLDDupResults);
9578 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9579 /// ARMISD::VDUPLANE.
9580 static SDValue PerformVDUPLANECombine(SDNode *N,
9581 TargetLowering::DAGCombinerInfo &DCI) {
9582 SDValue Op = N->getOperand(0);
9584 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9585 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9586 if (CombineVLDDUP(N, DCI))
9587 return SDValue(N, 0);
9589 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9590 // redundant. Ignore bit_converts for now; element sizes are checked below.
9591 while (Op.getOpcode() == ISD::BITCAST)
9592 Op = Op.getOperand(0);
9593 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9596 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9597 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9598 // The canonical VMOV for a zero vector uses a 32-bit element size.
9599 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9601 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9603 EVT VT = N->getValueType(0);
9604 if (EltSize > VT.getVectorElementType().getSizeInBits())
9607 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9610 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9611 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9612 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9616 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9618 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9623 APFloat APF = C->getValueAPF();
9624 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9625 != APFloat::opOK || !isExact)
9628 c0 = (I == 0) ? cN : c0;
9629 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9636 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9637 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9638 /// when the VMUL has a constant operand that is a power of 2.
9640 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9641 /// vmul.f32 d16, d17, d16
9642 /// vcvt.s32.f32 d16, d16
9644 /// vcvt.s32.f32 d16, d16, #3
9645 static SDValue PerformVCVTCombine(SDNode *N,
9646 TargetLowering::DAGCombinerInfo &DCI,
9647 const ARMSubtarget *Subtarget) {
9648 SelectionDAG &DAG = DCI.DAG;
9649 SDValue Op = N->getOperand(0);
9651 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9652 Op.getOpcode() != ISD::FMUL)
9656 SDValue N0 = Op->getOperand(0);
9657 SDValue ConstVec = Op->getOperand(1);
9658 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9660 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9661 !isConstVecPow2(ConstVec, isSigned, C))
9664 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9665 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9666 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9667 // These instructions only exist converting from f32 to i32. We can handle
9668 // smaller integers by generating an extra truncate, but larger ones would
9673 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9674 Intrinsic::arm_neon_vcvtfp2fxu;
9675 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9676 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9677 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9678 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9679 DAG.getConstant(Log2_64(C), MVT::i32));
9681 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9682 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9687 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9688 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9689 /// when the VDIV has a constant operand that is a power of 2.
9691 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9692 /// vcvt.f32.s32 d16, d16
9693 /// vdiv.f32 d16, d17, d16
9695 /// vcvt.f32.s32 d16, d16, #3
9696 static SDValue PerformVDIVCombine(SDNode *N,
9697 TargetLowering::DAGCombinerInfo &DCI,
9698 const ARMSubtarget *Subtarget) {
9699 SelectionDAG &DAG = DCI.DAG;
9700 SDValue Op = N->getOperand(0);
9701 unsigned OpOpcode = Op.getNode()->getOpcode();
9703 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9704 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9708 SDValue ConstVec = N->getOperand(1);
9709 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9711 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9712 !isConstVecPow2(ConstVec, isSigned, C))
9715 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9716 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9717 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9718 // These instructions only exist converting from i32 to f32. We can handle
9719 // smaller integers by generating an extra extend, but larger ones would
9724 SDValue ConvInput = Op.getOperand(0);
9725 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9726 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9727 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9728 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9731 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9732 Intrinsic::arm_neon_vcvtfxu2fp;
9733 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9735 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9736 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9739 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9740 /// operand of a vector shift operation, where all the elements of the
9741 /// build_vector must have the same constant integer value.
9742 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9743 // Ignore bit_converts.
9744 while (Op.getOpcode() == ISD::BITCAST)
9745 Op = Op.getOperand(0);
9746 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9747 APInt SplatBits, SplatUndef;
9748 unsigned SplatBitSize;
9750 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9751 HasAnyUndefs, ElementBits) ||
9752 SplatBitSize > ElementBits)
9754 Cnt = SplatBits.getSExtValue();
9758 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9759 /// operand of a vector shift left operation. That value must be in the range:
9760 /// 0 <= Value < ElementBits for a left shift; or
9761 /// 0 <= Value <= ElementBits for a long left shift.
9762 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9763 assert(VT.isVector() && "vector shift count is not a vector type");
9764 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9765 if (! getVShiftImm(Op, ElementBits, Cnt))
9767 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9770 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9771 /// operand of a vector shift right operation. For a shift opcode, the value
9772 /// is positive, but for an intrinsic the value count must be negative. The
9773 /// absolute value must be in the range:
9774 /// 1 <= |Value| <= ElementBits for a right shift; or
9775 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9776 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9778 assert(VT.isVector() && "vector shift count is not a vector type");
9779 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9780 if (! getVShiftImm(Op, ElementBits, Cnt))
9784 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9787 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9788 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9789 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9792 // Don't do anything for most intrinsics.
9795 // Vector shifts: check for immediate versions and lower them.
9796 // Note: This is done during DAG combining instead of DAG legalizing because
9797 // the build_vectors for 64-bit vector element shift counts are generally
9798 // not legal, and it is hard to see their values after they get legalized to
9799 // loads from a constant pool.
9800 case Intrinsic::arm_neon_vshifts:
9801 case Intrinsic::arm_neon_vshiftu:
9802 case Intrinsic::arm_neon_vshiftls:
9803 case Intrinsic::arm_neon_vshiftlu:
9804 case Intrinsic::arm_neon_vshiftn:
9805 case Intrinsic::arm_neon_vrshifts:
9806 case Intrinsic::arm_neon_vrshiftu:
9807 case Intrinsic::arm_neon_vrshiftn:
9808 case Intrinsic::arm_neon_vqshifts:
9809 case Intrinsic::arm_neon_vqshiftu:
9810 case Intrinsic::arm_neon_vqshiftsu:
9811 case Intrinsic::arm_neon_vqshiftns:
9812 case Intrinsic::arm_neon_vqshiftnu:
9813 case Intrinsic::arm_neon_vqshiftnsu:
9814 case Intrinsic::arm_neon_vqrshiftns:
9815 case Intrinsic::arm_neon_vqrshiftnu:
9816 case Intrinsic::arm_neon_vqrshiftnsu: {
9817 EVT VT = N->getOperand(1).getValueType();
9819 unsigned VShiftOpc = 0;
9822 case Intrinsic::arm_neon_vshifts:
9823 case Intrinsic::arm_neon_vshiftu:
9824 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9825 VShiftOpc = ARMISD::VSHL;
9828 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9829 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9830 ARMISD::VSHRs : ARMISD::VSHRu);
9835 case Intrinsic::arm_neon_vshiftls:
9836 case Intrinsic::arm_neon_vshiftlu:
9837 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9839 llvm_unreachable("invalid shift count for vshll intrinsic");
9841 case Intrinsic::arm_neon_vrshifts:
9842 case Intrinsic::arm_neon_vrshiftu:
9843 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9847 case Intrinsic::arm_neon_vqshifts:
9848 case Intrinsic::arm_neon_vqshiftu:
9849 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9853 case Intrinsic::arm_neon_vqshiftsu:
9854 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9856 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9858 case Intrinsic::arm_neon_vshiftn:
9859 case Intrinsic::arm_neon_vrshiftn:
9860 case Intrinsic::arm_neon_vqshiftns:
9861 case Intrinsic::arm_neon_vqshiftnu:
9862 case Intrinsic::arm_neon_vqshiftnsu:
9863 case Intrinsic::arm_neon_vqrshiftns:
9864 case Intrinsic::arm_neon_vqrshiftnu:
9865 case Intrinsic::arm_neon_vqrshiftnsu:
9866 // Narrowing shifts require an immediate right shift.
9867 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9869 llvm_unreachable("invalid shift count for narrowing vector shift "
9873 llvm_unreachable("unhandled vector shift");
9877 case Intrinsic::arm_neon_vshifts:
9878 case Intrinsic::arm_neon_vshiftu:
9879 // Opcode already set above.
9881 case Intrinsic::arm_neon_vshiftls:
9882 case Intrinsic::arm_neon_vshiftlu:
9883 if (Cnt == VT.getVectorElementType().getSizeInBits())
9884 VShiftOpc = ARMISD::VSHLLi;
9886 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9887 ARMISD::VSHLLs : ARMISD::VSHLLu);
9889 case Intrinsic::arm_neon_vshiftn:
9890 VShiftOpc = ARMISD::VSHRN; break;
9891 case Intrinsic::arm_neon_vrshifts:
9892 VShiftOpc = ARMISD::VRSHRs; break;
9893 case Intrinsic::arm_neon_vrshiftu:
9894 VShiftOpc = ARMISD::VRSHRu; break;
9895 case Intrinsic::arm_neon_vrshiftn:
9896 VShiftOpc = ARMISD::VRSHRN; break;
9897 case Intrinsic::arm_neon_vqshifts:
9898 VShiftOpc = ARMISD::VQSHLs; break;
9899 case Intrinsic::arm_neon_vqshiftu:
9900 VShiftOpc = ARMISD::VQSHLu; break;
9901 case Intrinsic::arm_neon_vqshiftsu:
9902 VShiftOpc = ARMISD::VQSHLsu; break;
9903 case Intrinsic::arm_neon_vqshiftns:
9904 VShiftOpc = ARMISD::VQSHRNs; break;
9905 case Intrinsic::arm_neon_vqshiftnu:
9906 VShiftOpc = ARMISD::VQSHRNu; break;
9907 case Intrinsic::arm_neon_vqshiftnsu:
9908 VShiftOpc = ARMISD::VQSHRNsu; break;
9909 case Intrinsic::arm_neon_vqrshiftns:
9910 VShiftOpc = ARMISD::VQRSHRNs; break;
9911 case Intrinsic::arm_neon_vqrshiftnu:
9912 VShiftOpc = ARMISD::VQRSHRNu; break;
9913 case Intrinsic::arm_neon_vqrshiftnsu:
9914 VShiftOpc = ARMISD::VQRSHRNsu; break;
9917 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9918 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9921 case Intrinsic::arm_neon_vshiftins: {
9922 EVT VT = N->getOperand(1).getValueType();
9924 unsigned VShiftOpc = 0;
9926 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9927 VShiftOpc = ARMISD::VSLI;
9928 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9929 VShiftOpc = ARMISD::VSRI;
9931 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9934 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9935 N->getOperand(1), N->getOperand(2),
9936 DAG.getConstant(Cnt, MVT::i32));
9939 case Intrinsic::arm_neon_vqrshifts:
9940 case Intrinsic::arm_neon_vqrshiftu:
9941 // No immediate versions of these to check for.
9948 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9949 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9950 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9951 /// vector element shift counts are generally not legal, and it is hard to see
9952 /// their values after they get legalized to loads from a constant pool.
9953 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9954 const ARMSubtarget *ST) {
9955 EVT VT = N->getValueType(0);
9956 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9957 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9958 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9959 SDValue N1 = N->getOperand(1);
9960 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9961 SDValue N0 = N->getOperand(0);
9962 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9963 DAG.MaskedValueIsZero(N0.getOperand(0),
9964 APInt::getHighBitsSet(32, 16)))
9965 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9969 // Nothing to be done for scalar shifts.
9970 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9971 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9974 assert(ST->hasNEON() && "unexpected vector shift");
9977 switch (N->getOpcode()) {
9978 default: llvm_unreachable("unexpected shift opcode");
9981 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9982 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9983 DAG.getConstant(Cnt, MVT::i32));
9988 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9989 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9990 ARMISD::VSHRs : ARMISD::VSHRu);
9991 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9992 DAG.getConstant(Cnt, MVT::i32));
9998 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9999 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10000 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10001 const ARMSubtarget *ST) {
10002 SDValue N0 = N->getOperand(0);
10004 // Check for sign- and zero-extensions of vector extract operations of 8-
10005 // and 16-bit vector elements. NEON supports these directly. They are
10006 // handled during DAG combining because type legalization will promote them
10007 // to 32-bit types and it is messy to recognize the operations after that.
10008 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10009 SDValue Vec = N0.getOperand(0);
10010 SDValue Lane = N0.getOperand(1);
10011 EVT VT = N->getValueType(0);
10012 EVT EltVT = N0.getValueType();
10013 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10015 if (VT == MVT::i32 &&
10016 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10017 TLI.isTypeLegal(Vec.getValueType()) &&
10018 isa<ConstantSDNode>(Lane)) {
10021 switch (N->getOpcode()) {
10022 default: llvm_unreachable("unexpected opcode");
10023 case ISD::SIGN_EXTEND:
10024 Opc = ARMISD::VGETLANEs;
10026 case ISD::ZERO_EXTEND:
10027 case ISD::ANY_EXTEND:
10028 Opc = ARMISD::VGETLANEu;
10031 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10038 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10039 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10040 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10041 const ARMSubtarget *ST) {
10042 // If the target supports NEON, try to use vmax/vmin instructions for f32
10043 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
10044 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
10045 // a NaN; only do the transformation when it matches that behavior.
10047 // For now only do this when using NEON for FP operations; if using VFP, it
10048 // is not obvious that the benefit outweighs the cost of switching to the
10050 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10051 N->getValueType(0) != MVT::f32)
10054 SDValue CondLHS = N->getOperand(0);
10055 SDValue CondRHS = N->getOperand(1);
10056 SDValue LHS = N->getOperand(2);
10057 SDValue RHS = N->getOperand(3);
10058 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10060 unsigned Opcode = 0;
10062 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10063 IsReversed = false; // x CC y ? x : y
10064 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10065 IsReversed = true ; // x CC y ? y : x
10079 // If LHS is NaN, an ordered comparison will be false and the result will
10080 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
10081 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10082 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10083 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10085 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10086 // will return -0, so vmin can only be used for unsafe math or if one of
10087 // the operands is known to be nonzero.
10088 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10089 !DAG.getTarget().Options.UnsafeFPMath &&
10090 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10092 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10101 // If LHS is NaN, an ordered comparison will be false and the result will
10102 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
10103 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10104 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10105 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10107 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10108 // will return +0, so vmax can only be used for unsafe math or if one of
10109 // the operands is known to be nonzero.
10110 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10111 !DAG.getTarget().Options.UnsafeFPMath &&
10112 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10114 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10120 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10123 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10125 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10126 SDValue Cmp = N->getOperand(4);
10127 if (Cmp.getOpcode() != ARMISD::CMPZ)
10128 // Only looking at EQ and NE cases.
10131 EVT VT = N->getValueType(0);
10133 SDValue LHS = Cmp.getOperand(0);
10134 SDValue RHS = Cmp.getOperand(1);
10135 SDValue FalseVal = N->getOperand(0);
10136 SDValue TrueVal = N->getOperand(1);
10137 SDValue ARMcc = N->getOperand(2);
10138 ARMCC::CondCodes CC =
10139 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10157 /// FIXME: Turn this into a target neutral optimization?
10159 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10160 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10161 N->getOperand(3), Cmp);
10162 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10164 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10165 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10166 N->getOperand(3), NewCmp);
10169 if (Res.getNode()) {
10170 APInt KnownZero, KnownOne;
10171 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10172 // Capture demanded bits information that would be otherwise lost.
10173 if (KnownZero == 0xfffffffe)
10174 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10175 DAG.getValueType(MVT::i1));
10176 else if (KnownZero == 0xffffff00)
10177 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10178 DAG.getValueType(MVT::i8));
10179 else if (KnownZero == 0xffff0000)
10180 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10181 DAG.getValueType(MVT::i16));
10187 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10188 DAGCombinerInfo &DCI) const {
10189 switch (N->getOpcode()) {
10191 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10192 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10193 case ISD::SUB: return PerformSUBCombine(N, DCI);
10194 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10195 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10196 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10197 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10198 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10199 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10200 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10201 case ISD::STORE: return PerformSTORECombine(N, DCI);
10202 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10203 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10204 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10205 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10206 case ISD::FP_TO_SINT:
10207 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10208 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10209 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10212 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10213 case ISD::SIGN_EXTEND:
10214 case ISD::ZERO_EXTEND:
10215 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10216 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10217 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10218 case ARMISD::VLD2DUP:
10219 case ARMISD::VLD3DUP:
10220 case ARMISD::VLD4DUP:
10221 return CombineBaseUpdate(N, DCI);
10222 case ARMISD::BUILD_VECTOR:
10223 return PerformARMBUILD_VECTORCombine(N, DCI);
10224 case ISD::INTRINSIC_VOID:
10225 case ISD::INTRINSIC_W_CHAIN:
10226 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10227 case Intrinsic::arm_neon_vld1:
10228 case Intrinsic::arm_neon_vld2:
10229 case Intrinsic::arm_neon_vld3:
10230 case Intrinsic::arm_neon_vld4:
10231 case Intrinsic::arm_neon_vld2lane:
10232 case Intrinsic::arm_neon_vld3lane:
10233 case Intrinsic::arm_neon_vld4lane:
10234 case Intrinsic::arm_neon_vst1:
10235 case Intrinsic::arm_neon_vst2:
10236 case Intrinsic::arm_neon_vst3:
10237 case Intrinsic::arm_neon_vst4:
10238 case Intrinsic::arm_neon_vst2lane:
10239 case Intrinsic::arm_neon_vst3lane:
10240 case Intrinsic::arm_neon_vst4lane:
10241 return CombineBaseUpdate(N, DCI);
10249 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10251 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10254 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10255 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10256 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10258 switch (VT.getSimpleVT().SimpleTy) {
10264 // Unaligned access can use (for example) LRDB, LRDH, LDR
10265 if (AllowsUnaligned) {
10267 *Fast = Subtarget->hasV7Ops();
10274 // For any little-endian targets with neon, we can support unaligned ld/st
10275 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10276 // A big-endian target may also explictly support unaligned accesses
10277 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10287 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10288 unsigned AlignCheck) {
10289 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10290 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10293 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10294 unsigned DstAlign, unsigned SrcAlign,
10295 bool IsMemset, bool ZeroMemset,
10297 MachineFunction &MF) const {
10298 const Function *F = MF.getFunction();
10300 // See if we can use NEON instructions for this...
10301 if ((!IsMemset || ZeroMemset) &&
10302 Subtarget->hasNEON() &&
10303 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10304 Attribute::NoImplicitFloat)) {
10307 (memOpAlign(SrcAlign, DstAlign, 16) ||
10308 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10310 } else if (Size >= 8 &&
10311 (memOpAlign(SrcAlign, DstAlign, 8) ||
10312 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10317 // Lowering to i32/i16 if the size permits.
10320 else if (Size >= 2)
10323 // Let the target-independent logic figure it out.
10327 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10328 if (Val.getOpcode() != ISD::LOAD)
10331 EVT VT1 = Val.getValueType();
10332 if (!VT1.isSimple() || !VT1.isInteger() ||
10333 !VT2.isSimple() || !VT2.isInteger())
10336 switch (VT1.getSimpleVT().SimpleTy) {
10341 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10348 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10349 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10352 if (!isTypeLegal(EVT::getEVT(Ty1)))
10355 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10357 // Assuming the caller doesn't have a zeroext or signext return parameter,
10358 // truncation all the way down to i1 is valid.
10363 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10367 unsigned Scale = 1;
10368 switch (VT.getSimpleVT().SimpleTy) {
10369 default: return false;
10384 if ((V & (Scale - 1)) != 0)
10387 return V == (V & ((1LL << 5) - 1));
10390 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10391 const ARMSubtarget *Subtarget) {
10392 bool isNeg = false;
10398 switch (VT.getSimpleVT().SimpleTy) {
10399 default: return false;
10404 // + imm12 or - imm8
10406 return V == (V & ((1LL << 8) - 1));
10407 return V == (V & ((1LL << 12) - 1));
10410 // Same as ARM mode. FIXME: NEON?
10411 if (!Subtarget->hasVFP2())
10416 return V == (V & ((1LL << 8) - 1));
10420 /// isLegalAddressImmediate - Return true if the integer value can be used
10421 /// as the offset of the target addressing mode for load / store of the
10423 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10424 const ARMSubtarget *Subtarget) {
10428 if (!VT.isSimple())
10431 if (Subtarget->isThumb1Only())
10432 return isLegalT1AddressImmediate(V, VT);
10433 else if (Subtarget->isThumb2())
10434 return isLegalT2AddressImmediate(V, VT, Subtarget);
10439 switch (VT.getSimpleVT().SimpleTy) {
10440 default: return false;
10445 return V == (V & ((1LL << 12) - 1));
10448 return V == (V & ((1LL << 8) - 1));
10451 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10456 return V == (V & ((1LL << 8) - 1));
10460 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10462 int Scale = AM.Scale;
10466 switch (VT.getSimpleVT().SimpleTy) {
10467 default: return false;
10475 Scale = Scale & ~1;
10476 return Scale == 2 || Scale == 4 || Scale == 8;
10479 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10483 // Note, we allow "void" uses (basically, uses that aren't loads or
10484 // stores), because arm allows folding a scale into many arithmetic
10485 // operations. This should be made more precise and revisited later.
10487 // Allow r << imm, but the imm has to be a multiple of two.
10488 if (Scale & 1) return false;
10489 return isPowerOf2_32(Scale);
10493 /// isLegalAddressingMode - Return true if the addressing mode represented
10494 /// by AM is legal for this target, for a load/store of the specified type.
10495 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10497 EVT VT = getValueType(Ty, true);
10498 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10501 // Can never fold addr of global into load/store.
10505 switch (AM.Scale) {
10506 case 0: // no scale reg, must be "r+i" or "r", or "i".
10509 if (Subtarget->isThumb1Only())
10513 // ARM doesn't support any R+R*scale+imm addr modes.
10517 if (!VT.isSimple())
10520 if (Subtarget->isThumb2())
10521 return isLegalT2ScaledAddressingMode(AM, VT);
10523 int Scale = AM.Scale;
10524 switch (VT.getSimpleVT().SimpleTy) {
10525 default: return false;
10529 if (Scale < 0) Scale = -Scale;
10533 return isPowerOf2_32(Scale & ~1);
10537 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10542 // Note, we allow "void" uses (basically, uses that aren't loads or
10543 // stores), because arm allows folding a scale into many arithmetic
10544 // operations. This should be made more precise and revisited later.
10546 // Allow r << imm, but the imm has to be a multiple of two.
10547 if (Scale & 1) return false;
10548 return isPowerOf2_32(Scale);
10554 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10555 /// icmp immediate, that is the target has icmp instructions which can compare
10556 /// a register against the immediate without having to materialize the
10557 /// immediate into a register.
10558 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10559 // Thumb2 and ARM modes can use cmn for negative immediates.
10560 if (!Subtarget->isThumb())
10561 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10562 if (Subtarget->isThumb2())
10563 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10564 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10565 return Imm >= 0 && Imm <= 255;
10568 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10569 /// *or sub* immediate, that is the target has add or sub instructions which can
10570 /// add a register with the immediate without having to materialize the
10571 /// immediate into a register.
10572 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10573 // Same encoding for add/sub, just flip the sign.
10574 int64_t AbsImm = llvm::abs64(Imm);
10575 if (!Subtarget->isThumb())
10576 return ARM_AM::getSOImmVal(AbsImm) != -1;
10577 if (Subtarget->isThumb2())
10578 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10579 // Thumb1 only has 8-bit unsigned immediate.
10580 return AbsImm >= 0 && AbsImm <= 255;
10583 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10584 bool isSEXTLoad, SDValue &Base,
10585 SDValue &Offset, bool &isInc,
10586 SelectionDAG &DAG) {
10587 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10590 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10591 // AddressingMode 3
10592 Base = Ptr->getOperand(0);
10593 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10594 int RHSC = (int)RHS->getZExtValue();
10595 if (RHSC < 0 && RHSC > -256) {
10596 assert(Ptr->getOpcode() == ISD::ADD);
10598 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10602 isInc = (Ptr->getOpcode() == ISD::ADD);
10603 Offset = Ptr->getOperand(1);
10605 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10606 // AddressingMode 2
10607 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10608 int RHSC = (int)RHS->getZExtValue();
10609 if (RHSC < 0 && RHSC > -0x1000) {
10610 assert(Ptr->getOpcode() == ISD::ADD);
10612 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10613 Base = Ptr->getOperand(0);
10618 if (Ptr->getOpcode() == ISD::ADD) {
10620 ARM_AM::ShiftOpc ShOpcVal=
10621 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10622 if (ShOpcVal != ARM_AM::no_shift) {
10623 Base = Ptr->getOperand(1);
10624 Offset = Ptr->getOperand(0);
10626 Base = Ptr->getOperand(0);
10627 Offset = Ptr->getOperand(1);
10632 isInc = (Ptr->getOpcode() == ISD::ADD);
10633 Base = Ptr->getOperand(0);
10634 Offset = Ptr->getOperand(1);
10638 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10642 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10643 bool isSEXTLoad, SDValue &Base,
10644 SDValue &Offset, bool &isInc,
10645 SelectionDAG &DAG) {
10646 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10649 Base = Ptr->getOperand(0);
10650 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10651 int RHSC = (int)RHS->getZExtValue();
10652 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10653 assert(Ptr->getOpcode() == ISD::ADD);
10655 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10657 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10658 isInc = Ptr->getOpcode() == ISD::ADD;
10659 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10667 /// getPreIndexedAddressParts - returns true by value, base pointer and
10668 /// offset pointer and addressing mode by reference if the node's address
10669 /// can be legally represented as pre-indexed load / store address.
10671 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10673 ISD::MemIndexedMode &AM,
10674 SelectionDAG &DAG) const {
10675 if (Subtarget->isThumb1Only())
10680 bool isSEXTLoad = false;
10681 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10682 Ptr = LD->getBasePtr();
10683 VT = LD->getMemoryVT();
10684 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10685 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10686 Ptr = ST->getBasePtr();
10687 VT = ST->getMemoryVT();
10692 bool isLegal = false;
10693 if (Subtarget->isThumb2())
10694 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10695 Offset, isInc, DAG);
10697 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10698 Offset, isInc, DAG);
10702 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10706 /// getPostIndexedAddressParts - returns true by value, base pointer and
10707 /// offset pointer and addressing mode by reference if this node can be
10708 /// combined with a load / store to form a post-indexed load / store.
10709 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10712 ISD::MemIndexedMode &AM,
10713 SelectionDAG &DAG) const {
10714 if (Subtarget->isThumb1Only())
10719 bool isSEXTLoad = false;
10720 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10721 VT = LD->getMemoryVT();
10722 Ptr = LD->getBasePtr();
10723 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10724 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10725 VT = ST->getMemoryVT();
10726 Ptr = ST->getBasePtr();
10731 bool isLegal = false;
10732 if (Subtarget->isThumb2())
10733 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10736 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10742 // Swap base ptr and offset to catch more post-index load / store when
10743 // it's legal. In Thumb2 mode, offset must be an immediate.
10744 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10745 !Subtarget->isThumb2())
10746 std::swap(Base, Offset);
10748 // Post-indexed load / store update the base pointer.
10753 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10757 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10760 const SelectionDAG &DAG,
10761 unsigned Depth) const {
10762 unsigned BitWidth = KnownOne.getBitWidth();
10763 KnownZero = KnownOne = APInt(BitWidth, 0);
10764 switch (Op.getOpcode()) {
10770 // These nodes' second result is a boolean
10771 if (Op.getResNo() == 0)
10773 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10775 case ARMISD::CMOV: {
10776 // Bits are known zero/one if known on the LHS and RHS.
10777 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10778 if (KnownZero == 0 && KnownOne == 0) return;
10780 APInt KnownZeroRHS, KnownOneRHS;
10781 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10782 KnownZero &= KnownZeroRHS;
10783 KnownOne &= KnownOneRHS;
10789 //===----------------------------------------------------------------------===//
10790 // ARM Inline Assembly Support
10791 //===----------------------------------------------------------------------===//
10793 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10794 // Looking for "rev" which is V6+.
10795 if (!Subtarget->hasV6Ops())
10798 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10799 std::string AsmStr = IA->getAsmString();
10800 SmallVector<StringRef, 4> AsmPieces;
10801 SplitString(AsmStr, AsmPieces, ";\n");
10803 switch (AsmPieces.size()) {
10804 default: return false;
10806 AsmStr = AsmPieces[0];
10808 SplitString(AsmStr, AsmPieces, " \t,");
10811 if (AsmPieces.size() == 3 &&
10812 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10813 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10814 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10815 if (Ty && Ty->getBitWidth() == 32)
10816 return IntrinsicLowering::LowerToByteSwap(CI);
10824 /// getConstraintType - Given a constraint letter, return the type of
10825 /// constraint it is for this target.
10826 ARMTargetLowering::ConstraintType
10827 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10828 if (Constraint.size() == 1) {
10829 switch (Constraint[0]) {
10831 case 'l': return C_RegisterClass;
10832 case 'w': return C_RegisterClass;
10833 case 'h': return C_RegisterClass;
10834 case 'x': return C_RegisterClass;
10835 case 't': return C_RegisterClass;
10836 case 'j': return C_Other; // Constant for movw.
10837 // An address with a single base register. Due to the way we
10838 // currently handle addresses it is the same as an 'r' memory constraint.
10839 case 'Q': return C_Memory;
10841 } else if (Constraint.size() == 2) {
10842 switch (Constraint[0]) {
10844 // All 'U+' constraints are addresses.
10845 case 'U': return C_Memory;
10848 return TargetLowering::getConstraintType(Constraint);
10851 /// Examine constraint type and operand type and determine a weight value.
10852 /// This object must already have been set up with the operand type
10853 /// and the current alternative constraint selected.
10854 TargetLowering::ConstraintWeight
10855 ARMTargetLowering::getSingleConstraintMatchWeight(
10856 AsmOperandInfo &info, const char *constraint) const {
10857 ConstraintWeight weight = CW_Invalid;
10858 Value *CallOperandVal = info.CallOperandVal;
10859 // If we don't have a value, we can't do a match,
10860 // but allow it at the lowest weight.
10861 if (CallOperandVal == NULL)
10863 Type *type = CallOperandVal->getType();
10864 // Look at the constraint type.
10865 switch (*constraint) {
10867 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10870 if (type->isIntegerTy()) {
10871 if (Subtarget->isThumb())
10872 weight = CW_SpecificReg;
10874 weight = CW_Register;
10878 if (type->isFloatingPointTy())
10879 weight = CW_Register;
10885 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10887 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10889 if (Constraint.size() == 1) {
10890 // GCC ARM Constraint Letters
10891 switch (Constraint[0]) {
10892 case 'l': // Low regs or general regs.
10893 if (Subtarget->isThumb())
10894 return RCPair(0U, &ARM::tGPRRegClass);
10895 return RCPair(0U, &ARM::GPRRegClass);
10896 case 'h': // High regs or no regs.
10897 if (Subtarget->isThumb())
10898 return RCPair(0U, &ARM::hGPRRegClass);
10901 return RCPair(0U, &ARM::GPRRegClass);
10903 if (VT == MVT::f32)
10904 return RCPair(0U, &ARM::SPRRegClass);
10905 if (VT.getSizeInBits() == 64)
10906 return RCPair(0U, &ARM::DPRRegClass);
10907 if (VT.getSizeInBits() == 128)
10908 return RCPair(0U, &ARM::QPRRegClass);
10911 if (VT == MVT::f32)
10912 return RCPair(0U, &ARM::SPR_8RegClass);
10913 if (VT.getSizeInBits() == 64)
10914 return RCPair(0U, &ARM::DPR_8RegClass);
10915 if (VT.getSizeInBits() == 128)
10916 return RCPair(0U, &ARM::QPR_8RegClass);
10919 if (VT == MVT::f32)
10920 return RCPair(0U, &ARM::SPRRegClass);
10924 if (StringRef("{cc}").equals_lower(Constraint))
10925 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10927 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10930 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10931 /// vector. If it is invalid, don't add anything to Ops.
10932 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10933 std::string &Constraint,
10934 std::vector<SDValue>&Ops,
10935 SelectionDAG &DAG) const {
10936 SDValue Result(0, 0);
10938 // Currently only support length 1 constraints.
10939 if (Constraint.length() != 1) return;
10941 char ConstraintLetter = Constraint[0];
10942 switch (ConstraintLetter) {
10945 case 'I': case 'J': case 'K': case 'L':
10946 case 'M': case 'N': case 'O':
10947 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10951 int64_t CVal64 = C->getSExtValue();
10952 int CVal = (int) CVal64;
10953 // None of these constraints allow values larger than 32 bits. Check
10954 // that the value fits in an int.
10955 if (CVal != CVal64)
10958 switch (ConstraintLetter) {
10960 // Constant suitable for movw, must be between 0 and
10962 if (Subtarget->hasV6T2Ops())
10963 if (CVal >= 0 && CVal <= 65535)
10967 if (Subtarget->isThumb1Only()) {
10968 // This must be a constant between 0 and 255, for ADD
10970 if (CVal >= 0 && CVal <= 255)
10972 } else if (Subtarget->isThumb2()) {
10973 // A constant that can be used as an immediate value in a
10974 // data-processing instruction.
10975 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10978 // A constant that can be used as an immediate value in a
10979 // data-processing instruction.
10980 if (ARM_AM::getSOImmVal(CVal) != -1)
10986 if (Subtarget->isThumb()) { // FIXME thumb2
10987 // This must be a constant between -255 and -1, for negated ADD
10988 // immediates. This can be used in GCC with an "n" modifier that
10989 // prints the negated value, for use with SUB instructions. It is
10990 // not useful otherwise but is implemented for compatibility.
10991 if (CVal >= -255 && CVal <= -1)
10994 // This must be a constant between -4095 and 4095. It is not clear
10995 // what this constraint is intended for. Implemented for
10996 // compatibility with GCC.
10997 if (CVal >= -4095 && CVal <= 4095)
11003 if (Subtarget->isThumb1Only()) {
11004 // A 32-bit value where only one byte has a nonzero value. Exclude
11005 // zero to match GCC. This constraint is used by GCC internally for
11006 // constants that can be loaded with a move/shift combination.
11007 // It is not useful otherwise but is implemented for compatibility.
11008 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11010 } else if (Subtarget->isThumb2()) {
11011 // A constant whose bitwise inverse can be used as an immediate
11012 // value in a data-processing instruction. This can be used in GCC
11013 // with a "B" modifier that prints the inverted value, for use with
11014 // BIC and MVN instructions. It is not useful otherwise but is
11015 // implemented for compatibility.
11016 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11019 // A constant whose bitwise inverse can be used as an immediate
11020 // value in a data-processing instruction. This can be used in GCC
11021 // with a "B" modifier that prints the inverted value, for use with
11022 // BIC and MVN instructions. It is not useful otherwise but is
11023 // implemented for compatibility.
11024 if (ARM_AM::getSOImmVal(~CVal) != -1)
11030 if (Subtarget->isThumb1Only()) {
11031 // This must be a constant between -7 and 7,
11032 // for 3-operand ADD/SUB immediate instructions.
11033 if (CVal >= -7 && CVal < 7)
11035 } else if (Subtarget->isThumb2()) {
11036 // A constant whose negation can be used as an immediate value in a
11037 // data-processing instruction. This can be used in GCC with an "n"
11038 // modifier that prints the negated value, for use with SUB
11039 // instructions. It is not useful otherwise but is implemented for
11041 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11044 // A constant whose negation can be used as an immediate value in a
11045 // data-processing instruction. This can be used in GCC with an "n"
11046 // modifier that prints the negated value, for use with SUB
11047 // instructions. It is not useful otherwise but is implemented for
11049 if (ARM_AM::getSOImmVal(-CVal) != -1)
11055 if (Subtarget->isThumb()) { // FIXME thumb2
11056 // This must be a multiple of 4 between 0 and 1020, for
11057 // ADD sp + immediate.
11058 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11061 // A power of two or a constant between 0 and 32. This is used in
11062 // GCC for the shift amount on shifted register operands, but it is
11063 // useful in general for any shift amounts.
11064 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11070 if (Subtarget->isThumb()) { // FIXME thumb2
11071 // This must be a constant between 0 and 31, for shift amounts.
11072 if (CVal >= 0 && CVal <= 31)
11078 if (Subtarget->isThumb()) { // FIXME thumb2
11079 // This must be a multiple of 4 between -508 and 508, for
11080 // ADD/SUB sp = sp + immediate.
11081 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11086 Result = DAG.getTargetConstant(CVal, Op.getValueType());
11090 if (Result.getNode()) {
11091 Ops.push_back(Result);
11094 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11097 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11098 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11099 unsigned Opcode = Op->getOpcode();
11100 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11101 "Invalid opcode for Div/Rem lowering");
11102 bool isSigned = (Opcode == ISD::SDIVREM);
11103 EVT VT = Op->getValueType(0);
11104 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11107 switch (VT.getSimpleVT().SimpleTy) {
11108 default: llvm_unreachable("Unexpected request for libcall!");
11109 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11110 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11111 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11112 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11115 SDValue InChain = DAG.getEntryNode();
11117 TargetLowering::ArgListTy Args;
11118 TargetLowering::ArgListEntry Entry;
11119 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11120 EVT ArgVT = Op->getOperand(i).getValueType();
11121 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11122 Entry.Node = Op->getOperand(i);
11124 Entry.isSExt = isSigned;
11125 Entry.isZExt = !isSigned;
11126 Args.push_back(Entry);
11129 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11132 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11136 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11137 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11138 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11139 Callee, Args, DAG, dl);
11140 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11142 return CallInfo.first;
11146 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11147 // The ARM target isn't yet aware of offsets.
11151 bool ARM::isBitFieldInvertedMask(unsigned v) {
11152 if (v == 0xffffffff)
11155 // there can be 1's on either or both "outsides", all the "inside"
11156 // bits must be 0's
11157 unsigned TO = CountTrailingOnes_32(v);
11158 unsigned LO = CountLeadingOnes_32(v);
11159 v = (v >> TO) << TO;
11160 v = (v << LO) >> LO;
11164 /// isFPImmLegal - Returns true if the target can instruction select the
11165 /// specified FP immediate natively. If false, the legalizer will
11166 /// materialize the FP immediate as a load from a constant pool.
11167 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11168 if (!Subtarget->hasVFP3())
11170 if (VT == MVT::f32)
11171 return ARM_AM::getFP32Imm(Imm) != -1;
11172 if (VT == MVT::f64)
11173 return ARM_AM::getFP64Imm(Imm) != -1;
11177 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11178 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11179 /// specified in the intrinsic calls.
11180 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11182 unsigned Intrinsic) const {
11183 switch (Intrinsic) {
11184 case Intrinsic::arm_neon_vld1:
11185 case Intrinsic::arm_neon_vld2:
11186 case Intrinsic::arm_neon_vld3:
11187 case Intrinsic::arm_neon_vld4:
11188 case Intrinsic::arm_neon_vld2lane:
11189 case Intrinsic::arm_neon_vld3lane:
11190 case Intrinsic::arm_neon_vld4lane: {
11191 Info.opc = ISD::INTRINSIC_W_CHAIN;
11192 // Conservatively set memVT to the entire set of vectors loaded.
11193 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11194 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11195 Info.ptrVal = I.getArgOperand(0);
11197 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11198 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11199 Info.vol = false; // volatile loads with NEON intrinsics not supported
11200 Info.readMem = true;
11201 Info.writeMem = false;
11204 case Intrinsic::arm_neon_vst1:
11205 case Intrinsic::arm_neon_vst2:
11206 case Intrinsic::arm_neon_vst3:
11207 case Intrinsic::arm_neon_vst4:
11208 case Intrinsic::arm_neon_vst2lane:
11209 case Intrinsic::arm_neon_vst3lane:
11210 case Intrinsic::arm_neon_vst4lane: {
11211 Info.opc = ISD::INTRINSIC_VOID;
11212 // Conservatively set memVT to the entire set of vectors stored.
11213 unsigned NumElts = 0;
11214 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11215 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11216 if (!ArgTy->isVectorTy())
11218 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11220 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11221 Info.ptrVal = I.getArgOperand(0);
11223 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11224 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11225 Info.vol = false; // volatile stores with NEON intrinsics not supported
11226 Info.readMem = false;
11227 Info.writeMem = true;
11230 case Intrinsic::arm_ldrex: {
11231 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11232 Info.opc = ISD::INTRINSIC_W_CHAIN;
11233 Info.memVT = MVT::getVT(PtrTy->getElementType());
11234 Info.ptrVal = I.getArgOperand(0);
11236 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11238 Info.readMem = true;
11239 Info.writeMem = false;
11242 case Intrinsic::arm_strex: {
11243 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11244 Info.opc = ISD::INTRINSIC_W_CHAIN;
11245 Info.memVT = MVT::getVT(PtrTy->getElementType());
11246 Info.ptrVal = I.getArgOperand(1);
11248 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11250 Info.readMem = false;
11251 Info.writeMem = true;
11254 case Intrinsic::arm_strexd: {
11255 Info.opc = ISD::INTRINSIC_W_CHAIN;
11256 Info.memVT = MVT::i64;
11257 Info.ptrVal = I.getArgOperand(2);
11261 Info.readMem = false;
11262 Info.writeMem = true;
11265 case Intrinsic::arm_ldrexd: {
11266 Info.opc = ISD::INTRINSIC_W_CHAIN;
11267 Info.memVT = MVT::i64;
11268 Info.ptrVal = I.getArgOperand(0);
11272 Info.readMem = true;
11273 Info.writeMem = false;