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/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57 // This option should go away when tail calls fully work.
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65 cl::desc("Generate calls via indirect call instructions"),
69 ARMInterworking("arm-interworking", cl::Hidden,
70 cl::desc("Enable / disable ARM interworking (for debugging only)"),
74 class ARMCCState : public CCState {
76 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77 const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78 LLVMContext &C, ParmContext PC)
79 : CCState(CC, isVarArg, MF, TM, locs, C) {
80 assert(((PC == Call) || (PC == Prologue)) &&
81 "ARMCCState users must specify whether their context is call"
82 "or prologue generation.");
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90 ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
94 EVT PromotedBitwiseVT) {
95 if (VT != PromotedLdStVT) {
96 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
97 AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
98 PromotedLdStVT.getSimpleVT());
100 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
101 AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
102 PromotedLdStVT.getSimpleVT());
105 EVT ElemTy = VT.getVectorElementType();
106 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
107 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
108 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
109 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
110 if (ElemTy == MVT::i32) {
111 setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
112 setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
113 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
114 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
116 setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
117 setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
118 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
119 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
121 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
122 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
123 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
124 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
125 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
126 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
128 if (VT.isInteger()) {
129 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
130 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
131 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
134 // Promote all bit-wise operations.
135 if (VT.isInteger() && VT != PromotedBitwiseVT) {
136 setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
137 AddPromotedToType (ISD::AND, VT.getSimpleVT(),
138 PromotedBitwiseVT.getSimpleVT());
139 setOperationAction(ISD::OR, VT.getSimpleVT(), Promote);
140 AddPromotedToType (ISD::OR, VT.getSimpleVT(),
141 PromotedBitwiseVT.getSimpleVT());
142 setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
143 AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
144 PromotedBitwiseVT.getSimpleVT());
147 // Neon does not support vector divide/remainder operations.
148 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
149 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
150 setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
151 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
152 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
153 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
156 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
157 addRegisterClass(VT, &ARM::DPRRegClass);
158 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
161 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
162 addRegisterClass(VT, &ARM::QPRRegClass);
163 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
166 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
167 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
168 return new TargetLoweringObjectFileMachO();
170 return new ARMElfTargetObjectFile();
173 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
174 : TargetLowering(TM, createTLOF(TM)) {
175 Subtarget = &TM.getSubtarget<ARMSubtarget>();
176 RegInfo = TM.getRegisterInfo();
177 Itins = TM.getInstrItineraryData();
179 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
181 if (Subtarget->isTargetDarwin()) {
182 // Uses VFP for Thumb libfuncs if available.
183 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
184 // Single-precision floating-point arithmetic.
185 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
186 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
187 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
188 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
190 // Double-precision floating-point arithmetic.
191 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
192 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
193 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
194 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
196 // Single-precision comparisons.
197 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
198 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
199 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
200 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
201 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
202 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
203 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
204 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
206 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
210 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
211 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
212 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
213 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
215 // Double-precision comparisons.
216 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
217 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
218 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
219 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
220 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
221 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
222 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
223 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
225 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
229 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
230 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
231 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
232 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
234 // Floating-point to integer conversions.
235 // i64 conversions are done via library routines even when generating VFP
236 // instructions, so use the same ones.
237 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
238 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
239 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
240 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
242 // Conversions between floating types.
243 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
244 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
246 // Integer to floating-point conversions.
247 // i64 conversions are done via library routines even when generating VFP
248 // instructions, so use the same ones.
249 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
250 // e.g., __floatunsidf vs. __floatunssidfvfp.
251 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
252 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
253 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
254 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
258 // These libcalls are not available in 32-bit.
259 setLibcallName(RTLIB::SHL_I128, 0);
260 setLibcallName(RTLIB::SRL_I128, 0);
261 setLibcallName(RTLIB::SRA_I128, 0);
263 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
264 // Double-precision floating-point arithmetic helper functions
265 // RTABI chapter 4.1.2, Table 2
266 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
267 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
268 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
269 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
270 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
271 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
272 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
273 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
275 // Double-precision floating-point comparison helper functions
276 // RTABI chapter 4.1.2, Table 3
277 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
278 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
279 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
280 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
281 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
282 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
283 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
284 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
285 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
286 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
287 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
288 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
289 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
290 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
291 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
292 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
293 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
297 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
298 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
299 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
300 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
302 // Single-precision floating-point arithmetic helper functions
303 // RTABI chapter 4.1.2, Table 4
304 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
305 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
306 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
307 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
308 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
309 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
310 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
311 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
313 // Single-precision floating-point comparison helper functions
314 // RTABI chapter 4.1.2, Table 5
315 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
316 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
317 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
318 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
319 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
320 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
321 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
322 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
323 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
324 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
325 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
326 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
327 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
328 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
329 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
330 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
331 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
335 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
336 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
337 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
338 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
340 // Floating-point to integer conversions.
341 // RTABI chapter 4.1.2, Table 6
342 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
343 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
344 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
345 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
346 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
347 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
348 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
349 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
350 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
354 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
355 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
356 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
357 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
359 // Conversions between floating types.
360 // RTABI chapter 4.1.2, Table 7
361 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
362 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
363 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
364 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
366 // Integer to floating-point conversions.
367 // RTABI chapter 4.1.2, Table 8
368 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
369 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
370 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
371 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
372 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
373 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
374 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
375 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
376 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
380 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
381 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
382 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
383 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
385 // Long long helper functions
386 // RTABI chapter 4.2, Table 9
387 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
388 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
389 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
390 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
391 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
395 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
396 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
398 // Integer division functions
399 // RTABI chapter 4.3.1
400 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
401 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
402 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
403 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
404 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
405 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
406 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
407 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
408 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
412 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
413 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
414 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
415 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
418 // RTABI chapter 4.3.4
419 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
420 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
421 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
422 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
423 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
424 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
427 // Use divmod compiler-rt calls for iOS 5.0 and later.
428 if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
429 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
430 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
431 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
434 if (Subtarget->isThumb1Only())
435 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
437 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
438 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
439 !Subtarget->isThumb1Only()) {
440 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
441 if (!Subtarget->isFPOnlySP())
442 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
444 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
447 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
449 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
450 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
451 setTruncStoreAction((MVT::SimpleValueType)VT,
452 (MVT::SimpleValueType)InnerVT, Expand);
453 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
454 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
455 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
458 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
460 if (Subtarget->hasNEON()) {
461 addDRTypeForNEON(MVT::v2f32);
462 addDRTypeForNEON(MVT::v8i8);
463 addDRTypeForNEON(MVT::v4i16);
464 addDRTypeForNEON(MVT::v2i32);
465 addDRTypeForNEON(MVT::v1i64);
467 addQRTypeForNEON(MVT::v4f32);
468 addQRTypeForNEON(MVT::v2f64);
469 addQRTypeForNEON(MVT::v16i8);
470 addQRTypeForNEON(MVT::v8i16);
471 addQRTypeForNEON(MVT::v4i32);
472 addQRTypeForNEON(MVT::v2i64);
474 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
475 // neither Neon nor VFP support any arithmetic operations on it.
476 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
477 // supported for v4f32.
478 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
479 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
480 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
481 // FIXME: Code duplication: FDIV and FREM are expanded always, see
482 // ARMTargetLowering::addTypeForNEON method for details.
483 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
484 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
485 // FIXME: Create unittest.
486 // In another words, find a way when "copysign" appears in DAG with vector
488 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
489 // FIXME: Code duplication: SETCC has custom operation action, see
490 // ARMTargetLowering::addTypeForNEON method for details.
491 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
492 // FIXME: Create unittest for FNEG and for FABS.
493 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
494 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
495 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
496 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
497 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
498 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
499 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
500 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
501 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
502 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
503 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
504 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
505 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
506 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
507 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
508 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
509 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
510 setOperationAction(ISD::FFLOOR, 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);
523 // Neon does not support some operations on v1i64 and v2i64 types.
524 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
525 // Custom handling for some quad-vector types to detect VMULL.
526 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
527 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
528 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
529 // Custom handling for some vector types to avoid expensive expansions
530 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
531 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
532 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
533 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
534 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
535 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
536 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
537 // a destination type that is wider than the source, and nor does
538 // it have a FP_TO_[SU]INT instruction with a narrower destination than
540 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
541 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
542 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
543 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
545 setTargetDAGCombine(ISD::INTRINSIC_VOID);
546 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
547 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
548 setTargetDAGCombine(ISD::SHL);
549 setTargetDAGCombine(ISD::SRL);
550 setTargetDAGCombine(ISD::SRA);
551 setTargetDAGCombine(ISD::SIGN_EXTEND);
552 setTargetDAGCombine(ISD::ZERO_EXTEND);
553 setTargetDAGCombine(ISD::ANY_EXTEND);
554 setTargetDAGCombine(ISD::SELECT_CC);
555 setTargetDAGCombine(ISD::BUILD_VECTOR);
556 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
557 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
558 setTargetDAGCombine(ISD::STORE);
559 setTargetDAGCombine(ISD::FP_TO_SINT);
560 setTargetDAGCombine(ISD::FP_TO_UINT);
561 setTargetDAGCombine(ISD::FDIV);
563 // It is legal to extload from v4i8 to v4i16 or v4i32.
564 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
565 MVT::v4i16, MVT::v2i16,
567 for (unsigned i = 0; i < 6; ++i) {
568 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
569 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
570 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
574 computeRegisterProperties();
576 // ARM does not have f32 extending load.
577 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
579 // ARM does not have i1 sign extending load.
580 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
582 // ARM supports all 4 flavors of integer indexed load / store.
583 if (!Subtarget->isThumb1Only()) {
584 for (unsigned im = (unsigned)ISD::PRE_INC;
585 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
586 setIndexedLoadAction(im, MVT::i1, Legal);
587 setIndexedLoadAction(im, MVT::i8, Legal);
588 setIndexedLoadAction(im, MVT::i16, Legal);
589 setIndexedLoadAction(im, MVT::i32, Legal);
590 setIndexedStoreAction(im, MVT::i1, Legal);
591 setIndexedStoreAction(im, MVT::i8, Legal);
592 setIndexedStoreAction(im, MVT::i16, Legal);
593 setIndexedStoreAction(im, MVT::i32, Legal);
597 // i64 operation support.
598 setOperationAction(ISD::MUL, MVT::i64, Expand);
599 setOperationAction(ISD::MULHU, MVT::i32, Expand);
600 if (Subtarget->isThumb1Only()) {
601 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
602 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
604 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
605 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
606 setOperationAction(ISD::MULHS, MVT::i32, Expand);
608 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
609 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
610 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
611 setOperationAction(ISD::SRL, MVT::i64, Custom);
612 setOperationAction(ISD::SRA, MVT::i64, Custom);
614 if (!Subtarget->isThumb1Only()) {
615 // FIXME: We should do this for Thumb1 as well.
616 setOperationAction(ISD::ADDC, MVT::i32, Custom);
617 setOperationAction(ISD::ADDE, MVT::i32, Custom);
618 setOperationAction(ISD::SUBC, MVT::i32, Custom);
619 setOperationAction(ISD::SUBE, MVT::i32, Custom);
622 // ARM does not have ROTL.
623 setOperationAction(ISD::ROTL, MVT::i32, Expand);
624 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
625 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
626 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
627 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
629 // These just redirect to CTTZ and CTLZ on ARM.
630 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
631 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
633 // Only ARMv6 has BSWAP.
634 if (!Subtarget->hasV6Ops())
635 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
637 // These are expanded into libcalls.
638 if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
639 // v7M has a hardware divider
640 setOperationAction(ISD::SDIV, MVT::i32, Expand);
641 setOperationAction(ISD::UDIV, MVT::i32, Expand);
643 setOperationAction(ISD::SREM, MVT::i32, Expand);
644 setOperationAction(ISD::UREM, MVT::i32, Expand);
645 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
646 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
648 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
649 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
650 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
651 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
652 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
654 setOperationAction(ISD::TRAP, MVT::Other, Legal);
656 // Use the default implementation.
657 setOperationAction(ISD::VASTART, MVT::Other, Custom);
658 setOperationAction(ISD::VAARG, MVT::Other, Expand);
659 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
660 setOperationAction(ISD::VAEND, MVT::Other, Expand);
661 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
662 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
664 if (!Subtarget->isTargetDarwin()) {
665 // Non-Darwin platforms may return values in these registers via the
666 // personality function.
667 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
668 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
669 setExceptionPointerRegister(ARM::R0);
670 setExceptionSelectorRegister(ARM::R1);
673 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
674 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
675 // the default expansion.
676 // FIXME: This should be checking for v6k, not just v6.
677 if (Subtarget->hasDataBarrier() ||
678 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
679 // membarrier needs custom lowering; the rest are legal and handled
681 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
682 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
683 // Custom lowering for 64-bit ops
684 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
685 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
686 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
687 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
688 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
689 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
690 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
691 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
692 setInsertFencesForAtomic(true);
694 // Set them all for expansion, which will force libcalls.
695 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
696 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
697 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
698 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
699 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
700 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
701 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
702 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
703 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
704 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
705 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
706 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
707 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
708 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
709 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
710 // Unordered/Monotonic case.
711 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
712 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
713 // Since the libcalls include locking, fold in the fences
714 setShouldFoldAtomicFences(true);
717 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
719 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
720 if (!Subtarget->hasV6Ops()) {
721 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
722 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
724 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
726 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
727 !Subtarget->isThumb1Only()) {
728 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
729 // iff target supports vfp2.
730 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
731 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
734 // We want to custom lower some of our intrinsics.
735 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
736 if (Subtarget->isTargetDarwin()) {
737 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
738 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
739 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
742 setOperationAction(ISD::SETCC, MVT::i32, Expand);
743 setOperationAction(ISD::SETCC, MVT::f32, Expand);
744 setOperationAction(ISD::SETCC, MVT::f64, Expand);
745 setOperationAction(ISD::SELECT, MVT::i32, Custom);
746 setOperationAction(ISD::SELECT, MVT::f32, Custom);
747 setOperationAction(ISD::SELECT, MVT::f64, Custom);
748 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
749 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
750 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
752 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
753 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
754 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
755 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
756 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
758 // We don't support sin/cos/fmod/copysign/pow
759 setOperationAction(ISD::FSIN, MVT::f64, Expand);
760 setOperationAction(ISD::FSIN, MVT::f32, Expand);
761 setOperationAction(ISD::FCOS, MVT::f32, Expand);
762 setOperationAction(ISD::FCOS, MVT::f64, Expand);
763 setOperationAction(ISD::FREM, MVT::f64, Expand);
764 setOperationAction(ISD::FREM, MVT::f32, Expand);
765 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
766 !Subtarget->isThumb1Only()) {
767 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
768 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
770 setOperationAction(ISD::FPOW, MVT::f64, Expand);
771 setOperationAction(ISD::FPOW, MVT::f32, Expand);
773 if (!Subtarget->hasVFP4()) {
774 setOperationAction(ISD::FMA, MVT::f64, Expand);
775 setOperationAction(ISD::FMA, MVT::f32, Expand);
778 // Various VFP goodness
779 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
780 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
781 if (Subtarget->hasVFP2()) {
782 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
783 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
784 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
785 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
787 // Special handling for half-precision FP.
788 if (!Subtarget->hasFP16()) {
789 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
790 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
794 // We have target-specific dag combine patterns for the following nodes:
795 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
796 setTargetDAGCombine(ISD::ADD);
797 setTargetDAGCombine(ISD::SUB);
798 setTargetDAGCombine(ISD::MUL);
800 if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
801 setTargetDAGCombine(ISD::AND);
802 setTargetDAGCombine(ISD::OR);
803 setTargetDAGCombine(ISD::XOR);
806 if (Subtarget->hasV6Ops())
807 setTargetDAGCombine(ISD::SRL);
809 setStackPointerRegisterToSaveRestore(ARM::SP);
811 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
812 !Subtarget->hasVFP2())
813 setSchedulingPreference(Sched::RegPressure);
815 setSchedulingPreference(Sched::Hybrid);
817 //// temporary - rewrite interface to use type
818 maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
819 maxStoresPerMemset = 16;
820 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
822 // On ARM arguments smaller than 4 bytes are extended, so all arguments
823 // are at least 4 bytes aligned.
824 setMinStackArgumentAlignment(4);
826 benefitFromCodePlacementOpt = true;
828 // Prefer likely predicted branches to selects on out-of-order cores.
829 predictableSelectIsExpensive = Subtarget->isCortexA9();
831 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
834 // FIXME: It might make sense to define the representative register class as the
835 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
836 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
837 // SPR's representative would be DPR_VFP2. This should work well if register
838 // pressure tracking were modified such that a register use would increment the
839 // pressure of the register class's representative and all of it's super
840 // classes' representatives transitively. We have not implemented this because
841 // of the difficulty prior to coalescing of modeling operand register classes
842 // due to the common occurrence of cross class copies and subregister insertions
844 std::pair<const TargetRegisterClass*, uint8_t>
845 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
846 const TargetRegisterClass *RRC = 0;
848 switch (VT.getSimpleVT().SimpleTy) {
850 return TargetLowering::findRepresentativeClass(VT);
851 // Use DPR as representative register class for all floating point
852 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
853 // the cost is 1 for both f32 and f64.
854 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
855 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
856 RRC = &ARM::DPRRegClass;
857 // When NEON is used for SP, only half of the register file is available
858 // because operations that define both SP and DP results will be constrained
859 // to the VFP2 class (D0-D15). We currently model this constraint prior to
860 // coalescing by double-counting the SP regs. See the FIXME above.
861 if (Subtarget->useNEONForSinglePrecisionFP())
864 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
865 case MVT::v4f32: case MVT::v2f64:
866 RRC = &ARM::DPRRegClass;
870 RRC = &ARM::DPRRegClass;
874 RRC = &ARM::DPRRegClass;
878 return std::make_pair(RRC, Cost);
881 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
884 case ARMISD::Wrapper: return "ARMISD::Wrapper";
885 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
886 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
887 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
888 case ARMISD::CALL: return "ARMISD::CALL";
889 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
890 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
891 case ARMISD::tCALL: return "ARMISD::tCALL";
892 case ARMISD::BRCOND: return "ARMISD::BRCOND";
893 case ARMISD::BR_JT: return "ARMISD::BR_JT";
894 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
895 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
896 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
897 case ARMISD::CMP: return "ARMISD::CMP";
898 case ARMISD::CMN: return "ARMISD::CMN";
899 case ARMISD::CMPZ: return "ARMISD::CMPZ";
900 case ARMISD::CMPFP: return "ARMISD::CMPFP";
901 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
902 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
903 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
905 case ARMISD::CMOV: return "ARMISD::CMOV";
906 case ARMISD::CAND: return "ARMISD::CAND";
907 case ARMISD::COR: return "ARMISD::COR";
908 case ARMISD::CXOR: return "ARMISD::CXOR";
910 case ARMISD::RBIT: return "ARMISD::RBIT";
912 case ARMISD::FTOSI: return "ARMISD::FTOSI";
913 case ARMISD::FTOUI: return "ARMISD::FTOUI";
914 case ARMISD::SITOF: return "ARMISD::SITOF";
915 case ARMISD::UITOF: return "ARMISD::UITOF";
917 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
918 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
919 case ARMISD::RRX: return "ARMISD::RRX";
921 case ARMISD::ADDC: return "ARMISD::ADDC";
922 case ARMISD::ADDE: return "ARMISD::ADDE";
923 case ARMISD::SUBC: return "ARMISD::SUBC";
924 case ARMISD::SUBE: return "ARMISD::SUBE";
926 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
927 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
929 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
930 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
932 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
934 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
936 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
938 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
939 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
941 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
943 case ARMISD::VCEQ: return "ARMISD::VCEQ";
944 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
945 case ARMISD::VCGE: return "ARMISD::VCGE";
946 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
947 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
948 case ARMISD::VCGEU: return "ARMISD::VCGEU";
949 case ARMISD::VCGT: return "ARMISD::VCGT";
950 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
951 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
952 case ARMISD::VCGTU: return "ARMISD::VCGTU";
953 case ARMISD::VTST: return "ARMISD::VTST";
955 case ARMISD::VSHL: return "ARMISD::VSHL";
956 case ARMISD::VSHRs: return "ARMISD::VSHRs";
957 case ARMISD::VSHRu: return "ARMISD::VSHRu";
958 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
959 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
960 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
961 case ARMISD::VSHRN: return "ARMISD::VSHRN";
962 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
963 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
964 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
965 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
966 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
967 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
968 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
969 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
970 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
971 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
972 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
973 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
974 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
975 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
976 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
977 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
978 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
979 case ARMISD::VDUP: return "ARMISD::VDUP";
980 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
981 case ARMISD::VEXT: return "ARMISD::VEXT";
982 case ARMISD::VREV64: return "ARMISD::VREV64";
983 case ARMISD::VREV32: return "ARMISD::VREV32";
984 case ARMISD::VREV16: return "ARMISD::VREV16";
985 case ARMISD::VZIP: return "ARMISD::VZIP";
986 case ARMISD::VUZP: return "ARMISD::VUZP";
987 case ARMISD::VTRN: return "ARMISD::VTRN";
988 case ARMISD::VTBL1: return "ARMISD::VTBL1";
989 case ARMISD::VTBL2: return "ARMISD::VTBL2";
990 case ARMISD::VMULLs: return "ARMISD::VMULLs";
991 case ARMISD::VMULLu: return "ARMISD::VMULLu";
992 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
993 case ARMISD::FMAX: return "ARMISD::FMAX";
994 case ARMISD::FMIN: return "ARMISD::FMIN";
995 case ARMISD::BFI: return "ARMISD::BFI";
996 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
997 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
998 case ARMISD::VBSL: return "ARMISD::VBSL";
999 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1000 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1001 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1002 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1003 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1004 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1005 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1006 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1007 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1008 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1009 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1010 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1011 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1012 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1013 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1014 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1015 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1016 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1017 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1018 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1022 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1023 if (!VT.isVector()) return getPointerTy();
1024 return VT.changeVectorElementTypeToInteger();
1027 /// getRegClassFor - Return the register class that should be used for the
1028 /// specified value type.
1029 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1030 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1031 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1032 // load / store 4 to 8 consecutive D registers.
1033 if (Subtarget->hasNEON()) {
1034 if (VT == MVT::v4i64)
1035 return &ARM::QQPRRegClass;
1036 if (VT == MVT::v8i64)
1037 return &ARM::QQQQPRRegClass;
1039 return TargetLowering::getRegClassFor(VT);
1042 // Create a fast isel object.
1044 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1045 return ARM::createFastISel(funcInfo);
1048 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1049 /// be used for loads / stores from the global.
1050 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1051 return (Subtarget->isThumb1Only() ? 127 : 4095);
1054 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1055 unsigned NumVals = N->getNumValues();
1057 return Sched::RegPressure;
1059 for (unsigned i = 0; i != NumVals; ++i) {
1060 EVT VT = N->getValueType(i);
1061 if (VT == MVT::Glue || VT == MVT::Other)
1063 if (VT.isFloatingPoint() || VT.isVector())
1067 if (!N->isMachineOpcode())
1068 return Sched::RegPressure;
1070 // Load are scheduled for latency even if there instruction itinerary
1071 // is not available.
1072 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1073 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1075 if (MCID.getNumDefs() == 0)
1076 return Sched::RegPressure;
1077 if (!Itins->isEmpty() &&
1078 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1081 return Sched::RegPressure;
1084 //===----------------------------------------------------------------------===//
1086 //===----------------------------------------------------------------------===//
1088 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1089 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1091 default: llvm_unreachable("Unknown condition code!");
1092 case ISD::SETNE: return ARMCC::NE;
1093 case ISD::SETEQ: return ARMCC::EQ;
1094 case ISD::SETGT: return ARMCC::GT;
1095 case ISD::SETGE: return ARMCC::GE;
1096 case ISD::SETLT: return ARMCC::LT;
1097 case ISD::SETLE: return ARMCC::LE;
1098 case ISD::SETUGT: return ARMCC::HI;
1099 case ISD::SETUGE: return ARMCC::HS;
1100 case ISD::SETULT: return ARMCC::LO;
1101 case ISD::SETULE: return ARMCC::LS;
1105 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1106 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1107 ARMCC::CondCodes &CondCode2) {
1108 CondCode2 = ARMCC::AL;
1110 default: llvm_unreachable("Unknown FP condition!");
1112 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1114 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1116 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1117 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1118 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1119 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1120 case ISD::SETO: CondCode = ARMCC::VC; break;
1121 case ISD::SETUO: CondCode = ARMCC::VS; break;
1122 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1123 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1124 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1126 case ISD::SETULT: CondCode = ARMCC::LT; break;
1128 case ISD::SETULE: CondCode = ARMCC::LE; break;
1130 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1134 //===----------------------------------------------------------------------===//
1135 // Calling Convention Implementation
1136 //===----------------------------------------------------------------------===//
1138 #include "ARMGenCallingConv.inc"
1140 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1141 /// given CallingConvention value.
1142 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1144 bool isVarArg) const {
1147 llvm_unreachable("Unsupported calling convention");
1148 case CallingConv::Fast:
1149 if (Subtarget->hasVFP2() && !isVarArg) {
1150 if (!Subtarget->isAAPCS_ABI())
1151 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1152 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1153 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1156 case CallingConv::C: {
1157 // Use target triple & subtarget features to do actual dispatch.
1158 if (!Subtarget->isAAPCS_ABI())
1159 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1160 else if (Subtarget->hasVFP2() &&
1161 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1163 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1164 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1166 case CallingConv::ARM_AAPCS_VFP:
1168 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1170 case CallingConv::ARM_AAPCS:
1171 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1172 case CallingConv::ARM_APCS:
1173 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1177 /// LowerCallResult - Lower the result values of a call into the
1178 /// appropriate copies out of appropriate physical registers.
1180 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1181 CallingConv::ID CallConv, bool isVarArg,
1182 const SmallVectorImpl<ISD::InputArg> &Ins,
1183 DebugLoc dl, SelectionDAG &DAG,
1184 SmallVectorImpl<SDValue> &InVals) const {
1186 // Assign locations to each value returned by this call.
1187 SmallVector<CCValAssign, 16> RVLocs;
1188 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1189 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1190 CCInfo.AnalyzeCallResult(Ins,
1191 CCAssignFnForNode(CallConv, /* Return*/ true,
1194 // Copy all of the result registers out of their specified physreg.
1195 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1196 CCValAssign VA = RVLocs[i];
1199 if (VA.needsCustom()) {
1200 // Handle f64 or half of a v2f64.
1201 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1203 Chain = Lo.getValue(1);
1204 InFlag = Lo.getValue(2);
1205 VA = RVLocs[++i]; // skip ahead to next loc
1206 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1208 Chain = Hi.getValue(1);
1209 InFlag = Hi.getValue(2);
1210 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1212 if (VA.getLocVT() == MVT::v2f64) {
1213 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1214 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1215 DAG.getConstant(0, MVT::i32));
1217 VA = RVLocs[++i]; // skip ahead to next loc
1218 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1219 Chain = Lo.getValue(1);
1220 InFlag = Lo.getValue(2);
1221 VA = RVLocs[++i]; // skip ahead to next loc
1222 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1223 Chain = Hi.getValue(1);
1224 InFlag = Hi.getValue(2);
1225 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1226 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1227 DAG.getConstant(1, MVT::i32));
1230 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1232 Chain = Val.getValue(1);
1233 InFlag = Val.getValue(2);
1236 switch (VA.getLocInfo()) {
1237 default: llvm_unreachable("Unknown loc info!");
1238 case CCValAssign::Full: break;
1239 case CCValAssign::BCvt:
1240 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1244 InVals.push_back(Val);
1250 /// LowerMemOpCallTo - Store the argument to the stack.
1252 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1253 SDValue StackPtr, SDValue Arg,
1254 DebugLoc dl, SelectionDAG &DAG,
1255 const CCValAssign &VA,
1256 ISD::ArgFlagsTy Flags) const {
1257 unsigned LocMemOffset = VA.getLocMemOffset();
1258 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1259 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1260 return DAG.getStore(Chain, dl, Arg, PtrOff,
1261 MachinePointerInfo::getStack(LocMemOffset),
1265 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1266 SDValue Chain, SDValue &Arg,
1267 RegsToPassVector &RegsToPass,
1268 CCValAssign &VA, CCValAssign &NextVA,
1270 SmallVector<SDValue, 8> &MemOpChains,
1271 ISD::ArgFlagsTy Flags) const {
1273 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1274 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1275 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1277 if (NextVA.isRegLoc())
1278 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1280 assert(NextVA.isMemLoc());
1281 if (StackPtr.getNode() == 0)
1282 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1284 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1290 /// LowerCall - Lowering a call into a callseq_start <-
1291 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1294 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1295 SmallVectorImpl<SDValue> &InVals) const {
1296 SelectionDAG &DAG = CLI.DAG;
1297 DebugLoc &dl = CLI.DL;
1298 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1299 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1300 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1301 SDValue Chain = CLI.Chain;
1302 SDValue Callee = CLI.Callee;
1303 bool &isTailCall = CLI.IsTailCall;
1304 CallingConv::ID CallConv = CLI.CallConv;
1305 bool doesNotRet = CLI.DoesNotReturn;
1306 bool isVarArg = CLI.IsVarArg;
1308 MachineFunction &MF = DAG.getMachineFunction();
1309 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1310 bool IsSibCall = false;
1311 // Disable tail calls if they're not supported.
1312 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1315 // Check if it's really possible to do a tail call.
1316 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1317 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1318 Outs, OutVals, Ins, DAG);
1319 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1320 // detected sibcalls.
1327 // Analyze operands of the call, assigning locations to each operand.
1328 SmallVector<CCValAssign, 16> ArgLocs;
1329 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1330 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1331 CCInfo.AnalyzeCallOperands(Outs,
1332 CCAssignFnForNode(CallConv, /* Return*/ false,
1335 // Get a count of how many bytes are to be pushed on the stack.
1336 unsigned NumBytes = CCInfo.getNextStackOffset();
1338 // For tail calls, memory operands are available in our caller's stack.
1342 // Adjust the stack pointer for the new arguments...
1343 // These operations are automatically eliminated by the prolog/epilog pass
1345 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1347 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1349 RegsToPassVector RegsToPass;
1350 SmallVector<SDValue, 8> MemOpChains;
1352 // Walk the register/memloc assignments, inserting copies/loads. In the case
1353 // of tail call optimization, arguments are handled later.
1354 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1356 ++i, ++realArgIdx) {
1357 CCValAssign &VA = ArgLocs[i];
1358 SDValue Arg = OutVals[realArgIdx];
1359 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1360 bool isByVal = Flags.isByVal();
1362 // Promote the value if needed.
1363 switch (VA.getLocInfo()) {
1364 default: llvm_unreachable("Unknown loc info!");
1365 case CCValAssign::Full: break;
1366 case CCValAssign::SExt:
1367 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1369 case CCValAssign::ZExt:
1370 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1372 case CCValAssign::AExt:
1373 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1375 case CCValAssign::BCvt:
1376 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1380 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1381 if (VA.needsCustom()) {
1382 if (VA.getLocVT() == MVT::v2f64) {
1383 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1384 DAG.getConstant(0, MVT::i32));
1385 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1386 DAG.getConstant(1, MVT::i32));
1388 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1389 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1391 VA = ArgLocs[++i]; // skip ahead to next loc
1392 if (VA.isRegLoc()) {
1393 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1394 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1396 assert(VA.isMemLoc());
1398 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1399 dl, DAG, VA, Flags));
1402 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1403 StackPtr, MemOpChains, Flags);
1405 } else if (VA.isRegLoc()) {
1406 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1407 } else if (isByVal) {
1408 assert(VA.isMemLoc());
1409 unsigned offset = 0;
1411 // True if this byval aggregate will be split between registers
1413 if (CCInfo.isFirstByValRegValid()) {
1414 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1416 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1417 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1418 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1419 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1420 MachinePointerInfo(),
1421 false, false, false, 0);
1422 MemOpChains.push_back(Load.getValue(1));
1423 RegsToPass.push_back(std::make_pair(j, Load));
1425 offset = ARM::R4 - CCInfo.getFirstByValReg();
1426 CCInfo.clearFirstByValReg();
1429 if (Flags.getByValSize() - 4*offset > 0) {
1430 unsigned LocMemOffset = VA.getLocMemOffset();
1431 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1432 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1434 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1435 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1436 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1438 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1440 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1441 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1442 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1443 Ops, array_lengthof(Ops)));
1445 } else if (!IsSibCall) {
1446 assert(VA.isMemLoc());
1448 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1449 dl, DAG, VA, Flags));
1453 if (!MemOpChains.empty())
1454 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1455 &MemOpChains[0], MemOpChains.size());
1457 // Build a sequence of copy-to-reg nodes chained together with token chain
1458 // and flag operands which copy the outgoing args into the appropriate regs.
1460 // Tail call byval lowering might overwrite argument registers so in case of
1461 // tail call optimization the copies to registers are lowered later.
1463 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1464 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1465 RegsToPass[i].second, InFlag);
1466 InFlag = Chain.getValue(1);
1469 // For tail calls lower the arguments to the 'real' stack slot.
1471 // Force all the incoming stack arguments to be loaded from the stack
1472 // before any new outgoing arguments are stored to the stack, because the
1473 // outgoing stack slots may alias the incoming argument stack slots, and
1474 // the alias isn't otherwise explicit. This is slightly more conservative
1475 // than necessary, because it means that each store effectively depends
1476 // on every argument instead of just those arguments it would clobber.
1478 // Do not flag preceding copytoreg stuff together with the following stuff.
1480 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1481 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1482 RegsToPass[i].second, InFlag);
1483 InFlag = Chain.getValue(1);
1488 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1489 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1490 // node so that legalize doesn't hack it.
1491 bool isDirect = false;
1492 bool isARMFunc = false;
1493 bool isLocalARMFunc = false;
1494 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1496 if (EnableARMLongCalls) {
1497 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1498 && "long-calls with non-static relocation model!");
1499 // Handle a global address or an external symbol. If it's not one of
1500 // those, the target's already in a register, so we don't need to do
1502 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1503 const GlobalValue *GV = G->getGlobal();
1504 // Create a constant pool entry for the callee address
1505 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1506 ARMConstantPoolValue *CPV =
1507 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1509 // Get the address of the callee into a register
1510 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1511 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1512 Callee = DAG.getLoad(getPointerTy(), dl,
1513 DAG.getEntryNode(), CPAddr,
1514 MachinePointerInfo::getConstantPool(),
1515 false, false, false, 0);
1516 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1517 const char *Sym = S->getSymbol();
1519 // Create a constant pool entry for the callee address
1520 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1521 ARMConstantPoolValue *CPV =
1522 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1523 ARMPCLabelIndex, 0);
1524 // Get the address of the callee into a register
1525 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1526 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1527 Callee = DAG.getLoad(getPointerTy(), dl,
1528 DAG.getEntryNode(), CPAddr,
1529 MachinePointerInfo::getConstantPool(),
1530 false, false, false, 0);
1532 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1533 const GlobalValue *GV = G->getGlobal();
1535 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1536 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1537 getTargetMachine().getRelocationModel() != Reloc::Static;
1538 isARMFunc = !Subtarget->isThumb() || isStub;
1539 // ARM call to a local ARM function is predicable.
1540 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1541 // tBX takes a register source operand.
1542 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1543 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1544 ARMConstantPoolValue *CPV =
1545 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1546 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1547 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1548 Callee = DAG.getLoad(getPointerTy(), dl,
1549 DAG.getEntryNode(), CPAddr,
1550 MachinePointerInfo::getConstantPool(),
1551 false, false, false, 0);
1552 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1553 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1554 getPointerTy(), Callee, PICLabel);
1556 // On ELF targets for PIC code, direct calls should go through the PLT
1557 unsigned OpFlags = 0;
1558 if (Subtarget->isTargetELF() &&
1559 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1560 OpFlags = ARMII::MO_PLT;
1561 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1563 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1565 bool isStub = Subtarget->isTargetDarwin() &&
1566 getTargetMachine().getRelocationModel() != Reloc::Static;
1567 isARMFunc = !Subtarget->isThumb() || isStub;
1568 // tBX takes a register source operand.
1569 const char *Sym = S->getSymbol();
1570 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1571 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1572 ARMConstantPoolValue *CPV =
1573 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1574 ARMPCLabelIndex, 4);
1575 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1576 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1577 Callee = DAG.getLoad(getPointerTy(), dl,
1578 DAG.getEntryNode(), CPAddr,
1579 MachinePointerInfo::getConstantPool(),
1580 false, false, false, 0);
1581 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1582 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1583 getPointerTy(), Callee, PICLabel);
1585 unsigned OpFlags = 0;
1586 // On ELF targets for PIC code, direct calls should go through the PLT
1587 if (Subtarget->isTargetELF() &&
1588 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1589 OpFlags = ARMII::MO_PLT;
1590 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1594 // FIXME: handle tail calls differently.
1596 if (Subtarget->isThumb()) {
1597 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1598 CallOpc = ARMISD::CALL_NOLINK;
1599 else if (doesNotRet && isDirect && !isARMFunc &&
1600 Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1601 // "mov lr, pc; b _foo" to avoid confusing the RSP
1602 CallOpc = ARMISD::CALL_NOLINK;
1604 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1606 if (!isDirect && !Subtarget->hasV5TOps()) {
1607 CallOpc = ARMISD::CALL_NOLINK;
1608 } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1609 // "mov lr, pc; b _foo" to avoid confusing the RSP
1610 CallOpc = ARMISD::CALL_NOLINK;
1612 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1615 std::vector<SDValue> Ops;
1616 Ops.push_back(Chain);
1617 Ops.push_back(Callee);
1619 // Add argument registers to the end of the list so that they are known live
1621 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1622 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1623 RegsToPass[i].second.getValueType()));
1625 // Add a register mask operand representing the call-preserved registers.
1626 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1627 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1628 assert(Mask && "Missing call preserved mask for calling convention");
1629 Ops.push_back(DAG.getRegisterMask(Mask));
1631 if (InFlag.getNode())
1632 Ops.push_back(InFlag);
1634 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1636 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1638 // Returns a chain and a flag for retval copy to use.
1639 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1640 InFlag = Chain.getValue(1);
1642 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1643 DAG.getIntPtrConstant(0, true), InFlag);
1645 InFlag = Chain.getValue(1);
1647 // Handle result values, copying them out of physregs into vregs that we
1649 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1653 /// HandleByVal - Every parameter *after* a byval parameter is passed
1654 /// on the stack. Remember the next parameter register to allocate,
1655 /// and then confiscate the rest of the parameter registers to insure
1658 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1659 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1660 assert((State->getCallOrPrologue() == Prologue ||
1661 State->getCallOrPrologue() == Call) &&
1662 "unhandled ParmContext");
1663 if ((!State->isFirstByValRegValid()) &&
1664 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1665 State->setFirstByValReg(reg);
1666 // At a call site, a byval parameter that is split between
1667 // registers and memory needs its size truncated here. In a
1668 // function prologue, such byval parameters are reassembled in
1669 // memory, and are not truncated.
1670 if (State->getCallOrPrologue() == Call) {
1671 unsigned excess = 4 * (ARM::R4 - reg);
1672 assert(size >= excess && "expected larger existing stack allocation");
1676 // Confiscate any remaining parameter registers to preclude their
1677 // assignment to subsequent parameters.
1678 while (State->AllocateReg(GPRArgRegs, 4))
1682 /// MatchingStackOffset - Return true if the given stack call argument is
1683 /// already available in the same position (relatively) of the caller's
1684 /// incoming argument stack.
1686 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1687 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1688 const TargetInstrInfo *TII) {
1689 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1691 if (Arg.getOpcode() == ISD::CopyFromReg) {
1692 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1693 if (!TargetRegisterInfo::isVirtualRegister(VR))
1695 MachineInstr *Def = MRI->getVRegDef(VR);
1698 if (!Flags.isByVal()) {
1699 if (!TII->isLoadFromStackSlot(Def, FI))
1704 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1705 if (Flags.isByVal())
1706 // ByVal argument is passed in as a pointer but it's now being
1707 // dereferenced. e.g.
1708 // define @foo(%struct.X* %A) {
1709 // tail call @bar(%struct.X* byval %A)
1712 SDValue Ptr = Ld->getBasePtr();
1713 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1716 FI = FINode->getIndex();
1720 assert(FI != INT_MAX);
1721 if (!MFI->isFixedObjectIndex(FI))
1723 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1726 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1727 /// for tail call optimization. Targets which want to do tail call
1728 /// optimization should implement this function.
1730 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1731 CallingConv::ID CalleeCC,
1733 bool isCalleeStructRet,
1734 bool isCallerStructRet,
1735 const SmallVectorImpl<ISD::OutputArg> &Outs,
1736 const SmallVectorImpl<SDValue> &OutVals,
1737 const SmallVectorImpl<ISD::InputArg> &Ins,
1738 SelectionDAG& DAG) const {
1739 const Function *CallerF = DAG.getMachineFunction().getFunction();
1740 CallingConv::ID CallerCC = CallerF->getCallingConv();
1741 bool CCMatch = CallerCC == CalleeCC;
1743 // Look for obvious safe cases to perform tail call optimization that do not
1744 // require ABI changes. This is what gcc calls sibcall.
1746 // Do not sibcall optimize vararg calls unless the call site is not passing
1748 if (isVarArg && !Outs.empty())
1751 // Also avoid sibcall optimization if either caller or callee uses struct
1752 // return semantics.
1753 if (isCalleeStructRet || isCallerStructRet)
1756 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1757 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1758 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1759 // support in the assembler and linker to be used. This would need to be
1760 // fixed to fully support tail calls in Thumb1.
1762 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1763 // LR. This means if we need to reload LR, it takes an extra instructions,
1764 // which outweighs the value of the tail call; but here we don't know yet
1765 // whether LR is going to be used. Probably the right approach is to
1766 // generate the tail call here and turn it back into CALL/RET in
1767 // emitEpilogue if LR is used.
1769 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1770 // but we need to make sure there are enough registers; the only valid
1771 // registers are the 4 used for parameters. We don't currently do this
1773 if (Subtarget->isThumb1Only())
1776 // If the calling conventions do not match, then we'd better make sure the
1777 // results are returned in the same way as what the caller expects.
1779 SmallVector<CCValAssign, 16> RVLocs1;
1780 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1781 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1782 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1784 SmallVector<CCValAssign, 16> RVLocs2;
1785 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1786 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1787 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1789 if (RVLocs1.size() != RVLocs2.size())
1791 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1792 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1794 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1796 if (RVLocs1[i].isRegLoc()) {
1797 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1800 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1806 // If the callee takes no arguments then go on to check the results of the
1808 if (!Outs.empty()) {
1809 // Check if stack adjustment is needed. For now, do not do this if any
1810 // argument is passed on the stack.
1811 SmallVector<CCValAssign, 16> ArgLocs;
1812 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1813 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1814 CCInfo.AnalyzeCallOperands(Outs,
1815 CCAssignFnForNode(CalleeCC, false, isVarArg));
1816 if (CCInfo.getNextStackOffset()) {
1817 MachineFunction &MF = DAG.getMachineFunction();
1819 // Check if the arguments are already laid out in the right way as
1820 // the caller's fixed stack objects.
1821 MachineFrameInfo *MFI = MF.getFrameInfo();
1822 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1823 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1824 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1826 ++i, ++realArgIdx) {
1827 CCValAssign &VA = ArgLocs[i];
1828 EVT RegVT = VA.getLocVT();
1829 SDValue Arg = OutVals[realArgIdx];
1830 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1831 if (VA.getLocInfo() == CCValAssign::Indirect)
1833 if (VA.needsCustom()) {
1834 // f64 and vector types are split into multiple registers or
1835 // register/stack-slot combinations. The types will not match
1836 // the registers; give up on memory f64 refs until we figure
1837 // out what to do about this.
1840 if (!ArgLocs[++i].isRegLoc())
1842 if (RegVT == MVT::v2f64) {
1843 if (!ArgLocs[++i].isRegLoc())
1845 if (!ArgLocs[++i].isRegLoc())
1848 } else if (!VA.isRegLoc()) {
1849 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1861 ARMTargetLowering::LowerReturn(SDValue Chain,
1862 CallingConv::ID CallConv, bool isVarArg,
1863 const SmallVectorImpl<ISD::OutputArg> &Outs,
1864 const SmallVectorImpl<SDValue> &OutVals,
1865 DebugLoc dl, SelectionDAG &DAG) const {
1867 // CCValAssign - represent the assignment of the return value to a location.
1868 SmallVector<CCValAssign, 16> RVLocs;
1870 // CCState - Info about the registers and stack slots.
1871 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1872 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1874 // Analyze outgoing return values.
1875 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1878 // If this is the first return lowered for this function, add
1879 // the regs to the liveout set for the function.
1880 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1881 for (unsigned i = 0; i != RVLocs.size(); ++i)
1882 if (RVLocs[i].isRegLoc())
1883 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1888 // Copy the result values into the output registers.
1889 for (unsigned i = 0, realRVLocIdx = 0;
1891 ++i, ++realRVLocIdx) {
1892 CCValAssign &VA = RVLocs[i];
1893 assert(VA.isRegLoc() && "Can only return in registers!");
1895 SDValue Arg = OutVals[realRVLocIdx];
1897 switch (VA.getLocInfo()) {
1898 default: llvm_unreachable("Unknown loc info!");
1899 case CCValAssign::Full: break;
1900 case CCValAssign::BCvt:
1901 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1905 if (VA.needsCustom()) {
1906 if (VA.getLocVT() == MVT::v2f64) {
1907 // Extract the first half and return it in two registers.
1908 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1909 DAG.getConstant(0, MVT::i32));
1910 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1911 DAG.getVTList(MVT::i32, MVT::i32), Half);
1913 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1914 Flag = Chain.getValue(1);
1915 VA = RVLocs[++i]; // skip ahead to next loc
1916 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1917 HalfGPRs.getValue(1), Flag);
1918 Flag = Chain.getValue(1);
1919 VA = RVLocs[++i]; // skip ahead to next loc
1921 // Extract the 2nd half and fall through to handle it as an f64 value.
1922 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1923 DAG.getConstant(1, MVT::i32));
1925 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1927 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1928 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1929 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1930 Flag = Chain.getValue(1);
1931 VA = RVLocs[++i]; // skip ahead to next loc
1932 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1935 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1937 // Guarantee that all emitted copies are
1938 // stuck together, avoiding something bad.
1939 Flag = Chain.getValue(1);
1944 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1946 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1951 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1952 if (N->getNumValues() != 1)
1954 if (!N->hasNUsesOfValue(1, 0))
1957 SDValue TCChain = Chain;
1958 SDNode *Copy = *N->use_begin();
1959 if (Copy->getOpcode() == ISD::CopyToReg) {
1960 // If the copy has a glue operand, we conservatively assume it isn't safe to
1961 // perform a tail call.
1962 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1964 TCChain = Copy->getOperand(0);
1965 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1966 SDNode *VMov = Copy;
1967 // f64 returned in a pair of GPRs.
1968 SmallPtrSet<SDNode*, 2> Copies;
1969 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1971 if (UI->getOpcode() != ISD::CopyToReg)
1975 if (Copies.size() > 2)
1978 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1980 SDValue UseChain = UI->getOperand(0);
1981 if (Copies.count(UseChain.getNode()))
1988 } else if (Copy->getOpcode() == ISD::BITCAST) {
1989 // f32 returned in a single GPR.
1990 if (!Copy->hasOneUse())
1992 Copy = *Copy->use_begin();
1993 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1995 Chain = Copy->getOperand(0);
2000 bool HasRet = false;
2001 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2003 if (UI->getOpcode() != ARMISD::RET_FLAG)
2015 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2016 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2019 if (!CI->isTailCall())
2022 return !Subtarget->isThumb1Only();
2025 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2026 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2027 // one of the above mentioned nodes. It has to be wrapped because otherwise
2028 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2029 // be used to form addressing mode. These wrapped nodes will be selected
2031 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2032 EVT PtrVT = Op.getValueType();
2033 // FIXME there is no actual debug info here
2034 DebugLoc dl = Op.getDebugLoc();
2035 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2037 if (CP->isMachineConstantPoolEntry())
2038 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2039 CP->getAlignment());
2041 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2042 CP->getAlignment());
2043 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2046 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2047 return MachineJumpTableInfo::EK_Inline;
2050 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2051 SelectionDAG &DAG) const {
2052 MachineFunction &MF = DAG.getMachineFunction();
2053 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2054 unsigned ARMPCLabelIndex = 0;
2055 DebugLoc DL = Op.getDebugLoc();
2056 EVT PtrVT = getPointerTy();
2057 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2058 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2060 if (RelocM == Reloc::Static) {
2061 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2063 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2064 ARMPCLabelIndex = AFI->createPICLabelUId();
2065 ARMConstantPoolValue *CPV =
2066 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2067 ARMCP::CPBlockAddress, PCAdj);
2068 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2070 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2071 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2072 MachinePointerInfo::getConstantPool(),
2073 false, false, false, 0);
2074 if (RelocM == Reloc::Static)
2076 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2077 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2080 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2082 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2083 SelectionDAG &DAG) const {
2084 DebugLoc dl = GA->getDebugLoc();
2085 EVT PtrVT = getPointerTy();
2086 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2087 MachineFunction &MF = DAG.getMachineFunction();
2088 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2089 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2090 ARMConstantPoolValue *CPV =
2091 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2092 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2093 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2094 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2095 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2096 MachinePointerInfo::getConstantPool(),
2097 false, false, false, 0);
2098 SDValue Chain = Argument.getValue(1);
2100 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2101 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2103 // call __tls_get_addr.
2106 Entry.Node = Argument;
2107 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2108 Args.push_back(Entry);
2109 // FIXME: is there useful debug info available here?
2110 TargetLowering::CallLoweringInfo CLI(Chain,
2111 (Type *) Type::getInt32Ty(*DAG.getContext()),
2112 false, false, false, false,
2113 0, CallingConv::C, /*isTailCall=*/false,
2114 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2115 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2116 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2117 return CallResult.first;
2120 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2121 // "local exec" model.
2123 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2125 TLSModel::Model model) const {
2126 const GlobalValue *GV = GA->getGlobal();
2127 DebugLoc dl = GA->getDebugLoc();
2129 SDValue Chain = DAG.getEntryNode();
2130 EVT PtrVT = getPointerTy();
2131 // Get the Thread Pointer
2132 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2134 if (model == TLSModel::InitialExec) {
2135 MachineFunction &MF = DAG.getMachineFunction();
2136 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2137 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2138 // Initial exec model.
2139 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2140 ARMConstantPoolValue *CPV =
2141 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2142 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2144 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2145 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2146 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2147 MachinePointerInfo::getConstantPool(),
2148 false, false, false, 0);
2149 Chain = Offset.getValue(1);
2151 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2152 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2154 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2155 MachinePointerInfo::getConstantPool(),
2156 false, false, false, 0);
2159 assert(model == TLSModel::LocalExec);
2160 ARMConstantPoolValue *CPV =
2161 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2162 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2163 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2164 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2165 MachinePointerInfo::getConstantPool(),
2166 false, false, false, 0);
2169 // The address of the thread local variable is the add of the thread
2170 // pointer with the offset of the variable.
2171 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2175 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2176 // TODO: implement the "local dynamic" model
2177 assert(Subtarget->isTargetELF() &&
2178 "TLS not implemented for non-ELF targets");
2179 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2181 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2184 case TLSModel::GeneralDynamic:
2185 case TLSModel::LocalDynamic:
2186 return LowerToTLSGeneralDynamicModel(GA, DAG);
2187 case TLSModel::InitialExec:
2188 case TLSModel::LocalExec:
2189 return LowerToTLSExecModels(GA, DAG, model);
2191 llvm_unreachable("bogus TLS model");
2194 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2195 SelectionDAG &DAG) const {
2196 EVT PtrVT = getPointerTy();
2197 DebugLoc dl = Op.getDebugLoc();
2198 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2199 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2200 if (RelocM == Reloc::PIC_) {
2201 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2202 ARMConstantPoolValue *CPV =
2203 ARMConstantPoolConstant::Create(GV,
2204 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2205 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2206 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2207 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2209 MachinePointerInfo::getConstantPool(),
2210 false, false, false, 0);
2211 SDValue Chain = Result.getValue(1);
2212 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2213 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2215 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2216 MachinePointerInfo::getGOT(),
2217 false, false, false, 0);
2221 // If we have T2 ops, we can materialize the address directly via movt/movw
2222 // pair. This is always cheaper.
2223 if (Subtarget->useMovt()) {
2225 // FIXME: Once remat is capable of dealing with instructions with register
2226 // operands, expand this into two nodes.
2227 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2228 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2230 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2231 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2232 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2233 MachinePointerInfo::getConstantPool(),
2234 false, false, false, 0);
2238 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2239 SelectionDAG &DAG) const {
2240 EVT PtrVT = getPointerTy();
2241 DebugLoc dl = Op.getDebugLoc();
2242 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2243 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2244 MachineFunction &MF = DAG.getMachineFunction();
2245 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2247 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2248 // update ARMFastISel::ARMMaterializeGV.
2249 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2251 // FIXME: Once remat is capable of dealing with instructions with register
2252 // operands, expand this into two nodes.
2253 if (RelocM == Reloc::Static)
2254 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2255 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2257 unsigned Wrapper = (RelocM == Reloc::PIC_)
2258 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2259 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2260 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2261 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2262 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2263 MachinePointerInfo::getGOT(),
2264 false, false, false, 0);
2268 unsigned ARMPCLabelIndex = 0;
2270 if (RelocM == Reloc::Static) {
2271 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2273 ARMPCLabelIndex = AFI->createPICLabelUId();
2274 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2275 ARMConstantPoolValue *CPV =
2276 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2278 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2280 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2282 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2283 MachinePointerInfo::getConstantPool(),
2284 false, false, false, 0);
2285 SDValue Chain = Result.getValue(1);
2287 if (RelocM == Reloc::PIC_) {
2288 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2289 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2292 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2293 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2294 false, false, false, 0);
2299 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2300 SelectionDAG &DAG) const {
2301 assert(Subtarget->isTargetELF() &&
2302 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2303 MachineFunction &MF = DAG.getMachineFunction();
2304 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2306 EVT PtrVT = getPointerTy();
2307 DebugLoc dl = Op.getDebugLoc();
2308 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2309 ARMConstantPoolValue *CPV =
2310 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2311 ARMPCLabelIndex, PCAdj);
2312 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2313 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2314 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2315 MachinePointerInfo::getConstantPool(),
2316 false, false, false, 0);
2317 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2318 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2322 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2323 DebugLoc dl = Op.getDebugLoc();
2324 SDValue Val = DAG.getConstant(0, MVT::i32);
2325 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2326 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2327 Op.getOperand(1), Val);
2331 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2332 DebugLoc dl = Op.getDebugLoc();
2333 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2334 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2338 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2339 const ARMSubtarget *Subtarget) const {
2340 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2341 DebugLoc dl = Op.getDebugLoc();
2343 default: return SDValue(); // Don't custom lower most intrinsics.
2344 case Intrinsic::arm_thread_pointer: {
2345 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2346 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2348 case Intrinsic::eh_sjlj_lsda: {
2349 MachineFunction &MF = DAG.getMachineFunction();
2350 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2351 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2352 EVT PtrVT = getPointerTy();
2353 DebugLoc dl = Op.getDebugLoc();
2354 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2356 unsigned PCAdj = (RelocM != Reloc::PIC_)
2357 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2358 ARMConstantPoolValue *CPV =
2359 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2360 ARMCP::CPLSDA, PCAdj);
2361 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2362 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2364 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2365 MachinePointerInfo::getConstantPool(),
2366 false, false, false, 0);
2368 if (RelocM == Reloc::PIC_) {
2369 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2370 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2374 case Intrinsic::arm_neon_vmulls:
2375 case Intrinsic::arm_neon_vmullu: {
2376 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2377 ? ARMISD::VMULLs : ARMISD::VMULLu;
2378 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2379 Op.getOperand(1), Op.getOperand(2));
2384 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2385 const ARMSubtarget *Subtarget) {
2386 DebugLoc dl = Op.getDebugLoc();
2387 if (!Subtarget->hasDataBarrier()) {
2388 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2389 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2391 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2392 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2393 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2394 DAG.getConstant(0, MVT::i32));
2397 SDValue Op5 = Op.getOperand(5);
2398 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2399 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2400 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2401 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2403 ARM_MB::MemBOpt DMBOpt;
2404 if (isDeviceBarrier)
2405 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2407 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2408 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2409 DAG.getConstant(DMBOpt, MVT::i32));
2413 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2414 const ARMSubtarget *Subtarget) {
2415 // FIXME: handle "fence singlethread" more efficiently.
2416 DebugLoc dl = Op.getDebugLoc();
2417 if (!Subtarget->hasDataBarrier()) {
2418 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2419 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2421 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2422 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2423 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2424 DAG.getConstant(0, MVT::i32));
2427 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2428 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2431 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2432 const ARMSubtarget *Subtarget) {
2433 // ARM pre v5TE and Thumb1 does not have preload instructions.
2434 if (!(Subtarget->isThumb2() ||
2435 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2436 // Just preserve the chain.
2437 return Op.getOperand(0);
2439 DebugLoc dl = Op.getDebugLoc();
2440 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2442 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2443 // ARMv7 with MP extension has PLDW.
2444 return Op.getOperand(0);
2446 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2447 if (Subtarget->isThumb()) {
2449 isRead = ~isRead & 1;
2450 isData = ~isData & 1;
2453 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2454 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2455 DAG.getConstant(isData, MVT::i32));
2458 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2459 MachineFunction &MF = DAG.getMachineFunction();
2460 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2462 // vastart just stores the address of the VarArgsFrameIndex slot into the
2463 // memory location argument.
2464 DebugLoc dl = Op.getDebugLoc();
2465 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2466 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2467 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2468 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2469 MachinePointerInfo(SV), false, false, 0);
2473 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2474 SDValue &Root, SelectionDAG &DAG,
2475 DebugLoc dl) const {
2476 MachineFunction &MF = DAG.getMachineFunction();
2477 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2479 const TargetRegisterClass *RC;
2480 if (AFI->isThumb1OnlyFunction())
2481 RC = &ARM::tGPRRegClass;
2483 RC = &ARM::GPRRegClass;
2485 // Transform the arguments stored in physical registers into virtual ones.
2486 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2487 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2490 if (NextVA.isMemLoc()) {
2491 MachineFrameInfo *MFI = MF.getFrameInfo();
2492 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2494 // Create load node to retrieve arguments from the stack.
2495 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2496 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2497 MachinePointerInfo::getFixedStack(FI),
2498 false, false, false, 0);
2500 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2501 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2504 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2508 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2509 unsigned &VARegSize, unsigned &VARegSaveSize)
2512 if (CCInfo.isFirstByValRegValid())
2513 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2515 unsigned int firstUnalloced;
2516 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2517 sizeof(GPRArgRegs) /
2518 sizeof(GPRArgRegs[0]));
2519 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2522 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2523 VARegSize = NumGPRs * 4;
2524 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2527 // The remaining GPRs hold either the beginning of variable-argument
2528 // data, or the beginning of an aggregate passed by value (usuall
2529 // byval). Either way, we allocate stack slots adjacent to the data
2530 // provided by our caller, and store the unallocated registers there.
2531 // If this is a variadic function, the va_list pointer will begin with
2532 // these values; otherwise, this reassembles a (byval) structure that
2533 // was split between registers and memory.
2535 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2536 DebugLoc dl, SDValue &Chain,
2537 unsigned ArgOffset) const {
2538 MachineFunction &MF = DAG.getMachineFunction();
2539 MachineFrameInfo *MFI = MF.getFrameInfo();
2540 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2541 unsigned firstRegToSaveIndex;
2542 if (CCInfo.isFirstByValRegValid())
2543 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2545 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2546 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2549 unsigned VARegSize, VARegSaveSize;
2550 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2551 if (VARegSaveSize) {
2552 // If this function is vararg, store any remaining integer argument regs
2553 // to their spots on the stack so that they may be loaded by deferencing
2554 // the result of va_next.
2555 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2556 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2557 ArgOffset + VARegSaveSize
2560 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2563 SmallVector<SDValue, 4> MemOps;
2564 for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2565 const TargetRegisterClass *RC;
2566 if (AFI->isThumb1OnlyFunction())
2567 RC = &ARM::tGPRRegClass;
2569 RC = &ARM::GPRRegClass;
2571 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2572 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2574 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2575 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2577 MemOps.push_back(Store);
2578 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2579 DAG.getConstant(4, getPointerTy()));
2581 if (!MemOps.empty())
2582 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2583 &MemOps[0], MemOps.size());
2585 // This will point to the next argument passed via stack.
2586 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2590 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2591 CallingConv::ID CallConv, bool isVarArg,
2592 const SmallVectorImpl<ISD::InputArg>
2594 DebugLoc dl, SelectionDAG &DAG,
2595 SmallVectorImpl<SDValue> &InVals)
2597 MachineFunction &MF = DAG.getMachineFunction();
2598 MachineFrameInfo *MFI = MF.getFrameInfo();
2600 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2602 // Assign locations to all of the incoming arguments.
2603 SmallVector<CCValAssign, 16> ArgLocs;
2604 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2605 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2606 CCInfo.AnalyzeFormalArguments(Ins,
2607 CCAssignFnForNode(CallConv, /* Return*/ false,
2610 SmallVector<SDValue, 16> ArgValues;
2611 int lastInsIndex = -1;
2614 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2615 CCValAssign &VA = ArgLocs[i];
2617 // Arguments stored in registers.
2618 if (VA.isRegLoc()) {
2619 EVT RegVT = VA.getLocVT();
2621 if (VA.needsCustom()) {
2622 // f64 and vector types are split up into multiple registers or
2623 // combinations of registers and stack slots.
2624 if (VA.getLocVT() == MVT::v2f64) {
2625 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2627 VA = ArgLocs[++i]; // skip ahead to next loc
2629 if (VA.isMemLoc()) {
2630 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2631 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2632 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2633 MachinePointerInfo::getFixedStack(FI),
2634 false, false, false, 0);
2636 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2639 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2640 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2641 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2642 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2643 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2645 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2648 const TargetRegisterClass *RC;
2650 if (RegVT == MVT::f32)
2651 RC = &ARM::SPRRegClass;
2652 else if (RegVT == MVT::f64)
2653 RC = &ARM::DPRRegClass;
2654 else if (RegVT == MVT::v2f64)
2655 RC = &ARM::QPRRegClass;
2656 else if (RegVT == MVT::i32)
2657 RC = AFI->isThumb1OnlyFunction() ?
2658 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2659 (const TargetRegisterClass*)&ARM::GPRRegClass;
2661 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2663 // Transform the arguments in physical registers into virtual ones.
2664 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2665 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2668 // If this is an 8 or 16-bit value, it is really passed promoted
2669 // to 32 bits. Insert an assert[sz]ext to capture this, then
2670 // truncate to the right size.
2671 switch (VA.getLocInfo()) {
2672 default: llvm_unreachable("Unknown loc info!");
2673 case CCValAssign::Full: break;
2674 case CCValAssign::BCvt:
2675 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2677 case CCValAssign::SExt:
2678 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2679 DAG.getValueType(VA.getValVT()));
2680 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2682 case CCValAssign::ZExt:
2683 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2684 DAG.getValueType(VA.getValVT()));
2685 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2689 InVals.push_back(ArgValue);
2691 } else { // VA.isRegLoc()
2694 assert(VA.isMemLoc());
2695 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2697 int index = ArgLocs[i].getValNo();
2699 // Some Ins[] entries become multiple ArgLoc[] entries.
2700 // Process them only once.
2701 if (index != lastInsIndex)
2703 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2704 // FIXME: For now, all byval parameter objects are marked mutable.
2705 // This can be changed with more analysis.
2706 // In case of tail call optimization mark all arguments mutable.
2707 // Since they could be overwritten by lowering of arguments in case of
2709 if (Flags.isByVal()) {
2710 unsigned VARegSize, VARegSaveSize;
2711 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2712 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2713 unsigned Bytes = Flags.getByValSize() - VARegSize;
2714 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2715 int FI = MFI->CreateFixedObject(Bytes,
2716 VA.getLocMemOffset(), false);
2717 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2719 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2720 VA.getLocMemOffset(), true);
2722 // Create load nodes to retrieve arguments from the stack.
2723 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2724 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2725 MachinePointerInfo::getFixedStack(FI),
2726 false, false, false, 0));
2728 lastInsIndex = index;
2735 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2740 /// isFloatingPointZero - Return true if this is +0.0.
2741 static bool isFloatingPointZero(SDValue Op) {
2742 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2743 return CFP->getValueAPF().isPosZero();
2744 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2745 // Maybe this has already been legalized into the constant pool?
2746 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2747 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2748 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2749 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2750 return CFP->getValueAPF().isPosZero();
2756 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2757 /// the given operands.
2759 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2760 SDValue &ARMcc, SelectionDAG &DAG,
2761 DebugLoc dl) const {
2762 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2763 unsigned C = RHSC->getZExtValue();
2764 if (!isLegalICmpImmediate(C)) {
2765 // Constant does not fit, try adjusting it by one?
2770 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2771 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2772 RHS = DAG.getConstant(C-1, MVT::i32);
2777 if (C != 0 && isLegalICmpImmediate(C-1)) {
2778 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2779 RHS = DAG.getConstant(C-1, MVT::i32);
2784 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2785 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2786 RHS = DAG.getConstant(C+1, MVT::i32);
2791 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2792 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2793 RHS = DAG.getConstant(C+1, MVT::i32);
2800 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2801 ARMISD::NodeType CompareType;
2804 CompareType = ARMISD::CMP;
2809 CompareType = ARMISD::CMPZ;
2812 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2813 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2816 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2818 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2819 DebugLoc dl) const {
2821 if (!isFloatingPointZero(RHS))
2822 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2824 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2825 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2828 /// duplicateCmp - Glue values can have only one use, so this function
2829 /// duplicates a comparison node.
2831 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2832 unsigned Opc = Cmp.getOpcode();
2833 DebugLoc DL = Cmp.getDebugLoc();
2834 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2835 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2837 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2838 Cmp = Cmp.getOperand(0);
2839 Opc = Cmp.getOpcode();
2840 if (Opc == ARMISD::CMPFP)
2841 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2843 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2844 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2846 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2849 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2850 SDValue Cond = Op.getOperand(0);
2851 SDValue SelectTrue = Op.getOperand(1);
2852 SDValue SelectFalse = Op.getOperand(2);
2853 DebugLoc dl = Op.getDebugLoc();
2857 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2858 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2860 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2861 const ConstantSDNode *CMOVTrue =
2862 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2863 const ConstantSDNode *CMOVFalse =
2864 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2866 if (CMOVTrue && CMOVFalse) {
2867 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2868 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2872 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2874 False = SelectFalse;
2875 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2880 if (True.getNode() && False.getNode()) {
2881 EVT VT = Op.getValueType();
2882 SDValue ARMcc = Cond.getOperand(2);
2883 SDValue CCR = Cond.getOperand(3);
2884 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2885 assert(True.getValueType() == VT);
2886 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2891 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2892 // undefined bits before doing a full-word comparison with zero.
2893 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2894 DAG.getConstant(1, Cond.getValueType()));
2896 return DAG.getSelectCC(dl, Cond,
2897 DAG.getConstant(0, Cond.getValueType()),
2898 SelectTrue, SelectFalse, ISD::SETNE);
2901 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2902 EVT VT = Op.getValueType();
2903 SDValue LHS = Op.getOperand(0);
2904 SDValue RHS = Op.getOperand(1);
2905 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2906 SDValue TrueVal = Op.getOperand(2);
2907 SDValue FalseVal = Op.getOperand(3);
2908 DebugLoc dl = Op.getDebugLoc();
2910 if (LHS.getValueType() == MVT::i32) {
2912 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2913 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2914 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2917 ARMCC::CondCodes CondCode, CondCode2;
2918 FPCCToARMCC(CC, CondCode, CondCode2);
2920 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2921 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2922 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2923 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2925 if (CondCode2 != ARMCC::AL) {
2926 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2927 // FIXME: Needs another CMP because flag can have but one use.
2928 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2929 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2930 Result, TrueVal, ARMcc2, CCR, Cmp2);
2935 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2936 /// to morph to an integer compare sequence.
2937 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2938 const ARMSubtarget *Subtarget) {
2939 SDNode *N = Op.getNode();
2940 if (!N->hasOneUse())
2941 // Otherwise it requires moving the value from fp to integer registers.
2943 if (!N->getNumValues())
2945 EVT VT = Op.getValueType();
2946 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2947 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2948 // vmrs are very slow, e.g. cortex-a8.
2951 if (isFloatingPointZero(Op)) {
2955 return ISD::isNormalLoad(N);
2958 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2959 if (isFloatingPointZero(Op))
2960 return DAG.getConstant(0, MVT::i32);
2962 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2963 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2964 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2965 Ld->isVolatile(), Ld->isNonTemporal(),
2966 Ld->isInvariant(), Ld->getAlignment());
2968 llvm_unreachable("Unknown VFP cmp argument!");
2971 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2972 SDValue &RetVal1, SDValue &RetVal2) {
2973 if (isFloatingPointZero(Op)) {
2974 RetVal1 = DAG.getConstant(0, MVT::i32);
2975 RetVal2 = DAG.getConstant(0, MVT::i32);
2979 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2980 SDValue Ptr = Ld->getBasePtr();
2981 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2982 Ld->getChain(), Ptr,
2983 Ld->getPointerInfo(),
2984 Ld->isVolatile(), Ld->isNonTemporal(),
2985 Ld->isInvariant(), Ld->getAlignment());
2987 EVT PtrType = Ptr.getValueType();
2988 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2989 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2990 PtrType, Ptr, DAG.getConstant(4, PtrType));
2991 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2992 Ld->getChain(), NewPtr,
2993 Ld->getPointerInfo().getWithOffset(4),
2994 Ld->isVolatile(), Ld->isNonTemporal(),
2995 Ld->isInvariant(), NewAlign);
2999 llvm_unreachable("Unknown VFP cmp argument!");
3002 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3003 /// f32 and even f64 comparisons to integer ones.
3005 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3006 SDValue Chain = Op.getOperand(0);
3007 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3008 SDValue LHS = Op.getOperand(2);
3009 SDValue RHS = Op.getOperand(3);
3010 SDValue Dest = Op.getOperand(4);
3011 DebugLoc dl = Op.getDebugLoc();
3013 bool LHSSeenZero = false;
3014 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3015 bool RHSSeenZero = false;
3016 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3017 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3018 // If unsafe fp math optimization is enabled and there are no other uses of
3019 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3020 // to an integer comparison.
3021 if (CC == ISD::SETOEQ)
3023 else if (CC == ISD::SETUNE)
3026 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3028 if (LHS.getValueType() == MVT::f32) {
3029 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3030 bitcastf32Toi32(LHS, DAG), Mask);
3031 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3032 bitcastf32Toi32(RHS, DAG), Mask);
3033 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3034 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3035 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3036 Chain, Dest, ARMcc, CCR, Cmp);
3041 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3042 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3043 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3044 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3045 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3046 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3047 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3048 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3049 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3055 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3056 SDValue Chain = Op.getOperand(0);
3057 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3058 SDValue LHS = Op.getOperand(2);
3059 SDValue RHS = Op.getOperand(3);
3060 SDValue Dest = Op.getOperand(4);
3061 DebugLoc dl = Op.getDebugLoc();
3063 if (LHS.getValueType() == MVT::i32) {
3065 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3066 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3067 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3068 Chain, Dest, ARMcc, CCR, Cmp);
3071 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3073 if (getTargetMachine().Options.UnsafeFPMath &&
3074 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3075 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3076 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3077 if (Result.getNode())
3081 ARMCC::CondCodes CondCode, CondCode2;
3082 FPCCToARMCC(CC, CondCode, CondCode2);
3084 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3085 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3086 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3087 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3088 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3089 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3090 if (CondCode2 != ARMCC::AL) {
3091 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3092 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3093 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3098 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3099 SDValue Chain = Op.getOperand(0);
3100 SDValue Table = Op.getOperand(1);
3101 SDValue Index = Op.getOperand(2);
3102 DebugLoc dl = Op.getDebugLoc();
3104 EVT PTy = getPointerTy();
3105 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3106 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3107 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3108 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3109 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3110 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3111 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3112 if (Subtarget->isThumb2()) {
3113 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3114 // which does another jump to the destination. This also makes it easier
3115 // to translate it to TBB / TBH later.
3116 // FIXME: This might not work if the function is extremely large.
3117 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3118 Addr, Op.getOperand(2), JTI, UId);
3120 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3121 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3122 MachinePointerInfo::getJumpTable(),
3123 false, false, false, 0);
3124 Chain = Addr.getValue(1);
3125 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3126 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3128 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3129 MachinePointerInfo::getJumpTable(),
3130 false, false, false, 0);
3131 Chain = Addr.getValue(1);
3132 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3136 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3137 EVT VT = Op.getValueType();
3138 DebugLoc dl = Op.getDebugLoc();
3140 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3141 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3143 return DAG.UnrollVectorOp(Op.getNode());
3146 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3147 "Invalid type for custom lowering!");
3148 if (VT != MVT::v4i16)
3149 return DAG.UnrollVectorOp(Op.getNode());
3151 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3152 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3155 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3156 EVT VT = Op.getValueType();
3158 return LowerVectorFP_TO_INT(Op, DAG);
3160 DebugLoc dl = Op.getDebugLoc();
3163 switch (Op.getOpcode()) {
3164 default: llvm_unreachable("Invalid opcode!");
3165 case ISD::FP_TO_SINT:
3166 Opc = ARMISD::FTOSI;
3168 case ISD::FP_TO_UINT:
3169 Opc = ARMISD::FTOUI;
3172 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3173 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3176 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3177 EVT VT = Op.getValueType();
3178 DebugLoc dl = Op.getDebugLoc();
3180 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3181 if (VT.getVectorElementType() == MVT::f32)
3183 return DAG.UnrollVectorOp(Op.getNode());
3186 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3187 "Invalid type for custom lowering!");
3188 if (VT != MVT::v4f32)
3189 return DAG.UnrollVectorOp(Op.getNode());
3193 switch (Op.getOpcode()) {
3194 default: llvm_unreachable("Invalid opcode!");
3195 case ISD::SINT_TO_FP:
3196 CastOpc = ISD::SIGN_EXTEND;
3197 Opc = ISD::SINT_TO_FP;
3199 case ISD::UINT_TO_FP:
3200 CastOpc = ISD::ZERO_EXTEND;
3201 Opc = ISD::UINT_TO_FP;
3205 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3206 return DAG.getNode(Opc, dl, VT, Op);
3209 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3210 EVT VT = Op.getValueType();
3212 return LowerVectorINT_TO_FP(Op, DAG);
3214 DebugLoc dl = Op.getDebugLoc();
3217 switch (Op.getOpcode()) {
3218 default: llvm_unreachable("Invalid opcode!");
3219 case ISD::SINT_TO_FP:
3220 Opc = ARMISD::SITOF;
3222 case ISD::UINT_TO_FP:
3223 Opc = ARMISD::UITOF;
3227 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3228 return DAG.getNode(Opc, dl, VT, Op);
3231 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3232 // Implement fcopysign with a fabs and a conditional fneg.
3233 SDValue Tmp0 = Op.getOperand(0);
3234 SDValue Tmp1 = Op.getOperand(1);
3235 DebugLoc dl = Op.getDebugLoc();
3236 EVT VT = Op.getValueType();
3237 EVT SrcVT = Tmp1.getValueType();
3238 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3239 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3240 bool UseNEON = !InGPR && Subtarget->hasNEON();
3243 // Use VBSL to copy the sign bit.
3244 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3245 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3246 DAG.getTargetConstant(EncodedVal, MVT::i32));
3247 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3249 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3250 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3251 DAG.getConstant(32, MVT::i32));
3252 else /*if (VT == MVT::f32)*/
3253 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3254 if (SrcVT == MVT::f32) {
3255 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3257 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3258 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3259 DAG.getConstant(32, MVT::i32));
3260 } else if (VT == MVT::f32)
3261 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3262 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3263 DAG.getConstant(32, MVT::i32));
3264 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3265 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3267 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3269 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3270 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3271 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3273 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3274 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3275 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3276 if (VT == MVT::f32) {
3277 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3278 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3279 DAG.getConstant(0, MVT::i32));
3281 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3287 // Bitcast operand 1 to i32.
3288 if (SrcVT == MVT::f64)
3289 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3290 &Tmp1, 1).getValue(1);
3291 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3293 // Or in the signbit with integer operations.
3294 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3295 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3296 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3297 if (VT == MVT::f32) {
3298 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3299 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3300 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3301 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3304 // f64: Or the high part with signbit and then combine two parts.
3305 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3307 SDValue Lo = Tmp0.getValue(0);
3308 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3309 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3310 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3313 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3314 MachineFunction &MF = DAG.getMachineFunction();
3315 MachineFrameInfo *MFI = MF.getFrameInfo();
3316 MFI->setReturnAddressIsTaken(true);
3318 EVT VT = Op.getValueType();
3319 DebugLoc dl = Op.getDebugLoc();
3320 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3322 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3323 SDValue Offset = DAG.getConstant(4, MVT::i32);
3324 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3325 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3326 MachinePointerInfo(), false, false, false, 0);
3329 // Return LR, which contains the return address. Mark it an implicit live-in.
3330 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3331 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3334 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3335 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3336 MFI->setFrameAddressIsTaken(true);
3338 EVT VT = Op.getValueType();
3339 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3340 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3341 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3342 ? ARM::R7 : ARM::R11;
3343 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3345 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3346 MachinePointerInfo(),
3347 false, false, false, 0);
3351 /// ExpandBITCAST - If the target supports VFP, this function is called to
3352 /// expand a bit convert where either the source or destination type is i64 to
3353 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3354 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3355 /// vectors), since the legalizer won't know what to do with that.
3356 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3357 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3358 DebugLoc dl = N->getDebugLoc();
3359 SDValue Op = N->getOperand(0);
3361 // This function is only supposed to be called for i64 types, either as the
3362 // source or destination of the bit convert.
3363 EVT SrcVT = Op.getValueType();
3364 EVT DstVT = N->getValueType(0);
3365 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3366 "ExpandBITCAST called for non-i64 type");
3368 // Turn i64->f64 into VMOVDRR.
3369 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3370 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3371 DAG.getConstant(0, MVT::i32));
3372 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3373 DAG.getConstant(1, MVT::i32));
3374 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3375 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3378 // Turn f64->i64 into VMOVRRD.
3379 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3380 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3381 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3382 // Merge the pieces into a single i64 value.
3383 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3389 /// getZeroVector - Returns a vector of specified type with all zero elements.
3390 /// Zero vectors are used to represent vector negation and in those cases
3391 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3392 /// not support i64 elements, so sometimes the zero vectors will need to be
3393 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3395 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3396 assert(VT.isVector() && "Expected a vector type");
3397 // The canonical modified immediate encoding of a zero vector is....0!
3398 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3399 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3400 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3401 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3404 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3405 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3406 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3407 SelectionDAG &DAG) const {
3408 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3409 EVT VT = Op.getValueType();
3410 unsigned VTBits = VT.getSizeInBits();
3411 DebugLoc dl = Op.getDebugLoc();
3412 SDValue ShOpLo = Op.getOperand(0);
3413 SDValue ShOpHi = Op.getOperand(1);
3414 SDValue ShAmt = Op.getOperand(2);
3416 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3418 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3420 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3421 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3422 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3423 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3424 DAG.getConstant(VTBits, MVT::i32));
3425 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3426 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3427 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3429 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3430 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3432 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3433 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3436 SDValue Ops[2] = { Lo, Hi };
3437 return DAG.getMergeValues(Ops, 2, dl);
3440 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3441 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3442 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3443 SelectionDAG &DAG) const {
3444 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3445 EVT VT = Op.getValueType();
3446 unsigned VTBits = VT.getSizeInBits();
3447 DebugLoc dl = Op.getDebugLoc();
3448 SDValue ShOpLo = Op.getOperand(0);
3449 SDValue ShOpHi = Op.getOperand(1);
3450 SDValue ShAmt = Op.getOperand(2);
3453 assert(Op.getOpcode() == ISD::SHL_PARTS);
3454 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3455 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3456 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3457 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3458 DAG.getConstant(VTBits, MVT::i32));
3459 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3460 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3462 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3463 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3464 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3466 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3467 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3470 SDValue Ops[2] = { Lo, Hi };
3471 return DAG.getMergeValues(Ops, 2, dl);
3474 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3475 SelectionDAG &DAG) const {
3476 // The rounding mode is in bits 23:22 of the FPSCR.
3477 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3478 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3479 // so that the shift + and get folded into a bitfield extract.
3480 DebugLoc dl = Op.getDebugLoc();
3481 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3482 DAG.getConstant(Intrinsic::arm_get_fpscr,
3484 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3485 DAG.getConstant(1U << 22, MVT::i32));
3486 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3487 DAG.getConstant(22, MVT::i32));
3488 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3489 DAG.getConstant(3, MVT::i32));
3492 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3493 const ARMSubtarget *ST) {
3494 EVT VT = N->getValueType(0);
3495 DebugLoc dl = N->getDebugLoc();
3497 if (!ST->hasV6T2Ops())
3500 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3501 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3504 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3505 const ARMSubtarget *ST) {
3506 EVT VT = N->getValueType(0);
3507 DebugLoc dl = N->getDebugLoc();
3512 // Lower vector shifts on NEON to use VSHL.
3513 assert(ST->hasNEON() && "unexpected vector shift");
3515 // Left shifts translate directly to the vshiftu intrinsic.
3516 if (N->getOpcode() == ISD::SHL)
3517 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3518 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3519 N->getOperand(0), N->getOperand(1));
3521 assert((N->getOpcode() == ISD::SRA ||
3522 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3524 // NEON uses the same intrinsics for both left and right shifts. For
3525 // right shifts, the shift amounts are negative, so negate the vector of
3527 EVT ShiftVT = N->getOperand(1).getValueType();
3528 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3529 getZeroVector(ShiftVT, DAG, dl),
3531 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3532 Intrinsic::arm_neon_vshifts :
3533 Intrinsic::arm_neon_vshiftu);
3534 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3535 DAG.getConstant(vshiftInt, MVT::i32),
3536 N->getOperand(0), NegatedCount);
3539 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3540 const ARMSubtarget *ST) {
3541 EVT VT = N->getValueType(0);
3542 DebugLoc dl = N->getDebugLoc();
3544 // We can get here for a node like i32 = ISD::SHL i32, i64
3548 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3549 "Unknown shift to lower!");
3551 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3552 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3553 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3556 // If we are in thumb mode, we don't have RRX.
3557 if (ST->isThumb1Only()) return SDValue();
3559 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3560 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3561 DAG.getConstant(0, MVT::i32));
3562 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3563 DAG.getConstant(1, MVT::i32));
3565 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3566 // captures the result into a carry flag.
3567 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3568 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3570 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3571 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3573 // Merge the pieces into a single i64 value.
3574 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3577 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3578 SDValue TmpOp0, TmpOp1;
3579 bool Invert = false;
3583 SDValue Op0 = Op.getOperand(0);
3584 SDValue Op1 = Op.getOperand(1);
3585 SDValue CC = Op.getOperand(2);
3586 EVT VT = Op.getValueType();
3587 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3588 DebugLoc dl = Op.getDebugLoc();
3590 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3591 switch (SetCCOpcode) {
3592 default: llvm_unreachable("Illegal FP comparison");
3594 case ISD::SETNE: Invert = true; // Fallthrough
3596 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3598 case ISD::SETLT: Swap = true; // Fallthrough
3600 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3602 case ISD::SETLE: Swap = true; // Fallthrough
3604 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3605 case ISD::SETUGE: Swap = true; // Fallthrough
3606 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3607 case ISD::SETUGT: Swap = true; // Fallthrough
3608 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3609 case ISD::SETUEQ: Invert = true; // Fallthrough
3611 // Expand this to (OLT | OGT).
3615 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3616 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3618 case ISD::SETUO: Invert = true; // Fallthrough
3620 // Expand this to (OLT | OGE).
3624 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3625 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3629 // Integer comparisons.
3630 switch (SetCCOpcode) {
3631 default: llvm_unreachable("Illegal integer comparison");
3632 case ISD::SETNE: Invert = true;
3633 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3634 case ISD::SETLT: Swap = true;
3635 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3636 case ISD::SETLE: Swap = true;
3637 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3638 case ISD::SETULT: Swap = true;
3639 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3640 case ISD::SETULE: Swap = true;
3641 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3644 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3645 if (Opc == ARMISD::VCEQ) {
3648 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3650 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3653 // Ignore bitconvert.
3654 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3655 AndOp = AndOp.getOperand(0);
3657 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3659 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3660 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3667 std::swap(Op0, Op1);
3669 // If one of the operands is a constant vector zero, attempt to fold the
3670 // comparison to a specialized compare-against-zero form.
3672 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3674 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3675 if (Opc == ARMISD::VCGE)
3676 Opc = ARMISD::VCLEZ;
3677 else if (Opc == ARMISD::VCGT)
3678 Opc = ARMISD::VCLTZ;
3683 if (SingleOp.getNode()) {
3686 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3688 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3690 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3692 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3694 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3696 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3699 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3703 Result = DAG.getNOT(dl, Result, VT);
3708 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3709 /// valid vector constant for a NEON instruction with a "modified immediate"
3710 /// operand (e.g., VMOV). If so, return the encoded value.
3711 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3712 unsigned SplatBitSize, SelectionDAG &DAG,
3713 EVT &VT, bool is128Bits, NEONModImmType type) {
3714 unsigned OpCmode, Imm;
3716 // SplatBitSize is set to the smallest size that splats the vector, so a
3717 // zero vector will always have SplatBitSize == 8. However, NEON modified
3718 // immediate instructions others than VMOV do not support the 8-bit encoding
3719 // of a zero vector, and the default encoding of zero is supposed to be the
3724 switch (SplatBitSize) {
3726 if (type != VMOVModImm)
3728 // Any 1-byte value is OK. Op=0, Cmode=1110.
3729 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3732 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3736 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3737 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3738 if ((SplatBits & ~0xff) == 0) {
3739 // Value = 0x00nn: Op=x, Cmode=100x.
3744 if ((SplatBits & ~0xff00) == 0) {
3745 // Value = 0xnn00: Op=x, Cmode=101x.
3747 Imm = SplatBits >> 8;
3753 // NEON's 32-bit VMOV supports splat values where:
3754 // * only one byte is nonzero, or
3755 // * the least significant byte is 0xff and the second byte is nonzero, or
3756 // * the least significant 2 bytes are 0xff and the third is nonzero.
3757 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3758 if ((SplatBits & ~0xff) == 0) {
3759 // Value = 0x000000nn: Op=x, Cmode=000x.
3764 if ((SplatBits & ~0xff00) == 0) {
3765 // Value = 0x0000nn00: Op=x, Cmode=001x.
3767 Imm = SplatBits >> 8;
3770 if ((SplatBits & ~0xff0000) == 0) {
3771 // Value = 0x00nn0000: Op=x, Cmode=010x.
3773 Imm = SplatBits >> 16;
3776 if ((SplatBits & ~0xff000000) == 0) {
3777 // Value = 0xnn000000: Op=x, Cmode=011x.
3779 Imm = SplatBits >> 24;
3783 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3784 if (type == OtherModImm) return SDValue();
3786 if ((SplatBits & ~0xffff) == 0 &&
3787 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3788 // Value = 0x0000nnff: Op=x, Cmode=1100.
3790 Imm = SplatBits >> 8;
3795 if ((SplatBits & ~0xffffff) == 0 &&
3796 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3797 // Value = 0x00nnffff: Op=x, Cmode=1101.
3799 Imm = SplatBits >> 16;
3800 SplatBits |= 0xffff;
3804 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3805 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3806 // VMOV.I32. A (very) minor optimization would be to replicate the value
3807 // and fall through here to test for a valid 64-bit splat. But, then the
3808 // caller would also need to check and handle the change in size.
3812 if (type != VMOVModImm)
3814 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3815 uint64_t BitMask = 0xff;
3817 unsigned ImmMask = 1;
3819 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3820 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3823 } else if ((SplatBits & BitMask) != 0) {
3829 // Op=1, Cmode=1110.
3832 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3837 llvm_unreachable("unexpected size for isNEONModifiedImm");
3840 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3841 return DAG.getTargetConstant(EncodedVal, MVT::i32);
3844 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3845 const ARMSubtarget *ST) const {
3846 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3849 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3850 assert(Op.getValueType() == MVT::f32 &&
3851 "ConstantFP custom lowering should only occur for f32.");
3853 // Try splatting with a VMOV.f32...
3854 APFloat FPVal = CFP->getValueAPF();
3855 int ImmVal = ARM_AM::getFP32Imm(FPVal);
3857 DebugLoc DL = Op.getDebugLoc();
3858 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3859 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3861 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3862 DAG.getConstant(0, MVT::i32));
3865 // If that fails, try a VMOV.i32
3867 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3868 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3870 if (NewVal != SDValue()) {
3871 DebugLoc DL = Op.getDebugLoc();
3872 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3874 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3876 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3877 DAG.getConstant(0, MVT::i32));
3880 // Finally, try a VMVN.i32
3881 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3883 if (NewVal != SDValue()) {
3884 DebugLoc DL = Op.getDebugLoc();
3885 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3886 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3888 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3889 DAG.getConstant(0, MVT::i32));
3896 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3897 bool &ReverseVEXT, unsigned &Imm) {
3898 unsigned NumElts = VT.getVectorNumElements();
3899 ReverseVEXT = false;
3901 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3907 // If this is a VEXT shuffle, the immediate value is the index of the first
3908 // element. The other shuffle indices must be the successive elements after
3910 unsigned ExpectedElt = Imm;
3911 for (unsigned i = 1; i < NumElts; ++i) {
3912 // Increment the expected index. If it wraps around, it may still be
3913 // a VEXT but the source vectors must be swapped.
3915 if (ExpectedElt == NumElts * 2) {
3920 if (M[i] < 0) continue; // ignore UNDEF indices
3921 if (ExpectedElt != static_cast<unsigned>(M[i]))
3925 // Adjust the index value if the source operands will be swapped.
3932 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3933 /// instruction with the specified blocksize. (The order of the elements
3934 /// within each block of the vector is reversed.)
3935 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3936 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3937 "Only possible block sizes for VREV are: 16, 32, 64");
3939 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3943 unsigned NumElts = VT.getVectorNumElements();
3944 unsigned BlockElts = M[0] + 1;
3945 // If the first shuffle index is UNDEF, be optimistic.
3947 BlockElts = BlockSize / EltSz;
3949 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3952 for (unsigned i = 0; i < NumElts; ++i) {
3953 if (M[i] < 0) continue; // ignore UNDEF indices
3954 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3961 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3962 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3963 // range, then 0 is placed into the resulting vector. So pretty much any mask
3964 // of 8 elements can work here.
3965 return VT == MVT::v8i8 && M.size() == 8;
3968 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3969 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3973 unsigned NumElts = VT.getVectorNumElements();
3974 WhichResult = (M[0] == 0 ? 0 : 1);
3975 for (unsigned i = 0; i < NumElts; i += 2) {
3976 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3977 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3983 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3984 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3985 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3986 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3987 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3991 unsigned NumElts = VT.getVectorNumElements();
3992 WhichResult = (M[0] == 0 ? 0 : 1);
3993 for (unsigned i = 0; i < NumElts; i += 2) {
3994 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3995 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4001 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4002 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4006 unsigned NumElts = VT.getVectorNumElements();
4007 WhichResult = (M[0] == 0 ? 0 : 1);
4008 for (unsigned i = 0; i != NumElts; ++i) {
4009 if (M[i] < 0) continue; // ignore UNDEF indices
4010 if ((unsigned) M[i] != 2 * i + WhichResult)
4014 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4015 if (VT.is64BitVector() && EltSz == 32)
4021 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4022 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4023 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4024 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4025 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4029 unsigned Half = VT.getVectorNumElements() / 2;
4030 WhichResult = (M[0] == 0 ? 0 : 1);
4031 for (unsigned j = 0; j != 2; ++j) {
4032 unsigned Idx = WhichResult;
4033 for (unsigned i = 0; i != Half; ++i) {
4034 int MIdx = M[i + j * Half];
4035 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4041 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4042 if (VT.is64BitVector() && EltSz == 32)
4048 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4049 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4053 unsigned NumElts = VT.getVectorNumElements();
4054 WhichResult = (M[0] == 0 ? 0 : 1);
4055 unsigned Idx = WhichResult * NumElts / 2;
4056 for (unsigned i = 0; i != NumElts; i += 2) {
4057 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4058 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4063 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4064 if (VT.is64BitVector() && EltSz == 32)
4070 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4071 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4072 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4073 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4074 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4078 unsigned NumElts = VT.getVectorNumElements();
4079 WhichResult = (M[0] == 0 ? 0 : 1);
4080 unsigned Idx = WhichResult * NumElts / 2;
4081 for (unsigned i = 0; i != NumElts; i += 2) {
4082 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4083 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4088 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4089 if (VT.is64BitVector() && EltSz == 32)
4095 // If N is an integer constant that can be moved into a register in one
4096 // instruction, return an SDValue of such a constant (will become a MOV
4097 // instruction). Otherwise return null.
4098 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4099 const ARMSubtarget *ST, DebugLoc dl) {
4101 if (!isa<ConstantSDNode>(N))
4103 Val = cast<ConstantSDNode>(N)->getZExtValue();
4105 if (ST->isThumb1Only()) {
4106 if (Val <= 255 || ~Val <= 255)
4107 return DAG.getConstant(Val, MVT::i32);
4109 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4110 return DAG.getConstant(Val, MVT::i32);
4115 // If this is a case we can't handle, return null and let the default
4116 // expansion code take care of it.
4117 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4118 const ARMSubtarget *ST) const {
4119 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4120 DebugLoc dl = Op.getDebugLoc();
4121 EVT VT = Op.getValueType();
4123 APInt SplatBits, SplatUndef;
4124 unsigned SplatBitSize;
4126 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4127 if (SplatBitSize <= 64) {
4128 // Check if an immediate VMOV works.
4130 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4131 SplatUndef.getZExtValue(), SplatBitSize,
4132 DAG, VmovVT, VT.is128BitVector(),
4134 if (Val.getNode()) {
4135 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4136 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4139 // Try an immediate VMVN.
4140 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4141 Val = isNEONModifiedImm(NegatedImm,
4142 SplatUndef.getZExtValue(), SplatBitSize,
4143 DAG, VmovVT, VT.is128BitVector(),
4145 if (Val.getNode()) {
4146 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4147 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4150 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4151 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4152 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4154 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4155 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4161 // Scan through the operands to see if only one value is used.
4162 unsigned NumElts = VT.getVectorNumElements();
4163 bool isOnlyLowElement = true;
4164 bool usesOnlyOneValue = true;
4165 bool isConstant = true;
4167 for (unsigned i = 0; i < NumElts; ++i) {
4168 SDValue V = Op.getOperand(i);
4169 if (V.getOpcode() == ISD::UNDEF)
4172 isOnlyLowElement = false;
4173 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4176 if (!Value.getNode())
4178 else if (V != Value)
4179 usesOnlyOneValue = false;
4182 if (!Value.getNode())
4183 return DAG.getUNDEF(VT);
4185 if (isOnlyLowElement)
4186 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4188 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4190 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4191 // i32 and try again.
4192 if (usesOnlyOneValue && EltSize <= 32) {
4194 return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4195 if (VT.getVectorElementType().isFloatingPoint()) {
4196 SmallVector<SDValue, 8> Ops;
4197 for (unsigned i = 0; i < NumElts; ++i)
4198 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4200 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4201 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4202 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4204 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4206 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4208 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4211 // If all elements are constants and the case above didn't get hit, fall back
4212 // to the default expansion, which will generate a load from the constant
4217 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4219 SDValue shuffle = ReconstructShuffle(Op, DAG);
4220 if (shuffle != SDValue())
4224 // Vectors with 32- or 64-bit elements can be built by directly assigning
4225 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4226 // will be legalized.
4227 if (EltSize >= 32) {
4228 // Do the expansion with floating-point types, since that is what the VFP
4229 // registers are defined to use, and since i64 is not legal.
4230 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4231 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4232 SmallVector<SDValue, 8> Ops;
4233 for (unsigned i = 0; i < NumElts; ++i)
4234 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4235 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4236 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4242 // Gather data to see if the operation can be modelled as a
4243 // shuffle in combination with VEXTs.
4244 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4245 SelectionDAG &DAG) const {
4246 DebugLoc dl = Op.getDebugLoc();
4247 EVT VT = Op.getValueType();
4248 unsigned NumElts = VT.getVectorNumElements();
4250 SmallVector<SDValue, 2> SourceVecs;
4251 SmallVector<unsigned, 2> MinElts;
4252 SmallVector<unsigned, 2> MaxElts;
4254 for (unsigned i = 0; i < NumElts; ++i) {
4255 SDValue V = Op.getOperand(i);
4256 if (V.getOpcode() == ISD::UNDEF)
4258 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4259 // A shuffle can only come from building a vector from various
4260 // elements of other vectors.
4262 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4263 VT.getVectorElementType()) {
4264 // This code doesn't know how to handle shuffles where the vector
4265 // element types do not match (this happens because type legalization
4266 // promotes the return type of EXTRACT_VECTOR_ELT).
4267 // FIXME: It might be appropriate to extend this code to handle
4268 // mismatched types.
4272 // Record this extraction against the appropriate vector if possible...
4273 SDValue SourceVec = V.getOperand(0);
4274 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4275 bool FoundSource = false;
4276 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4277 if (SourceVecs[j] == SourceVec) {
4278 if (MinElts[j] > EltNo)
4280 if (MaxElts[j] < EltNo)
4287 // Or record a new source if not...
4289 SourceVecs.push_back(SourceVec);
4290 MinElts.push_back(EltNo);
4291 MaxElts.push_back(EltNo);
4295 // Currently only do something sane when at most two source vectors
4297 if (SourceVecs.size() > 2)
4300 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4301 int VEXTOffsets[2] = {0, 0};
4303 // This loop extracts the usage patterns of the source vectors
4304 // and prepares appropriate SDValues for a shuffle if possible.
4305 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4306 if (SourceVecs[i].getValueType() == VT) {
4307 // No VEXT necessary
4308 ShuffleSrcs[i] = SourceVecs[i];
4311 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4312 // It probably isn't worth padding out a smaller vector just to
4313 // break it down again in a shuffle.
4317 // Since only 64-bit and 128-bit vectors are legal on ARM and
4318 // we've eliminated the other cases...
4319 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4320 "unexpected vector sizes in ReconstructShuffle");
4322 if (MaxElts[i] - MinElts[i] >= NumElts) {
4323 // Span too large for a VEXT to cope
4327 if (MinElts[i] >= NumElts) {
4328 // The extraction can just take the second half
4329 VEXTOffsets[i] = NumElts;
4330 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4332 DAG.getIntPtrConstant(NumElts));
4333 } else if (MaxElts[i] < NumElts) {
4334 // The extraction can just take the first half
4336 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4338 DAG.getIntPtrConstant(0));
4340 // An actual VEXT is needed
4341 VEXTOffsets[i] = MinElts[i];
4342 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4344 DAG.getIntPtrConstant(0));
4345 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4347 DAG.getIntPtrConstant(NumElts));
4348 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4349 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4353 SmallVector<int, 8> Mask;
4355 for (unsigned i = 0; i < NumElts; ++i) {
4356 SDValue Entry = Op.getOperand(i);
4357 if (Entry.getOpcode() == ISD::UNDEF) {
4362 SDValue ExtractVec = Entry.getOperand(0);
4363 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4364 .getOperand(1))->getSExtValue();
4365 if (ExtractVec == SourceVecs[0]) {
4366 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4368 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4372 // Final check before we try to produce nonsense...
4373 if (isShuffleMaskLegal(Mask, VT))
4374 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4380 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4381 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4382 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4383 /// are assumed to be legal.
4385 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4387 if (VT.getVectorNumElements() == 4 &&
4388 (VT.is128BitVector() || VT.is64BitVector())) {
4389 unsigned PFIndexes[4];
4390 for (unsigned i = 0; i != 4; ++i) {
4394 PFIndexes[i] = M[i];
4397 // Compute the index in the perfect shuffle table.
4398 unsigned PFTableIndex =
4399 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4400 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4401 unsigned Cost = (PFEntry >> 30);
4408 unsigned Imm, WhichResult;
4410 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4411 return (EltSize >= 32 ||
4412 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4413 isVREVMask(M, VT, 64) ||
4414 isVREVMask(M, VT, 32) ||
4415 isVREVMask(M, VT, 16) ||
4416 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4417 isVTBLMask(M, VT) ||
4418 isVTRNMask(M, VT, WhichResult) ||
4419 isVUZPMask(M, VT, WhichResult) ||
4420 isVZIPMask(M, VT, WhichResult) ||
4421 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4422 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4423 isVZIP_v_undef_Mask(M, VT, WhichResult));
4426 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4427 /// the specified operations to build the shuffle.
4428 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4429 SDValue RHS, SelectionDAG &DAG,
4431 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4432 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4433 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4436 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4445 OP_VUZPL, // VUZP, left result
4446 OP_VUZPR, // VUZP, right result
4447 OP_VZIPL, // VZIP, left result
4448 OP_VZIPR, // VZIP, right result
4449 OP_VTRNL, // VTRN, left result
4450 OP_VTRNR // VTRN, right result
4453 if (OpNum == OP_COPY) {
4454 if (LHSID == (1*9+2)*9+3) return LHS;
4455 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4459 SDValue OpLHS, OpRHS;
4460 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4461 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4462 EVT VT = OpLHS.getValueType();
4465 default: llvm_unreachable("Unknown shuffle opcode!");
4467 // VREV divides the vector in half and swaps within the half.
4468 if (VT.getVectorElementType() == MVT::i32 ||
4469 VT.getVectorElementType() == MVT::f32)
4470 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4471 // vrev <4 x i16> -> VREV32
4472 if (VT.getVectorElementType() == MVT::i16)
4473 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4474 // vrev <4 x i8> -> VREV16
4475 assert(VT.getVectorElementType() == MVT::i8);
4476 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4481 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4482 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4486 return DAG.getNode(ARMISD::VEXT, dl, VT,
4488 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4491 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4492 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4495 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4496 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4499 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4500 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4504 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4505 ArrayRef<int> ShuffleMask,
4506 SelectionDAG &DAG) {
4507 // Check to see if we can use the VTBL instruction.
4508 SDValue V1 = Op.getOperand(0);
4509 SDValue V2 = Op.getOperand(1);
4510 DebugLoc DL = Op.getDebugLoc();
4512 SmallVector<SDValue, 8> VTBLMask;
4513 for (ArrayRef<int>::iterator
4514 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4515 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4517 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4518 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4519 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4522 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4523 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4527 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4528 SDValue V1 = Op.getOperand(0);
4529 SDValue V2 = Op.getOperand(1);
4530 DebugLoc dl = Op.getDebugLoc();
4531 EVT VT = Op.getValueType();
4532 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4534 // Convert shuffles that are directly supported on NEON to target-specific
4535 // DAG nodes, instead of keeping them as shuffles and matching them again
4536 // during code selection. This is more efficient and avoids the possibility
4537 // of inconsistencies between legalization and selection.
4538 // FIXME: floating-point vectors should be canonicalized to integer vectors
4539 // of the same time so that they get CSEd properly.
4540 ArrayRef<int> ShuffleMask = SVN->getMask();
4542 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4543 if (EltSize <= 32) {
4544 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4545 int Lane = SVN->getSplatIndex();
4546 // If this is undef splat, generate it via "just" vdup, if possible.
4547 if (Lane == -1) Lane = 0;
4549 // Test if V1 is a SCALAR_TO_VECTOR.
4550 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4551 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4553 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4554 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4556 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4557 !isa<ConstantSDNode>(V1.getOperand(0))) {
4558 bool IsScalarToVector = true;
4559 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4560 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4561 IsScalarToVector = false;
4564 if (IsScalarToVector)
4565 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4567 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4568 DAG.getConstant(Lane, MVT::i32));
4573 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4576 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4577 DAG.getConstant(Imm, MVT::i32));
4580 if (isVREVMask(ShuffleMask, VT, 64))
4581 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4582 if (isVREVMask(ShuffleMask, VT, 32))
4583 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4584 if (isVREVMask(ShuffleMask, VT, 16))
4585 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4587 // Check for Neon shuffles that modify both input vectors in place.
4588 // If both results are used, i.e., if there are two shuffles with the same
4589 // source operands and with masks corresponding to both results of one of
4590 // these operations, DAG memoization will ensure that a single node is
4591 // used for both shuffles.
4592 unsigned WhichResult;
4593 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4594 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4595 V1, V2).getValue(WhichResult);
4596 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4597 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4598 V1, V2).getValue(WhichResult);
4599 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4600 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4601 V1, V2).getValue(WhichResult);
4603 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4604 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4605 V1, V1).getValue(WhichResult);
4606 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4607 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4608 V1, V1).getValue(WhichResult);
4609 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4610 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4611 V1, V1).getValue(WhichResult);
4614 // If the shuffle is not directly supported and it has 4 elements, use
4615 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4616 unsigned NumElts = VT.getVectorNumElements();
4618 unsigned PFIndexes[4];
4619 for (unsigned i = 0; i != 4; ++i) {
4620 if (ShuffleMask[i] < 0)
4623 PFIndexes[i] = ShuffleMask[i];
4626 // Compute the index in the perfect shuffle table.
4627 unsigned PFTableIndex =
4628 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4629 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4630 unsigned Cost = (PFEntry >> 30);
4633 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4636 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4637 if (EltSize >= 32) {
4638 // Do the expansion with floating-point types, since that is what the VFP
4639 // registers are defined to use, and since i64 is not legal.
4640 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4641 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4642 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4643 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4644 SmallVector<SDValue, 8> Ops;
4645 for (unsigned i = 0; i < NumElts; ++i) {
4646 if (ShuffleMask[i] < 0)
4647 Ops.push_back(DAG.getUNDEF(EltVT));
4649 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4650 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4651 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4654 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4655 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4658 if (VT == MVT::v8i8) {
4659 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4660 if (NewOp.getNode())
4667 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4668 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4669 SDValue Lane = Op.getOperand(2);
4670 if (!isa<ConstantSDNode>(Lane))
4676 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4677 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4678 SDValue Lane = Op.getOperand(1);
4679 if (!isa<ConstantSDNode>(Lane))
4682 SDValue Vec = Op.getOperand(0);
4683 if (Op.getValueType() == MVT::i32 &&
4684 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4685 DebugLoc dl = Op.getDebugLoc();
4686 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4692 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4693 // The only time a CONCAT_VECTORS operation can have legal types is when
4694 // two 64-bit vectors are concatenated to a 128-bit vector.
4695 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4696 "unexpected CONCAT_VECTORS");
4697 DebugLoc dl = Op.getDebugLoc();
4698 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4699 SDValue Op0 = Op.getOperand(0);
4700 SDValue Op1 = Op.getOperand(1);
4701 if (Op0.getOpcode() != ISD::UNDEF)
4702 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4703 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4704 DAG.getIntPtrConstant(0));
4705 if (Op1.getOpcode() != ISD::UNDEF)
4706 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4707 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4708 DAG.getIntPtrConstant(1));
4709 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4712 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4713 /// element has been zero/sign-extended, depending on the isSigned parameter,
4714 /// from an integer type half its size.
4715 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4717 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4718 EVT VT = N->getValueType(0);
4719 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4720 SDNode *BVN = N->getOperand(0).getNode();
4721 if (BVN->getValueType(0) != MVT::v4i32 ||
4722 BVN->getOpcode() != ISD::BUILD_VECTOR)
4724 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4725 unsigned HiElt = 1 - LoElt;
4726 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4727 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4728 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4729 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4730 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4733 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4734 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4737 if (Hi0->isNullValue() && Hi1->isNullValue())
4743 if (N->getOpcode() != ISD::BUILD_VECTOR)
4746 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4747 SDNode *Elt = N->getOperand(i).getNode();
4748 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4749 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4750 unsigned HalfSize = EltSize / 2;
4752 if (!isIntN(HalfSize, C->getSExtValue()))
4755 if (!isUIntN(HalfSize, C->getZExtValue()))
4766 /// isSignExtended - Check if a node is a vector value that is sign-extended
4767 /// or a constant BUILD_VECTOR with sign-extended elements.
4768 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4769 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4771 if (isExtendedBUILD_VECTOR(N, DAG, true))
4776 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4777 /// or a constant BUILD_VECTOR with zero-extended elements.
4778 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4779 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4781 if (isExtendedBUILD_VECTOR(N, DAG, false))
4786 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4787 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4788 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4789 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4790 return N->getOperand(0);
4791 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4792 return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4793 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4794 LD->isNonTemporal(), LD->isInvariant(),
4795 LD->getAlignment());
4796 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
4797 // have been legalized as a BITCAST from v4i32.
4798 if (N->getOpcode() == ISD::BITCAST) {
4799 SDNode *BVN = N->getOperand(0).getNode();
4800 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4801 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4802 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4803 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4804 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4806 // Construct a new BUILD_VECTOR with elements truncated to half the size.
4807 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4808 EVT VT = N->getValueType(0);
4809 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4810 unsigned NumElts = VT.getVectorNumElements();
4811 MVT TruncVT = MVT::getIntegerVT(EltSize);
4812 SmallVector<SDValue, 8> Ops;
4813 for (unsigned i = 0; i != NumElts; ++i) {
4814 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4815 const APInt &CInt = C->getAPIntValue();
4816 // Element types smaller than 32 bits are not legal, so use i32 elements.
4817 // The values are implicitly truncated so sext vs. zext doesn't matter.
4818 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4820 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4821 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4824 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4825 unsigned Opcode = N->getOpcode();
4826 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4827 SDNode *N0 = N->getOperand(0).getNode();
4828 SDNode *N1 = N->getOperand(1).getNode();
4829 return N0->hasOneUse() && N1->hasOneUse() &&
4830 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4835 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4836 unsigned Opcode = N->getOpcode();
4837 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4838 SDNode *N0 = N->getOperand(0).getNode();
4839 SDNode *N1 = N->getOperand(1).getNode();
4840 return N0->hasOneUse() && N1->hasOneUse() &&
4841 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4846 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4847 // Multiplications are only custom-lowered for 128-bit vectors so that
4848 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
4849 EVT VT = Op.getValueType();
4850 assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4851 SDNode *N0 = Op.getOperand(0).getNode();
4852 SDNode *N1 = Op.getOperand(1).getNode();
4853 unsigned NewOpc = 0;
4855 bool isN0SExt = isSignExtended(N0, DAG);
4856 bool isN1SExt = isSignExtended(N1, DAG);
4857 if (isN0SExt && isN1SExt)
4858 NewOpc = ARMISD::VMULLs;
4860 bool isN0ZExt = isZeroExtended(N0, DAG);
4861 bool isN1ZExt = isZeroExtended(N1, DAG);
4862 if (isN0ZExt && isN1ZExt)
4863 NewOpc = ARMISD::VMULLu;
4864 else if (isN1SExt || isN1ZExt) {
4865 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4866 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4867 if (isN1SExt && isAddSubSExt(N0, DAG)) {
4868 NewOpc = ARMISD::VMULLs;
4870 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4871 NewOpc = ARMISD::VMULLu;
4873 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4875 NewOpc = ARMISD::VMULLu;
4881 if (VT == MVT::v2i64)
4882 // Fall through to expand this. It is not legal.
4885 // Other vector multiplications are legal.
4890 // Legalize to a VMULL instruction.
4891 DebugLoc DL = Op.getDebugLoc();
4893 SDValue Op1 = SkipExtension(N1, DAG);
4895 Op0 = SkipExtension(N0, DAG);
4896 assert(Op0.getValueType().is64BitVector() &&
4897 Op1.getValueType().is64BitVector() &&
4898 "unexpected types for extended operands to VMULL");
4899 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4902 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4903 // isel lowering to take advantage of no-stall back to back vmul + vmla.
4910 SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4911 SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4912 EVT Op1VT = Op1.getValueType();
4913 return DAG.getNode(N0->getOpcode(), DL, VT,
4914 DAG.getNode(NewOpc, DL, VT,
4915 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4916 DAG.getNode(NewOpc, DL, VT,
4917 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4921 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4923 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4924 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4925 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4926 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4927 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4928 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4929 // Get reciprocal estimate.
4930 // float4 recip = vrecpeq_f32(yf);
4931 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4932 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4933 // Because char has a smaller range than uchar, we can actually get away
4934 // without any newton steps. This requires that we use a weird bias
4935 // of 0xb000, however (again, this has been exhaustively tested).
4936 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4937 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4938 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4939 Y = DAG.getConstant(0xb000, MVT::i32);
4940 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4941 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4942 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4943 // Convert back to short.
4944 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4945 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4950 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4952 // Convert to float.
4953 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4954 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4955 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4956 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4957 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4958 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4960 // Use reciprocal estimate and one refinement step.
4961 // float4 recip = vrecpeq_f32(yf);
4962 // recip *= vrecpsq_f32(yf, recip);
4963 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4964 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4965 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4966 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4968 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4969 // Because short has a smaller range than ushort, we can actually get away
4970 // with only a single newton step. This requires that we use a weird bias
4971 // of 89, however (again, this has been exhaustively tested).
4972 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4973 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4974 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4975 N1 = DAG.getConstant(0x89, MVT::i32);
4976 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4977 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4978 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4979 // Convert back to integer and return.
4980 // return vmovn_s32(vcvt_s32_f32(result));
4981 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4982 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4986 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4987 EVT VT = Op.getValueType();
4988 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4989 "unexpected type for custom-lowering ISD::SDIV");
4991 DebugLoc dl = Op.getDebugLoc();
4992 SDValue N0 = Op.getOperand(0);
4993 SDValue N1 = Op.getOperand(1);
4996 if (VT == MVT::v8i8) {
4997 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4998 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5000 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5001 DAG.getIntPtrConstant(4));
5002 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5003 DAG.getIntPtrConstant(4));
5004 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5005 DAG.getIntPtrConstant(0));
5006 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5007 DAG.getIntPtrConstant(0));
5009 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5010 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5012 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5013 N0 = LowerCONCAT_VECTORS(N0, DAG);
5015 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5018 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5021 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5022 EVT VT = Op.getValueType();
5023 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5024 "unexpected type for custom-lowering ISD::UDIV");
5026 DebugLoc dl = Op.getDebugLoc();
5027 SDValue N0 = Op.getOperand(0);
5028 SDValue N1 = Op.getOperand(1);
5031 if (VT == MVT::v8i8) {
5032 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5033 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5035 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5036 DAG.getIntPtrConstant(4));
5037 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5038 DAG.getIntPtrConstant(4));
5039 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5040 DAG.getIntPtrConstant(0));
5041 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5042 DAG.getIntPtrConstant(0));
5044 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5045 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5047 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5048 N0 = LowerCONCAT_VECTORS(N0, DAG);
5050 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5051 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5056 // v4i16 sdiv ... Convert to float.
5057 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5058 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5059 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5060 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5061 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5062 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5064 // Use reciprocal estimate and two refinement steps.
5065 // float4 recip = vrecpeq_f32(yf);
5066 // recip *= vrecpsq_f32(yf, recip);
5067 // recip *= vrecpsq_f32(yf, recip);
5068 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5069 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5070 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5071 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5073 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5074 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5075 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5077 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5078 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5079 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5080 // and that it will never cause us to return an answer too large).
5081 // float4 result = as_float4(as_int4(xf*recip) + 2);
5082 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5083 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5084 N1 = DAG.getConstant(2, MVT::i32);
5085 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5086 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5087 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5088 // Convert back to integer and return.
5089 // return vmovn_u32(vcvt_s32_f32(result));
5090 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5091 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5095 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5096 EVT VT = Op.getNode()->getValueType(0);
5097 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5100 bool ExtraOp = false;
5101 switch (Op.getOpcode()) {
5102 default: llvm_unreachable("Invalid code");
5103 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5104 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5105 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5106 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5110 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5112 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5113 Op.getOperand(1), Op.getOperand(2));
5116 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5117 // Monotonic load/store is legal for all targets
5118 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5121 // Aquire/Release load/store is not legal for targets without a
5122 // dmb or equivalent available.
5128 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5129 SelectionDAG &DAG, unsigned NewOp) {
5130 DebugLoc dl = Node->getDebugLoc();
5131 assert (Node->getValueType(0) == MVT::i64 &&
5132 "Only know how to expand i64 atomics");
5134 SmallVector<SDValue, 6> Ops;
5135 Ops.push_back(Node->getOperand(0)); // Chain
5136 Ops.push_back(Node->getOperand(1)); // Ptr
5138 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5139 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5140 // High part of Val1
5141 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5142 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5143 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5144 // High part of Val1
5145 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5146 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5147 // High part of Val2
5148 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5149 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5151 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5153 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5154 cast<MemSDNode>(Node)->getMemOperand());
5155 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5156 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5157 Results.push_back(Result.getValue(2));
5160 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5161 switch (Op.getOpcode()) {
5162 default: llvm_unreachable("Don't know how to custom lower this!");
5163 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5164 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5165 case ISD::GlobalAddress:
5166 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5167 LowerGlobalAddressELF(Op, DAG);
5168 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5169 case ISD::SELECT: return LowerSELECT(Op, DAG);
5170 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5171 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5172 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5173 case ISD::VASTART: return LowerVASTART(Op, DAG);
5174 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5175 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5176 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5177 case ISD::SINT_TO_FP:
5178 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5179 case ISD::FP_TO_SINT:
5180 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5181 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5182 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5183 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5184 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5185 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5186 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5187 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5189 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5192 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5193 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5194 case ISD::SRL_PARTS:
5195 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5196 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5197 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5198 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5199 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5200 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5201 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5202 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5203 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5204 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5205 case ISD::MUL: return LowerMUL(Op, DAG);
5206 case ISD::SDIV: return LowerSDIV(Op, DAG);
5207 case ISD::UDIV: return LowerUDIV(Op, DAG);
5211 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5212 case ISD::ATOMIC_LOAD:
5213 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5217 /// ReplaceNodeResults - Replace the results of node with an illegal result
5218 /// type with new values built out of custom code.
5219 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5220 SmallVectorImpl<SDValue>&Results,
5221 SelectionDAG &DAG) const {
5223 switch (N->getOpcode()) {
5225 llvm_unreachable("Don't know how to custom expand this!");
5227 Res = ExpandBITCAST(N, DAG);
5231 Res = Expand64BitShift(N, DAG, Subtarget);
5233 case ISD::ATOMIC_LOAD_ADD:
5234 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5236 case ISD::ATOMIC_LOAD_AND:
5237 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5239 case ISD::ATOMIC_LOAD_NAND:
5240 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5242 case ISD::ATOMIC_LOAD_OR:
5243 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5245 case ISD::ATOMIC_LOAD_SUB:
5246 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5248 case ISD::ATOMIC_LOAD_XOR:
5249 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5251 case ISD::ATOMIC_SWAP:
5252 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5254 case ISD::ATOMIC_CMP_SWAP:
5255 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5259 Results.push_back(Res);
5262 //===----------------------------------------------------------------------===//
5263 // ARM Scheduler Hooks
5264 //===----------------------------------------------------------------------===//
5267 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5268 MachineBasicBlock *BB,
5269 unsigned Size) const {
5270 unsigned dest = MI->getOperand(0).getReg();
5271 unsigned ptr = MI->getOperand(1).getReg();
5272 unsigned oldval = MI->getOperand(2).getReg();
5273 unsigned newval = MI->getOperand(3).getReg();
5274 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5275 DebugLoc dl = MI->getDebugLoc();
5276 bool isThumb2 = Subtarget->isThumb2();
5278 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5279 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5280 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5281 (const TargetRegisterClass*)&ARM::GPRRegClass);
5284 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5285 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5286 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5289 unsigned ldrOpc, strOpc;
5291 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5293 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5294 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5297 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5298 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5301 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5302 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5306 MachineFunction *MF = BB->getParent();
5307 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5308 MachineFunction::iterator It = BB;
5309 ++It; // insert the new blocks after the current block
5311 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5312 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5313 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5314 MF->insert(It, loop1MBB);
5315 MF->insert(It, loop2MBB);
5316 MF->insert(It, exitMBB);
5318 // Transfer the remainder of BB and its successor edges to exitMBB.
5319 exitMBB->splice(exitMBB->begin(), BB,
5320 llvm::next(MachineBasicBlock::iterator(MI)),
5322 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5326 // fallthrough --> loop1MBB
5327 BB->addSuccessor(loop1MBB);
5330 // ldrex dest, [ptr]
5334 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5335 if (ldrOpc == ARM::t2LDREX)
5337 AddDefaultPred(MIB);
5338 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5339 .addReg(dest).addReg(oldval));
5340 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5341 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5342 BB->addSuccessor(loop2MBB);
5343 BB->addSuccessor(exitMBB);
5346 // strex scratch, newval, [ptr]
5350 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5351 if (strOpc == ARM::t2STREX)
5353 AddDefaultPred(MIB);
5354 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5355 .addReg(scratch).addImm(0));
5356 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5357 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5358 BB->addSuccessor(loop1MBB);
5359 BB->addSuccessor(exitMBB);
5365 MI->eraseFromParent(); // The instruction is gone now.
5371 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5372 unsigned Size, unsigned BinOpcode) const {
5373 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5374 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5376 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5377 MachineFunction *MF = BB->getParent();
5378 MachineFunction::iterator It = BB;
5381 unsigned dest = MI->getOperand(0).getReg();
5382 unsigned ptr = MI->getOperand(1).getReg();
5383 unsigned incr = MI->getOperand(2).getReg();
5384 DebugLoc dl = MI->getDebugLoc();
5385 bool isThumb2 = Subtarget->isThumb2();
5387 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5389 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5390 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5393 unsigned ldrOpc, strOpc;
5395 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5397 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5398 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5401 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5402 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5405 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5406 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5410 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5411 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5412 MF->insert(It, loopMBB);
5413 MF->insert(It, exitMBB);
5415 // Transfer the remainder of BB and its successor edges to exitMBB.
5416 exitMBB->splice(exitMBB->begin(), BB,
5417 llvm::next(MachineBasicBlock::iterator(MI)),
5419 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5421 const TargetRegisterClass *TRC = isThumb2 ?
5422 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5423 (const TargetRegisterClass*)&ARM::GPRRegClass;
5424 unsigned scratch = MRI.createVirtualRegister(TRC);
5425 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5429 // fallthrough --> loopMBB
5430 BB->addSuccessor(loopMBB);
5434 // <binop> scratch2, dest, incr
5435 // strex scratch, scratch2, ptr
5438 // fallthrough --> exitMBB
5440 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5441 if (ldrOpc == ARM::t2LDREX)
5443 AddDefaultPred(MIB);
5445 // operand order needs to go the other way for NAND
5446 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5447 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5448 addReg(incr).addReg(dest)).addReg(0);
5450 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5451 addReg(dest).addReg(incr)).addReg(0);
5454 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5455 if (strOpc == ARM::t2STREX)
5457 AddDefaultPred(MIB);
5458 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5459 .addReg(scratch).addImm(0));
5460 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5461 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5463 BB->addSuccessor(loopMBB);
5464 BB->addSuccessor(exitMBB);
5470 MI->eraseFromParent(); // The instruction is gone now.
5476 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5477 MachineBasicBlock *BB,
5480 ARMCC::CondCodes Cond) const {
5481 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5483 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5484 MachineFunction *MF = BB->getParent();
5485 MachineFunction::iterator It = BB;
5488 unsigned dest = MI->getOperand(0).getReg();
5489 unsigned ptr = MI->getOperand(1).getReg();
5490 unsigned incr = MI->getOperand(2).getReg();
5491 unsigned oldval = dest;
5492 DebugLoc dl = MI->getDebugLoc();
5493 bool isThumb2 = Subtarget->isThumb2();
5495 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5497 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5498 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5501 unsigned ldrOpc, strOpc, extendOpc;
5503 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5505 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5506 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5507 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5510 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5511 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5512 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5515 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5516 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5521 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5522 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5523 MF->insert(It, loopMBB);
5524 MF->insert(It, exitMBB);
5526 // Transfer the remainder of BB and its successor edges to exitMBB.
5527 exitMBB->splice(exitMBB->begin(), BB,
5528 llvm::next(MachineBasicBlock::iterator(MI)),
5530 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5532 const TargetRegisterClass *TRC = isThumb2 ?
5533 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5534 (const TargetRegisterClass*)&ARM::GPRRegClass;
5535 unsigned scratch = MRI.createVirtualRegister(TRC);
5536 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5540 // fallthrough --> loopMBB
5541 BB->addSuccessor(loopMBB);
5545 // (sign extend dest, if required)
5547 // cmov.cond scratch2, dest, incr
5548 // strex scratch, scratch2, ptr
5551 // fallthrough --> exitMBB
5553 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5554 if (ldrOpc == ARM::t2LDREX)
5556 AddDefaultPred(MIB);
5558 // Sign extend the value, if necessary.
5559 if (signExtend && extendOpc) {
5560 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5561 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5566 // Build compare and cmov instructions.
5567 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5568 .addReg(oldval).addReg(incr));
5569 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5570 .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5572 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5573 if (strOpc == ARM::t2STREX)
5575 AddDefaultPred(MIB);
5576 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5577 .addReg(scratch).addImm(0));
5578 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5579 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5581 BB->addSuccessor(loopMBB);
5582 BB->addSuccessor(exitMBB);
5588 MI->eraseFromParent(); // The instruction is gone now.
5594 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5595 unsigned Op1, unsigned Op2,
5596 bool NeedsCarry, bool IsCmpxchg) const {
5597 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5598 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5600 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5601 MachineFunction *MF = BB->getParent();
5602 MachineFunction::iterator It = BB;
5605 unsigned destlo = MI->getOperand(0).getReg();
5606 unsigned desthi = MI->getOperand(1).getReg();
5607 unsigned ptr = MI->getOperand(2).getReg();
5608 unsigned vallo = MI->getOperand(3).getReg();
5609 unsigned valhi = MI->getOperand(4).getReg();
5610 DebugLoc dl = MI->getDebugLoc();
5611 bool isThumb2 = Subtarget->isThumb2();
5613 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5615 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5616 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5617 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5620 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5621 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5623 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5624 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5626 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5627 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5629 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5630 MF->insert(It, loopMBB);
5632 MF->insert(It, contBB);
5633 MF->insert(It, cont2BB);
5635 MF->insert(It, exitMBB);
5637 // Transfer the remainder of BB and its successor edges to exitMBB.
5638 exitMBB->splice(exitMBB->begin(), BB,
5639 llvm::next(MachineBasicBlock::iterator(MI)),
5641 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5643 const TargetRegisterClass *TRC = isThumb2 ?
5644 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5645 (const TargetRegisterClass*)&ARM::GPRRegClass;
5646 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5650 // fallthrough --> loopMBB
5651 BB->addSuccessor(loopMBB);
5654 // ldrexd r2, r3, ptr
5655 // <binopa> r0, r2, incr
5656 // <binopb> r1, r3, incr
5657 // strexd storesuccess, r0, r1, ptr
5658 // cmp storesuccess, #0
5660 // fallthrough --> exitMBB
5662 // Note that the registers are explicitly specified because there is not any
5663 // way to force the register allocator to allocate a register pair.
5665 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5666 // need to properly enforce the restriction that the two output registers
5667 // for ldrexd must be different.
5670 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5671 .addReg(ARM::R2, RegState::Define)
5672 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5673 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
5674 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5675 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5679 for (unsigned i = 0; i < 2; i++) {
5680 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5682 .addReg(i == 0 ? destlo : desthi)
5683 .addReg(i == 0 ? vallo : valhi));
5684 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5685 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5686 BB->addSuccessor(exitMBB);
5687 BB->addSuccessor(i == 0 ? contBB : cont2BB);
5688 BB = (i == 0 ? contBB : cont2BB);
5691 // Copy to physregs for strexd
5692 unsigned setlo = MI->getOperand(5).getReg();
5693 unsigned sethi = MI->getOperand(6).getReg();
5694 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5695 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5697 // Perform binary operation
5698 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5699 .addReg(destlo).addReg(vallo))
5700 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5701 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5702 .addReg(desthi).addReg(valhi)).addReg(0);
5704 // Copy to physregs for strexd
5705 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5706 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5710 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5711 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5713 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5714 .addReg(storesuccess).addImm(0));
5715 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5716 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5718 BB->addSuccessor(loopMBB);
5719 BB->addSuccessor(exitMBB);
5725 MI->eraseFromParent(); // The instruction is gone now.
5730 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5731 /// registers the function context.
5732 void ARMTargetLowering::
5733 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5734 MachineBasicBlock *DispatchBB, int FI) const {
5735 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5736 DebugLoc dl = MI->getDebugLoc();
5737 MachineFunction *MF = MBB->getParent();
5738 MachineRegisterInfo *MRI = &MF->getRegInfo();
5739 MachineConstantPool *MCP = MF->getConstantPool();
5740 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5741 const Function *F = MF->getFunction();
5743 bool isThumb = Subtarget->isThumb();
5744 bool isThumb2 = Subtarget->isThumb2();
5746 unsigned PCLabelId = AFI->createPICLabelUId();
5747 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5748 ARMConstantPoolValue *CPV =
5749 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5750 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5752 const TargetRegisterClass *TRC = isThumb ?
5753 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5754 (const TargetRegisterClass*)&ARM::GPRRegClass;
5756 // Grab constant pool and fixed stack memory operands.
5757 MachineMemOperand *CPMMO =
5758 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5759 MachineMemOperand::MOLoad, 4, 4);
5761 MachineMemOperand *FIMMOSt =
5762 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5763 MachineMemOperand::MOStore, 4, 4);
5765 // Load the address of the dispatch MBB into the jump buffer.
5767 // Incoming value: jbuf
5768 // ldr.n r5, LCPI1_1
5771 // str r5, [$jbuf, #+4] ; &jbuf[1]
5772 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5773 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5774 .addConstantPoolIndex(CPI)
5775 .addMemOperand(CPMMO));
5776 // Set the low bit because of thumb mode.
5777 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5779 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5780 .addReg(NewVReg1, RegState::Kill)
5782 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5783 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5784 .addReg(NewVReg2, RegState::Kill)
5786 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5787 .addReg(NewVReg3, RegState::Kill)
5789 .addImm(36) // &jbuf[1] :: pc
5790 .addMemOperand(FIMMOSt));
5791 } else if (isThumb) {
5792 // Incoming value: jbuf
5793 // ldr.n r1, LCPI1_4
5797 // add r2, $jbuf, #+4 ; &jbuf[1]
5799 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5800 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5801 .addConstantPoolIndex(CPI)
5802 .addMemOperand(CPMMO));
5803 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5804 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5805 .addReg(NewVReg1, RegState::Kill)
5807 // Set the low bit because of thumb mode.
5808 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5809 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5810 .addReg(ARM::CPSR, RegState::Define)
5812 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5813 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5814 .addReg(ARM::CPSR, RegState::Define)
5815 .addReg(NewVReg2, RegState::Kill)
5816 .addReg(NewVReg3, RegState::Kill));
5817 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5818 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5820 .addImm(36)); // &jbuf[1] :: pc
5821 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5822 .addReg(NewVReg4, RegState::Kill)
5823 .addReg(NewVReg5, RegState::Kill)
5825 .addMemOperand(FIMMOSt));
5827 // Incoming value: jbuf
5830 // str r1, [$jbuf, #+4] ; &jbuf[1]
5831 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5832 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
5833 .addConstantPoolIndex(CPI)
5835 .addMemOperand(CPMMO));
5836 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5837 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5838 .addReg(NewVReg1, RegState::Kill)
5839 .addImm(PCLabelId));
5840 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5841 .addReg(NewVReg2, RegState::Kill)
5843 .addImm(36) // &jbuf[1] :: pc
5844 .addMemOperand(FIMMOSt));
5848 MachineBasicBlock *ARMTargetLowering::
5849 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5850 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5851 DebugLoc dl = MI->getDebugLoc();
5852 MachineFunction *MF = MBB->getParent();
5853 MachineRegisterInfo *MRI = &MF->getRegInfo();
5854 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5855 MachineFrameInfo *MFI = MF->getFrameInfo();
5856 int FI = MFI->getFunctionContextIndex();
5858 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5859 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5860 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5862 // Get a mapping of the call site numbers to all of the landing pads they're
5864 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5865 unsigned MaxCSNum = 0;
5866 MachineModuleInfo &MMI = MF->getMMI();
5867 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5869 if (!BB->isLandingPad()) continue;
5871 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5873 for (MachineBasicBlock::iterator
5874 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5875 if (!II->isEHLabel()) continue;
5877 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5878 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5880 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5881 for (SmallVectorImpl<unsigned>::iterator
5882 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5883 CSI != CSE; ++CSI) {
5884 CallSiteNumToLPad[*CSI].push_back(BB);
5885 MaxCSNum = std::max(MaxCSNum, *CSI);
5891 // Get an ordered list of the machine basic blocks for the jump table.
5892 std::vector<MachineBasicBlock*> LPadList;
5893 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5894 LPadList.reserve(CallSiteNumToLPad.size());
5895 for (unsigned I = 1; I <= MaxCSNum; ++I) {
5896 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5897 for (SmallVectorImpl<MachineBasicBlock*>::iterator
5898 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5899 LPadList.push_back(*II);
5900 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5904 assert(!LPadList.empty() &&
5905 "No landing pad destinations for the dispatch jump table!");
5907 // Create the jump table and associated information.
5908 MachineJumpTableInfo *JTI =
5909 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5910 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5911 unsigned UId = AFI->createJumpTableUId();
5913 // Create the MBBs for the dispatch code.
5915 // Shove the dispatch's address into the return slot in the function context.
5916 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5917 DispatchBB->setIsLandingPad();
5919 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5920 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5921 DispatchBB->addSuccessor(TrapBB);
5923 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5924 DispatchBB->addSuccessor(DispContBB);
5927 MF->insert(MF->end(), DispatchBB);
5928 MF->insert(MF->end(), DispContBB);
5929 MF->insert(MF->end(), TrapBB);
5931 // Insert code into the entry block that creates and registers the function
5933 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5935 MachineMemOperand *FIMMOLd =
5936 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5937 MachineMemOperand::MOLoad |
5938 MachineMemOperand::MOVolatile, 4, 4);
5940 if (AFI->isThumb1OnlyFunction())
5941 BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5942 else if (!Subtarget->hasVFP2())
5943 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5945 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5947 unsigned NumLPads = LPadList.size();
5948 if (Subtarget->isThumb2()) {
5949 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5950 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5953 .addMemOperand(FIMMOLd));
5955 if (NumLPads < 256) {
5956 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5958 .addImm(LPadList.size()));
5960 unsigned VReg1 = MRI->createVirtualRegister(TRC);
5961 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5962 .addImm(NumLPads & 0xFFFF));
5964 unsigned VReg2 = VReg1;
5965 if ((NumLPads & 0xFFFF0000) != 0) {
5966 VReg2 = MRI->createVirtualRegister(TRC);
5967 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5969 .addImm(NumLPads >> 16));
5972 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5977 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5982 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5983 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5984 .addJumpTableIndex(MJTI)
5987 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5990 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5991 .addReg(NewVReg3, RegState::Kill)
5993 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5995 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5996 .addReg(NewVReg4, RegState::Kill)
5998 .addJumpTableIndex(MJTI)
6000 } else if (Subtarget->isThumb()) {
6001 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6002 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6005 .addMemOperand(FIMMOLd));
6007 if (NumLPads < 256) {
6008 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6012 MachineConstantPool *ConstantPool = MF->getConstantPool();
6013 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6014 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6016 // MachineConstantPool wants an explicit alignment.
6017 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6019 Align = getTargetData()->getTypeAllocSize(C->getType());
6020 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6022 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6023 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6024 .addReg(VReg1, RegState::Define)
6025 .addConstantPoolIndex(Idx));
6026 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6031 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6036 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6037 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6038 .addReg(ARM::CPSR, RegState::Define)
6042 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6043 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6044 .addJumpTableIndex(MJTI)
6047 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6048 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6049 .addReg(ARM::CPSR, RegState::Define)
6050 .addReg(NewVReg2, RegState::Kill)
6053 MachineMemOperand *JTMMOLd =
6054 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6055 MachineMemOperand::MOLoad, 4, 4);
6057 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6058 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6059 .addReg(NewVReg4, RegState::Kill)
6061 .addMemOperand(JTMMOLd));
6063 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6064 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6065 .addReg(ARM::CPSR, RegState::Define)
6066 .addReg(NewVReg5, RegState::Kill)
6069 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6070 .addReg(NewVReg6, RegState::Kill)
6071 .addJumpTableIndex(MJTI)
6074 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6075 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6078 .addMemOperand(FIMMOLd));
6080 if (NumLPads < 256) {
6081 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6084 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6085 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6086 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6087 .addImm(NumLPads & 0xFFFF));
6089 unsigned VReg2 = VReg1;
6090 if ((NumLPads & 0xFFFF0000) != 0) {
6091 VReg2 = MRI->createVirtualRegister(TRC);
6092 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6094 .addImm(NumLPads >> 16));
6097 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6101 MachineConstantPool *ConstantPool = MF->getConstantPool();
6102 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6103 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6105 // MachineConstantPool wants an explicit alignment.
6106 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6108 Align = getTargetData()->getTypeAllocSize(C->getType());
6109 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6111 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6112 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6113 .addReg(VReg1, RegState::Define)
6114 .addConstantPoolIndex(Idx)
6116 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6118 .addReg(VReg1, RegState::Kill));
6121 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6126 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6128 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6130 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6131 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6132 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6133 .addJumpTableIndex(MJTI)
6136 MachineMemOperand *JTMMOLd =
6137 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6138 MachineMemOperand::MOLoad, 4, 4);
6139 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6141 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6142 .addReg(NewVReg3, RegState::Kill)
6145 .addMemOperand(JTMMOLd));
6147 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6148 .addReg(NewVReg5, RegState::Kill)
6150 .addJumpTableIndex(MJTI)
6154 // Add the jump table entries as successors to the MBB.
6155 MachineBasicBlock *PrevMBB = 0;
6156 for (std::vector<MachineBasicBlock*>::iterator
6157 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6158 MachineBasicBlock *CurMBB = *I;
6159 if (PrevMBB != CurMBB)
6160 DispContBB->addSuccessor(CurMBB);
6164 // N.B. the order the invoke BBs are processed in doesn't matter here.
6165 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6166 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6167 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6168 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6169 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6170 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6171 MachineBasicBlock *BB = *I;
6173 // Remove the landing pad successor from the invoke block and replace it
6174 // with the new dispatch block.
6175 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6177 while (!Successors.empty()) {
6178 MachineBasicBlock *SMBB = Successors.pop_back_val();
6179 if (SMBB->isLandingPad()) {
6180 BB->removeSuccessor(SMBB);
6181 MBBLPads.push_back(SMBB);
6185 BB->addSuccessor(DispatchBB);
6187 // Find the invoke call and mark all of the callee-saved registers as
6188 // 'implicit defined' so that they're spilled. This prevents code from
6189 // moving instructions to before the EH block, where they will never be
6191 for (MachineBasicBlock::reverse_iterator
6192 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6193 if (!II->isCall()) continue;
6195 DenseMap<unsigned, bool> DefRegs;
6196 for (MachineInstr::mop_iterator
6197 OI = II->operands_begin(), OE = II->operands_end();
6199 if (!OI->isReg()) continue;
6200 DefRegs[OI->getReg()] = true;
6203 MachineInstrBuilder MIB(&*II);
6205 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6206 unsigned Reg = SavedRegs[i];
6207 if (Subtarget->isThumb2() &&
6208 !ARM::tGPRRegClass.contains(Reg) &&
6209 !ARM::hGPRRegClass.contains(Reg))
6211 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6213 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6216 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6223 // Mark all former landing pads as non-landing pads. The dispatch is the only
6225 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6226 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6227 (*I)->setIsLandingPad(false);
6229 // The instruction is gone now.
6230 MI->eraseFromParent();
6236 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6237 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6238 E = MBB->succ_end(); I != E; ++I)
6241 llvm_unreachable("Expecting a BB with two successors!");
6244 MachineBasicBlock *ARMTargetLowering::
6245 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6246 // This pseudo instruction has 3 operands: dst, src, size
6247 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6248 // Otherwise, we will generate unrolled scalar copies.
6249 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6250 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6251 MachineFunction::iterator It = BB;
6254 unsigned dest = MI->getOperand(0).getReg();
6255 unsigned src = MI->getOperand(1).getReg();
6256 unsigned SizeVal = MI->getOperand(2).getImm();
6257 unsigned Align = MI->getOperand(3).getImm();
6258 DebugLoc dl = MI->getDebugLoc();
6260 bool isThumb2 = Subtarget->isThumb2();
6261 MachineFunction *MF = BB->getParent();
6262 MachineRegisterInfo &MRI = MF->getRegInfo();
6263 unsigned ldrOpc, strOpc, UnitSize = 0;
6265 const TargetRegisterClass *TRC = isThumb2 ?
6266 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6267 (const TargetRegisterClass*)&ARM::GPRRegClass;
6268 const TargetRegisterClass *TRC_Vec = 0;
6271 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6272 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6274 } else if (Align & 2) {
6275 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6276 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6279 // Check whether we can use NEON instructions.
6280 if (!MF->getFunction()->hasFnAttr(Attribute::NoImplicitFloat) &&
6281 Subtarget->hasNEON()) {
6282 if ((Align % 16 == 0) && SizeVal >= 16) {
6283 ldrOpc = ARM::VLD1q32wb_fixed;
6284 strOpc = ARM::VST1q32wb_fixed;
6286 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6288 else if ((Align % 8 == 0) && SizeVal >= 8) {
6289 ldrOpc = ARM::VLD1d32wb_fixed;
6290 strOpc = ARM::VST1d32wb_fixed;
6292 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6295 // Can't use NEON instructions.
6296 if (UnitSize == 0) {
6297 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6298 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6303 unsigned BytesLeft = SizeVal % UnitSize;
6304 unsigned LoopSize = SizeVal - BytesLeft;
6306 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6307 // Use LDR and STR to copy.
6308 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6309 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6310 unsigned srcIn = src;
6311 unsigned destIn = dest;
6312 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6313 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6314 unsigned srcOut = MRI.createVirtualRegister(TRC);
6315 unsigned destOut = MRI.createVirtualRegister(TRC);
6316 if (UnitSize >= 8) {
6317 AddDefaultPred(BuildMI(*BB, MI, dl,
6318 TII->get(ldrOpc), scratch)
6319 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6321 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6322 .addReg(destIn).addImm(0).addReg(scratch));
6323 } else if (isThumb2) {
6324 AddDefaultPred(BuildMI(*BB, MI, dl,
6325 TII->get(ldrOpc), scratch)
6326 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6328 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6329 .addReg(scratch).addReg(destIn)
6332 AddDefaultPred(BuildMI(*BB, MI, dl,
6333 TII->get(ldrOpc), scratch)
6334 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6337 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6338 .addReg(scratch).addReg(destIn)
6339 .addReg(0).addImm(UnitSize));
6345 // Handle the leftover bytes with LDRB and STRB.
6346 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6347 // [destOut] = STRB_POST(scratch, destIn, 1)
6348 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6349 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6350 for (unsigned i = 0; i < BytesLeft; i++) {
6351 unsigned scratch = MRI.createVirtualRegister(TRC);
6352 unsigned srcOut = MRI.createVirtualRegister(TRC);
6353 unsigned destOut = MRI.createVirtualRegister(TRC);
6355 AddDefaultPred(BuildMI(*BB, MI, dl,
6356 TII->get(ldrOpc),scratch)
6357 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6359 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6360 .addReg(scratch).addReg(destIn)
6361 .addReg(0).addImm(1));
6363 AddDefaultPred(BuildMI(*BB, MI, dl,
6364 TII->get(ldrOpc),scratch)
6365 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6367 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6368 .addReg(scratch).addReg(destIn)
6369 .addReg(0).addImm(1));
6374 MI->eraseFromParent(); // The instruction is gone now.
6378 // Expand the pseudo op to a loop.
6381 // movw varEnd, # --> with thumb2
6383 // ldrcp varEnd, idx --> without thumb2
6384 // fallthrough --> loopMBB
6386 // PHI varPhi, varEnd, varLoop
6387 // PHI srcPhi, src, srcLoop
6388 // PHI destPhi, dst, destLoop
6389 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6390 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6391 // subs varLoop, varPhi, #UnitSize
6393 // fallthrough --> exitMBB
6395 // epilogue to handle left-over bytes
6396 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6397 // [destOut] = STRB_POST(scratch, destLoop, 1)
6398 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6399 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6400 MF->insert(It, loopMBB);
6401 MF->insert(It, exitMBB);
6403 // Transfer the remainder of BB and its successor edges to exitMBB.
6404 exitMBB->splice(exitMBB->begin(), BB,
6405 llvm::next(MachineBasicBlock::iterator(MI)),
6407 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6409 // Load an immediate to varEnd.
6410 unsigned varEnd = MRI.createVirtualRegister(TRC);
6412 unsigned VReg1 = varEnd;
6413 if ((LoopSize & 0xFFFF0000) != 0)
6414 VReg1 = MRI.createVirtualRegister(TRC);
6415 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6416 .addImm(LoopSize & 0xFFFF));
6418 if ((LoopSize & 0xFFFF0000) != 0)
6419 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6421 .addImm(LoopSize >> 16));
6423 MachineConstantPool *ConstantPool = MF->getConstantPool();
6424 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6425 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6427 // MachineConstantPool wants an explicit alignment.
6428 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6430 Align = getTargetData()->getTypeAllocSize(C->getType());
6431 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6433 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6434 .addReg(varEnd, RegState::Define)
6435 .addConstantPoolIndex(Idx)
6438 BB->addSuccessor(loopMBB);
6440 // Generate the loop body:
6441 // varPhi = PHI(varLoop, varEnd)
6442 // srcPhi = PHI(srcLoop, src)
6443 // destPhi = PHI(destLoop, dst)
6444 MachineBasicBlock *entryBB = BB;
6446 unsigned varLoop = MRI.createVirtualRegister(TRC);
6447 unsigned varPhi = MRI.createVirtualRegister(TRC);
6448 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6449 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6450 unsigned destLoop = MRI.createVirtualRegister(TRC);
6451 unsigned destPhi = MRI.createVirtualRegister(TRC);
6453 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6454 .addReg(varLoop).addMBB(loopMBB)
6455 .addReg(varEnd).addMBB(entryBB);
6456 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6457 .addReg(srcLoop).addMBB(loopMBB)
6458 .addReg(src).addMBB(entryBB);
6459 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6460 .addReg(destLoop).addMBB(loopMBB)
6461 .addReg(dest).addMBB(entryBB);
6463 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6464 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6465 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6466 if (UnitSize >= 8) {
6467 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6468 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6470 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6471 .addReg(destPhi).addImm(0).addReg(scratch));
6472 } else if (isThumb2) {
6473 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6474 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6476 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6477 .addReg(scratch).addReg(destPhi)
6480 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6481 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6484 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6485 .addReg(scratch).addReg(destPhi)
6486 .addReg(0).addImm(UnitSize));
6489 // Decrement loop variable by UnitSize.
6490 MachineInstrBuilder MIB = BuildMI(BB, dl,
6491 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6492 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6493 MIB->getOperand(5).setReg(ARM::CPSR);
6494 MIB->getOperand(5).setIsDef(true);
6496 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6497 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6499 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6500 BB->addSuccessor(loopMBB);
6501 BB->addSuccessor(exitMBB);
6503 // Add epilogue to handle BytesLeft.
6505 MachineInstr *StartOfExit = exitMBB->begin();
6506 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6507 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6509 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6510 // [destOut] = STRB_POST(scratch, destLoop, 1)
6511 unsigned srcIn = srcLoop;
6512 unsigned destIn = destLoop;
6513 for (unsigned i = 0; i < BytesLeft; i++) {
6514 unsigned scratch = MRI.createVirtualRegister(TRC);
6515 unsigned srcOut = MRI.createVirtualRegister(TRC);
6516 unsigned destOut = MRI.createVirtualRegister(TRC);
6518 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6519 TII->get(ldrOpc),scratch)
6520 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6522 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6523 .addReg(scratch).addReg(destIn)
6526 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6527 TII->get(ldrOpc),scratch)
6528 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6530 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6531 .addReg(scratch).addReg(destIn)
6532 .addReg(0).addImm(1));
6538 MI->eraseFromParent(); // The instruction is gone now.
6543 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6544 MachineBasicBlock *BB) const {
6545 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6546 DebugLoc dl = MI->getDebugLoc();
6547 bool isThumb2 = Subtarget->isThumb2();
6548 switch (MI->getOpcode()) {
6551 llvm_unreachable("Unexpected instr type to insert");
6553 // The Thumb2 pre-indexed stores have the same MI operands, they just
6554 // define them differently in the .td files from the isel patterns, so
6555 // they need pseudos.
6556 case ARM::t2STR_preidx:
6557 MI->setDesc(TII->get(ARM::t2STR_PRE));
6559 case ARM::t2STRB_preidx:
6560 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6562 case ARM::t2STRH_preidx:
6563 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6566 case ARM::STRi_preidx:
6567 case ARM::STRBi_preidx: {
6568 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6569 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6570 // Decode the offset.
6571 unsigned Offset = MI->getOperand(4).getImm();
6572 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6573 Offset = ARM_AM::getAM2Offset(Offset);
6577 MachineMemOperand *MMO = *MI->memoperands_begin();
6578 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6579 .addOperand(MI->getOperand(0)) // Rn_wb
6580 .addOperand(MI->getOperand(1)) // Rt
6581 .addOperand(MI->getOperand(2)) // Rn
6582 .addImm(Offset) // offset (skip GPR==zero_reg)
6583 .addOperand(MI->getOperand(5)) // pred
6584 .addOperand(MI->getOperand(6))
6585 .addMemOperand(MMO);
6586 MI->eraseFromParent();
6589 case ARM::STRr_preidx:
6590 case ARM::STRBr_preidx:
6591 case ARM::STRH_preidx: {
6593 switch (MI->getOpcode()) {
6594 default: llvm_unreachable("unexpected opcode!");
6595 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6596 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6597 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6599 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6600 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6601 MIB.addOperand(MI->getOperand(i));
6602 MI->eraseFromParent();
6605 case ARM::ATOMIC_LOAD_ADD_I8:
6606 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6607 case ARM::ATOMIC_LOAD_ADD_I16:
6608 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6609 case ARM::ATOMIC_LOAD_ADD_I32:
6610 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6612 case ARM::ATOMIC_LOAD_AND_I8:
6613 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6614 case ARM::ATOMIC_LOAD_AND_I16:
6615 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6616 case ARM::ATOMIC_LOAD_AND_I32:
6617 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6619 case ARM::ATOMIC_LOAD_OR_I8:
6620 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6621 case ARM::ATOMIC_LOAD_OR_I16:
6622 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6623 case ARM::ATOMIC_LOAD_OR_I32:
6624 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6626 case ARM::ATOMIC_LOAD_XOR_I8:
6627 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6628 case ARM::ATOMIC_LOAD_XOR_I16:
6629 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6630 case ARM::ATOMIC_LOAD_XOR_I32:
6631 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6633 case ARM::ATOMIC_LOAD_NAND_I8:
6634 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6635 case ARM::ATOMIC_LOAD_NAND_I16:
6636 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6637 case ARM::ATOMIC_LOAD_NAND_I32:
6638 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6640 case ARM::ATOMIC_LOAD_SUB_I8:
6641 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6642 case ARM::ATOMIC_LOAD_SUB_I16:
6643 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6644 case ARM::ATOMIC_LOAD_SUB_I32:
6645 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6647 case ARM::ATOMIC_LOAD_MIN_I8:
6648 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6649 case ARM::ATOMIC_LOAD_MIN_I16:
6650 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6651 case ARM::ATOMIC_LOAD_MIN_I32:
6652 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6654 case ARM::ATOMIC_LOAD_MAX_I8:
6655 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6656 case ARM::ATOMIC_LOAD_MAX_I16:
6657 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6658 case ARM::ATOMIC_LOAD_MAX_I32:
6659 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6661 case ARM::ATOMIC_LOAD_UMIN_I8:
6662 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6663 case ARM::ATOMIC_LOAD_UMIN_I16:
6664 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6665 case ARM::ATOMIC_LOAD_UMIN_I32:
6666 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6668 case ARM::ATOMIC_LOAD_UMAX_I8:
6669 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6670 case ARM::ATOMIC_LOAD_UMAX_I16:
6671 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6672 case ARM::ATOMIC_LOAD_UMAX_I32:
6673 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6675 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
6676 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6677 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6679 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
6680 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6681 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6684 case ARM::ATOMADD6432:
6685 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6686 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6687 /*NeedsCarry*/ true);
6688 case ARM::ATOMSUB6432:
6689 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6690 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6691 /*NeedsCarry*/ true);
6692 case ARM::ATOMOR6432:
6693 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6694 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6695 case ARM::ATOMXOR6432:
6696 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6697 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6698 case ARM::ATOMAND6432:
6699 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6700 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6701 case ARM::ATOMSWAP6432:
6702 return EmitAtomicBinary64(MI, BB, 0, 0, false);
6703 case ARM::ATOMCMPXCHG6432:
6704 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6705 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6706 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6708 case ARM::tMOVCCr_pseudo: {
6709 // To "insert" a SELECT_CC instruction, we actually have to insert the
6710 // diamond control-flow pattern. The incoming instruction knows the
6711 // destination vreg to set, the condition code register to branch on, the
6712 // true/false values to select between, and a branch opcode to use.
6713 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6714 MachineFunction::iterator It = BB;
6720 // cmpTY ccX, r1, r2
6722 // fallthrough --> copy0MBB
6723 MachineBasicBlock *thisMBB = BB;
6724 MachineFunction *F = BB->getParent();
6725 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6726 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6727 F->insert(It, copy0MBB);
6728 F->insert(It, sinkMBB);
6730 // Transfer the remainder of BB and its successor edges to sinkMBB.
6731 sinkMBB->splice(sinkMBB->begin(), BB,
6732 llvm::next(MachineBasicBlock::iterator(MI)),
6734 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6736 BB->addSuccessor(copy0MBB);
6737 BB->addSuccessor(sinkMBB);
6739 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6740 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6743 // %FalseValue = ...
6744 // # fallthrough to sinkMBB
6747 // Update machine-CFG edges
6748 BB->addSuccessor(sinkMBB);
6751 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6754 BuildMI(*BB, BB->begin(), dl,
6755 TII->get(ARM::PHI), MI->getOperand(0).getReg())
6756 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6757 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6759 MI->eraseFromParent(); // The pseudo instruction is gone now.
6764 case ARM::BCCZi64: {
6765 // If there is an unconditional branch to the other successor, remove it.
6766 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6768 // Compare both parts that make up the double comparison separately for
6770 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6772 unsigned LHS1 = MI->getOperand(1).getReg();
6773 unsigned LHS2 = MI->getOperand(2).getReg();
6775 AddDefaultPred(BuildMI(BB, dl,
6776 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6777 .addReg(LHS1).addImm(0));
6778 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6779 .addReg(LHS2).addImm(0)
6780 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6782 unsigned RHS1 = MI->getOperand(3).getReg();
6783 unsigned RHS2 = MI->getOperand(4).getReg();
6784 AddDefaultPred(BuildMI(BB, dl,
6785 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6786 .addReg(LHS1).addReg(RHS1));
6787 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6788 .addReg(LHS2).addReg(RHS2)
6789 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6792 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6793 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6794 if (MI->getOperand(0).getImm() == ARMCC::NE)
6795 std::swap(destMBB, exitMBB);
6797 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6798 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6800 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6802 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6804 MI->eraseFromParent(); // The pseudo instruction is gone now.
6808 case ARM::Int_eh_sjlj_setjmp:
6809 case ARM::Int_eh_sjlj_setjmp_nofp:
6810 case ARM::tInt_eh_sjlj_setjmp:
6811 case ARM::t2Int_eh_sjlj_setjmp:
6812 case ARM::t2Int_eh_sjlj_setjmp_nofp:
6813 EmitSjLjDispatchBlock(MI, BB);
6818 // To insert an ABS instruction, we have to insert the
6819 // diamond control-flow pattern. The incoming instruction knows the
6820 // source vreg to test against 0, the destination vreg to set,
6821 // the condition code register to branch on, the
6822 // true/false values to select between, and a branch opcode to use.
6827 // BCC (branch to SinkBB if V0 >= 0)
6828 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
6829 // SinkBB: V1 = PHI(V2, V3)
6830 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6831 MachineFunction::iterator BBI = BB;
6833 MachineFunction *Fn = BB->getParent();
6834 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6835 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6836 Fn->insert(BBI, RSBBB);
6837 Fn->insert(BBI, SinkBB);
6839 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6840 unsigned int ABSDstReg = MI->getOperand(0).getReg();
6841 bool isThumb2 = Subtarget->isThumb2();
6842 MachineRegisterInfo &MRI = Fn->getRegInfo();
6843 // In Thumb mode S must not be specified if source register is the SP or
6844 // PC and if destination register is the SP, so restrict register class
6845 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6846 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6847 (const TargetRegisterClass*)&ARM::GPRRegClass);
6849 // Transfer the remainder of BB and its successor edges to sinkMBB.
6850 SinkBB->splice(SinkBB->begin(), BB,
6851 llvm::next(MachineBasicBlock::iterator(MI)),
6853 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6855 BB->addSuccessor(RSBBB);
6856 BB->addSuccessor(SinkBB);
6858 // fall through to SinkMBB
6859 RSBBB->addSuccessor(SinkBB);
6861 // insert a cmp at the end of BB
6862 AddDefaultPred(BuildMI(BB, dl,
6863 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6864 .addReg(ABSSrcReg).addImm(0));
6866 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6868 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6869 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6871 // insert rsbri in RSBBB
6872 // Note: BCC and rsbri will be converted into predicated rsbmi
6873 // by if-conversion pass
6874 BuildMI(*RSBBB, RSBBB->begin(), dl,
6875 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6876 .addReg(ABSSrcReg, RegState::Kill)
6877 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6879 // insert PHI in SinkBB,
6880 // reuse ABSDstReg to not change uses of ABS instruction
6881 BuildMI(*SinkBB, SinkBB->begin(), dl,
6882 TII->get(ARM::PHI), ABSDstReg)
6883 .addReg(NewRsbDstReg).addMBB(RSBBB)
6884 .addReg(ABSSrcReg).addMBB(BB);
6886 // remove ABS instruction
6887 MI->eraseFromParent();
6889 // return last added BB
6892 case ARM::COPY_STRUCT_BYVAL_I32:
6894 return EmitStructByval(MI, BB);
6898 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6899 SDNode *Node) const {
6900 if (!MI->hasPostISelHook()) {
6901 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6902 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6906 const MCInstrDesc *MCID = &MI->getDesc();
6907 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6908 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6909 // operand is still set to noreg. If needed, set the optional operand's
6910 // register to CPSR, and remove the redundant implicit def.
6912 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6914 // Rename pseudo opcodes.
6915 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6917 const ARMBaseInstrInfo *TII =
6918 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6919 MCID = &TII->get(NewOpc);
6921 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6922 "converted opcode should be the same except for cc_out");
6926 // Add the optional cc_out operand
6927 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6929 unsigned ccOutIdx = MCID->getNumOperands() - 1;
6931 // Any ARM instruction that sets the 's' bit should specify an optional
6932 // "cc_out" operand in the last operand position.
6933 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6934 assert(!NewOpc && "Optional cc_out operand required");
6937 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6938 // since we already have an optional CPSR def.
6939 bool definesCPSR = false;
6940 bool deadCPSR = false;
6941 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6943 const MachineOperand &MO = MI->getOperand(i);
6944 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6948 MI->RemoveOperand(i);
6953 assert(!NewOpc && "Optional cc_out operand required");
6956 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6958 assert(!MI->getOperand(ccOutIdx).getReg() &&
6959 "expect uninitialized optional cc_out operand");
6963 // If this instruction was defined with an optional CPSR def and its dag node
6964 // had a live implicit CPSR def, then activate the optional CPSR def.
6965 MachineOperand &MO = MI->getOperand(ccOutIdx);
6966 MO.setReg(ARM::CPSR);
6970 //===----------------------------------------------------------------------===//
6971 // ARM Optimization Hooks
6972 //===----------------------------------------------------------------------===//
6975 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6976 TargetLowering::DAGCombinerInfo &DCI) {
6977 SelectionDAG &DAG = DCI.DAG;
6978 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6979 EVT VT = N->getValueType(0);
6980 unsigned Opc = N->getOpcode();
6981 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6982 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6983 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6984 ISD::CondCode CC = ISD::SETCC_INVALID;
6987 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6989 SDValue CCOp = Slct.getOperand(0);
6990 if (CCOp.getOpcode() == ISD::SETCC)
6991 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6994 bool DoXform = false;
6996 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6999 if (LHS.getOpcode() == ISD::Constant &&
7000 cast<ConstantSDNode>(LHS)->isNullValue()) {
7002 } else if (CC != ISD::SETCC_INVALID &&
7003 RHS.getOpcode() == ISD::Constant &&
7004 cast<ConstantSDNode>(RHS)->isNullValue()) {
7005 std::swap(LHS, RHS);
7006 SDValue Op0 = Slct.getOperand(0);
7007 EVT OpVT = isSlctCC ? Op0.getValueType() :
7008 Op0.getOperand(0).getValueType();
7009 bool isInt = OpVT.isInteger();
7010 CC = ISD::getSetCCInverse(CC, isInt);
7012 if (!TLI.isCondCodeLegal(CC, OpVT))
7013 return SDValue(); // Inverse operator isn't legal.
7020 SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
7022 return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
7023 Slct.getOperand(0), Slct.getOperand(1), CC);
7024 SDValue CCOp = Slct.getOperand(0);
7026 CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
7027 CCOp.getOperand(0), CCOp.getOperand(1), CC);
7028 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7029 CCOp, OtherOp, Result);
7034 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7035 // (only after legalization).
7036 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7037 TargetLowering::DAGCombinerInfo &DCI,
7038 const ARMSubtarget *Subtarget) {
7040 // Only perform optimization if after legalize, and if NEON is available. We
7041 // also expected both operands to be BUILD_VECTORs.
7042 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7043 || N0.getOpcode() != ISD::BUILD_VECTOR
7044 || N1.getOpcode() != ISD::BUILD_VECTOR)
7047 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7048 EVT VT = N->getValueType(0);
7049 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7052 // Check that the vector operands are of the right form.
7053 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7054 // operands, where N is the size of the formed vector.
7055 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7056 // index such that we have a pair wise add pattern.
7058 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7059 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7061 SDValue Vec = N0->getOperand(0)->getOperand(0);
7062 SDNode *V = Vec.getNode();
7063 unsigned nextIndex = 0;
7065 // For each operands to the ADD which are BUILD_VECTORs,
7066 // check to see if each of their operands are an EXTRACT_VECTOR with
7067 // the same vector and appropriate index.
7068 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7069 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7070 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7072 SDValue ExtVec0 = N0->getOperand(i);
7073 SDValue ExtVec1 = N1->getOperand(i);
7075 // First operand is the vector, verify its the same.
7076 if (V != ExtVec0->getOperand(0).getNode() ||
7077 V != ExtVec1->getOperand(0).getNode())
7080 // Second is the constant, verify its correct.
7081 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7082 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7084 // For the constant, we want to see all the even or all the odd.
7085 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7086 || C1->getZExtValue() != nextIndex+1)
7095 // Create VPADDL node.
7096 SelectionDAG &DAG = DCI.DAG;
7097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7099 // Build operand list.
7100 SmallVector<SDValue, 8> Ops;
7101 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7102 TLI.getPointerTy()));
7104 // Input is the vector.
7107 // Get widened type and narrowed type.
7109 unsigned numElem = VT.getVectorNumElements();
7110 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7111 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7112 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7113 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7115 llvm_unreachable("Invalid vector element type for padd optimization.");
7118 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7119 widenType, &Ops[0], Ops.size());
7120 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7123 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7124 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7125 /// called with the default operands, and if that fails, with commuted
7127 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7128 TargetLowering::DAGCombinerInfo &DCI,
7129 const ARMSubtarget *Subtarget){
7131 // Attempt to create vpaddl for this add.
7132 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7133 if (Result.getNode())
7136 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7137 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
7138 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7139 if (Result.getNode()) return Result;
7144 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7146 static SDValue PerformADDCombine(SDNode *N,
7147 TargetLowering::DAGCombinerInfo &DCI,
7148 const ARMSubtarget *Subtarget) {
7149 SDValue N0 = N->getOperand(0);
7150 SDValue N1 = N->getOperand(1);
7152 // First try with the default operand order.
7153 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7154 if (Result.getNode())
7157 // If that didn't work, try again with the operands commuted.
7158 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7161 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7163 static SDValue PerformSUBCombine(SDNode *N,
7164 TargetLowering::DAGCombinerInfo &DCI) {
7165 SDValue N0 = N->getOperand(0);
7166 SDValue N1 = N->getOperand(1);
7168 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7169 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
7170 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7171 if (Result.getNode()) return Result;
7177 /// PerformVMULCombine
7178 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7179 /// special multiplier accumulator forwarding.
7185 static SDValue PerformVMULCombine(SDNode *N,
7186 TargetLowering::DAGCombinerInfo &DCI,
7187 const ARMSubtarget *Subtarget) {
7188 if (!Subtarget->hasVMLxForwarding())
7191 SelectionDAG &DAG = DCI.DAG;
7192 SDValue N0 = N->getOperand(0);
7193 SDValue N1 = N->getOperand(1);
7194 unsigned Opcode = N0.getOpcode();
7195 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7196 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7197 Opcode = N1.getOpcode();
7198 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7199 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7204 EVT VT = N->getValueType(0);
7205 DebugLoc DL = N->getDebugLoc();
7206 SDValue N00 = N0->getOperand(0);
7207 SDValue N01 = N0->getOperand(1);
7208 return DAG.getNode(Opcode, DL, VT,
7209 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7210 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7213 static SDValue PerformMULCombine(SDNode *N,
7214 TargetLowering::DAGCombinerInfo &DCI,
7215 const ARMSubtarget *Subtarget) {
7216 SelectionDAG &DAG = DCI.DAG;
7218 if (Subtarget->isThumb1Only())
7221 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7224 EVT VT = N->getValueType(0);
7225 if (VT.is64BitVector() || VT.is128BitVector())
7226 return PerformVMULCombine(N, DCI, Subtarget);
7230 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7234 int64_t MulAmt = C->getSExtValue();
7235 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7237 ShiftAmt = ShiftAmt & (32 - 1);
7238 SDValue V = N->getOperand(0);
7239 DebugLoc DL = N->getDebugLoc();
7242 MulAmt >>= ShiftAmt;
7245 if (isPowerOf2_32(MulAmt - 1)) {
7246 // (mul x, 2^N + 1) => (add (shl x, N), x)
7247 Res = DAG.getNode(ISD::ADD, DL, VT,
7249 DAG.getNode(ISD::SHL, DL, VT,
7251 DAG.getConstant(Log2_32(MulAmt - 1),
7253 } else if (isPowerOf2_32(MulAmt + 1)) {
7254 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7255 Res = DAG.getNode(ISD::SUB, DL, VT,
7256 DAG.getNode(ISD::SHL, DL, VT,
7258 DAG.getConstant(Log2_32(MulAmt + 1),
7264 uint64_t MulAmtAbs = -MulAmt;
7265 if (isPowerOf2_32(MulAmtAbs + 1)) {
7266 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7267 Res = DAG.getNode(ISD::SUB, DL, VT,
7269 DAG.getNode(ISD::SHL, DL, VT,
7271 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7273 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7274 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7275 Res = DAG.getNode(ISD::ADD, DL, VT,
7277 DAG.getNode(ISD::SHL, DL, VT,
7279 DAG.getConstant(Log2_32(MulAmtAbs-1),
7281 Res = DAG.getNode(ISD::SUB, DL, VT,
7282 DAG.getConstant(0, MVT::i32),Res);
7289 Res = DAG.getNode(ISD::SHL, DL, VT,
7290 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7292 // Do not add new nodes to DAG combiner worklist.
7293 DCI.CombineTo(N, Res, false);
7297 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
7298 if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
7301 SDValue FalseVal = N.getOperand(0);
7302 ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
7306 return C->isAllOnesValue();
7307 return C->isNullValue();
7310 /// formConditionalOp - Combine an operation with a conditional move operand
7311 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7312 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7313 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7315 SDValue N0 = N->getOperand(0);
7316 SDValue N1 = N->getOperand(1);
7318 bool isAND = N->getOpcode() == ISD::AND;
7319 bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7320 if (!isCand && Commutable) {
7321 isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7329 switch (N->getOpcode()) {
7330 default: llvm_unreachable("Unexpected node");
7331 case ISD::AND: Opc = ARMISD::CAND; break;
7332 case ISD::OR: Opc = ARMISD::COR; break;
7333 case ISD::XOR: Opc = ARMISD::CXOR; break;
7335 return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7336 N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7340 static SDValue PerformANDCombine(SDNode *N,
7341 TargetLowering::DAGCombinerInfo &DCI,
7342 const ARMSubtarget *Subtarget) {
7344 // Attempt to use immediate-form VBIC
7345 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7346 DebugLoc dl = N->getDebugLoc();
7347 EVT VT = N->getValueType(0);
7348 SelectionDAG &DAG = DCI.DAG;
7350 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7353 APInt SplatBits, SplatUndef;
7354 unsigned SplatBitSize;
7357 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7358 if (SplatBitSize <= 64) {
7360 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7361 SplatUndef.getZExtValue(), SplatBitSize,
7362 DAG, VbicVT, VT.is128BitVector(),
7364 if (Val.getNode()) {
7366 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7367 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7368 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7373 if (!Subtarget->isThumb1Only()) {
7374 // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7375 SDValue CAND = formConditionalOp(N, DAG, true);
7383 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7384 static SDValue PerformORCombine(SDNode *N,
7385 TargetLowering::DAGCombinerInfo &DCI,
7386 const ARMSubtarget *Subtarget) {
7387 // Attempt to use immediate-form VORR
7388 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7389 DebugLoc dl = N->getDebugLoc();
7390 EVT VT = N->getValueType(0);
7391 SelectionDAG &DAG = DCI.DAG;
7393 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7396 APInt SplatBits, SplatUndef;
7397 unsigned SplatBitSize;
7399 if (BVN && Subtarget->hasNEON() &&
7400 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7401 if (SplatBitSize <= 64) {
7403 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7404 SplatUndef.getZExtValue(), SplatBitSize,
7405 DAG, VorrVT, VT.is128BitVector(),
7407 if (Val.getNode()) {
7409 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7410 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7411 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7416 if (!Subtarget->isThumb1Only()) {
7417 // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7418 SDValue COR = formConditionalOp(N, DAG, true);
7423 SDValue N0 = N->getOperand(0);
7424 if (N0.getOpcode() != ISD::AND)
7426 SDValue N1 = N->getOperand(1);
7428 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7429 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7430 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7432 unsigned SplatBitSize;
7435 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7437 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7438 HasAnyUndefs) && !HasAnyUndefs) {
7439 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7441 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7442 HasAnyUndefs) && !HasAnyUndefs &&
7443 SplatBits0 == ~SplatBits1) {
7444 // Canonicalize the vector type to make instruction selection simpler.
7445 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7446 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7447 N0->getOperand(1), N0->getOperand(0),
7449 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7454 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7457 // BFI is only available on V6T2+
7458 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7461 DebugLoc DL = N->getDebugLoc();
7462 // 1) or (and A, mask), val => ARMbfi A, val, mask
7463 // iff (val & mask) == val
7465 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7466 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7467 // && mask == ~mask2
7468 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7469 // && ~mask == mask2
7470 // (i.e., copy a bitfield value into another bitfield of the same width)
7475 SDValue N00 = N0.getOperand(0);
7477 // The value and the mask need to be constants so we can verify this is
7478 // actually a bitfield set. If the mask is 0xffff, we can do better
7479 // via a movt instruction, so don't use BFI in that case.
7480 SDValue MaskOp = N0.getOperand(1);
7481 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7484 unsigned Mask = MaskC->getZExtValue();
7488 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7489 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7491 unsigned Val = N1C->getZExtValue();
7492 if ((Val & ~Mask) != Val)
7495 if (ARM::isBitFieldInvertedMask(Mask)) {
7496 Val >>= CountTrailingZeros_32(~Mask);
7498 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7499 DAG.getConstant(Val, MVT::i32),
7500 DAG.getConstant(Mask, MVT::i32));
7502 // Do not add new nodes to DAG combiner worklist.
7503 DCI.CombineTo(N, Res, false);
7506 } else if (N1.getOpcode() == ISD::AND) {
7507 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7508 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7511 unsigned Mask2 = N11C->getZExtValue();
7513 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7515 if (ARM::isBitFieldInvertedMask(Mask) &&
7517 // The pack halfword instruction works better for masks that fit it,
7518 // so use that when it's available.
7519 if (Subtarget->hasT2ExtractPack() &&
7520 (Mask == 0xffff || Mask == 0xffff0000))
7523 unsigned amt = CountTrailingZeros_32(Mask2);
7524 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7525 DAG.getConstant(amt, MVT::i32));
7526 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7527 DAG.getConstant(Mask, MVT::i32));
7528 // Do not add new nodes to DAG combiner worklist.
7529 DCI.CombineTo(N, Res, false);
7531 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7533 // The pack halfword instruction works better for masks that fit it,
7534 // so use that when it's available.
7535 if (Subtarget->hasT2ExtractPack() &&
7536 (Mask2 == 0xffff || Mask2 == 0xffff0000))
7539 unsigned lsb = CountTrailingZeros_32(Mask);
7540 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7541 DAG.getConstant(lsb, MVT::i32));
7542 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7543 DAG.getConstant(Mask2, MVT::i32));
7544 // Do not add new nodes to DAG combiner worklist.
7545 DCI.CombineTo(N, Res, false);
7550 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7551 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7552 ARM::isBitFieldInvertedMask(~Mask)) {
7553 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7554 // where lsb(mask) == #shamt and masked bits of B are known zero.
7555 SDValue ShAmt = N00.getOperand(1);
7556 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7557 unsigned LSB = CountTrailingZeros_32(Mask);
7561 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7562 DAG.getConstant(~Mask, MVT::i32));
7564 // Do not add new nodes to DAG combiner worklist.
7565 DCI.CombineTo(N, Res, false);
7571 static SDValue PerformXORCombine(SDNode *N,
7572 TargetLowering::DAGCombinerInfo &DCI,
7573 const ARMSubtarget *Subtarget) {
7574 EVT VT = N->getValueType(0);
7575 SelectionDAG &DAG = DCI.DAG;
7577 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7580 if (!Subtarget->isThumb1Only()) {
7581 // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7582 SDValue CXOR = formConditionalOp(N, DAG, true);
7590 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7591 /// the bits being cleared by the AND are not demanded by the BFI.
7592 static SDValue PerformBFICombine(SDNode *N,
7593 TargetLowering::DAGCombinerInfo &DCI) {
7594 SDValue N1 = N->getOperand(1);
7595 if (N1.getOpcode() == ISD::AND) {
7596 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7599 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7600 unsigned LSB = CountTrailingZeros_32(~InvMask);
7601 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7602 unsigned Mask = (1 << Width)-1;
7603 unsigned Mask2 = N11C->getZExtValue();
7604 if ((Mask & (~Mask2)) == 0)
7605 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7606 N->getOperand(0), N1.getOperand(0),
7612 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7613 /// ARMISD::VMOVRRD.
7614 static SDValue PerformVMOVRRDCombine(SDNode *N,
7615 TargetLowering::DAGCombinerInfo &DCI) {
7616 // vmovrrd(vmovdrr x, y) -> x,y
7617 SDValue InDouble = N->getOperand(0);
7618 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7619 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7621 // vmovrrd(load f64) -> (load i32), (load i32)
7622 SDNode *InNode = InDouble.getNode();
7623 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7624 InNode->getValueType(0) == MVT::f64 &&
7625 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7626 !cast<LoadSDNode>(InNode)->isVolatile()) {
7627 // TODO: Should this be done for non-FrameIndex operands?
7628 LoadSDNode *LD = cast<LoadSDNode>(InNode);
7630 SelectionDAG &DAG = DCI.DAG;
7631 DebugLoc DL = LD->getDebugLoc();
7632 SDValue BasePtr = LD->getBasePtr();
7633 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7634 LD->getPointerInfo(), LD->isVolatile(),
7635 LD->isNonTemporal(), LD->isInvariant(),
7636 LD->getAlignment());
7638 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7639 DAG.getConstant(4, MVT::i32));
7640 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7641 LD->getPointerInfo(), LD->isVolatile(),
7642 LD->isNonTemporal(), LD->isInvariant(),
7643 std::min(4U, LD->getAlignment() / 2));
7645 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7646 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7647 DCI.RemoveFromWorklist(LD);
7655 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7656 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
7657 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7658 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7659 SDValue Op0 = N->getOperand(0);
7660 SDValue Op1 = N->getOperand(1);
7661 if (Op0.getOpcode() == ISD::BITCAST)
7662 Op0 = Op0.getOperand(0);
7663 if (Op1.getOpcode() == ISD::BITCAST)
7664 Op1 = Op1.getOperand(0);
7665 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7666 Op0.getNode() == Op1.getNode() &&
7667 Op0.getResNo() == 0 && Op1.getResNo() == 1)
7668 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7669 N->getValueType(0), Op0.getOperand(0));
7673 /// PerformSTORECombine - Target-specific dag combine xforms for
7675 static SDValue PerformSTORECombine(SDNode *N,
7676 TargetLowering::DAGCombinerInfo &DCI) {
7677 StoreSDNode *St = cast<StoreSDNode>(N);
7678 if (St->isVolatile())
7681 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
7682 // pack all of the elements in one place. Next, store to memory in fewer
7684 SDValue StVal = St->getValue();
7685 EVT VT = StVal.getValueType();
7686 if (St->isTruncatingStore() && VT.isVector()) {
7687 SelectionDAG &DAG = DCI.DAG;
7688 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7689 EVT StVT = St->getMemoryVT();
7690 unsigned NumElems = VT.getVectorNumElements();
7691 assert(StVT != VT && "Cannot truncate to the same type");
7692 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7693 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7695 // From, To sizes and ElemCount must be pow of two
7696 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7698 // We are going to use the original vector elt for storing.
7699 // Accumulated smaller vector elements must be a multiple of the store size.
7700 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7702 unsigned SizeRatio = FromEltSz / ToEltSz;
7703 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7705 // Create a type on which we perform the shuffle.
7706 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7707 NumElems*SizeRatio);
7708 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7710 DebugLoc DL = St->getDebugLoc();
7711 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7712 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7713 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7715 // Can't shuffle using an illegal type.
7716 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7718 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7719 DAG.getUNDEF(WideVec.getValueType()),
7721 // At this point all of the data is stored at the bottom of the
7722 // register. We now need to save it to mem.
7724 // Find the largest store unit
7725 MVT StoreType = MVT::i8;
7726 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7727 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7728 MVT Tp = (MVT::SimpleValueType)tp;
7729 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7732 // Didn't find a legal store type.
7733 if (!TLI.isTypeLegal(StoreType))
7736 // Bitcast the original vector into a vector of store-size units
7737 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7738 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7739 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7740 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7741 SmallVector<SDValue, 8> Chains;
7742 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7743 TLI.getPointerTy());
7744 SDValue BasePtr = St->getBasePtr();
7746 // Perform one or more big stores into memory.
7747 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7748 for (unsigned I = 0; I < E; I++) {
7749 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7750 StoreType, ShuffWide,
7751 DAG.getIntPtrConstant(I));
7752 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7753 St->getPointerInfo(), St->isVolatile(),
7754 St->isNonTemporal(), St->getAlignment());
7755 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7757 Chains.push_back(Ch);
7759 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7763 if (!ISD::isNormalStore(St))
7766 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7767 // ARM stores of arguments in the same cache line.
7768 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7769 StVal.getNode()->hasOneUse()) {
7770 SelectionDAG &DAG = DCI.DAG;
7771 DebugLoc DL = St->getDebugLoc();
7772 SDValue BasePtr = St->getBasePtr();
7773 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7774 StVal.getNode()->getOperand(0), BasePtr,
7775 St->getPointerInfo(), St->isVolatile(),
7776 St->isNonTemporal(), St->getAlignment());
7778 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7779 DAG.getConstant(4, MVT::i32));
7780 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7781 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7782 St->isNonTemporal(),
7783 std::min(4U, St->getAlignment() / 2));
7786 if (StVal.getValueType() != MVT::i64 ||
7787 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7790 // Bitcast an i64 store extracted from a vector to f64.
7791 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7792 SelectionDAG &DAG = DCI.DAG;
7793 DebugLoc dl = StVal.getDebugLoc();
7794 SDValue IntVec = StVal.getOperand(0);
7795 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7796 IntVec.getValueType().getVectorNumElements());
7797 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7798 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7799 Vec, StVal.getOperand(1));
7800 dl = N->getDebugLoc();
7801 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7802 // Make the DAGCombiner fold the bitcasts.
7803 DCI.AddToWorklist(Vec.getNode());
7804 DCI.AddToWorklist(ExtElt.getNode());
7805 DCI.AddToWorklist(V.getNode());
7806 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7807 St->getPointerInfo(), St->isVolatile(),
7808 St->isNonTemporal(), St->getAlignment(),
7812 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7813 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
7814 /// i64 vector to have f64 elements, since the value can then be loaded
7815 /// directly into a VFP register.
7816 static bool hasNormalLoadOperand(SDNode *N) {
7817 unsigned NumElts = N->getValueType(0).getVectorNumElements();
7818 for (unsigned i = 0; i < NumElts; ++i) {
7819 SDNode *Elt = N->getOperand(i).getNode();
7820 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7826 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7827 /// ISD::BUILD_VECTOR.
7828 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7829 TargetLowering::DAGCombinerInfo &DCI){
7830 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7831 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
7832 // into a pair of GPRs, which is fine when the value is used as a scalar,
7833 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7834 SelectionDAG &DAG = DCI.DAG;
7835 if (N->getNumOperands() == 2) {
7836 SDValue RV = PerformVMOVDRRCombine(N, DAG);
7841 // Load i64 elements as f64 values so that type legalization does not split
7842 // them up into i32 values.
7843 EVT VT = N->getValueType(0);
7844 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7846 DebugLoc dl = N->getDebugLoc();
7847 SmallVector<SDValue, 8> Ops;
7848 unsigned NumElts = VT.getVectorNumElements();
7849 for (unsigned i = 0; i < NumElts; ++i) {
7850 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7852 // Make the DAGCombiner fold the bitcast.
7853 DCI.AddToWorklist(V.getNode());
7855 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7856 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7857 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7860 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7861 /// ISD::INSERT_VECTOR_ELT.
7862 static SDValue PerformInsertEltCombine(SDNode *N,
7863 TargetLowering::DAGCombinerInfo &DCI) {
7864 // Bitcast an i64 load inserted into a vector to f64.
7865 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7866 EVT VT = N->getValueType(0);
7867 SDNode *Elt = N->getOperand(1).getNode();
7868 if (VT.getVectorElementType() != MVT::i64 ||
7869 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7872 SelectionDAG &DAG = DCI.DAG;
7873 DebugLoc dl = N->getDebugLoc();
7874 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7875 VT.getVectorNumElements());
7876 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7877 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7878 // Make the DAGCombiner fold the bitcasts.
7879 DCI.AddToWorklist(Vec.getNode());
7880 DCI.AddToWorklist(V.getNode());
7881 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7882 Vec, V, N->getOperand(2));
7883 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7886 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7887 /// ISD::VECTOR_SHUFFLE.
7888 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7889 // The LLVM shufflevector instruction does not require the shuffle mask
7890 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7891 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
7892 // operands do not match the mask length, they are extended by concatenating
7893 // them with undef vectors. That is probably the right thing for other
7894 // targets, but for NEON it is better to concatenate two double-register
7895 // size vector operands into a single quad-register size vector. Do that
7896 // transformation here:
7897 // shuffle(concat(v1, undef), concat(v2, undef)) ->
7898 // shuffle(concat(v1, v2), undef)
7899 SDValue Op0 = N->getOperand(0);
7900 SDValue Op1 = N->getOperand(1);
7901 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7902 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7903 Op0.getNumOperands() != 2 ||
7904 Op1.getNumOperands() != 2)
7906 SDValue Concat0Op1 = Op0.getOperand(1);
7907 SDValue Concat1Op1 = Op1.getOperand(1);
7908 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7909 Concat1Op1.getOpcode() != ISD::UNDEF)
7911 // Skip the transformation if any of the types are illegal.
7912 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7913 EVT VT = N->getValueType(0);
7914 if (!TLI.isTypeLegal(VT) ||
7915 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7916 !TLI.isTypeLegal(Concat1Op1.getValueType()))
7919 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7920 Op0.getOperand(0), Op1.getOperand(0));
7921 // Translate the shuffle mask.
7922 SmallVector<int, 16> NewMask;
7923 unsigned NumElts = VT.getVectorNumElements();
7924 unsigned HalfElts = NumElts/2;
7925 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7926 for (unsigned n = 0; n < NumElts; ++n) {
7927 int MaskElt = SVN->getMaskElt(n);
7929 if (MaskElt < (int)HalfElts)
7931 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7932 NewElt = HalfElts + MaskElt - NumElts;
7933 NewMask.push_back(NewElt);
7935 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7936 DAG.getUNDEF(VT), NewMask.data());
7939 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7940 /// NEON load/store intrinsics to merge base address updates.
7941 static SDValue CombineBaseUpdate(SDNode *N,
7942 TargetLowering::DAGCombinerInfo &DCI) {
7943 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7946 SelectionDAG &DAG = DCI.DAG;
7947 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7948 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7949 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7950 SDValue Addr = N->getOperand(AddrOpIdx);
7952 // Search for a use of the address operand that is an increment.
7953 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7954 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7956 if (User->getOpcode() != ISD::ADD ||
7957 UI.getUse().getResNo() != Addr.getResNo())
7960 // Check that the add is independent of the load/store. Otherwise, folding
7961 // it would create a cycle.
7962 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7965 // Find the new opcode for the updating load/store.
7967 bool isLaneOp = false;
7968 unsigned NewOpc = 0;
7969 unsigned NumVecs = 0;
7971 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7973 default: llvm_unreachable("unexpected intrinsic for Neon base update");
7974 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
7976 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
7978 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
7980 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
7982 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7983 NumVecs = 2; isLaneOp = true; break;
7984 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7985 NumVecs = 3; isLaneOp = true; break;
7986 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7987 NumVecs = 4; isLaneOp = true; break;
7988 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
7989 NumVecs = 1; isLoad = false; break;
7990 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
7991 NumVecs = 2; isLoad = false; break;
7992 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
7993 NumVecs = 3; isLoad = false; break;
7994 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
7995 NumVecs = 4; isLoad = false; break;
7996 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7997 NumVecs = 2; isLoad = false; isLaneOp = true; break;
7998 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7999 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8000 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8001 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8005 switch (N->getOpcode()) {
8006 default: llvm_unreachable("unexpected opcode for Neon base update");
8007 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8008 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8009 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8013 // Find the size of memory referenced by the load/store.
8016 VecTy = N->getValueType(0);
8018 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8019 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8021 NumBytes /= VecTy.getVectorNumElements();
8023 // If the increment is a constant, it must match the memory ref size.
8024 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8025 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8026 uint64_t IncVal = CInc->getZExtValue();
8027 if (IncVal != NumBytes)
8029 } else if (NumBytes >= 3 * 16) {
8030 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8031 // separate instructions that make it harder to use a non-constant update.
8035 // Create the new updating load/store node.
8037 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8039 for (n = 0; n < NumResultVecs; ++n)
8041 Tys[n++] = MVT::i32;
8042 Tys[n] = MVT::Other;
8043 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8044 SmallVector<SDValue, 8> Ops;
8045 Ops.push_back(N->getOperand(0)); // incoming chain
8046 Ops.push_back(N->getOperand(AddrOpIdx));
8048 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8049 Ops.push_back(N->getOperand(i));
8051 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8052 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8053 Ops.data(), Ops.size(),
8054 MemInt->getMemoryVT(),
8055 MemInt->getMemOperand());
8058 std::vector<SDValue> NewResults;
8059 for (unsigned i = 0; i < NumResultVecs; ++i) {
8060 NewResults.push_back(SDValue(UpdN.getNode(), i));
8062 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8063 DCI.CombineTo(N, NewResults);
8064 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8071 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8072 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8073 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8075 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8076 SelectionDAG &DAG = DCI.DAG;
8077 EVT VT = N->getValueType(0);
8078 // vldN-dup instructions only support 64-bit vectors for N > 1.
8079 if (!VT.is64BitVector())
8082 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8083 SDNode *VLD = N->getOperand(0).getNode();
8084 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8086 unsigned NumVecs = 0;
8087 unsigned NewOpc = 0;
8088 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8089 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8091 NewOpc = ARMISD::VLD2DUP;
8092 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8094 NewOpc = ARMISD::VLD3DUP;
8095 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8097 NewOpc = ARMISD::VLD4DUP;
8102 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8103 // numbers match the load.
8104 unsigned VLDLaneNo =
8105 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8106 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8108 // Ignore uses of the chain result.
8109 if (UI.getUse().getResNo() == NumVecs)
8112 if (User->getOpcode() != ARMISD::VDUPLANE ||
8113 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8117 // Create the vldN-dup node.
8120 for (n = 0; n < NumVecs; ++n)
8122 Tys[n] = MVT::Other;
8123 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8124 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8125 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8126 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8127 Ops, 2, VLDMemInt->getMemoryVT(),
8128 VLDMemInt->getMemOperand());
8131 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8133 unsigned ResNo = UI.getUse().getResNo();
8134 // Ignore uses of the chain result.
8135 if (ResNo == NumVecs)
8138 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8141 // Now the vldN-lane intrinsic is dead except for its chain result.
8142 // Update uses of the chain.
8143 std::vector<SDValue> VLDDupResults;
8144 for (unsigned n = 0; n < NumVecs; ++n)
8145 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8146 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8147 DCI.CombineTo(VLD, VLDDupResults);
8152 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8153 /// ARMISD::VDUPLANE.
8154 static SDValue PerformVDUPLANECombine(SDNode *N,
8155 TargetLowering::DAGCombinerInfo &DCI) {
8156 SDValue Op = N->getOperand(0);
8158 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8159 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8160 if (CombineVLDDUP(N, DCI))
8161 return SDValue(N, 0);
8163 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8164 // redundant. Ignore bit_converts for now; element sizes are checked below.
8165 while (Op.getOpcode() == ISD::BITCAST)
8166 Op = Op.getOperand(0);
8167 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8170 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8171 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8172 // The canonical VMOV for a zero vector uses a 32-bit element size.
8173 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8175 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8177 EVT VT = N->getValueType(0);
8178 if (EltSize > VT.getVectorElementType().getSizeInBits())
8181 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8184 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8185 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8186 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8190 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8192 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8197 APFloat APF = C->getValueAPF();
8198 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8199 != APFloat::opOK || !isExact)
8202 c0 = (I == 0) ? cN : c0;
8203 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8210 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8211 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8212 /// when the VMUL has a constant operand that is a power of 2.
8214 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8215 /// vmul.f32 d16, d17, d16
8216 /// vcvt.s32.f32 d16, d16
8218 /// vcvt.s32.f32 d16, d16, #3
8219 static SDValue PerformVCVTCombine(SDNode *N,
8220 TargetLowering::DAGCombinerInfo &DCI,
8221 const ARMSubtarget *Subtarget) {
8222 SelectionDAG &DAG = DCI.DAG;
8223 SDValue Op = N->getOperand(0);
8225 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8226 Op.getOpcode() != ISD::FMUL)
8230 SDValue N0 = Op->getOperand(0);
8231 SDValue ConstVec = Op->getOperand(1);
8232 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8234 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8235 !isConstVecPow2(ConstVec, isSigned, C))
8238 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8239 Intrinsic::arm_neon_vcvtfp2fxu;
8240 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8242 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8243 DAG.getConstant(Log2_64(C), MVT::i32));
8246 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8247 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8248 /// when the VDIV has a constant operand that is a power of 2.
8250 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8251 /// vcvt.f32.s32 d16, d16
8252 /// vdiv.f32 d16, d17, d16
8254 /// vcvt.f32.s32 d16, d16, #3
8255 static SDValue PerformVDIVCombine(SDNode *N,
8256 TargetLowering::DAGCombinerInfo &DCI,
8257 const ARMSubtarget *Subtarget) {
8258 SelectionDAG &DAG = DCI.DAG;
8259 SDValue Op = N->getOperand(0);
8260 unsigned OpOpcode = Op.getNode()->getOpcode();
8262 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8263 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8267 SDValue ConstVec = N->getOperand(1);
8268 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8270 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8271 !isConstVecPow2(ConstVec, isSigned, C))
8274 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8275 Intrinsic::arm_neon_vcvtfxu2fp;
8276 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8278 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8279 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8282 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8283 /// operand of a vector shift operation, where all the elements of the
8284 /// build_vector must have the same constant integer value.
8285 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8286 // Ignore bit_converts.
8287 while (Op.getOpcode() == ISD::BITCAST)
8288 Op = Op.getOperand(0);
8289 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8290 APInt SplatBits, SplatUndef;
8291 unsigned SplatBitSize;
8293 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8294 HasAnyUndefs, ElementBits) ||
8295 SplatBitSize > ElementBits)
8297 Cnt = SplatBits.getSExtValue();
8301 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8302 /// operand of a vector shift left operation. That value must be in the range:
8303 /// 0 <= Value < ElementBits for a left shift; or
8304 /// 0 <= Value <= ElementBits for a long left shift.
8305 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8306 assert(VT.isVector() && "vector shift count is not a vector type");
8307 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8308 if (! getVShiftImm(Op, ElementBits, Cnt))
8310 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8313 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8314 /// operand of a vector shift right operation. For a shift opcode, the value
8315 /// is positive, but for an intrinsic the value count must be negative. The
8316 /// absolute value must be in the range:
8317 /// 1 <= |Value| <= ElementBits for a right shift; or
8318 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8319 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8321 assert(VT.isVector() && "vector shift count is not a vector type");
8322 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8323 if (! getVShiftImm(Op, ElementBits, Cnt))
8327 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8330 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8331 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8332 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8335 // Don't do anything for most intrinsics.
8338 // Vector shifts: check for immediate versions and lower them.
8339 // Note: This is done during DAG combining instead of DAG legalizing because
8340 // the build_vectors for 64-bit vector element shift counts are generally
8341 // not legal, and it is hard to see their values after they get legalized to
8342 // loads from a constant pool.
8343 case Intrinsic::arm_neon_vshifts:
8344 case Intrinsic::arm_neon_vshiftu:
8345 case Intrinsic::arm_neon_vshiftls:
8346 case Intrinsic::arm_neon_vshiftlu:
8347 case Intrinsic::arm_neon_vshiftn:
8348 case Intrinsic::arm_neon_vrshifts:
8349 case Intrinsic::arm_neon_vrshiftu:
8350 case Intrinsic::arm_neon_vrshiftn:
8351 case Intrinsic::arm_neon_vqshifts:
8352 case Intrinsic::arm_neon_vqshiftu:
8353 case Intrinsic::arm_neon_vqshiftsu:
8354 case Intrinsic::arm_neon_vqshiftns:
8355 case Intrinsic::arm_neon_vqshiftnu:
8356 case Intrinsic::arm_neon_vqshiftnsu:
8357 case Intrinsic::arm_neon_vqrshiftns:
8358 case Intrinsic::arm_neon_vqrshiftnu:
8359 case Intrinsic::arm_neon_vqrshiftnsu: {
8360 EVT VT = N->getOperand(1).getValueType();
8362 unsigned VShiftOpc = 0;
8365 case Intrinsic::arm_neon_vshifts:
8366 case Intrinsic::arm_neon_vshiftu:
8367 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8368 VShiftOpc = ARMISD::VSHL;
8371 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8372 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8373 ARMISD::VSHRs : ARMISD::VSHRu);
8378 case Intrinsic::arm_neon_vshiftls:
8379 case Intrinsic::arm_neon_vshiftlu:
8380 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8382 llvm_unreachable("invalid shift count for vshll intrinsic");
8384 case Intrinsic::arm_neon_vrshifts:
8385 case Intrinsic::arm_neon_vrshiftu:
8386 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8390 case Intrinsic::arm_neon_vqshifts:
8391 case Intrinsic::arm_neon_vqshiftu:
8392 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8396 case Intrinsic::arm_neon_vqshiftsu:
8397 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8399 llvm_unreachable("invalid shift count for vqshlu intrinsic");
8401 case Intrinsic::arm_neon_vshiftn:
8402 case Intrinsic::arm_neon_vrshiftn:
8403 case Intrinsic::arm_neon_vqshiftns:
8404 case Intrinsic::arm_neon_vqshiftnu:
8405 case Intrinsic::arm_neon_vqshiftnsu:
8406 case Intrinsic::arm_neon_vqrshiftns:
8407 case Intrinsic::arm_neon_vqrshiftnu:
8408 case Intrinsic::arm_neon_vqrshiftnsu:
8409 // Narrowing shifts require an immediate right shift.
8410 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8412 llvm_unreachable("invalid shift count for narrowing vector shift "
8416 llvm_unreachable("unhandled vector shift");
8420 case Intrinsic::arm_neon_vshifts:
8421 case Intrinsic::arm_neon_vshiftu:
8422 // Opcode already set above.
8424 case Intrinsic::arm_neon_vshiftls:
8425 case Intrinsic::arm_neon_vshiftlu:
8426 if (Cnt == VT.getVectorElementType().getSizeInBits())
8427 VShiftOpc = ARMISD::VSHLLi;
8429 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8430 ARMISD::VSHLLs : ARMISD::VSHLLu);
8432 case Intrinsic::arm_neon_vshiftn:
8433 VShiftOpc = ARMISD::VSHRN; break;
8434 case Intrinsic::arm_neon_vrshifts:
8435 VShiftOpc = ARMISD::VRSHRs; break;
8436 case Intrinsic::arm_neon_vrshiftu:
8437 VShiftOpc = ARMISD::VRSHRu; break;
8438 case Intrinsic::arm_neon_vrshiftn:
8439 VShiftOpc = ARMISD::VRSHRN; break;
8440 case Intrinsic::arm_neon_vqshifts:
8441 VShiftOpc = ARMISD::VQSHLs; break;
8442 case Intrinsic::arm_neon_vqshiftu:
8443 VShiftOpc = ARMISD::VQSHLu; break;
8444 case Intrinsic::arm_neon_vqshiftsu:
8445 VShiftOpc = ARMISD::VQSHLsu; break;
8446 case Intrinsic::arm_neon_vqshiftns:
8447 VShiftOpc = ARMISD::VQSHRNs; break;
8448 case Intrinsic::arm_neon_vqshiftnu:
8449 VShiftOpc = ARMISD::VQSHRNu; break;
8450 case Intrinsic::arm_neon_vqshiftnsu:
8451 VShiftOpc = ARMISD::VQSHRNsu; break;
8452 case Intrinsic::arm_neon_vqrshiftns:
8453 VShiftOpc = ARMISD::VQRSHRNs; break;
8454 case Intrinsic::arm_neon_vqrshiftnu:
8455 VShiftOpc = ARMISD::VQRSHRNu; break;
8456 case Intrinsic::arm_neon_vqrshiftnsu:
8457 VShiftOpc = ARMISD::VQRSHRNsu; break;
8460 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8461 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8464 case Intrinsic::arm_neon_vshiftins: {
8465 EVT VT = N->getOperand(1).getValueType();
8467 unsigned VShiftOpc = 0;
8469 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8470 VShiftOpc = ARMISD::VSLI;
8471 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8472 VShiftOpc = ARMISD::VSRI;
8474 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8477 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8478 N->getOperand(1), N->getOperand(2),
8479 DAG.getConstant(Cnt, MVT::i32));
8482 case Intrinsic::arm_neon_vqrshifts:
8483 case Intrinsic::arm_neon_vqrshiftu:
8484 // No immediate versions of these to check for.
8491 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8492 /// lowers them. As with the vector shift intrinsics, this is done during DAG
8493 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8494 /// vector element shift counts are generally not legal, and it is hard to see
8495 /// their values after they get legalized to loads from a constant pool.
8496 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8497 const ARMSubtarget *ST) {
8498 EVT VT = N->getValueType(0);
8499 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8500 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8501 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8502 SDValue N1 = N->getOperand(1);
8503 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8504 SDValue N0 = N->getOperand(0);
8505 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8506 DAG.MaskedValueIsZero(N0.getOperand(0),
8507 APInt::getHighBitsSet(32, 16)))
8508 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8512 // Nothing to be done for scalar shifts.
8513 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8514 if (!VT.isVector() || !TLI.isTypeLegal(VT))
8517 assert(ST->hasNEON() && "unexpected vector shift");
8520 switch (N->getOpcode()) {
8521 default: llvm_unreachable("unexpected shift opcode");
8524 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8525 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8526 DAG.getConstant(Cnt, MVT::i32));
8531 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8532 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8533 ARMISD::VSHRs : ARMISD::VSHRu);
8534 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8535 DAG.getConstant(Cnt, MVT::i32));
8541 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8542 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8543 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8544 const ARMSubtarget *ST) {
8545 SDValue N0 = N->getOperand(0);
8547 // Check for sign- and zero-extensions of vector extract operations of 8-
8548 // and 16-bit vector elements. NEON supports these directly. They are
8549 // handled during DAG combining because type legalization will promote them
8550 // to 32-bit types and it is messy to recognize the operations after that.
8551 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8552 SDValue Vec = N0.getOperand(0);
8553 SDValue Lane = N0.getOperand(1);
8554 EVT VT = N->getValueType(0);
8555 EVT EltVT = N0.getValueType();
8556 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8558 if (VT == MVT::i32 &&
8559 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8560 TLI.isTypeLegal(Vec.getValueType()) &&
8561 isa<ConstantSDNode>(Lane)) {
8564 switch (N->getOpcode()) {
8565 default: llvm_unreachable("unexpected opcode");
8566 case ISD::SIGN_EXTEND:
8567 Opc = ARMISD::VGETLANEs;
8569 case ISD::ZERO_EXTEND:
8570 case ISD::ANY_EXTEND:
8571 Opc = ARMISD::VGETLANEu;
8574 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8581 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8582 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8583 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8584 const ARMSubtarget *ST) {
8585 // If the target supports NEON, try to use vmax/vmin instructions for f32
8586 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
8587 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
8588 // a NaN; only do the transformation when it matches that behavior.
8590 // For now only do this when using NEON for FP operations; if using VFP, it
8591 // is not obvious that the benefit outweighs the cost of switching to the
8593 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8594 N->getValueType(0) != MVT::f32)
8597 SDValue CondLHS = N->getOperand(0);
8598 SDValue CondRHS = N->getOperand(1);
8599 SDValue LHS = N->getOperand(2);
8600 SDValue RHS = N->getOperand(3);
8601 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8603 unsigned Opcode = 0;
8605 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8606 IsReversed = false; // x CC y ? x : y
8607 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8608 IsReversed = true ; // x CC y ? y : x
8622 // If LHS is NaN, an ordered comparison will be false and the result will
8623 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
8624 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8625 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8626 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8628 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8629 // will return -0, so vmin can only be used for unsafe math or if one of
8630 // the operands is known to be nonzero.
8631 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8632 !DAG.getTarget().Options.UnsafeFPMath &&
8633 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8635 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8644 // If LHS is NaN, an ordered comparison will be false and the result will
8645 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
8646 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8647 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8648 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8650 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8651 // will return +0, so vmax can only be used for unsafe math or if one of
8652 // the operands is known to be nonzero.
8653 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8654 !DAG.getTarget().Options.UnsafeFPMath &&
8655 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8657 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8663 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8666 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8668 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8669 SDValue Cmp = N->getOperand(4);
8670 if (Cmp.getOpcode() != ARMISD::CMPZ)
8671 // Only looking at EQ and NE cases.
8674 EVT VT = N->getValueType(0);
8675 DebugLoc dl = N->getDebugLoc();
8676 SDValue LHS = Cmp.getOperand(0);
8677 SDValue RHS = Cmp.getOperand(1);
8678 SDValue FalseVal = N->getOperand(0);
8679 SDValue TrueVal = N->getOperand(1);
8680 SDValue ARMcc = N->getOperand(2);
8681 ARMCC::CondCodes CC =
8682 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8700 /// FIXME: Turn this into a target neutral optimization?
8702 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8703 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8704 N->getOperand(3), Cmp);
8705 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8707 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8708 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8709 N->getOperand(3), NewCmp);
8712 if (Res.getNode()) {
8713 APInt KnownZero, KnownOne;
8714 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8715 // Capture demanded bits information that would be otherwise lost.
8716 if (KnownZero == 0xfffffffe)
8717 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8718 DAG.getValueType(MVT::i1));
8719 else if (KnownZero == 0xffffff00)
8720 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8721 DAG.getValueType(MVT::i8));
8722 else if (KnownZero == 0xffff0000)
8723 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8724 DAG.getValueType(MVT::i16));
8730 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8731 DAGCombinerInfo &DCI) const {
8732 switch (N->getOpcode()) {
8734 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
8735 case ISD::SUB: return PerformSUBCombine(N, DCI);
8736 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
8737 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
8738 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
8739 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
8740 case ARMISD::BFI: return PerformBFICombine(N, DCI);
8741 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8742 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8743 case ISD::STORE: return PerformSTORECombine(N, DCI);
8744 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8745 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8746 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8747 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8748 case ISD::FP_TO_SINT:
8749 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8750 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
8751 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8754 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
8755 case ISD::SIGN_EXTEND:
8756 case ISD::ZERO_EXTEND:
8757 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8758 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8759 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8760 case ARMISD::VLD2DUP:
8761 case ARMISD::VLD3DUP:
8762 case ARMISD::VLD4DUP:
8763 return CombineBaseUpdate(N, DCI);
8764 case ISD::INTRINSIC_VOID:
8765 case ISD::INTRINSIC_W_CHAIN:
8766 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8767 case Intrinsic::arm_neon_vld1:
8768 case Intrinsic::arm_neon_vld2:
8769 case Intrinsic::arm_neon_vld3:
8770 case Intrinsic::arm_neon_vld4:
8771 case Intrinsic::arm_neon_vld2lane:
8772 case Intrinsic::arm_neon_vld3lane:
8773 case Intrinsic::arm_neon_vld4lane:
8774 case Intrinsic::arm_neon_vst1:
8775 case Intrinsic::arm_neon_vst2:
8776 case Intrinsic::arm_neon_vst3:
8777 case Intrinsic::arm_neon_vst4:
8778 case Intrinsic::arm_neon_vst2lane:
8779 case Intrinsic::arm_neon_vst3lane:
8780 case Intrinsic::arm_neon_vst4lane:
8781 return CombineBaseUpdate(N, DCI);
8789 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8791 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8794 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8795 if (!Subtarget->allowsUnalignedMem())
8798 switch (VT.getSimpleVT().SimpleTy) {
8805 // FIXME: VLD1 etc with standard alignment is legal.
8809 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8810 unsigned AlignCheck) {
8811 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8812 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8815 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8816 unsigned DstAlign, unsigned SrcAlign,
8819 MachineFunction &MF) const {
8820 const Function *F = MF.getFunction();
8822 // See if we can use NEON instructions for this...
8824 !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8825 Subtarget->hasNEON()) {
8826 if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8828 } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8833 // Lowering to i32/i16 if the size permits.
8836 } else if (Size >= 2) {
8840 // Let the target-independent logic figure it out.
8844 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8849 switch (VT.getSimpleVT().SimpleTy) {
8850 default: return false;
8865 if ((V & (Scale - 1)) != 0)
8868 return V == (V & ((1LL << 5) - 1));
8871 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8872 const ARMSubtarget *Subtarget) {
8879 switch (VT.getSimpleVT().SimpleTy) {
8880 default: return false;
8885 // + imm12 or - imm8
8887 return V == (V & ((1LL << 8) - 1));
8888 return V == (V & ((1LL << 12) - 1));
8891 // Same as ARM mode. FIXME: NEON?
8892 if (!Subtarget->hasVFP2())
8897 return V == (V & ((1LL << 8) - 1));
8901 /// isLegalAddressImmediate - Return true if the integer value can be used
8902 /// as the offset of the target addressing mode for load / store of the
8904 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8905 const ARMSubtarget *Subtarget) {
8912 if (Subtarget->isThumb1Only())
8913 return isLegalT1AddressImmediate(V, VT);
8914 else if (Subtarget->isThumb2())
8915 return isLegalT2AddressImmediate(V, VT, Subtarget);
8920 switch (VT.getSimpleVT().SimpleTy) {
8921 default: return false;
8926 return V == (V & ((1LL << 12) - 1));
8929 return V == (V & ((1LL << 8) - 1));
8932 if (!Subtarget->hasVFP2()) // FIXME: NEON?
8937 return V == (V & ((1LL << 8) - 1));
8941 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8943 int Scale = AM.Scale;
8947 switch (VT.getSimpleVT().SimpleTy) {
8948 default: return false;
8957 return Scale == 2 || Scale == 4 || Scale == 8;
8960 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8964 // Note, we allow "void" uses (basically, uses that aren't loads or
8965 // stores), because arm allows folding a scale into many arithmetic
8966 // operations. This should be made more precise and revisited later.
8968 // Allow r << imm, but the imm has to be a multiple of two.
8969 if (Scale & 1) return false;
8970 return isPowerOf2_32(Scale);
8974 /// isLegalAddressingMode - Return true if the addressing mode represented
8975 /// by AM is legal for this target, for a load/store of the specified type.
8976 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8978 EVT VT = getValueType(Ty, true);
8979 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8982 // Can never fold addr of global into load/store.
8987 case 0: // no scale reg, must be "r+i" or "r", or "i".
8990 if (Subtarget->isThumb1Only())
8994 // ARM doesn't support any R+R*scale+imm addr modes.
9001 if (Subtarget->isThumb2())
9002 return isLegalT2ScaledAddressingMode(AM, VT);
9004 int Scale = AM.Scale;
9005 switch (VT.getSimpleVT().SimpleTy) {
9006 default: return false;
9010 if (Scale < 0) Scale = -Scale;
9014 return isPowerOf2_32(Scale & ~1);
9018 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9023 // Note, we allow "void" uses (basically, uses that aren't loads or
9024 // stores), because arm allows folding a scale into many arithmetic
9025 // operations. This should be made more precise and revisited later.
9027 // Allow r << imm, but the imm has to be a multiple of two.
9028 if (Scale & 1) return false;
9029 return isPowerOf2_32(Scale);
9035 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9036 /// icmp immediate, that is the target has icmp instructions which can compare
9037 /// a register against the immediate without having to materialize the
9038 /// immediate into a register.
9039 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9040 // Thumb2 and ARM modes can use cmn for negative immediates.
9041 if (!Subtarget->isThumb())
9042 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9043 if (Subtarget->isThumb2())
9044 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9045 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9046 return Imm >= 0 && Imm <= 255;
9049 /// isLegalAddImmediate - Return true if the specified immediate is legal
9050 /// add immediate, that is the target has add instructions which can add
9051 /// a register with the immediate without having to materialize the
9052 /// immediate into a register.
9053 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9054 return ARM_AM::getSOImmVal(Imm) != -1;
9057 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9058 bool isSEXTLoad, SDValue &Base,
9059 SDValue &Offset, bool &isInc,
9060 SelectionDAG &DAG) {
9061 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9064 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9066 Base = Ptr->getOperand(0);
9067 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9068 int RHSC = (int)RHS->getZExtValue();
9069 if (RHSC < 0 && RHSC > -256) {
9070 assert(Ptr->getOpcode() == ISD::ADD);
9072 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9076 isInc = (Ptr->getOpcode() == ISD::ADD);
9077 Offset = Ptr->getOperand(1);
9079 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9081 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9082 int RHSC = (int)RHS->getZExtValue();
9083 if (RHSC < 0 && RHSC > -0x1000) {
9084 assert(Ptr->getOpcode() == ISD::ADD);
9086 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9087 Base = Ptr->getOperand(0);
9092 if (Ptr->getOpcode() == ISD::ADD) {
9094 ARM_AM::ShiftOpc ShOpcVal=
9095 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9096 if (ShOpcVal != ARM_AM::no_shift) {
9097 Base = Ptr->getOperand(1);
9098 Offset = Ptr->getOperand(0);
9100 Base = Ptr->getOperand(0);
9101 Offset = Ptr->getOperand(1);
9106 isInc = (Ptr->getOpcode() == ISD::ADD);
9107 Base = Ptr->getOperand(0);
9108 Offset = Ptr->getOperand(1);
9112 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9116 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9117 bool isSEXTLoad, SDValue &Base,
9118 SDValue &Offset, bool &isInc,
9119 SelectionDAG &DAG) {
9120 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9123 Base = Ptr->getOperand(0);
9124 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9125 int RHSC = (int)RHS->getZExtValue();
9126 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9127 assert(Ptr->getOpcode() == ISD::ADD);
9129 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9131 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9132 isInc = Ptr->getOpcode() == ISD::ADD;
9133 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9141 /// getPreIndexedAddressParts - returns true by value, base pointer and
9142 /// offset pointer and addressing mode by reference if the node's address
9143 /// can be legally represented as pre-indexed load / store address.
9145 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9147 ISD::MemIndexedMode &AM,
9148 SelectionDAG &DAG) const {
9149 if (Subtarget->isThumb1Only())
9154 bool isSEXTLoad = false;
9155 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9156 Ptr = LD->getBasePtr();
9157 VT = LD->getMemoryVT();
9158 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9159 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9160 Ptr = ST->getBasePtr();
9161 VT = ST->getMemoryVT();
9166 bool isLegal = false;
9167 if (Subtarget->isThumb2())
9168 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9169 Offset, isInc, DAG);
9171 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9172 Offset, isInc, DAG);
9176 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9180 /// getPostIndexedAddressParts - returns true by value, base pointer and
9181 /// offset pointer and addressing mode by reference if this node can be
9182 /// combined with a load / store to form a post-indexed load / store.
9183 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9186 ISD::MemIndexedMode &AM,
9187 SelectionDAG &DAG) const {
9188 if (Subtarget->isThumb1Only())
9193 bool isSEXTLoad = false;
9194 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9195 VT = LD->getMemoryVT();
9196 Ptr = LD->getBasePtr();
9197 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9198 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9199 VT = ST->getMemoryVT();
9200 Ptr = ST->getBasePtr();
9205 bool isLegal = false;
9206 if (Subtarget->isThumb2())
9207 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9210 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9216 // Swap base ptr and offset to catch more post-index load / store when
9217 // it's legal. In Thumb2 mode, offset must be an immediate.
9218 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9219 !Subtarget->isThumb2())
9220 std::swap(Base, Offset);
9222 // Post-indexed load / store update the base pointer.
9227 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9231 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9234 const SelectionDAG &DAG,
9235 unsigned Depth) const {
9236 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9237 switch (Op.getOpcode()) {
9239 case ARMISD::CMOV: {
9240 // Bits are known zero/one if known on the LHS and RHS.
9241 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9242 if (KnownZero == 0 && KnownOne == 0) return;
9244 APInt KnownZeroRHS, KnownOneRHS;
9245 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9246 KnownZero &= KnownZeroRHS;
9247 KnownOne &= KnownOneRHS;
9253 //===----------------------------------------------------------------------===//
9254 // ARM Inline Assembly Support
9255 //===----------------------------------------------------------------------===//
9257 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9258 // Looking for "rev" which is V6+.
9259 if (!Subtarget->hasV6Ops())
9262 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9263 std::string AsmStr = IA->getAsmString();
9264 SmallVector<StringRef, 4> AsmPieces;
9265 SplitString(AsmStr, AsmPieces, ";\n");
9267 switch (AsmPieces.size()) {
9268 default: return false;
9270 AsmStr = AsmPieces[0];
9272 SplitString(AsmStr, AsmPieces, " \t,");
9275 if (AsmPieces.size() == 3 &&
9276 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9277 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9278 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9279 if (Ty && Ty->getBitWidth() == 32)
9280 return IntrinsicLowering::LowerToByteSwap(CI);
9288 /// getConstraintType - Given a constraint letter, return the type of
9289 /// constraint it is for this target.
9290 ARMTargetLowering::ConstraintType
9291 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9292 if (Constraint.size() == 1) {
9293 switch (Constraint[0]) {
9295 case 'l': return C_RegisterClass;
9296 case 'w': return C_RegisterClass;
9297 case 'h': return C_RegisterClass;
9298 case 'x': return C_RegisterClass;
9299 case 't': return C_RegisterClass;
9300 case 'j': return C_Other; // Constant for movw.
9301 // An address with a single base register. Due to the way we
9302 // currently handle addresses it is the same as an 'r' memory constraint.
9303 case 'Q': return C_Memory;
9305 } else if (Constraint.size() == 2) {
9306 switch (Constraint[0]) {
9308 // All 'U+' constraints are addresses.
9309 case 'U': return C_Memory;
9312 return TargetLowering::getConstraintType(Constraint);
9315 /// Examine constraint type and operand type and determine a weight value.
9316 /// This object must already have been set up with the operand type
9317 /// and the current alternative constraint selected.
9318 TargetLowering::ConstraintWeight
9319 ARMTargetLowering::getSingleConstraintMatchWeight(
9320 AsmOperandInfo &info, const char *constraint) const {
9321 ConstraintWeight weight = CW_Invalid;
9322 Value *CallOperandVal = info.CallOperandVal;
9323 // If we don't have a value, we can't do a match,
9324 // but allow it at the lowest weight.
9325 if (CallOperandVal == NULL)
9327 Type *type = CallOperandVal->getType();
9328 // Look at the constraint type.
9329 switch (*constraint) {
9331 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9334 if (type->isIntegerTy()) {
9335 if (Subtarget->isThumb())
9336 weight = CW_SpecificReg;
9338 weight = CW_Register;
9342 if (type->isFloatingPointTy())
9343 weight = CW_Register;
9349 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9351 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9353 if (Constraint.size() == 1) {
9354 // GCC ARM Constraint Letters
9355 switch (Constraint[0]) {
9356 case 'l': // Low regs or general regs.
9357 if (Subtarget->isThumb())
9358 return RCPair(0U, &ARM::tGPRRegClass);
9359 return RCPair(0U, &ARM::GPRRegClass);
9360 case 'h': // High regs or no regs.
9361 if (Subtarget->isThumb())
9362 return RCPair(0U, &ARM::hGPRRegClass);
9365 return RCPair(0U, &ARM::GPRRegClass);
9368 return RCPair(0U, &ARM::SPRRegClass);
9369 if (VT.getSizeInBits() == 64)
9370 return RCPair(0U, &ARM::DPRRegClass);
9371 if (VT.getSizeInBits() == 128)
9372 return RCPair(0U, &ARM::QPRRegClass);
9376 return RCPair(0U, &ARM::SPR_8RegClass);
9377 if (VT.getSizeInBits() == 64)
9378 return RCPair(0U, &ARM::DPR_8RegClass);
9379 if (VT.getSizeInBits() == 128)
9380 return RCPair(0U, &ARM::QPR_8RegClass);
9384 return RCPair(0U, &ARM::SPRRegClass);
9388 if (StringRef("{cc}").equals_lower(Constraint))
9389 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9391 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9394 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9395 /// vector. If it is invalid, don't add anything to Ops.
9396 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9397 std::string &Constraint,
9398 std::vector<SDValue>&Ops,
9399 SelectionDAG &DAG) const {
9400 SDValue Result(0, 0);
9402 // Currently only support length 1 constraints.
9403 if (Constraint.length() != 1) return;
9405 char ConstraintLetter = Constraint[0];
9406 switch (ConstraintLetter) {
9409 case 'I': case 'J': case 'K': case 'L':
9410 case 'M': case 'N': case 'O':
9411 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9415 int64_t CVal64 = C->getSExtValue();
9416 int CVal = (int) CVal64;
9417 // None of these constraints allow values larger than 32 bits. Check
9418 // that the value fits in an int.
9422 switch (ConstraintLetter) {
9424 // Constant suitable for movw, must be between 0 and
9426 if (Subtarget->hasV6T2Ops())
9427 if (CVal >= 0 && CVal <= 65535)
9431 if (Subtarget->isThumb1Only()) {
9432 // This must be a constant between 0 and 255, for ADD
9434 if (CVal >= 0 && CVal <= 255)
9436 } else if (Subtarget->isThumb2()) {
9437 // A constant that can be used as an immediate value in a
9438 // data-processing instruction.
9439 if (ARM_AM::getT2SOImmVal(CVal) != -1)
9442 // A constant that can be used as an immediate value in a
9443 // data-processing instruction.
9444 if (ARM_AM::getSOImmVal(CVal) != -1)
9450 if (Subtarget->isThumb()) { // FIXME thumb2
9451 // This must be a constant between -255 and -1, for negated ADD
9452 // immediates. This can be used in GCC with an "n" modifier that
9453 // prints the negated value, for use with SUB instructions. It is
9454 // not useful otherwise but is implemented for compatibility.
9455 if (CVal >= -255 && CVal <= -1)
9458 // This must be a constant between -4095 and 4095. It is not clear
9459 // what this constraint is intended for. Implemented for
9460 // compatibility with GCC.
9461 if (CVal >= -4095 && CVal <= 4095)
9467 if (Subtarget->isThumb1Only()) {
9468 // A 32-bit value where only one byte has a nonzero value. Exclude
9469 // zero to match GCC. This constraint is used by GCC internally for
9470 // constants that can be loaded with a move/shift combination.
9471 // It is not useful otherwise but is implemented for compatibility.
9472 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9474 } else if (Subtarget->isThumb2()) {
9475 // A constant whose bitwise inverse can be used as an immediate
9476 // value in a data-processing instruction. This can be used in GCC
9477 // with a "B" modifier that prints the inverted value, for use with
9478 // BIC and MVN instructions. It is not useful otherwise but is
9479 // implemented for compatibility.
9480 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9483 // A constant whose bitwise inverse can be used as an immediate
9484 // value in a data-processing instruction. This can be used in GCC
9485 // with a "B" modifier that prints the inverted value, for use with
9486 // BIC and MVN instructions. It is not useful otherwise but is
9487 // implemented for compatibility.
9488 if (ARM_AM::getSOImmVal(~CVal) != -1)
9494 if (Subtarget->isThumb1Only()) {
9495 // This must be a constant between -7 and 7,
9496 // for 3-operand ADD/SUB immediate instructions.
9497 if (CVal >= -7 && CVal < 7)
9499 } else if (Subtarget->isThumb2()) {
9500 // A constant whose negation can be used as an immediate value in a
9501 // data-processing instruction. This can be used in GCC with an "n"
9502 // modifier that prints the negated value, for use with SUB
9503 // instructions. It is not useful otherwise but is implemented for
9505 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9508 // A constant whose negation can be used as an immediate value in a
9509 // data-processing instruction. This can be used in GCC with an "n"
9510 // modifier that prints the negated value, for use with SUB
9511 // instructions. It is not useful otherwise but is implemented for
9513 if (ARM_AM::getSOImmVal(-CVal) != -1)
9519 if (Subtarget->isThumb()) { // FIXME thumb2
9520 // This must be a multiple of 4 between 0 and 1020, for
9521 // ADD sp + immediate.
9522 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9525 // A power of two or a constant between 0 and 32. This is used in
9526 // GCC for the shift amount on shifted register operands, but it is
9527 // useful in general for any shift amounts.
9528 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9534 if (Subtarget->isThumb()) { // FIXME thumb2
9535 // This must be a constant between 0 and 31, for shift amounts.
9536 if (CVal >= 0 && CVal <= 31)
9542 if (Subtarget->isThumb()) { // FIXME thumb2
9543 // This must be a multiple of 4 between -508 and 508, for
9544 // ADD/SUB sp = sp + immediate.
9545 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9550 Result = DAG.getTargetConstant(CVal, Op.getValueType());
9554 if (Result.getNode()) {
9555 Ops.push_back(Result);
9558 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9562 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9563 // The ARM target isn't yet aware of offsets.
9567 bool ARM::isBitFieldInvertedMask(unsigned v) {
9568 if (v == 0xffffffff)
9570 // there can be 1's on either or both "outsides", all the "inside"
9572 unsigned int lsb = 0, msb = 31;
9573 while (v & (1 << msb)) --msb;
9574 while (v & (1 << lsb)) ++lsb;
9575 for (unsigned int i = lsb; i <= msb; ++i) {
9582 /// isFPImmLegal - Returns true if the target can instruction select the
9583 /// specified FP immediate natively. If false, the legalizer will
9584 /// materialize the FP immediate as a load from a constant pool.
9585 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9586 if (!Subtarget->hasVFP3())
9589 return ARM_AM::getFP32Imm(Imm) != -1;
9591 return ARM_AM::getFP64Imm(Imm) != -1;
9595 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9596 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9597 /// specified in the intrinsic calls.
9598 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9600 unsigned Intrinsic) const {
9601 switch (Intrinsic) {
9602 case Intrinsic::arm_neon_vld1:
9603 case Intrinsic::arm_neon_vld2:
9604 case Intrinsic::arm_neon_vld3:
9605 case Intrinsic::arm_neon_vld4:
9606 case Intrinsic::arm_neon_vld2lane:
9607 case Intrinsic::arm_neon_vld3lane:
9608 case Intrinsic::arm_neon_vld4lane: {
9609 Info.opc = ISD::INTRINSIC_W_CHAIN;
9610 // Conservatively set memVT to the entire set of vectors loaded.
9611 uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9612 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9613 Info.ptrVal = I.getArgOperand(0);
9615 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9616 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9617 Info.vol = false; // volatile loads with NEON intrinsics not supported
9618 Info.readMem = true;
9619 Info.writeMem = false;
9622 case Intrinsic::arm_neon_vst1:
9623 case Intrinsic::arm_neon_vst2:
9624 case Intrinsic::arm_neon_vst3:
9625 case Intrinsic::arm_neon_vst4:
9626 case Intrinsic::arm_neon_vst2lane:
9627 case Intrinsic::arm_neon_vst3lane:
9628 case Intrinsic::arm_neon_vst4lane: {
9629 Info.opc = ISD::INTRINSIC_VOID;
9630 // Conservatively set memVT to the entire set of vectors stored.
9631 unsigned NumElts = 0;
9632 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9633 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9634 if (!ArgTy->isVectorTy())
9636 NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9638 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9639 Info.ptrVal = I.getArgOperand(0);
9641 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9642 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9643 Info.vol = false; // volatile stores with NEON intrinsics not supported
9644 Info.readMem = false;
9645 Info.writeMem = true;
9648 case Intrinsic::arm_strexd: {
9649 Info.opc = ISD::INTRINSIC_W_CHAIN;
9650 Info.memVT = MVT::i64;
9651 Info.ptrVal = I.getArgOperand(2);
9655 Info.readMem = false;
9656 Info.writeMem = true;
9659 case Intrinsic::arm_ldrexd: {
9660 Info.opc = ISD::INTRINSIC_W_CHAIN;
9661 Info.memVT = MVT::i64;
9662 Info.ptrVal = I.getArgOperand(0);
9666 Info.readMem = true;
9667 Info.writeMem = false;