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,
1045 const TargetLibraryInfo *libInfo) const {
1046 return ARM::createFastISel(funcInfo, libInfo);
1049 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1050 /// be used for loads / stores from the global.
1051 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1052 return (Subtarget->isThumb1Only() ? 127 : 4095);
1055 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1056 unsigned NumVals = N->getNumValues();
1058 return Sched::RegPressure;
1060 for (unsigned i = 0; i != NumVals; ++i) {
1061 EVT VT = N->getValueType(i);
1062 if (VT == MVT::Glue || VT == MVT::Other)
1064 if (VT.isFloatingPoint() || VT.isVector())
1068 if (!N->isMachineOpcode())
1069 return Sched::RegPressure;
1071 // Load are scheduled for latency even if there instruction itinerary
1072 // is not available.
1073 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1074 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1076 if (MCID.getNumDefs() == 0)
1077 return Sched::RegPressure;
1078 if (!Itins->isEmpty() &&
1079 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1082 return Sched::RegPressure;
1085 //===----------------------------------------------------------------------===//
1087 //===----------------------------------------------------------------------===//
1089 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1090 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1092 default: llvm_unreachable("Unknown condition code!");
1093 case ISD::SETNE: return ARMCC::NE;
1094 case ISD::SETEQ: return ARMCC::EQ;
1095 case ISD::SETGT: return ARMCC::GT;
1096 case ISD::SETGE: return ARMCC::GE;
1097 case ISD::SETLT: return ARMCC::LT;
1098 case ISD::SETLE: return ARMCC::LE;
1099 case ISD::SETUGT: return ARMCC::HI;
1100 case ISD::SETUGE: return ARMCC::HS;
1101 case ISD::SETULT: return ARMCC::LO;
1102 case ISD::SETULE: return ARMCC::LS;
1106 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1107 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1108 ARMCC::CondCodes &CondCode2) {
1109 CondCode2 = ARMCC::AL;
1111 default: llvm_unreachable("Unknown FP condition!");
1113 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1115 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1117 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1118 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1119 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1120 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1121 case ISD::SETO: CondCode = ARMCC::VC; break;
1122 case ISD::SETUO: CondCode = ARMCC::VS; break;
1123 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1124 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1125 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1127 case ISD::SETULT: CondCode = ARMCC::LT; break;
1129 case ISD::SETULE: CondCode = ARMCC::LE; break;
1131 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1135 //===----------------------------------------------------------------------===//
1136 // Calling Convention Implementation
1137 //===----------------------------------------------------------------------===//
1139 #include "ARMGenCallingConv.inc"
1141 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1142 /// given CallingConvention value.
1143 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1145 bool isVarArg) const {
1148 llvm_unreachable("Unsupported calling convention");
1149 case CallingConv::Fast:
1150 if (Subtarget->hasVFP2() && !isVarArg) {
1151 if (!Subtarget->isAAPCS_ABI())
1152 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1153 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1154 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1157 case CallingConv::C: {
1158 // Use target triple & subtarget features to do actual dispatch.
1159 if (!Subtarget->isAAPCS_ABI())
1160 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1161 else if (Subtarget->hasVFP2() &&
1162 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1164 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1165 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1167 case CallingConv::ARM_AAPCS_VFP:
1169 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1171 case CallingConv::ARM_AAPCS:
1172 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1173 case CallingConv::ARM_APCS:
1174 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1175 case CallingConv::GHC:
1176 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1180 /// LowerCallResult - Lower the result values of a call into the
1181 /// appropriate copies out of appropriate physical registers.
1183 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1184 CallingConv::ID CallConv, bool isVarArg,
1185 const SmallVectorImpl<ISD::InputArg> &Ins,
1186 DebugLoc dl, SelectionDAG &DAG,
1187 SmallVectorImpl<SDValue> &InVals) const {
1189 // Assign locations to each value returned by this call.
1190 SmallVector<CCValAssign, 16> RVLocs;
1191 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1192 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1193 CCInfo.AnalyzeCallResult(Ins,
1194 CCAssignFnForNode(CallConv, /* Return*/ true,
1197 // Copy all of the result registers out of their specified physreg.
1198 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1199 CCValAssign VA = RVLocs[i];
1202 if (VA.needsCustom()) {
1203 // Handle f64 or half of a v2f64.
1204 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1206 Chain = Lo.getValue(1);
1207 InFlag = Lo.getValue(2);
1208 VA = RVLocs[++i]; // skip ahead to next loc
1209 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1211 Chain = Hi.getValue(1);
1212 InFlag = Hi.getValue(2);
1213 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1215 if (VA.getLocVT() == MVT::v2f64) {
1216 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1217 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1218 DAG.getConstant(0, MVT::i32));
1220 VA = RVLocs[++i]; // skip ahead to next loc
1221 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1222 Chain = Lo.getValue(1);
1223 InFlag = Lo.getValue(2);
1224 VA = RVLocs[++i]; // skip ahead to next loc
1225 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1226 Chain = Hi.getValue(1);
1227 InFlag = Hi.getValue(2);
1228 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1229 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1230 DAG.getConstant(1, MVT::i32));
1233 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1235 Chain = Val.getValue(1);
1236 InFlag = Val.getValue(2);
1239 switch (VA.getLocInfo()) {
1240 default: llvm_unreachable("Unknown loc info!");
1241 case CCValAssign::Full: break;
1242 case CCValAssign::BCvt:
1243 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1247 InVals.push_back(Val);
1253 /// LowerMemOpCallTo - Store the argument to the stack.
1255 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1256 SDValue StackPtr, SDValue Arg,
1257 DebugLoc dl, SelectionDAG &DAG,
1258 const CCValAssign &VA,
1259 ISD::ArgFlagsTy Flags) const {
1260 unsigned LocMemOffset = VA.getLocMemOffset();
1261 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1262 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1263 return DAG.getStore(Chain, dl, Arg, PtrOff,
1264 MachinePointerInfo::getStack(LocMemOffset),
1268 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1269 SDValue Chain, SDValue &Arg,
1270 RegsToPassVector &RegsToPass,
1271 CCValAssign &VA, CCValAssign &NextVA,
1273 SmallVector<SDValue, 8> &MemOpChains,
1274 ISD::ArgFlagsTy Flags) const {
1276 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1277 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1278 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1280 if (NextVA.isRegLoc())
1281 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1283 assert(NextVA.isMemLoc());
1284 if (StackPtr.getNode() == 0)
1285 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1287 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1293 /// LowerCall - Lowering a call into a callseq_start <-
1294 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1297 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1298 SmallVectorImpl<SDValue> &InVals) const {
1299 SelectionDAG &DAG = CLI.DAG;
1300 DebugLoc &dl = CLI.DL;
1301 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1302 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1303 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1304 SDValue Chain = CLI.Chain;
1305 SDValue Callee = CLI.Callee;
1306 bool &isTailCall = CLI.IsTailCall;
1307 CallingConv::ID CallConv = CLI.CallConv;
1308 bool doesNotRet = CLI.DoesNotReturn;
1309 bool isVarArg = CLI.IsVarArg;
1311 MachineFunction &MF = DAG.getMachineFunction();
1312 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1313 bool IsSibCall = false;
1314 // Disable tail calls if they're not supported.
1315 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1318 // Check if it's really possible to do a tail call.
1319 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1320 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1321 Outs, OutVals, Ins, DAG);
1322 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1323 // detected sibcalls.
1330 // Analyze operands of the call, assigning locations to each operand.
1331 SmallVector<CCValAssign, 16> ArgLocs;
1332 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1333 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1334 CCInfo.AnalyzeCallOperands(Outs,
1335 CCAssignFnForNode(CallConv, /* Return*/ false,
1338 // Get a count of how many bytes are to be pushed on the stack.
1339 unsigned NumBytes = CCInfo.getNextStackOffset();
1341 // For tail calls, memory operands are available in our caller's stack.
1345 // Adjust the stack pointer for the new arguments...
1346 // These operations are automatically eliminated by the prolog/epilog pass
1348 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1350 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1352 RegsToPassVector RegsToPass;
1353 SmallVector<SDValue, 8> MemOpChains;
1355 // Walk the register/memloc assignments, inserting copies/loads. In the case
1356 // of tail call optimization, arguments are handled later.
1357 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1359 ++i, ++realArgIdx) {
1360 CCValAssign &VA = ArgLocs[i];
1361 SDValue Arg = OutVals[realArgIdx];
1362 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1363 bool isByVal = Flags.isByVal();
1365 // Promote the value if needed.
1366 switch (VA.getLocInfo()) {
1367 default: llvm_unreachable("Unknown loc info!");
1368 case CCValAssign::Full: break;
1369 case CCValAssign::SExt:
1370 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1372 case CCValAssign::ZExt:
1373 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1375 case CCValAssign::AExt:
1376 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1378 case CCValAssign::BCvt:
1379 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1383 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1384 if (VA.needsCustom()) {
1385 if (VA.getLocVT() == MVT::v2f64) {
1386 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1387 DAG.getConstant(0, MVT::i32));
1388 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1389 DAG.getConstant(1, MVT::i32));
1391 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1392 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1394 VA = ArgLocs[++i]; // skip ahead to next loc
1395 if (VA.isRegLoc()) {
1396 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1397 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1399 assert(VA.isMemLoc());
1401 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1402 dl, DAG, VA, Flags));
1405 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1406 StackPtr, MemOpChains, Flags);
1408 } else if (VA.isRegLoc()) {
1409 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1410 } else if (isByVal) {
1411 assert(VA.isMemLoc());
1412 unsigned offset = 0;
1414 // True if this byval aggregate will be split between registers
1416 if (CCInfo.isFirstByValRegValid()) {
1417 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1419 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1420 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1421 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1422 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1423 MachinePointerInfo(),
1424 false, false, false, 0);
1425 MemOpChains.push_back(Load.getValue(1));
1426 RegsToPass.push_back(std::make_pair(j, Load));
1428 offset = ARM::R4 - CCInfo.getFirstByValReg();
1429 CCInfo.clearFirstByValReg();
1432 if (Flags.getByValSize() - 4*offset > 0) {
1433 unsigned LocMemOffset = VA.getLocMemOffset();
1434 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1435 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1437 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1438 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1439 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1441 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1443 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1444 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1445 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1446 Ops, array_lengthof(Ops)));
1448 } else if (!IsSibCall) {
1449 assert(VA.isMemLoc());
1451 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1452 dl, DAG, VA, Flags));
1456 if (!MemOpChains.empty())
1457 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1458 &MemOpChains[0], MemOpChains.size());
1460 // Build a sequence of copy-to-reg nodes chained together with token chain
1461 // and flag operands which copy the outgoing args into the appropriate regs.
1463 // Tail call byval lowering might overwrite argument registers so in case of
1464 // tail call optimization the copies to registers are lowered later.
1466 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1467 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1468 RegsToPass[i].second, InFlag);
1469 InFlag = Chain.getValue(1);
1472 // For tail calls lower the arguments to the 'real' stack slot.
1474 // Force all the incoming stack arguments to be loaded from the stack
1475 // before any new outgoing arguments are stored to the stack, because the
1476 // outgoing stack slots may alias the incoming argument stack slots, and
1477 // the alias isn't otherwise explicit. This is slightly more conservative
1478 // than necessary, because it means that each store effectively depends
1479 // on every argument instead of just those arguments it would clobber.
1481 // Do not flag preceding copytoreg stuff together with the following stuff.
1483 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1484 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1485 RegsToPass[i].second, InFlag);
1486 InFlag = Chain.getValue(1);
1491 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1492 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1493 // node so that legalize doesn't hack it.
1494 bool isDirect = false;
1495 bool isARMFunc = false;
1496 bool isLocalARMFunc = false;
1497 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1499 if (EnableARMLongCalls) {
1500 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1501 && "long-calls with non-static relocation model!");
1502 // Handle a global address or an external symbol. If it's not one of
1503 // those, the target's already in a register, so we don't need to do
1505 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1506 const GlobalValue *GV = G->getGlobal();
1507 // Create a constant pool entry for the callee address
1508 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1509 ARMConstantPoolValue *CPV =
1510 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1512 // Get the address of the callee into a register
1513 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1514 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1515 Callee = DAG.getLoad(getPointerTy(), dl,
1516 DAG.getEntryNode(), CPAddr,
1517 MachinePointerInfo::getConstantPool(),
1518 false, false, false, 0);
1519 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1520 const char *Sym = S->getSymbol();
1522 // Create a constant pool entry for the callee address
1523 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1524 ARMConstantPoolValue *CPV =
1525 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1526 ARMPCLabelIndex, 0);
1527 // Get the address of the callee into a register
1528 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1529 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1530 Callee = DAG.getLoad(getPointerTy(), dl,
1531 DAG.getEntryNode(), CPAddr,
1532 MachinePointerInfo::getConstantPool(),
1533 false, false, false, 0);
1535 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1536 const GlobalValue *GV = G->getGlobal();
1538 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1539 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1540 getTargetMachine().getRelocationModel() != Reloc::Static;
1541 isARMFunc = !Subtarget->isThumb() || isStub;
1542 // ARM call to a local ARM function is predicable.
1543 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1544 // tBX takes a register source operand.
1545 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1546 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1547 ARMConstantPoolValue *CPV =
1548 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1549 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1550 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1551 Callee = DAG.getLoad(getPointerTy(), dl,
1552 DAG.getEntryNode(), CPAddr,
1553 MachinePointerInfo::getConstantPool(),
1554 false, false, false, 0);
1555 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1556 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1557 getPointerTy(), Callee, PICLabel);
1559 // On ELF targets for PIC code, direct calls should go through the PLT
1560 unsigned OpFlags = 0;
1561 if (Subtarget->isTargetELF() &&
1562 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1563 OpFlags = ARMII::MO_PLT;
1564 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1566 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1568 bool isStub = Subtarget->isTargetDarwin() &&
1569 getTargetMachine().getRelocationModel() != Reloc::Static;
1570 isARMFunc = !Subtarget->isThumb() || isStub;
1571 // tBX takes a register source operand.
1572 const char *Sym = S->getSymbol();
1573 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1574 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1575 ARMConstantPoolValue *CPV =
1576 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1577 ARMPCLabelIndex, 4);
1578 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1579 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1580 Callee = DAG.getLoad(getPointerTy(), dl,
1581 DAG.getEntryNode(), CPAddr,
1582 MachinePointerInfo::getConstantPool(),
1583 false, false, false, 0);
1584 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1585 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1586 getPointerTy(), Callee, PICLabel);
1588 unsigned OpFlags = 0;
1589 // On ELF targets for PIC code, direct calls should go through the PLT
1590 if (Subtarget->isTargetELF() &&
1591 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1592 OpFlags = ARMII::MO_PLT;
1593 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1597 // FIXME: handle tail calls differently.
1599 if (Subtarget->isThumb()) {
1600 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1601 CallOpc = ARMISD::CALL_NOLINK;
1602 else if (doesNotRet && isDirect && !isARMFunc &&
1603 Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1604 // "mov lr, pc; b _foo" to avoid confusing the RSP
1605 CallOpc = ARMISD::CALL_NOLINK;
1607 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1609 if (!isDirect && !Subtarget->hasV5TOps()) {
1610 CallOpc = ARMISD::CALL_NOLINK;
1611 } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1612 // "mov lr, pc; b _foo" to avoid confusing the RSP
1613 CallOpc = ARMISD::CALL_NOLINK;
1615 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1618 std::vector<SDValue> Ops;
1619 Ops.push_back(Chain);
1620 Ops.push_back(Callee);
1622 // Add argument registers to the end of the list so that they are known live
1624 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1625 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1626 RegsToPass[i].second.getValueType()));
1628 // Add a register mask operand representing the call-preserved registers.
1629 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1630 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1631 assert(Mask && "Missing call preserved mask for calling convention");
1632 Ops.push_back(DAG.getRegisterMask(Mask));
1634 if (InFlag.getNode())
1635 Ops.push_back(InFlag);
1637 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1639 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1641 // Returns a chain and a flag for retval copy to use.
1642 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1643 InFlag = Chain.getValue(1);
1645 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1646 DAG.getIntPtrConstant(0, true), InFlag);
1648 InFlag = Chain.getValue(1);
1650 // Handle result values, copying them out of physregs into vregs that we
1652 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1656 /// HandleByVal - Every parameter *after* a byval parameter is passed
1657 /// on the stack. Remember the next parameter register to allocate,
1658 /// and then confiscate the rest of the parameter registers to insure
1661 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1662 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1663 assert((State->getCallOrPrologue() == Prologue ||
1664 State->getCallOrPrologue() == Call) &&
1665 "unhandled ParmContext");
1666 if ((!State->isFirstByValRegValid()) &&
1667 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1668 State->setFirstByValReg(reg);
1669 // At a call site, a byval parameter that is split between
1670 // registers and memory needs its size truncated here. In a
1671 // function prologue, such byval parameters are reassembled in
1672 // memory, and are not truncated.
1673 if (State->getCallOrPrologue() == Call) {
1674 unsigned excess = 4 * (ARM::R4 - reg);
1675 assert(size >= excess && "expected larger existing stack allocation");
1679 // Confiscate any remaining parameter registers to preclude their
1680 // assignment to subsequent parameters.
1681 while (State->AllocateReg(GPRArgRegs, 4))
1685 /// MatchingStackOffset - Return true if the given stack call argument is
1686 /// already available in the same position (relatively) of the caller's
1687 /// incoming argument stack.
1689 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1690 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1691 const TargetInstrInfo *TII) {
1692 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1694 if (Arg.getOpcode() == ISD::CopyFromReg) {
1695 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1696 if (!TargetRegisterInfo::isVirtualRegister(VR))
1698 MachineInstr *Def = MRI->getVRegDef(VR);
1701 if (!Flags.isByVal()) {
1702 if (!TII->isLoadFromStackSlot(Def, FI))
1707 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1708 if (Flags.isByVal())
1709 // ByVal argument is passed in as a pointer but it's now being
1710 // dereferenced. e.g.
1711 // define @foo(%struct.X* %A) {
1712 // tail call @bar(%struct.X* byval %A)
1715 SDValue Ptr = Ld->getBasePtr();
1716 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1719 FI = FINode->getIndex();
1723 assert(FI != INT_MAX);
1724 if (!MFI->isFixedObjectIndex(FI))
1726 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1729 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1730 /// for tail call optimization. Targets which want to do tail call
1731 /// optimization should implement this function.
1733 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1734 CallingConv::ID CalleeCC,
1736 bool isCalleeStructRet,
1737 bool isCallerStructRet,
1738 const SmallVectorImpl<ISD::OutputArg> &Outs,
1739 const SmallVectorImpl<SDValue> &OutVals,
1740 const SmallVectorImpl<ISD::InputArg> &Ins,
1741 SelectionDAG& DAG) const {
1742 const Function *CallerF = DAG.getMachineFunction().getFunction();
1743 CallingConv::ID CallerCC = CallerF->getCallingConv();
1744 bool CCMatch = CallerCC == CalleeCC;
1746 // Look for obvious safe cases to perform tail call optimization that do not
1747 // require ABI changes. This is what gcc calls sibcall.
1749 // Do not sibcall optimize vararg calls unless the call site is not passing
1751 if (isVarArg && !Outs.empty())
1754 // Also avoid sibcall optimization if either caller or callee uses struct
1755 // return semantics.
1756 if (isCalleeStructRet || isCallerStructRet)
1759 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1760 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1761 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1762 // support in the assembler and linker to be used. This would need to be
1763 // fixed to fully support tail calls in Thumb1.
1765 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1766 // LR. This means if we need to reload LR, it takes an extra instructions,
1767 // which outweighs the value of the tail call; but here we don't know yet
1768 // whether LR is going to be used. Probably the right approach is to
1769 // generate the tail call here and turn it back into CALL/RET in
1770 // emitEpilogue if LR is used.
1772 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1773 // but we need to make sure there are enough registers; the only valid
1774 // registers are the 4 used for parameters. We don't currently do this
1776 if (Subtarget->isThumb1Only())
1779 // If the calling conventions do not match, then we'd better make sure the
1780 // results are returned in the same way as what the caller expects.
1782 SmallVector<CCValAssign, 16> RVLocs1;
1783 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1784 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1785 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1787 SmallVector<CCValAssign, 16> RVLocs2;
1788 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1789 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1790 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1792 if (RVLocs1.size() != RVLocs2.size())
1794 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1795 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1797 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1799 if (RVLocs1[i].isRegLoc()) {
1800 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1803 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1809 // If the callee takes no arguments then go on to check the results of the
1811 if (!Outs.empty()) {
1812 // Check if stack adjustment is needed. For now, do not do this if any
1813 // argument is passed on the stack.
1814 SmallVector<CCValAssign, 16> ArgLocs;
1815 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1816 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1817 CCInfo.AnalyzeCallOperands(Outs,
1818 CCAssignFnForNode(CalleeCC, false, isVarArg));
1819 if (CCInfo.getNextStackOffset()) {
1820 MachineFunction &MF = DAG.getMachineFunction();
1822 // Check if the arguments are already laid out in the right way as
1823 // the caller's fixed stack objects.
1824 MachineFrameInfo *MFI = MF.getFrameInfo();
1825 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1826 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1827 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1829 ++i, ++realArgIdx) {
1830 CCValAssign &VA = ArgLocs[i];
1831 EVT RegVT = VA.getLocVT();
1832 SDValue Arg = OutVals[realArgIdx];
1833 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1834 if (VA.getLocInfo() == CCValAssign::Indirect)
1836 if (VA.needsCustom()) {
1837 // f64 and vector types are split into multiple registers or
1838 // register/stack-slot combinations. The types will not match
1839 // the registers; give up on memory f64 refs until we figure
1840 // out what to do about this.
1843 if (!ArgLocs[++i].isRegLoc())
1845 if (RegVT == MVT::v2f64) {
1846 if (!ArgLocs[++i].isRegLoc())
1848 if (!ArgLocs[++i].isRegLoc())
1851 } else if (!VA.isRegLoc()) {
1852 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1864 ARMTargetLowering::LowerReturn(SDValue Chain,
1865 CallingConv::ID CallConv, bool isVarArg,
1866 const SmallVectorImpl<ISD::OutputArg> &Outs,
1867 const SmallVectorImpl<SDValue> &OutVals,
1868 DebugLoc dl, SelectionDAG &DAG) const {
1870 // CCValAssign - represent the assignment of the return value to a location.
1871 SmallVector<CCValAssign, 16> RVLocs;
1873 // CCState - Info about the registers and stack slots.
1874 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1875 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1877 // Analyze outgoing return values.
1878 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1881 // If this is the first return lowered for this function, add
1882 // the regs to the liveout set for the function.
1883 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1884 for (unsigned i = 0; i != RVLocs.size(); ++i)
1885 if (RVLocs[i].isRegLoc())
1886 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1891 // Copy the result values into the output registers.
1892 for (unsigned i = 0, realRVLocIdx = 0;
1894 ++i, ++realRVLocIdx) {
1895 CCValAssign &VA = RVLocs[i];
1896 assert(VA.isRegLoc() && "Can only return in registers!");
1898 SDValue Arg = OutVals[realRVLocIdx];
1900 switch (VA.getLocInfo()) {
1901 default: llvm_unreachable("Unknown loc info!");
1902 case CCValAssign::Full: break;
1903 case CCValAssign::BCvt:
1904 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1908 if (VA.needsCustom()) {
1909 if (VA.getLocVT() == MVT::v2f64) {
1910 // Extract the first half and return it in two registers.
1911 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1912 DAG.getConstant(0, MVT::i32));
1913 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1914 DAG.getVTList(MVT::i32, MVT::i32), Half);
1916 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1917 Flag = Chain.getValue(1);
1918 VA = RVLocs[++i]; // skip ahead to next loc
1919 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1920 HalfGPRs.getValue(1), Flag);
1921 Flag = Chain.getValue(1);
1922 VA = RVLocs[++i]; // skip ahead to next loc
1924 // Extract the 2nd half and fall through to handle it as an f64 value.
1925 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1926 DAG.getConstant(1, MVT::i32));
1928 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1930 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1931 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1932 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1933 Flag = Chain.getValue(1);
1934 VA = RVLocs[++i]; // skip ahead to next loc
1935 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1938 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1940 // Guarantee that all emitted copies are
1941 // stuck together, avoiding something bad.
1942 Flag = Chain.getValue(1);
1947 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1949 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1954 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1955 if (N->getNumValues() != 1)
1957 if (!N->hasNUsesOfValue(1, 0))
1960 SDValue TCChain = Chain;
1961 SDNode *Copy = *N->use_begin();
1962 if (Copy->getOpcode() == ISD::CopyToReg) {
1963 // If the copy has a glue operand, we conservatively assume it isn't safe to
1964 // perform a tail call.
1965 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1967 TCChain = Copy->getOperand(0);
1968 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1969 SDNode *VMov = Copy;
1970 // f64 returned in a pair of GPRs.
1971 SmallPtrSet<SDNode*, 2> Copies;
1972 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1974 if (UI->getOpcode() != ISD::CopyToReg)
1978 if (Copies.size() > 2)
1981 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1983 SDValue UseChain = UI->getOperand(0);
1984 if (Copies.count(UseChain.getNode()))
1991 } else if (Copy->getOpcode() == ISD::BITCAST) {
1992 // f32 returned in a single GPR.
1993 if (!Copy->hasOneUse())
1995 Copy = *Copy->use_begin();
1996 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1998 Chain = Copy->getOperand(0);
2003 bool HasRet = false;
2004 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2006 if (UI->getOpcode() != ARMISD::RET_FLAG)
2018 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2019 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2022 if (!CI->isTailCall())
2025 return !Subtarget->isThumb1Only();
2028 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2029 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2030 // one of the above mentioned nodes. It has to be wrapped because otherwise
2031 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2032 // be used to form addressing mode. These wrapped nodes will be selected
2034 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2035 EVT PtrVT = Op.getValueType();
2036 // FIXME there is no actual debug info here
2037 DebugLoc dl = Op.getDebugLoc();
2038 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2040 if (CP->isMachineConstantPoolEntry())
2041 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2042 CP->getAlignment());
2044 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2045 CP->getAlignment());
2046 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2049 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2050 return MachineJumpTableInfo::EK_Inline;
2053 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2054 SelectionDAG &DAG) const {
2055 MachineFunction &MF = DAG.getMachineFunction();
2056 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2057 unsigned ARMPCLabelIndex = 0;
2058 DebugLoc DL = Op.getDebugLoc();
2059 EVT PtrVT = getPointerTy();
2060 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2061 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2063 if (RelocM == Reloc::Static) {
2064 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2066 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2067 ARMPCLabelIndex = AFI->createPICLabelUId();
2068 ARMConstantPoolValue *CPV =
2069 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2070 ARMCP::CPBlockAddress, PCAdj);
2071 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2073 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2074 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2075 MachinePointerInfo::getConstantPool(),
2076 false, false, false, 0);
2077 if (RelocM == Reloc::Static)
2079 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2080 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2083 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2085 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2086 SelectionDAG &DAG) const {
2087 DebugLoc dl = GA->getDebugLoc();
2088 EVT PtrVT = getPointerTy();
2089 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2090 MachineFunction &MF = DAG.getMachineFunction();
2091 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2092 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2093 ARMConstantPoolValue *CPV =
2094 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2095 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2096 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2097 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2098 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2099 MachinePointerInfo::getConstantPool(),
2100 false, false, false, 0);
2101 SDValue Chain = Argument.getValue(1);
2103 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2104 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2106 // call __tls_get_addr.
2109 Entry.Node = Argument;
2110 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2111 Args.push_back(Entry);
2112 // FIXME: is there useful debug info available here?
2113 TargetLowering::CallLoweringInfo CLI(Chain,
2114 (Type *) Type::getInt32Ty(*DAG.getContext()),
2115 false, false, false, false,
2116 0, CallingConv::C, /*isTailCall=*/false,
2117 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2118 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2119 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2120 return CallResult.first;
2123 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2124 // "local exec" model.
2126 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2128 TLSModel::Model model) const {
2129 const GlobalValue *GV = GA->getGlobal();
2130 DebugLoc dl = GA->getDebugLoc();
2132 SDValue Chain = DAG.getEntryNode();
2133 EVT PtrVT = getPointerTy();
2134 // Get the Thread Pointer
2135 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2137 if (model == TLSModel::InitialExec) {
2138 MachineFunction &MF = DAG.getMachineFunction();
2139 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2140 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2141 // Initial exec model.
2142 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2143 ARMConstantPoolValue *CPV =
2144 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2145 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2147 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2148 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2149 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2150 MachinePointerInfo::getConstantPool(),
2151 false, false, false, 0);
2152 Chain = Offset.getValue(1);
2154 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2155 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2157 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2158 MachinePointerInfo::getConstantPool(),
2159 false, false, false, 0);
2162 assert(model == TLSModel::LocalExec);
2163 ARMConstantPoolValue *CPV =
2164 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2165 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2166 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2167 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2168 MachinePointerInfo::getConstantPool(),
2169 false, false, false, 0);
2172 // The address of the thread local variable is the add of the thread
2173 // pointer with the offset of the variable.
2174 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2178 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2179 // TODO: implement the "local dynamic" model
2180 assert(Subtarget->isTargetELF() &&
2181 "TLS not implemented for non-ELF targets");
2182 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2184 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2187 case TLSModel::GeneralDynamic:
2188 case TLSModel::LocalDynamic:
2189 return LowerToTLSGeneralDynamicModel(GA, DAG);
2190 case TLSModel::InitialExec:
2191 case TLSModel::LocalExec:
2192 return LowerToTLSExecModels(GA, DAG, model);
2194 llvm_unreachable("bogus TLS model");
2197 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2198 SelectionDAG &DAG) const {
2199 EVT PtrVT = getPointerTy();
2200 DebugLoc dl = Op.getDebugLoc();
2201 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2202 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2203 if (RelocM == Reloc::PIC_) {
2204 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2205 ARMConstantPoolValue *CPV =
2206 ARMConstantPoolConstant::Create(GV,
2207 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2208 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2209 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2210 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2212 MachinePointerInfo::getConstantPool(),
2213 false, false, false, 0);
2214 SDValue Chain = Result.getValue(1);
2215 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2216 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2218 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2219 MachinePointerInfo::getGOT(),
2220 false, false, false, 0);
2224 // If we have T2 ops, we can materialize the address directly via movt/movw
2225 // pair. This is always cheaper.
2226 if (Subtarget->useMovt()) {
2228 // FIXME: Once remat is capable of dealing with instructions with register
2229 // operands, expand this into two nodes.
2230 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2231 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2233 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2234 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2235 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2236 MachinePointerInfo::getConstantPool(),
2237 false, false, false, 0);
2241 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2242 SelectionDAG &DAG) const {
2243 EVT PtrVT = getPointerTy();
2244 DebugLoc dl = Op.getDebugLoc();
2245 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2246 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2247 MachineFunction &MF = DAG.getMachineFunction();
2248 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2250 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2251 // update ARMFastISel::ARMMaterializeGV.
2252 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2254 // FIXME: Once remat is capable of dealing with instructions with register
2255 // operands, expand this into two nodes.
2256 if (RelocM == Reloc::Static)
2257 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2258 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2260 unsigned Wrapper = (RelocM == Reloc::PIC_)
2261 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2262 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2263 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2264 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2265 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2266 MachinePointerInfo::getGOT(),
2267 false, false, false, 0);
2271 unsigned ARMPCLabelIndex = 0;
2273 if (RelocM == Reloc::Static) {
2274 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2276 ARMPCLabelIndex = AFI->createPICLabelUId();
2277 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2278 ARMConstantPoolValue *CPV =
2279 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2281 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2283 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2285 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2286 MachinePointerInfo::getConstantPool(),
2287 false, false, false, 0);
2288 SDValue Chain = Result.getValue(1);
2290 if (RelocM == Reloc::PIC_) {
2291 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2292 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2295 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2296 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2297 false, false, false, 0);
2302 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2303 SelectionDAG &DAG) const {
2304 assert(Subtarget->isTargetELF() &&
2305 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2306 MachineFunction &MF = DAG.getMachineFunction();
2307 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2308 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2309 EVT PtrVT = getPointerTy();
2310 DebugLoc dl = Op.getDebugLoc();
2311 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2312 ARMConstantPoolValue *CPV =
2313 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2314 ARMPCLabelIndex, PCAdj);
2315 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2316 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2317 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2318 MachinePointerInfo::getConstantPool(),
2319 false, false, false, 0);
2320 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2321 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2325 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2326 DebugLoc dl = Op.getDebugLoc();
2327 SDValue Val = DAG.getConstant(0, MVT::i32);
2328 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2329 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2330 Op.getOperand(1), Val);
2334 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2335 DebugLoc dl = Op.getDebugLoc();
2336 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2337 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2341 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2342 const ARMSubtarget *Subtarget) const {
2343 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2344 DebugLoc dl = Op.getDebugLoc();
2346 default: return SDValue(); // Don't custom lower most intrinsics.
2347 case Intrinsic::arm_thread_pointer: {
2348 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2349 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2351 case Intrinsic::eh_sjlj_lsda: {
2352 MachineFunction &MF = DAG.getMachineFunction();
2353 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2354 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2355 EVT PtrVT = getPointerTy();
2356 DebugLoc dl = Op.getDebugLoc();
2357 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2359 unsigned PCAdj = (RelocM != Reloc::PIC_)
2360 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2361 ARMConstantPoolValue *CPV =
2362 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2363 ARMCP::CPLSDA, PCAdj);
2364 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2365 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2367 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2368 MachinePointerInfo::getConstantPool(),
2369 false, false, false, 0);
2371 if (RelocM == Reloc::PIC_) {
2372 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2373 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2377 case Intrinsic::arm_neon_vmulls:
2378 case Intrinsic::arm_neon_vmullu: {
2379 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2380 ? ARMISD::VMULLs : ARMISD::VMULLu;
2381 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2382 Op.getOperand(1), Op.getOperand(2));
2387 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2388 const ARMSubtarget *Subtarget) {
2389 DebugLoc dl = Op.getDebugLoc();
2390 if (!Subtarget->hasDataBarrier()) {
2391 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2392 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2394 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2395 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2396 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2397 DAG.getConstant(0, MVT::i32));
2400 SDValue Op5 = Op.getOperand(5);
2401 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2402 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2403 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2404 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2406 ARM_MB::MemBOpt DMBOpt;
2407 if (isDeviceBarrier)
2408 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2410 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2411 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2412 DAG.getConstant(DMBOpt, MVT::i32));
2416 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2417 const ARMSubtarget *Subtarget) {
2418 // FIXME: handle "fence singlethread" more efficiently.
2419 DebugLoc dl = Op.getDebugLoc();
2420 if (!Subtarget->hasDataBarrier()) {
2421 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2422 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2424 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2425 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2426 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2427 DAG.getConstant(0, MVT::i32));
2430 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2431 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2434 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2435 const ARMSubtarget *Subtarget) {
2436 // ARM pre v5TE and Thumb1 does not have preload instructions.
2437 if (!(Subtarget->isThumb2() ||
2438 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2439 // Just preserve the chain.
2440 return Op.getOperand(0);
2442 DebugLoc dl = Op.getDebugLoc();
2443 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2445 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2446 // ARMv7 with MP extension has PLDW.
2447 return Op.getOperand(0);
2449 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2450 if (Subtarget->isThumb()) {
2452 isRead = ~isRead & 1;
2453 isData = ~isData & 1;
2456 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2457 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2458 DAG.getConstant(isData, MVT::i32));
2461 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2462 MachineFunction &MF = DAG.getMachineFunction();
2463 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2465 // vastart just stores the address of the VarArgsFrameIndex slot into the
2466 // memory location argument.
2467 DebugLoc dl = Op.getDebugLoc();
2468 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2469 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2470 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2471 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2472 MachinePointerInfo(SV), false, false, 0);
2476 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2477 SDValue &Root, SelectionDAG &DAG,
2478 DebugLoc dl) const {
2479 MachineFunction &MF = DAG.getMachineFunction();
2480 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2482 const TargetRegisterClass *RC;
2483 if (AFI->isThumb1OnlyFunction())
2484 RC = &ARM::tGPRRegClass;
2486 RC = &ARM::GPRRegClass;
2488 // Transform the arguments stored in physical registers into virtual ones.
2489 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2490 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2493 if (NextVA.isMemLoc()) {
2494 MachineFrameInfo *MFI = MF.getFrameInfo();
2495 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2497 // Create load node to retrieve arguments from the stack.
2498 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2499 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2500 MachinePointerInfo::getFixedStack(FI),
2501 false, false, false, 0);
2503 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2504 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2507 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2511 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2512 unsigned &VARegSize, unsigned &VARegSaveSize)
2515 if (CCInfo.isFirstByValRegValid())
2516 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2518 unsigned int firstUnalloced;
2519 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2520 sizeof(GPRArgRegs) /
2521 sizeof(GPRArgRegs[0]));
2522 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2525 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2526 VARegSize = NumGPRs * 4;
2527 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2530 // The remaining GPRs hold either the beginning of variable-argument
2531 // data, or the beginning of an aggregate passed by value (usuall
2532 // byval). Either way, we allocate stack slots adjacent to the data
2533 // provided by our caller, and store the unallocated registers there.
2534 // If this is a variadic function, the va_list pointer will begin with
2535 // these values; otherwise, this reassembles a (byval) structure that
2536 // was split between registers and memory.
2538 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2539 DebugLoc dl, SDValue &Chain,
2540 unsigned ArgOffset) const {
2541 MachineFunction &MF = DAG.getMachineFunction();
2542 MachineFrameInfo *MFI = MF.getFrameInfo();
2543 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2544 unsigned firstRegToSaveIndex;
2545 if (CCInfo.isFirstByValRegValid())
2546 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2548 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2549 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2552 unsigned VARegSize, VARegSaveSize;
2553 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2554 if (VARegSaveSize) {
2555 // If this function is vararg, store any remaining integer argument regs
2556 // to their spots on the stack so that they may be loaded by deferencing
2557 // the result of va_next.
2558 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2559 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2560 ArgOffset + VARegSaveSize
2563 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2566 SmallVector<SDValue, 4> MemOps;
2567 for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2568 const TargetRegisterClass *RC;
2569 if (AFI->isThumb1OnlyFunction())
2570 RC = &ARM::tGPRRegClass;
2572 RC = &ARM::GPRRegClass;
2574 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2575 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2577 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2578 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2580 MemOps.push_back(Store);
2581 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2582 DAG.getConstant(4, getPointerTy()));
2584 if (!MemOps.empty())
2585 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2586 &MemOps[0], MemOps.size());
2588 // This will point to the next argument passed via stack.
2589 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2593 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2594 CallingConv::ID CallConv, bool isVarArg,
2595 const SmallVectorImpl<ISD::InputArg>
2597 DebugLoc dl, SelectionDAG &DAG,
2598 SmallVectorImpl<SDValue> &InVals)
2600 MachineFunction &MF = DAG.getMachineFunction();
2601 MachineFrameInfo *MFI = MF.getFrameInfo();
2603 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2605 // Assign locations to all of the incoming arguments.
2606 SmallVector<CCValAssign, 16> ArgLocs;
2607 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2608 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2609 CCInfo.AnalyzeFormalArguments(Ins,
2610 CCAssignFnForNode(CallConv, /* Return*/ false,
2613 SmallVector<SDValue, 16> ArgValues;
2614 int lastInsIndex = -1;
2617 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2618 CCValAssign &VA = ArgLocs[i];
2620 // Arguments stored in registers.
2621 if (VA.isRegLoc()) {
2622 EVT RegVT = VA.getLocVT();
2624 if (VA.needsCustom()) {
2625 // f64 and vector types are split up into multiple registers or
2626 // combinations of registers and stack slots.
2627 if (VA.getLocVT() == MVT::v2f64) {
2628 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2630 VA = ArgLocs[++i]; // skip ahead to next loc
2632 if (VA.isMemLoc()) {
2633 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2634 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2635 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2636 MachinePointerInfo::getFixedStack(FI),
2637 false, false, false, 0);
2639 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2642 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2643 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2644 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2645 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2646 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2648 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2651 const TargetRegisterClass *RC;
2653 if (RegVT == MVT::f32)
2654 RC = &ARM::SPRRegClass;
2655 else if (RegVT == MVT::f64)
2656 RC = &ARM::DPRRegClass;
2657 else if (RegVT == MVT::v2f64)
2658 RC = &ARM::QPRRegClass;
2659 else if (RegVT == MVT::i32)
2660 RC = AFI->isThumb1OnlyFunction() ?
2661 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2662 (const TargetRegisterClass*)&ARM::GPRRegClass;
2664 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2666 // Transform the arguments in physical registers into virtual ones.
2667 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2668 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2671 // If this is an 8 or 16-bit value, it is really passed promoted
2672 // to 32 bits. Insert an assert[sz]ext to capture this, then
2673 // truncate to the right size.
2674 switch (VA.getLocInfo()) {
2675 default: llvm_unreachable("Unknown loc info!");
2676 case CCValAssign::Full: break;
2677 case CCValAssign::BCvt:
2678 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2680 case CCValAssign::SExt:
2681 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2682 DAG.getValueType(VA.getValVT()));
2683 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2685 case CCValAssign::ZExt:
2686 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2687 DAG.getValueType(VA.getValVT()));
2688 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2692 InVals.push_back(ArgValue);
2694 } else { // VA.isRegLoc()
2697 assert(VA.isMemLoc());
2698 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2700 int index = ArgLocs[i].getValNo();
2702 // Some Ins[] entries become multiple ArgLoc[] entries.
2703 // Process them only once.
2704 if (index != lastInsIndex)
2706 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2707 // FIXME: For now, all byval parameter objects are marked mutable.
2708 // This can be changed with more analysis.
2709 // In case of tail call optimization mark all arguments mutable.
2710 // Since they could be overwritten by lowering of arguments in case of
2712 if (Flags.isByVal()) {
2713 unsigned VARegSize, VARegSaveSize;
2714 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2715 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2716 unsigned Bytes = Flags.getByValSize() - VARegSize;
2717 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2718 int FI = MFI->CreateFixedObject(Bytes,
2719 VA.getLocMemOffset(), false);
2720 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2722 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2723 VA.getLocMemOffset(), true);
2725 // Create load nodes to retrieve arguments from the stack.
2726 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2727 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2728 MachinePointerInfo::getFixedStack(FI),
2729 false, false, false, 0));
2731 lastInsIndex = index;
2738 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2743 /// isFloatingPointZero - Return true if this is +0.0.
2744 static bool isFloatingPointZero(SDValue Op) {
2745 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2746 return CFP->getValueAPF().isPosZero();
2747 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2748 // Maybe this has already been legalized into the constant pool?
2749 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2750 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2751 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2752 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2753 return CFP->getValueAPF().isPosZero();
2759 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2760 /// the given operands.
2762 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2763 SDValue &ARMcc, SelectionDAG &DAG,
2764 DebugLoc dl) const {
2765 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2766 unsigned C = RHSC->getZExtValue();
2767 if (!isLegalICmpImmediate(C)) {
2768 // Constant does not fit, try adjusting it by one?
2773 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2774 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2775 RHS = DAG.getConstant(C-1, MVT::i32);
2780 if (C != 0 && isLegalICmpImmediate(C-1)) {
2781 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2782 RHS = DAG.getConstant(C-1, MVT::i32);
2787 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2788 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2789 RHS = DAG.getConstant(C+1, MVT::i32);
2794 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2795 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2796 RHS = DAG.getConstant(C+1, MVT::i32);
2803 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2804 ARMISD::NodeType CompareType;
2807 CompareType = ARMISD::CMP;
2812 CompareType = ARMISD::CMPZ;
2815 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2816 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2819 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2821 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2822 DebugLoc dl) const {
2824 if (!isFloatingPointZero(RHS))
2825 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2827 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2828 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2831 /// duplicateCmp - Glue values can have only one use, so this function
2832 /// duplicates a comparison node.
2834 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2835 unsigned Opc = Cmp.getOpcode();
2836 DebugLoc DL = Cmp.getDebugLoc();
2837 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2838 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2840 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2841 Cmp = Cmp.getOperand(0);
2842 Opc = Cmp.getOpcode();
2843 if (Opc == ARMISD::CMPFP)
2844 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2846 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2847 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2849 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2852 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2853 SDValue Cond = Op.getOperand(0);
2854 SDValue SelectTrue = Op.getOperand(1);
2855 SDValue SelectFalse = Op.getOperand(2);
2856 DebugLoc dl = Op.getDebugLoc();
2860 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2861 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2863 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2864 const ConstantSDNode *CMOVTrue =
2865 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2866 const ConstantSDNode *CMOVFalse =
2867 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2869 if (CMOVTrue && CMOVFalse) {
2870 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2871 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2875 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2877 False = SelectFalse;
2878 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2883 if (True.getNode() && False.getNode()) {
2884 EVT VT = Op.getValueType();
2885 SDValue ARMcc = Cond.getOperand(2);
2886 SDValue CCR = Cond.getOperand(3);
2887 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2888 assert(True.getValueType() == VT);
2889 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2894 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2895 // undefined bits before doing a full-word comparison with zero.
2896 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2897 DAG.getConstant(1, Cond.getValueType()));
2899 return DAG.getSelectCC(dl, Cond,
2900 DAG.getConstant(0, Cond.getValueType()),
2901 SelectTrue, SelectFalse, ISD::SETNE);
2904 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2905 EVT VT = Op.getValueType();
2906 SDValue LHS = Op.getOperand(0);
2907 SDValue RHS = Op.getOperand(1);
2908 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2909 SDValue TrueVal = Op.getOperand(2);
2910 SDValue FalseVal = Op.getOperand(3);
2911 DebugLoc dl = Op.getDebugLoc();
2913 if (LHS.getValueType() == MVT::i32) {
2915 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2916 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2917 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2920 ARMCC::CondCodes CondCode, CondCode2;
2921 FPCCToARMCC(CC, CondCode, CondCode2);
2923 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2924 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2925 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2926 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2928 if (CondCode2 != ARMCC::AL) {
2929 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2930 // FIXME: Needs another CMP because flag can have but one use.
2931 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2932 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2933 Result, TrueVal, ARMcc2, CCR, Cmp2);
2938 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2939 /// to morph to an integer compare sequence.
2940 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2941 const ARMSubtarget *Subtarget) {
2942 SDNode *N = Op.getNode();
2943 if (!N->hasOneUse())
2944 // Otherwise it requires moving the value from fp to integer registers.
2946 if (!N->getNumValues())
2948 EVT VT = Op.getValueType();
2949 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2950 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2951 // vmrs are very slow, e.g. cortex-a8.
2954 if (isFloatingPointZero(Op)) {
2958 return ISD::isNormalLoad(N);
2961 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2962 if (isFloatingPointZero(Op))
2963 return DAG.getConstant(0, MVT::i32);
2965 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2966 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2967 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2968 Ld->isVolatile(), Ld->isNonTemporal(),
2969 Ld->isInvariant(), Ld->getAlignment());
2971 llvm_unreachable("Unknown VFP cmp argument!");
2974 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2975 SDValue &RetVal1, SDValue &RetVal2) {
2976 if (isFloatingPointZero(Op)) {
2977 RetVal1 = DAG.getConstant(0, MVT::i32);
2978 RetVal2 = DAG.getConstant(0, MVT::i32);
2982 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2983 SDValue Ptr = Ld->getBasePtr();
2984 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2985 Ld->getChain(), Ptr,
2986 Ld->getPointerInfo(),
2987 Ld->isVolatile(), Ld->isNonTemporal(),
2988 Ld->isInvariant(), Ld->getAlignment());
2990 EVT PtrType = Ptr.getValueType();
2991 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2992 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2993 PtrType, Ptr, DAG.getConstant(4, PtrType));
2994 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2995 Ld->getChain(), NewPtr,
2996 Ld->getPointerInfo().getWithOffset(4),
2997 Ld->isVolatile(), Ld->isNonTemporal(),
2998 Ld->isInvariant(), NewAlign);
3002 llvm_unreachable("Unknown VFP cmp argument!");
3005 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3006 /// f32 and even f64 comparisons to integer ones.
3008 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3009 SDValue Chain = Op.getOperand(0);
3010 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3011 SDValue LHS = Op.getOperand(2);
3012 SDValue RHS = Op.getOperand(3);
3013 SDValue Dest = Op.getOperand(4);
3014 DebugLoc dl = Op.getDebugLoc();
3016 bool LHSSeenZero = false;
3017 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3018 bool RHSSeenZero = false;
3019 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3020 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3021 // If unsafe fp math optimization is enabled and there are no other uses of
3022 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3023 // to an integer comparison.
3024 if (CC == ISD::SETOEQ)
3026 else if (CC == ISD::SETUNE)
3029 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3031 if (LHS.getValueType() == MVT::f32) {
3032 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3033 bitcastf32Toi32(LHS, DAG), Mask);
3034 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3035 bitcastf32Toi32(RHS, DAG), Mask);
3036 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3037 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3038 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3039 Chain, Dest, ARMcc, CCR, Cmp);
3044 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3045 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3046 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3047 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3048 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3049 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3050 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3051 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3052 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3058 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3059 SDValue Chain = Op.getOperand(0);
3060 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3061 SDValue LHS = Op.getOperand(2);
3062 SDValue RHS = Op.getOperand(3);
3063 SDValue Dest = Op.getOperand(4);
3064 DebugLoc dl = Op.getDebugLoc();
3066 if (LHS.getValueType() == MVT::i32) {
3068 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3069 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3070 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3071 Chain, Dest, ARMcc, CCR, Cmp);
3074 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3076 if (getTargetMachine().Options.UnsafeFPMath &&
3077 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3078 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3079 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3080 if (Result.getNode())
3084 ARMCC::CondCodes CondCode, CondCode2;
3085 FPCCToARMCC(CC, CondCode, CondCode2);
3087 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3088 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3089 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3090 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3091 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3092 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3093 if (CondCode2 != ARMCC::AL) {
3094 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3095 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3096 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3101 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3102 SDValue Chain = Op.getOperand(0);
3103 SDValue Table = Op.getOperand(1);
3104 SDValue Index = Op.getOperand(2);
3105 DebugLoc dl = Op.getDebugLoc();
3107 EVT PTy = getPointerTy();
3108 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3109 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3110 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3111 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3112 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3113 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3114 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3115 if (Subtarget->isThumb2()) {
3116 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3117 // which does another jump to the destination. This also makes it easier
3118 // to translate it to TBB / TBH later.
3119 // FIXME: This might not work if the function is extremely large.
3120 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3121 Addr, Op.getOperand(2), JTI, UId);
3123 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3124 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3125 MachinePointerInfo::getJumpTable(),
3126 false, false, false, 0);
3127 Chain = Addr.getValue(1);
3128 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3129 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3131 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3132 MachinePointerInfo::getJumpTable(),
3133 false, false, false, 0);
3134 Chain = Addr.getValue(1);
3135 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3139 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3140 EVT VT = Op.getValueType();
3141 DebugLoc dl = Op.getDebugLoc();
3143 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3144 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3146 return DAG.UnrollVectorOp(Op.getNode());
3149 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3150 "Invalid type for custom lowering!");
3151 if (VT != MVT::v4i16)
3152 return DAG.UnrollVectorOp(Op.getNode());
3154 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3155 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3158 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3159 EVT VT = Op.getValueType();
3161 return LowerVectorFP_TO_INT(Op, DAG);
3163 DebugLoc dl = Op.getDebugLoc();
3166 switch (Op.getOpcode()) {
3167 default: llvm_unreachable("Invalid opcode!");
3168 case ISD::FP_TO_SINT:
3169 Opc = ARMISD::FTOSI;
3171 case ISD::FP_TO_UINT:
3172 Opc = ARMISD::FTOUI;
3175 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3176 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3179 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3180 EVT VT = Op.getValueType();
3181 DebugLoc dl = Op.getDebugLoc();
3183 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3184 if (VT.getVectorElementType() == MVT::f32)
3186 return DAG.UnrollVectorOp(Op.getNode());
3189 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3190 "Invalid type for custom lowering!");
3191 if (VT != MVT::v4f32)
3192 return DAG.UnrollVectorOp(Op.getNode());
3196 switch (Op.getOpcode()) {
3197 default: llvm_unreachable("Invalid opcode!");
3198 case ISD::SINT_TO_FP:
3199 CastOpc = ISD::SIGN_EXTEND;
3200 Opc = ISD::SINT_TO_FP;
3202 case ISD::UINT_TO_FP:
3203 CastOpc = ISD::ZERO_EXTEND;
3204 Opc = ISD::UINT_TO_FP;
3208 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3209 return DAG.getNode(Opc, dl, VT, Op);
3212 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3213 EVT VT = Op.getValueType();
3215 return LowerVectorINT_TO_FP(Op, DAG);
3217 DebugLoc dl = Op.getDebugLoc();
3220 switch (Op.getOpcode()) {
3221 default: llvm_unreachable("Invalid opcode!");
3222 case ISD::SINT_TO_FP:
3223 Opc = ARMISD::SITOF;
3225 case ISD::UINT_TO_FP:
3226 Opc = ARMISD::UITOF;
3230 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3231 return DAG.getNode(Opc, dl, VT, Op);
3234 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3235 // Implement fcopysign with a fabs and a conditional fneg.
3236 SDValue Tmp0 = Op.getOperand(0);
3237 SDValue Tmp1 = Op.getOperand(1);
3238 DebugLoc dl = Op.getDebugLoc();
3239 EVT VT = Op.getValueType();
3240 EVT SrcVT = Tmp1.getValueType();
3241 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3242 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3243 bool UseNEON = !InGPR && Subtarget->hasNEON();
3246 // Use VBSL to copy the sign bit.
3247 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3248 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3249 DAG.getTargetConstant(EncodedVal, MVT::i32));
3250 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3252 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3253 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3254 DAG.getConstant(32, MVT::i32));
3255 else /*if (VT == MVT::f32)*/
3256 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3257 if (SrcVT == MVT::f32) {
3258 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3260 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3261 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3262 DAG.getConstant(32, MVT::i32));
3263 } else if (VT == MVT::f32)
3264 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3265 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3266 DAG.getConstant(32, MVT::i32));
3267 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3268 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3270 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3272 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3273 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3274 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3276 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3277 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3278 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3279 if (VT == MVT::f32) {
3280 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3281 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3282 DAG.getConstant(0, MVT::i32));
3284 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3290 // Bitcast operand 1 to i32.
3291 if (SrcVT == MVT::f64)
3292 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3293 &Tmp1, 1).getValue(1);
3294 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3296 // Or in the signbit with integer operations.
3297 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3298 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3299 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3300 if (VT == MVT::f32) {
3301 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3302 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3303 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3304 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3307 // f64: Or the high part with signbit and then combine two parts.
3308 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3310 SDValue Lo = Tmp0.getValue(0);
3311 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3312 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3313 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3316 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3317 MachineFunction &MF = DAG.getMachineFunction();
3318 MachineFrameInfo *MFI = MF.getFrameInfo();
3319 MFI->setReturnAddressIsTaken(true);
3321 EVT VT = Op.getValueType();
3322 DebugLoc dl = Op.getDebugLoc();
3323 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3325 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3326 SDValue Offset = DAG.getConstant(4, MVT::i32);
3327 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3328 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3329 MachinePointerInfo(), false, false, false, 0);
3332 // Return LR, which contains the return address. Mark it an implicit live-in.
3333 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3334 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3337 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3338 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3339 MFI->setFrameAddressIsTaken(true);
3341 EVT VT = Op.getValueType();
3342 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3343 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3344 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3345 ? ARM::R7 : ARM::R11;
3346 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3348 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3349 MachinePointerInfo(),
3350 false, false, false, 0);
3354 /// ExpandBITCAST - If the target supports VFP, this function is called to
3355 /// expand a bit convert where either the source or destination type is i64 to
3356 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3357 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3358 /// vectors), since the legalizer won't know what to do with that.
3359 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3361 DebugLoc dl = N->getDebugLoc();
3362 SDValue Op = N->getOperand(0);
3364 // This function is only supposed to be called for i64 types, either as the
3365 // source or destination of the bit convert.
3366 EVT SrcVT = Op.getValueType();
3367 EVT DstVT = N->getValueType(0);
3368 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3369 "ExpandBITCAST called for non-i64 type");
3371 // Turn i64->f64 into VMOVDRR.
3372 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3373 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3374 DAG.getConstant(0, MVT::i32));
3375 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3376 DAG.getConstant(1, MVT::i32));
3377 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3378 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3381 // Turn f64->i64 into VMOVRRD.
3382 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3383 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3384 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3385 // Merge the pieces into a single i64 value.
3386 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3392 /// getZeroVector - Returns a vector of specified type with all zero elements.
3393 /// Zero vectors are used to represent vector negation and in those cases
3394 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3395 /// not support i64 elements, so sometimes the zero vectors will need to be
3396 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3398 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3399 assert(VT.isVector() && "Expected a vector type");
3400 // The canonical modified immediate encoding of a zero vector is....0!
3401 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3402 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3403 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3404 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3407 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3408 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3409 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3410 SelectionDAG &DAG) const {
3411 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3412 EVT VT = Op.getValueType();
3413 unsigned VTBits = VT.getSizeInBits();
3414 DebugLoc dl = Op.getDebugLoc();
3415 SDValue ShOpLo = Op.getOperand(0);
3416 SDValue ShOpHi = Op.getOperand(1);
3417 SDValue ShAmt = Op.getOperand(2);
3419 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3421 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3423 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3424 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3425 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3426 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3427 DAG.getConstant(VTBits, MVT::i32));
3428 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3429 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3430 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3432 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3433 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3435 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3436 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3439 SDValue Ops[2] = { Lo, Hi };
3440 return DAG.getMergeValues(Ops, 2, dl);
3443 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3444 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3445 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3446 SelectionDAG &DAG) const {
3447 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3448 EVT VT = Op.getValueType();
3449 unsigned VTBits = VT.getSizeInBits();
3450 DebugLoc dl = Op.getDebugLoc();
3451 SDValue ShOpLo = Op.getOperand(0);
3452 SDValue ShOpHi = Op.getOperand(1);
3453 SDValue ShAmt = Op.getOperand(2);
3456 assert(Op.getOpcode() == ISD::SHL_PARTS);
3457 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3458 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3459 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3460 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3461 DAG.getConstant(VTBits, MVT::i32));
3462 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3463 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3465 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3466 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3467 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3469 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3470 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3473 SDValue Ops[2] = { Lo, Hi };
3474 return DAG.getMergeValues(Ops, 2, dl);
3477 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3478 SelectionDAG &DAG) const {
3479 // The rounding mode is in bits 23:22 of the FPSCR.
3480 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3481 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3482 // so that the shift + and get folded into a bitfield extract.
3483 DebugLoc dl = Op.getDebugLoc();
3484 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3485 DAG.getConstant(Intrinsic::arm_get_fpscr,
3487 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3488 DAG.getConstant(1U << 22, MVT::i32));
3489 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3490 DAG.getConstant(22, MVT::i32));
3491 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3492 DAG.getConstant(3, MVT::i32));
3495 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3496 const ARMSubtarget *ST) {
3497 EVT VT = N->getValueType(0);
3498 DebugLoc dl = N->getDebugLoc();
3500 if (!ST->hasV6T2Ops())
3503 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3504 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3507 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3508 const ARMSubtarget *ST) {
3509 EVT VT = N->getValueType(0);
3510 DebugLoc dl = N->getDebugLoc();
3515 // Lower vector shifts on NEON to use VSHL.
3516 assert(ST->hasNEON() && "unexpected vector shift");
3518 // Left shifts translate directly to the vshiftu intrinsic.
3519 if (N->getOpcode() == ISD::SHL)
3520 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3521 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3522 N->getOperand(0), N->getOperand(1));
3524 assert((N->getOpcode() == ISD::SRA ||
3525 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3527 // NEON uses the same intrinsics for both left and right shifts. For
3528 // right shifts, the shift amounts are negative, so negate the vector of
3530 EVT ShiftVT = N->getOperand(1).getValueType();
3531 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3532 getZeroVector(ShiftVT, DAG, dl),
3534 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3535 Intrinsic::arm_neon_vshifts :
3536 Intrinsic::arm_neon_vshiftu);
3537 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3538 DAG.getConstant(vshiftInt, MVT::i32),
3539 N->getOperand(0), NegatedCount);
3542 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3543 const ARMSubtarget *ST) {
3544 EVT VT = N->getValueType(0);
3545 DebugLoc dl = N->getDebugLoc();
3547 // We can get here for a node like i32 = ISD::SHL i32, i64
3551 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3552 "Unknown shift to lower!");
3554 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3555 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3556 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3559 // If we are in thumb mode, we don't have RRX.
3560 if (ST->isThumb1Only()) return SDValue();
3562 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3563 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3564 DAG.getConstant(0, MVT::i32));
3565 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3566 DAG.getConstant(1, MVT::i32));
3568 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3569 // captures the result into a carry flag.
3570 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3571 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3573 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3574 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3576 // Merge the pieces into a single i64 value.
3577 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3580 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3581 SDValue TmpOp0, TmpOp1;
3582 bool Invert = false;
3586 SDValue Op0 = Op.getOperand(0);
3587 SDValue Op1 = Op.getOperand(1);
3588 SDValue CC = Op.getOperand(2);
3589 EVT VT = Op.getValueType();
3590 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3591 DebugLoc dl = Op.getDebugLoc();
3593 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3594 switch (SetCCOpcode) {
3595 default: llvm_unreachable("Illegal FP comparison");
3597 case ISD::SETNE: Invert = true; // Fallthrough
3599 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3601 case ISD::SETLT: Swap = true; // Fallthrough
3603 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3605 case ISD::SETLE: Swap = true; // Fallthrough
3607 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3608 case ISD::SETUGE: Swap = true; // Fallthrough
3609 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3610 case ISD::SETUGT: Swap = true; // Fallthrough
3611 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3612 case ISD::SETUEQ: Invert = true; // Fallthrough
3614 // Expand this to (OLT | OGT).
3618 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3619 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3621 case ISD::SETUO: Invert = true; // Fallthrough
3623 // Expand this to (OLT | OGE).
3627 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3628 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3632 // Integer comparisons.
3633 switch (SetCCOpcode) {
3634 default: llvm_unreachable("Illegal integer comparison");
3635 case ISD::SETNE: Invert = true;
3636 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3637 case ISD::SETLT: Swap = true;
3638 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3639 case ISD::SETLE: Swap = true;
3640 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3641 case ISD::SETULT: Swap = true;
3642 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3643 case ISD::SETULE: Swap = true;
3644 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3647 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3648 if (Opc == ARMISD::VCEQ) {
3651 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3653 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3656 // Ignore bitconvert.
3657 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3658 AndOp = AndOp.getOperand(0);
3660 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3662 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3663 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3670 std::swap(Op0, Op1);
3672 // If one of the operands is a constant vector zero, attempt to fold the
3673 // comparison to a specialized compare-against-zero form.
3675 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3677 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3678 if (Opc == ARMISD::VCGE)
3679 Opc = ARMISD::VCLEZ;
3680 else if (Opc == ARMISD::VCGT)
3681 Opc = ARMISD::VCLTZ;
3686 if (SingleOp.getNode()) {
3689 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3691 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3693 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3695 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3697 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3699 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3702 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3706 Result = DAG.getNOT(dl, Result, VT);
3711 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3712 /// valid vector constant for a NEON instruction with a "modified immediate"
3713 /// operand (e.g., VMOV). If so, return the encoded value.
3714 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3715 unsigned SplatBitSize, SelectionDAG &DAG,
3716 EVT &VT, bool is128Bits, NEONModImmType type) {
3717 unsigned OpCmode, Imm;
3719 // SplatBitSize is set to the smallest size that splats the vector, so a
3720 // zero vector will always have SplatBitSize == 8. However, NEON modified
3721 // immediate instructions others than VMOV do not support the 8-bit encoding
3722 // of a zero vector, and the default encoding of zero is supposed to be the
3727 switch (SplatBitSize) {
3729 if (type != VMOVModImm)
3731 // Any 1-byte value is OK. Op=0, Cmode=1110.
3732 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3735 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3739 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3740 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3741 if ((SplatBits & ~0xff) == 0) {
3742 // Value = 0x00nn: Op=x, Cmode=100x.
3747 if ((SplatBits & ~0xff00) == 0) {
3748 // Value = 0xnn00: Op=x, Cmode=101x.
3750 Imm = SplatBits >> 8;
3756 // NEON's 32-bit VMOV supports splat values where:
3757 // * only one byte is nonzero, or
3758 // * the least significant byte is 0xff and the second byte is nonzero, or
3759 // * the least significant 2 bytes are 0xff and the third is nonzero.
3760 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3761 if ((SplatBits & ~0xff) == 0) {
3762 // Value = 0x000000nn: Op=x, Cmode=000x.
3767 if ((SplatBits & ~0xff00) == 0) {
3768 // Value = 0x0000nn00: Op=x, Cmode=001x.
3770 Imm = SplatBits >> 8;
3773 if ((SplatBits & ~0xff0000) == 0) {
3774 // Value = 0x00nn0000: Op=x, Cmode=010x.
3776 Imm = SplatBits >> 16;
3779 if ((SplatBits & ~0xff000000) == 0) {
3780 // Value = 0xnn000000: Op=x, Cmode=011x.
3782 Imm = SplatBits >> 24;
3786 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3787 if (type == OtherModImm) return SDValue();
3789 if ((SplatBits & ~0xffff) == 0 &&
3790 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3791 // Value = 0x0000nnff: Op=x, Cmode=1100.
3793 Imm = SplatBits >> 8;
3798 if ((SplatBits & ~0xffffff) == 0 &&
3799 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3800 // Value = 0x00nnffff: Op=x, Cmode=1101.
3802 Imm = SplatBits >> 16;
3803 SplatBits |= 0xffff;
3807 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3808 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3809 // VMOV.I32. A (very) minor optimization would be to replicate the value
3810 // and fall through here to test for a valid 64-bit splat. But, then the
3811 // caller would also need to check and handle the change in size.
3815 if (type != VMOVModImm)
3817 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3818 uint64_t BitMask = 0xff;
3820 unsigned ImmMask = 1;
3822 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3823 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3826 } else if ((SplatBits & BitMask) != 0) {
3832 // Op=1, Cmode=1110.
3835 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3840 llvm_unreachable("unexpected size for isNEONModifiedImm");
3843 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3844 return DAG.getTargetConstant(EncodedVal, MVT::i32);
3847 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3848 const ARMSubtarget *ST) const {
3849 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3852 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3853 assert(Op.getValueType() == MVT::f32 &&
3854 "ConstantFP custom lowering should only occur for f32.");
3856 // Try splatting with a VMOV.f32...
3857 APFloat FPVal = CFP->getValueAPF();
3858 int ImmVal = ARM_AM::getFP32Imm(FPVal);
3860 DebugLoc DL = Op.getDebugLoc();
3861 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3862 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3864 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3865 DAG.getConstant(0, MVT::i32));
3868 // If that fails, try a VMOV.i32
3870 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3871 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3873 if (NewVal != SDValue()) {
3874 DebugLoc DL = Op.getDebugLoc();
3875 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3877 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3879 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3880 DAG.getConstant(0, MVT::i32));
3883 // Finally, try a VMVN.i32
3884 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3886 if (NewVal != SDValue()) {
3887 DebugLoc DL = Op.getDebugLoc();
3888 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3889 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3891 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3892 DAG.getConstant(0, MVT::i32));
3899 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3900 bool &ReverseVEXT, unsigned &Imm) {
3901 unsigned NumElts = VT.getVectorNumElements();
3902 ReverseVEXT = false;
3904 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3910 // If this is a VEXT shuffle, the immediate value is the index of the first
3911 // element. The other shuffle indices must be the successive elements after
3913 unsigned ExpectedElt = Imm;
3914 for (unsigned i = 1; i < NumElts; ++i) {
3915 // Increment the expected index. If it wraps around, it may still be
3916 // a VEXT but the source vectors must be swapped.
3918 if (ExpectedElt == NumElts * 2) {
3923 if (M[i] < 0) continue; // ignore UNDEF indices
3924 if (ExpectedElt != static_cast<unsigned>(M[i]))
3928 // Adjust the index value if the source operands will be swapped.
3935 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3936 /// instruction with the specified blocksize. (The order of the elements
3937 /// within each block of the vector is reversed.)
3938 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3939 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3940 "Only possible block sizes for VREV are: 16, 32, 64");
3942 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3946 unsigned NumElts = VT.getVectorNumElements();
3947 unsigned BlockElts = M[0] + 1;
3948 // If the first shuffle index is UNDEF, be optimistic.
3950 BlockElts = BlockSize / EltSz;
3952 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3955 for (unsigned i = 0; i < NumElts; ++i) {
3956 if (M[i] < 0) continue; // ignore UNDEF indices
3957 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3964 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3965 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3966 // range, then 0 is placed into the resulting vector. So pretty much any mask
3967 // of 8 elements can work here.
3968 return VT == MVT::v8i8 && M.size() == 8;
3971 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3972 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3976 unsigned NumElts = VT.getVectorNumElements();
3977 WhichResult = (M[0] == 0 ? 0 : 1);
3978 for (unsigned i = 0; i < NumElts; i += 2) {
3979 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3980 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3986 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3987 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3988 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3989 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3990 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3994 unsigned NumElts = VT.getVectorNumElements();
3995 WhichResult = (M[0] == 0 ? 0 : 1);
3996 for (unsigned i = 0; i < NumElts; i += 2) {
3997 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3998 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4004 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4005 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4009 unsigned NumElts = VT.getVectorNumElements();
4010 WhichResult = (M[0] == 0 ? 0 : 1);
4011 for (unsigned i = 0; i != NumElts; ++i) {
4012 if (M[i] < 0) continue; // ignore UNDEF indices
4013 if ((unsigned) M[i] != 2 * i + WhichResult)
4017 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4018 if (VT.is64BitVector() && EltSz == 32)
4024 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4025 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4026 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4027 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4028 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4032 unsigned Half = VT.getVectorNumElements() / 2;
4033 WhichResult = (M[0] == 0 ? 0 : 1);
4034 for (unsigned j = 0; j != 2; ++j) {
4035 unsigned Idx = WhichResult;
4036 for (unsigned i = 0; i != Half; ++i) {
4037 int MIdx = M[i + j * Half];
4038 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4044 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4045 if (VT.is64BitVector() && EltSz == 32)
4051 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4052 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4056 unsigned NumElts = VT.getVectorNumElements();
4057 WhichResult = (M[0] == 0 ? 0 : 1);
4058 unsigned Idx = WhichResult * NumElts / 2;
4059 for (unsigned i = 0; i != NumElts; i += 2) {
4060 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4061 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4066 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4067 if (VT.is64BitVector() && EltSz == 32)
4073 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4074 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4075 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4076 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4077 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4081 unsigned NumElts = VT.getVectorNumElements();
4082 WhichResult = (M[0] == 0 ? 0 : 1);
4083 unsigned Idx = WhichResult * NumElts / 2;
4084 for (unsigned i = 0; i != NumElts; i += 2) {
4085 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4086 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4091 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4092 if (VT.is64BitVector() && EltSz == 32)
4098 // If N is an integer constant that can be moved into a register in one
4099 // instruction, return an SDValue of such a constant (will become a MOV
4100 // instruction). Otherwise return null.
4101 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4102 const ARMSubtarget *ST, DebugLoc dl) {
4104 if (!isa<ConstantSDNode>(N))
4106 Val = cast<ConstantSDNode>(N)->getZExtValue();
4108 if (ST->isThumb1Only()) {
4109 if (Val <= 255 || ~Val <= 255)
4110 return DAG.getConstant(Val, MVT::i32);
4112 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4113 return DAG.getConstant(Val, MVT::i32);
4118 // If this is a case we can't handle, return null and let the default
4119 // expansion code take care of it.
4120 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4121 const ARMSubtarget *ST) const {
4122 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4123 DebugLoc dl = Op.getDebugLoc();
4124 EVT VT = Op.getValueType();
4126 APInt SplatBits, SplatUndef;
4127 unsigned SplatBitSize;
4129 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4130 if (SplatBitSize <= 64) {
4131 // Check if an immediate VMOV works.
4133 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4134 SplatUndef.getZExtValue(), SplatBitSize,
4135 DAG, VmovVT, VT.is128BitVector(),
4137 if (Val.getNode()) {
4138 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4139 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4142 // Try an immediate VMVN.
4143 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4144 Val = isNEONModifiedImm(NegatedImm,
4145 SplatUndef.getZExtValue(), SplatBitSize,
4146 DAG, VmovVT, VT.is128BitVector(),
4148 if (Val.getNode()) {
4149 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4150 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4153 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4154 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4155 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4157 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4158 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4164 // Scan through the operands to see if only one value is used.
4165 unsigned NumElts = VT.getVectorNumElements();
4166 bool isOnlyLowElement = true;
4167 bool usesOnlyOneValue = true;
4168 bool isConstant = true;
4170 for (unsigned i = 0; i < NumElts; ++i) {
4171 SDValue V = Op.getOperand(i);
4172 if (V.getOpcode() == ISD::UNDEF)
4175 isOnlyLowElement = false;
4176 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4179 if (!Value.getNode())
4181 else if (V != Value)
4182 usesOnlyOneValue = false;
4185 if (!Value.getNode())
4186 return DAG.getUNDEF(VT);
4188 if (isOnlyLowElement)
4189 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4191 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4193 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4194 // i32 and try again.
4195 if (usesOnlyOneValue && EltSize <= 32) {
4197 return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4198 if (VT.getVectorElementType().isFloatingPoint()) {
4199 SmallVector<SDValue, 8> Ops;
4200 for (unsigned i = 0; i < NumElts; ++i)
4201 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4203 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4204 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4205 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4207 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4209 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4211 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4214 // If all elements are constants and the case above didn't get hit, fall back
4215 // to the default expansion, which will generate a load from the constant
4220 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4222 SDValue shuffle = ReconstructShuffle(Op, DAG);
4223 if (shuffle != SDValue())
4227 // Vectors with 32- or 64-bit elements can be built by directly assigning
4228 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4229 // will be legalized.
4230 if (EltSize >= 32) {
4231 // Do the expansion with floating-point types, since that is what the VFP
4232 // registers are defined to use, and since i64 is not legal.
4233 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4234 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4235 SmallVector<SDValue, 8> Ops;
4236 for (unsigned i = 0; i < NumElts; ++i)
4237 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4238 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4239 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4245 // Gather data to see if the operation can be modelled as a
4246 // shuffle in combination with VEXTs.
4247 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4248 SelectionDAG &DAG) const {
4249 DebugLoc dl = Op.getDebugLoc();
4250 EVT VT = Op.getValueType();
4251 unsigned NumElts = VT.getVectorNumElements();
4253 SmallVector<SDValue, 2> SourceVecs;
4254 SmallVector<unsigned, 2> MinElts;
4255 SmallVector<unsigned, 2> MaxElts;
4257 for (unsigned i = 0; i < NumElts; ++i) {
4258 SDValue V = Op.getOperand(i);
4259 if (V.getOpcode() == ISD::UNDEF)
4261 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4262 // A shuffle can only come from building a vector from various
4263 // elements of other vectors.
4265 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4266 VT.getVectorElementType()) {
4267 // This code doesn't know how to handle shuffles where the vector
4268 // element types do not match (this happens because type legalization
4269 // promotes the return type of EXTRACT_VECTOR_ELT).
4270 // FIXME: It might be appropriate to extend this code to handle
4271 // mismatched types.
4275 // Record this extraction against the appropriate vector if possible...
4276 SDValue SourceVec = V.getOperand(0);
4277 // If the element number isn't a constant, we can't effectively
4278 // analyze what's going on.
4279 if (!isa<ConstantSDNode>(V.getOperand(1)))
4281 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4282 bool FoundSource = false;
4283 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4284 if (SourceVecs[j] == SourceVec) {
4285 if (MinElts[j] > EltNo)
4287 if (MaxElts[j] < EltNo)
4294 // Or record a new source if not...
4296 SourceVecs.push_back(SourceVec);
4297 MinElts.push_back(EltNo);
4298 MaxElts.push_back(EltNo);
4302 // Currently only do something sane when at most two source vectors
4304 if (SourceVecs.size() > 2)
4307 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4308 int VEXTOffsets[2] = {0, 0};
4310 // This loop extracts the usage patterns of the source vectors
4311 // and prepares appropriate SDValues for a shuffle if possible.
4312 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4313 if (SourceVecs[i].getValueType() == VT) {
4314 // No VEXT necessary
4315 ShuffleSrcs[i] = SourceVecs[i];
4318 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4319 // It probably isn't worth padding out a smaller vector just to
4320 // break it down again in a shuffle.
4324 // Since only 64-bit and 128-bit vectors are legal on ARM and
4325 // we've eliminated the other cases...
4326 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4327 "unexpected vector sizes in ReconstructShuffle");
4329 if (MaxElts[i] - MinElts[i] >= NumElts) {
4330 // Span too large for a VEXT to cope
4334 if (MinElts[i] >= NumElts) {
4335 // The extraction can just take the second half
4336 VEXTOffsets[i] = NumElts;
4337 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4339 DAG.getIntPtrConstant(NumElts));
4340 } else if (MaxElts[i] < NumElts) {
4341 // The extraction can just take the first half
4343 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4345 DAG.getIntPtrConstant(0));
4347 // An actual VEXT is needed
4348 VEXTOffsets[i] = MinElts[i];
4349 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4351 DAG.getIntPtrConstant(0));
4352 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4354 DAG.getIntPtrConstant(NumElts));
4355 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4356 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4360 SmallVector<int, 8> Mask;
4362 for (unsigned i = 0; i < NumElts; ++i) {
4363 SDValue Entry = Op.getOperand(i);
4364 if (Entry.getOpcode() == ISD::UNDEF) {
4369 SDValue ExtractVec = Entry.getOperand(0);
4370 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4371 .getOperand(1))->getSExtValue();
4372 if (ExtractVec == SourceVecs[0]) {
4373 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4375 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4379 // Final check before we try to produce nonsense...
4380 if (isShuffleMaskLegal(Mask, VT))
4381 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4387 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4388 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4389 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4390 /// are assumed to be legal.
4392 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4394 if (VT.getVectorNumElements() == 4 &&
4395 (VT.is128BitVector() || VT.is64BitVector())) {
4396 unsigned PFIndexes[4];
4397 for (unsigned i = 0; i != 4; ++i) {
4401 PFIndexes[i] = M[i];
4404 // Compute the index in the perfect shuffle table.
4405 unsigned PFTableIndex =
4406 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4407 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4408 unsigned Cost = (PFEntry >> 30);
4415 unsigned Imm, WhichResult;
4417 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4418 return (EltSize >= 32 ||
4419 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4420 isVREVMask(M, VT, 64) ||
4421 isVREVMask(M, VT, 32) ||
4422 isVREVMask(M, VT, 16) ||
4423 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4424 isVTBLMask(M, VT) ||
4425 isVTRNMask(M, VT, WhichResult) ||
4426 isVUZPMask(M, VT, WhichResult) ||
4427 isVZIPMask(M, VT, WhichResult) ||
4428 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4429 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4430 isVZIP_v_undef_Mask(M, VT, WhichResult));
4433 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4434 /// the specified operations to build the shuffle.
4435 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4436 SDValue RHS, SelectionDAG &DAG,
4438 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4439 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4440 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4443 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4452 OP_VUZPL, // VUZP, left result
4453 OP_VUZPR, // VUZP, right result
4454 OP_VZIPL, // VZIP, left result
4455 OP_VZIPR, // VZIP, right result
4456 OP_VTRNL, // VTRN, left result
4457 OP_VTRNR // VTRN, right result
4460 if (OpNum == OP_COPY) {
4461 if (LHSID == (1*9+2)*9+3) return LHS;
4462 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4466 SDValue OpLHS, OpRHS;
4467 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4468 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4469 EVT VT = OpLHS.getValueType();
4472 default: llvm_unreachable("Unknown shuffle opcode!");
4474 // VREV divides the vector in half and swaps within the half.
4475 if (VT.getVectorElementType() == MVT::i32 ||
4476 VT.getVectorElementType() == MVT::f32)
4477 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4478 // vrev <4 x i16> -> VREV32
4479 if (VT.getVectorElementType() == MVT::i16)
4480 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4481 // vrev <4 x i8> -> VREV16
4482 assert(VT.getVectorElementType() == MVT::i8);
4483 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4488 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4489 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4493 return DAG.getNode(ARMISD::VEXT, dl, VT,
4495 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4498 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4499 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4502 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4503 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4506 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4507 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4511 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4512 ArrayRef<int> ShuffleMask,
4513 SelectionDAG &DAG) {
4514 // Check to see if we can use the VTBL instruction.
4515 SDValue V1 = Op.getOperand(0);
4516 SDValue V2 = Op.getOperand(1);
4517 DebugLoc DL = Op.getDebugLoc();
4519 SmallVector<SDValue, 8> VTBLMask;
4520 for (ArrayRef<int>::iterator
4521 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4522 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4524 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4525 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4526 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4529 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4530 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4534 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4535 SDValue V1 = Op.getOperand(0);
4536 SDValue V2 = Op.getOperand(1);
4537 DebugLoc dl = Op.getDebugLoc();
4538 EVT VT = Op.getValueType();
4539 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4541 // Convert shuffles that are directly supported on NEON to target-specific
4542 // DAG nodes, instead of keeping them as shuffles and matching them again
4543 // during code selection. This is more efficient and avoids the possibility
4544 // of inconsistencies between legalization and selection.
4545 // FIXME: floating-point vectors should be canonicalized to integer vectors
4546 // of the same time so that they get CSEd properly.
4547 ArrayRef<int> ShuffleMask = SVN->getMask();
4549 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4550 if (EltSize <= 32) {
4551 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4552 int Lane = SVN->getSplatIndex();
4553 // If this is undef splat, generate it via "just" vdup, if possible.
4554 if (Lane == -1) Lane = 0;
4556 // Test if V1 is a SCALAR_TO_VECTOR.
4557 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4558 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4560 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4561 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4563 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4564 !isa<ConstantSDNode>(V1.getOperand(0))) {
4565 bool IsScalarToVector = true;
4566 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4567 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4568 IsScalarToVector = false;
4571 if (IsScalarToVector)
4572 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4574 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4575 DAG.getConstant(Lane, MVT::i32));
4580 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4583 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4584 DAG.getConstant(Imm, MVT::i32));
4587 if (isVREVMask(ShuffleMask, VT, 64))
4588 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4589 if (isVREVMask(ShuffleMask, VT, 32))
4590 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4591 if (isVREVMask(ShuffleMask, VT, 16))
4592 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4594 // Check for Neon shuffles that modify both input vectors in place.
4595 // If both results are used, i.e., if there are two shuffles with the same
4596 // source operands and with masks corresponding to both results of one of
4597 // these operations, DAG memoization will ensure that a single node is
4598 // used for both shuffles.
4599 unsigned WhichResult;
4600 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4601 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4602 V1, V2).getValue(WhichResult);
4603 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4604 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4605 V1, V2).getValue(WhichResult);
4606 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4607 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4608 V1, V2).getValue(WhichResult);
4610 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4611 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4612 V1, V1).getValue(WhichResult);
4613 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4614 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4615 V1, V1).getValue(WhichResult);
4616 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4617 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4618 V1, V1).getValue(WhichResult);
4621 // If the shuffle is not directly supported and it has 4 elements, use
4622 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4623 unsigned NumElts = VT.getVectorNumElements();
4625 unsigned PFIndexes[4];
4626 for (unsigned i = 0; i != 4; ++i) {
4627 if (ShuffleMask[i] < 0)
4630 PFIndexes[i] = ShuffleMask[i];
4633 // Compute the index in the perfect shuffle table.
4634 unsigned PFTableIndex =
4635 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4636 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4637 unsigned Cost = (PFEntry >> 30);
4640 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4643 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4644 if (EltSize >= 32) {
4645 // Do the expansion with floating-point types, since that is what the VFP
4646 // registers are defined to use, and since i64 is not legal.
4647 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4648 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4649 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4650 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4651 SmallVector<SDValue, 8> Ops;
4652 for (unsigned i = 0; i < NumElts; ++i) {
4653 if (ShuffleMask[i] < 0)
4654 Ops.push_back(DAG.getUNDEF(EltVT));
4656 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4657 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4658 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4661 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4662 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4665 if (VT == MVT::v8i8) {
4666 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4667 if (NewOp.getNode())
4674 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4675 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4676 SDValue Lane = Op.getOperand(2);
4677 if (!isa<ConstantSDNode>(Lane))
4683 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4684 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4685 SDValue Lane = Op.getOperand(1);
4686 if (!isa<ConstantSDNode>(Lane))
4689 SDValue Vec = Op.getOperand(0);
4690 if (Op.getValueType() == MVT::i32 &&
4691 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4692 DebugLoc dl = Op.getDebugLoc();
4693 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4699 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4700 // The only time a CONCAT_VECTORS operation can have legal types is when
4701 // two 64-bit vectors are concatenated to a 128-bit vector.
4702 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4703 "unexpected CONCAT_VECTORS");
4704 DebugLoc dl = Op.getDebugLoc();
4705 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4706 SDValue Op0 = Op.getOperand(0);
4707 SDValue Op1 = Op.getOperand(1);
4708 if (Op0.getOpcode() != ISD::UNDEF)
4709 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4710 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4711 DAG.getIntPtrConstant(0));
4712 if (Op1.getOpcode() != ISD::UNDEF)
4713 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4714 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4715 DAG.getIntPtrConstant(1));
4716 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4719 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4720 /// element has been zero/sign-extended, depending on the isSigned parameter,
4721 /// from an integer type half its size.
4722 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4724 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4725 EVT VT = N->getValueType(0);
4726 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4727 SDNode *BVN = N->getOperand(0).getNode();
4728 if (BVN->getValueType(0) != MVT::v4i32 ||
4729 BVN->getOpcode() != ISD::BUILD_VECTOR)
4731 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4732 unsigned HiElt = 1 - LoElt;
4733 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4734 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4735 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4736 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4737 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4740 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4741 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4744 if (Hi0->isNullValue() && Hi1->isNullValue())
4750 if (N->getOpcode() != ISD::BUILD_VECTOR)
4753 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4754 SDNode *Elt = N->getOperand(i).getNode();
4755 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4756 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4757 unsigned HalfSize = EltSize / 2;
4759 if (!isIntN(HalfSize, C->getSExtValue()))
4762 if (!isUIntN(HalfSize, C->getZExtValue()))
4773 /// isSignExtended - Check if a node is a vector value that is sign-extended
4774 /// or a constant BUILD_VECTOR with sign-extended elements.
4775 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4776 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4778 if (isExtendedBUILD_VECTOR(N, DAG, true))
4783 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4784 /// or a constant BUILD_VECTOR with zero-extended elements.
4785 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4786 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4788 if (isExtendedBUILD_VECTOR(N, DAG, false))
4793 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4794 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4795 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4796 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4797 return N->getOperand(0);
4798 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4799 return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4800 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4801 LD->isNonTemporal(), LD->isInvariant(),
4802 LD->getAlignment());
4803 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
4804 // have been legalized as a BITCAST from v4i32.
4805 if (N->getOpcode() == ISD::BITCAST) {
4806 SDNode *BVN = N->getOperand(0).getNode();
4807 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4808 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4809 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4810 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4811 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4813 // Construct a new BUILD_VECTOR with elements truncated to half the size.
4814 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4815 EVT VT = N->getValueType(0);
4816 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4817 unsigned NumElts = VT.getVectorNumElements();
4818 MVT TruncVT = MVT::getIntegerVT(EltSize);
4819 SmallVector<SDValue, 8> Ops;
4820 for (unsigned i = 0; i != NumElts; ++i) {
4821 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4822 const APInt &CInt = C->getAPIntValue();
4823 // Element types smaller than 32 bits are not legal, so use i32 elements.
4824 // The values are implicitly truncated so sext vs. zext doesn't matter.
4825 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4827 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4828 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4831 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4832 unsigned Opcode = N->getOpcode();
4833 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4834 SDNode *N0 = N->getOperand(0).getNode();
4835 SDNode *N1 = N->getOperand(1).getNode();
4836 return N0->hasOneUse() && N1->hasOneUse() &&
4837 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4842 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4843 unsigned Opcode = N->getOpcode();
4844 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4845 SDNode *N0 = N->getOperand(0).getNode();
4846 SDNode *N1 = N->getOperand(1).getNode();
4847 return N0->hasOneUse() && N1->hasOneUse() &&
4848 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4853 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4854 // Multiplications are only custom-lowered for 128-bit vectors so that
4855 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
4856 EVT VT = Op.getValueType();
4857 assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4858 SDNode *N0 = Op.getOperand(0).getNode();
4859 SDNode *N1 = Op.getOperand(1).getNode();
4860 unsigned NewOpc = 0;
4862 bool isN0SExt = isSignExtended(N0, DAG);
4863 bool isN1SExt = isSignExtended(N1, DAG);
4864 if (isN0SExt && isN1SExt)
4865 NewOpc = ARMISD::VMULLs;
4867 bool isN0ZExt = isZeroExtended(N0, DAG);
4868 bool isN1ZExt = isZeroExtended(N1, DAG);
4869 if (isN0ZExt && isN1ZExt)
4870 NewOpc = ARMISD::VMULLu;
4871 else if (isN1SExt || isN1ZExt) {
4872 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4873 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4874 if (isN1SExt && isAddSubSExt(N0, DAG)) {
4875 NewOpc = ARMISD::VMULLs;
4877 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4878 NewOpc = ARMISD::VMULLu;
4880 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4882 NewOpc = ARMISD::VMULLu;
4888 if (VT == MVT::v2i64)
4889 // Fall through to expand this. It is not legal.
4892 // Other vector multiplications are legal.
4897 // Legalize to a VMULL instruction.
4898 DebugLoc DL = Op.getDebugLoc();
4900 SDValue Op1 = SkipExtension(N1, DAG);
4902 Op0 = SkipExtension(N0, DAG);
4903 assert(Op0.getValueType().is64BitVector() &&
4904 Op1.getValueType().is64BitVector() &&
4905 "unexpected types for extended operands to VMULL");
4906 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4909 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4910 // isel lowering to take advantage of no-stall back to back vmul + vmla.
4917 SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4918 SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4919 EVT Op1VT = Op1.getValueType();
4920 return DAG.getNode(N0->getOpcode(), DL, VT,
4921 DAG.getNode(NewOpc, DL, VT,
4922 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4923 DAG.getNode(NewOpc, DL, VT,
4924 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4928 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4930 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4931 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4932 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4933 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4934 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4935 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4936 // Get reciprocal estimate.
4937 // float4 recip = vrecpeq_f32(yf);
4938 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4939 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4940 // Because char has a smaller range than uchar, we can actually get away
4941 // without any newton steps. This requires that we use a weird bias
4942 // of 0xb000, however (again, this has been exhaustively tested).
4943 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4944 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4945 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4946 Y = DAG.getConstant(0xb000, MVT::i32);
4947 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4948 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4949 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4950 // Convert back to short.
4951 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4952 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4957 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4959 // Convert to float.
4960 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4961 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4962 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4963 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4964 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4965 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4967 // Use reciprocal estimate and one refinement step.
4968 // float4 recip = vrecpeq_f32(yf);
4969 // recip *= vrecpsq_f32(yf, recip);
4970 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4971 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4972 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4973 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4975 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4976 // Because short has a smaller range than ushort, we can actually get away
4977 // with only a single newton step. This requires that we use a weird bias
4978 // of 89, however (again, this has been exhaustively tested).
4979 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4980 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4981 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4982 N1 = DAG.getConstant(0x89, MVT::i32);
4983 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4984 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4985 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4986 // Convert back to integer and return.
4987 // return vmovn_s32(vcvt_s32_f32(result));
4988 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4989 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4993 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4994 EVT VT = Op.getValueType();
4995 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4996 "unexpected type for custom-lowering ISD::SDIV");
4998 DebugLoc dl = Op.getDebugLoc();
4999 SDValue N0 = Op.getOperand(0);
5000 SDValue N1 = Op.getOperand(1);
5003 if (VT == MVT::v8i8) {
5004 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5005 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5007 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5008 DAG.getIntPtrConstant(4));
5009 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5010 DAG.getIntPtrConstant(4));
5011 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5012 DAG.getIntPtrConstant(0));
5013 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5014 DAG.getIntPtrConstant(0));
5016 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5017 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5019 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5020 N0 = LowerCONCAT_VECTORS(N0, DAG);
5022 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5025 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5028 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5029 EVT VT = Op.getValueType();
5030 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5031 "unexpected type for custom-lowering ISD::UDIV");
5033 DebugLoc dl = Op.getDebugLoc();
5034 SDValue N0 = Op.getOperand(0);
5035 SDValue N1 = Op.getOperand(1);
5038 if (VT == MVT::v8i8) {
5039 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5040 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5042 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5043 DAG.getIntPtrConstant(4));
5044 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5045 DAG.getIntPtrConstant(4));
5046 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5047 DAG.getIntPtrConstant(0));
5048 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5049 DAG.getIntPtrConstant(0));
5051 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5052 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5054 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5055 N0 = LowerCONCAT_VECTORS(N0, DAG);
5057 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5058 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5063 // v4i16 sdiv ... Convert to float.
5064 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5065 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5066 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5067 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5068 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5069 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5071 // Use reciprocal estimate and two refinement steps.
5072 // float4 recip = vrecpeq_f32(yf);
5073 // recip *= vrecpsq_f32(yf, recip);
5074 // recip *= vrecpsq_f32(yf, recip);
5075 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5076 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5077 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5078 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5080 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5081 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5082 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5084 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5085 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5086 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5087 // and that it will never cause us to return an answer too large).
5088 // float4 result = as_float4(as_int4(xf*recip) + 2);
5089 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5090 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5091 N1 = DAG.getConstant(2, MVT::i32);
5092 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5093 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5094 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5095 // Convert back to integer and return.
5096 // return vmovn_u32(vcvt_s32_f32(result));
5097 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5098 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5102 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5103 EVT VT = Op.getNode()->getValueType(0);
5104 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5107 bool ExtraOp = false;
5108 switch (Op.getOpcode()) {
5109 default: llvm_unreachable("Invalid code");
5110 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5111 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5112 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5113 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5117 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5119 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5120 Op.getOperand(1), Op.getOperand(2));
5123 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5124 // Monotonic load/store is legal for all targets
5125 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5128 // Aquire/Release load/store is not legal for targets without a
5129 // dmb or equivalent available.
5135 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5136 SelectionDAG &DAG, unsigned NewOp) {
5137 DebugLoc dl = Node->getDebugLoc();
5138 assert (Node->getValueType(0) == MVT::i64 &&
5139 "Only know how to expand i64 atomics");
5141 SmallVector<SDValue, 6> Ops;
5142 Ops.push_back(Node->getOperand(0)); // Chain
5143 Ops.push_back(Node->getOperand(1)); // Ptr
5145 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5146 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5147 // High part of Val1
5148 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5149 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5150 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5151 // High part of Val1
5152 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5153 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5154 // High part of Val2
5155 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5156 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5158 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5160 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5161 cast<MemSDNode>(Node)->getMemOperand());
5162 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5163 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5164 Results.push_back(Result.getValue(2));
5167 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5168 switch (Op.getOpcode()) {
5169 default: llvm_unreachable("Don't know how to custom lower this!");
5170 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5171 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5172 case ISD::GlobalAddress:
5173 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5174 LowerGlobalAddressELF(Op, DAG);
5175 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5176 case ISD::SELECT: return LowerSELECT(Op, DAG);
5177 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5178 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5179 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5180 case ISD::VASTART: return LowerVASTART(Op, DAG);
5181 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5182 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5183 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5184 case ISD::SINT_TO_FP:
5185 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5186 case ISD::FP_TO_SINT:
5187 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5188 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5189 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5190 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5191 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5192 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5193 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5194 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5196 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5199 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5200 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5201 case ISD::SRL_PARTS:
5202 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5203 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5204 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5205 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5206 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5207 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5208 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5209 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5210 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5211 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5212 case ISD::MUL: return LowerMUL(Op, DAG);
5213 case ISD::SDIV: return LowerSDIV(Op, DAG);
5214 case ISD::UDIV: return LowerUDIV(Op, DAG);
5218 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5219 case ISD::ATOMIC_LOAD:
5220 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5224 /// ReplaceNodeResults - Replace the results of node with an illegal result
5225 /// type with new values built out of custom code.
5226 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5227 SmallVectorImpl<SDValue>&Results,
5228 SelectionDAG &DAG) const {
5230 switch (N->getOpcode()) {
5232 llvm_unreachable("Don't know how to custom expand this!");
5234 Res = ExpandBITCAST(N, DAG);
5238 Res = Expand64BitShift(N, DAG, Subtarget);
5240 case ISD::ATOMIC_LOAD_ADD:
5241 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5243 case ISD::ATOMIC_LOAD_AND:
5244 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5246 case ISD::ATOMIC_LOAD_NAND:
5247 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5249 case ISD::ATOMIC_LOAD_OR:
5250 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5252 case ISD::ATOMIC_LOAD_SUB:
5253 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5255 case ISD::ATOMIC_LOAD_XOR:
5256 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5258 case ISD::ATOMIC_SWAP:
5259 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5261 case ISD::ATOMIC_CMP_SWAP:
5262 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5266 Results.push_back(Res);
5269 //===----------------------------------------------------------------------===//
5270 // ARM Scheduler Hooks
5271 //===----------------------------------------------------------------------===//
5274 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5275 MachineBasicBlock *BB,
5276 unsigned Size) const {
5277 unsigned dest = MI->getOperand(0).getReg();
5278 unsigned ptr = MI->getOperand(1).getReg();
5279 unsigned oldval = MI->getOperand(2).getReg();
5280 unsigned newval = MI->getOperand(3).getReg();
5281 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5282 DebugLoc dl = MI->getDebugLoc();
5283 bool isThumb2 = Subtarget->isThumb2();
5285 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5286 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5287 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5288 (const TargetRegisterClass*)&ARM::GPRRegClass);
5291 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5292 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5293 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5296 unsigned ldrOpc, strOpc;
5298 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5300 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5301 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5304 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5305 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5308 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5309 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5313 MachineFunction *MF = BB->getParent();
5314 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5315 MachineFunction::iterator It = BB;
5316 ++It; // insert the new blocks after the current block
5318 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5319 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5320 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5321 MF->insert(It, loop1MBB);
5322 MF->insert(It, loop2MBB);
5323 MF->insert(It, exitMBB);
5325 // Transfer the remainder of BB and its successor edges to exitMBB.
5326 exitMBB->splice(exitMBB->begin(), BB,
5327 llvm::next(MachineBasicBlock::iterator(MI)),
5329 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5333 // fallthrough --> loop1MBB
5334 BB->addSuccessor(loop1MBB);
5337 // ldrex dest, [ptr]
5341 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5342 if (ldrOpc == ARM::t2LDREX)
5344 AddDefaultPred(MIB);
5345 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5346 .addReg(dest).addReg(oldval));
5347 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5348 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5349 BB->addSuccessor(loop2MBB);
5350 BB->addSuccessor(exitMBB);
5353 // strex scratch, newval, [ptr]
5357 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5358 if (strOpc == ARM::t2STREX)
5360 AddDefaultPred(MIB);
5361 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5362 .addReg(scratch).addImm(0));
5363 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5364 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5365 BB->addSuccessor(loop1MBB);
5366 BB->addSuccessor(exitMBB);
5372 MI->eraseFromParent(); // The instruction is gone now.
5378 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5379 unsigned Size, unsigned BinOpcode) const {
5380 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5381 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5383 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5384 MachineFunction *MF = BB->getParent();
5385 MachineFunction::iterator It = BB;
5388 unsigned dest = MI->getOperand(0).getReg();
5389 unsigned ptr = MI->getOperand(1).getReg();
5390 unsigned incr = MI->getOperand(2).getReg();
5391 DebugLoc dl = MI->getDebugLoc();
5392 bool isThumb2 = Subtarget->isThumb2();
5394 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5396 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5397 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5400 unsigned ldrOpc, strOpc;
5402 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5404 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5405 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5408 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5409 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5412 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5413 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5417 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5418 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5419 MF->insert(It, loopMBB);
5420 MF->insert(It, exitMBB);
5422 // Transfer the remainder of BB and its successor edges to exitMBB.
5423 exitMBB->splice(exitMBB->begin(), BB,
5424 llvm::next(MachineBasicBlock::iterator(MI)),
5426 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5428 const TargetRegisterClass *TRC = isThumb2 ?
5429 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5430 (const TargetRegisterClass*)&ARM::GPRRegClass;
5431 unsigned scratch = MRI.createVirtualRegister(TRC);
5432 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5436 // fallthrough --> loopMBB
5437 BB->addSuccessor(loopMBB);
5441 // <binop> scratch2, dest, incr
5442 // strex scratch, scratch2, ptr
5445 // fallthrough --> exitMBB
5447 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5448 if (ldrOpc == ARM::t2LDREX)
5450 AddDefaultPred(MIB);
5452 // operand order needs to go the other way for NAND
5453 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5454 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5455 addReg(incr).addReg(dest)).addReg(0);
5457 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5458 addReg(dest).addReg(incr)).addReg(0);
5461 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5462 if (strOpc == ARM::t2STREX)
5464 AddDefaultPred(MIB);
5465 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5466 .addReg(scratch).addImm(0));
5467 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5468 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5470 BB->addSuccessor(loopMBB);
5471 BB->addSuccessor(exitMBB);
5477 MI->eraseFromParent(); // The instruction is gone now.
5483 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5484 MachineBasicBlock *BB,
5487 ARMCC::CondCodes Cond) const {
5488 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5490 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5491 MachineFunction *MF = BB->getParent();
5492 MachineFunction::iterator It = BB;
5495 unsigned dest = MI->getOperand(0).getReg();
5496 unsigned ptr = MI->getOperand(1).getReg();
5497 unsigned incr = MI->getOperand(2).getReg();
5498 unsigned oldval = dest;
5499 DebugLoc dl = MI->getDebugLoc();
5500 bool isThumb2 = Subtarget->isThumb2();
5502 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5504 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5505 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5508 unsigned ldrOpc, strOpc, extendOpc;
5510 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5512 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5513 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5514 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5517 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5518 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5519 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5522 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5523 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5528 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5529 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5530 MF->insert(It, loopMBB);
5531 MF->insert(It, exitMBB);
5533 // Transfer the remainder of BB and its successor edges to exitMBB.
5534 exitMBB->splice(exitMBB->begin(), BB,
5535 llvm::next(MachineBasicBlock::iterator(MI)),
5537 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5539 const TargetRegisterClass *TRC = isThumb2 ?
5540 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5541 (const TargetRegisterClass*)&ARM::GPRRegClass;
5542 unsigned scratch = MRI.createVirtualRegister(TRC);
5543 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5547 // fallthrough --> loopMBB
5548 BB->addSuccessor(loopMBB);
5552 // (sign extend dest, if required)
5554 // cmov.cond scratch2, dest, incr
5555 // strex scratch, scratch2, ptr
5558 // fallthrough --> exitMBB
5560 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5561 if (ldrOpc == ARM::t2LDREX)
5563 AddDefaultPred(MIB);
5565 // Sign extend the value, if necessary.
5566 if (signExtend && extendOpc) {
5567 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5568 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5573 // Build compare and cmov instructions.
5574 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5575 .addReg(oldval).addReg(incr));
5576 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5577 .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5579 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5580 if (strOpc == ARM::t2STREX)
5582 AddDefaultPred(MIB);
5583 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5584 .addReg(scratch).addImm(0));
5585 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5586 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5588 BB->addSuccessor(loopMBB);
5589 BB->addSuccessor(exitMBB);
5595 MI->eraseFromParent(); // The instruction is gone now.
5601 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5602 unsigned Op1, unsigned Op2,
5603 bool NeedsCarry, bool IsCmpxchg) const {
5604 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5605 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5607 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5608 MachineFunction *MF = BB->getParent();
5609 MachineFunction::iterator It = BB;
5612 unsigned destlo = MI->getOperand(0).getReg();
5613 unsigned desthi = MI->getOperand(1).getReg();
5614 unsigned ptr = MI->getOperand(2).getReg();
5615 unsigned vallo = MI->getOperand(3).getReg();
5616 unsigned valhi = MI->getOperand(4).getReg();
5617 DebugLoc dl = MI->getDebugLoc();
5618 bool isThumb2 = Subtarget->isThumb2();
5620 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5622 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5623 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5624 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5627 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5628 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5630 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5631 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5633 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5634 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5636 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5637 MF->insert(It, loopMBB);
5639 MF->insert(It, contBB);
5640 MF->insert(It, cont2BB);
5642 MF->insert(It, exitMBB);
5644 // Transfer the remainder of BB and its successor edges to exitMBB.
5645 exitMBB->splice(exitMBB->begin(), BB,
5646 llvm::next(MachineBasicBlock::iterator(MI)),
5648 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5650 const TargetRegisterClass *TRC = isThumb2 ?
5651 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5652 (const TargetRegisterClass*)&ARM::GPRRegClass;
5653 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5657 // fallthrough --> loopMBB
5658 BB->addSuccessor(loopMBB);
5661 // ldrexd r2, r3, ptr
5662 // <binopa> r0, r2, incr
5663 // <binopb> r1, r3, incr
5664 // strexd storesuccess, r0, r1, ptr
5665 // cmp storesuccess, #0
5667 // fallthrough --> exitMBB
5669 // Note that the registers are explicitly specified because there is not any
5670 // way to force the register allocator to allocate a register pair.
5672 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5673 // need to properly enforce the restriction that the two output registers
5674 // for ldrexd must be different.
5677 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5678 .addReg(ARM::R2, RegState::Define)
5679 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5680 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
5681 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5682 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5686 for (unsigned i = 0; i < 2; i++) {
5687 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5689 .addReg(i == 0 ? destlo : desthi)
5690 .addReg(i == 0 ? vallo : valhi));
5691 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5692 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5693 BB->addSuccessor(exitMBB);
5694 BB->addSuccessor(i == 0 ? contBB : cont2BB);
5695 BB = (i == 0 ? contBB : cont2BB);
5698 // Copy to physregs for strexd
5699 unsigned setlo = MI->getOperand(5).getReg();
5700 unsigned sethi = MI->getOperand(6).getReg();
5701 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5702 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5704 // Perform binary operation
5705 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5706 .addReg(destlo).addReg(vallo))
5707 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5708 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5709 .addReg(desthi).addReg(valhi)).addReg(0);
5711 // Copy to physregs for strexd
5712 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5713 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5717 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5718 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5720 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5721 .addReg(storesuccess).addImm(0));
5722 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5723 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5725 BB->addSuccessor(loopMBB);
5726 BB->addSuccessor(exitMBB);
5732 MI->eraseFromParent(); // The instruction is gone now.
5737 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5738 /// registers the function context.
5739 void ARMTargetLowering::
5740 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5741 MachineBasicBlock *DispatchBB, int FI) const {
5742 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5743 DebugLoc dl = MI->getDebugLoc();
5744 MachineFunction *MF = MBB->getParent();
5745 MachineRegisterInfo *MRI = &MF->getRegInfo();
5746 MachineConstantPool *MCP = MF->getConstantPool();
5747 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5748 const Function *F = MF->getFunction();
5750 bool isThumb = Subtarget->isThumb();
5751 bool isThumb2 = Subtarget->isThumb2();
5753 unsigned PCLabelId = AFI->createPICLabelUId();
5754 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5755 ARMConstantPoolValue *CPV =
5756 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5757 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5759 const TargetRegisterClass *TRC = isThumb ?
5760 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5761 (const TargetRegisterClass*)&ARM::GPRRegClass;
5763 // Grab constant pool and fixed stack memory operands.
5764 MachineMemOperand *CPMMO =
5765 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5766 MachineMemOperand::MOLoad, 4, 4);
5768 MachineMemOperand *FIMMOSt =
5769 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5770 MachineMemOperand::MOStore, 4, 4);
5772 // Load the address of the dispatch MBB into the jump buffer.
5774 // Incoming value: jbuf
5775 // ldr.n r5, LCPI1_1
5778 // str r5, [$jbuf, #+4] ; &jbuf[1]
5779 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5780 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5781 .addConstantPoolIndex(CPI)
5782 .addMemOperand(CPMMO));
5783 // Set the low bit because of thumb mode.
5784 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5786 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5787 .addReg(NewVReg1, RegState::Kill)
5789 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5790 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5791 .addReg(NewVReg2, RegState::Kill)
5793 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5794 .addReg(NewVReg3, RegState::Kill)
5796 .addImm(36) // &jbuf[1] :: pc
5797 .addMemOperand(FIMMOSt));
5798 } else if (isThumb) {
5799 // Incoming value: jbuf
5800 // ldr.n r1, LCPI1_4
5804 // add r2, $jbuf, #+4 ; &jbuf[1]
5806 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5807 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5808 .addConstantPoolIndex(CPI)
5809 .addMemOperand(CPMMO));
5810 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5811 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5812 .addReg(NewVReg1, RegState::Kill)
5814 // Set the low bit because of thumb mode.
5815 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5816 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5817 .addReg(ARM::CPSR, RegState::Define)
5819 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5820 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5821 .addReg(ARM::CPSR, RegState::Define)
5822 .addReg(NewVReg2, RegState::Kill)
5823 .addReg(NewVReg3, RegState::Kill));
5824 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5825 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5827 .addImm(36)); // &jbuf[1] :: pc
5828 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5829 .addReg(NewVReg4, RegState::Kill)
5830 .addReg(NewVReg5, RegState::Kill)
5832 .addMemOperand(FIMMOSt));
5834 // Incoming value: jbuf
5837 // str r1, [$jbuf, #+4] ; &jbuf[1]
5838 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5839 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
5840 .addConstantPoolIndex(CPI)
5842 .addMemOperand(CPMMO));
5843 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5844 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5845 .addReg(NewVReg1, RegState::Kill)
5846 .addImm(PCLabelId));
5847 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5848 .addReg(NewVReg2, RegState::Kill)
5850 .addImm(36) // &jbuf[1] :: pc
5851 .addMemOperand(FIMMOSt));
5855 MachineBasicBlock *ARMTargetLowering::
5856 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5857 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5858 DebugLoc dl = MI->getDebugLoc();
5859 MachineFunction *MF = MBB->getParent();
5860 MachineRegisterInfo *MRI = &MF->getRegInfo();
5861 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5862 MachineFrameInfo *MFI = MF->getFrameInfo();
5863 int FI = MFI->getFunctionContextIndex();
5865 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5866 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5867 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5869 // Get a mapping of the call site numbers to all of the landing pads they're
5871 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5872 unsigned MaxCSNum = 0;
5873 MachineModuleInfo &MMI = MF->getMMI();
5874 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5876 if (!BB->isLandingPad()) continue;
5878 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5880 for (MachineBasicBlock::iterator
5881 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5882 if (!II->isEHLabel()) continue;
5884 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5885 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5887 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5888 for (SmallVectorImpl<unsigned>::iterator
5889 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5890 CSI != CSE; ++CSI) {
5891 CallSiteNumToLPad[*CSI].push_back(BB);
5892 MaxCSNum = std::max(MaxCSNum, *CSI);
5898 // Get an ordered list of the machine basic blocks for the jump table.
5899 std::vector<MachineBasicBlock*> LPadList;
5900 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5901 LPadList.reserve(CallSiteNumToLPad.size());
5902 for (unsigned I = 1; I <= MaxCSNum; ++I) {
5903 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5904 for (SmallVectorImpl<MachineBasicBlock*>::iterator
5905 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5906 LPadList.push_back(*II);
5907 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5911 assert(!LPadList.empty() &&
5912 "No landing pad destinations for the dispatch jump table!");
5914 // Create the jump table and associated information.
5915 MachineJumpTableInfo *JTI =
5916 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5917 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5918 unsigned UId = AFI->createJumpTableUId();
5920 // Create the MBBs for the dispatch code.
5922 // Shove the dispatch's address into the return slot in the function context.
5923 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5924 DispatchBB->setIsLandingPad();
5926 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5927 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5928 DispatchBB->addSuccessor(TrapBB);
5930 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5931 DispatchBB->addSuccessor(DispContBB);
5934 MF->insert(MF->end(), DispatchBB);
5935 MF->insert(MF->end(), DispContBB);
5936 MF->insert(MF->end(), TrapBB);
5938 // Insert code into the entry block that creates and registers the function
5940 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5942 MachineMemOperand *FIMMOLd =
5943 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5944 MachineMemOperand::MOLoad |
5945 MachineMemOperand::MOVolatile, 4, 4);
5947 if (AFI->isThumb1OnlyFunction())
5948 BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5949 else if (!Subtarget->hasVFP2())
5950 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5952 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5954 unsigned NumLPads = LPadList.size();
5955 if (Subtarget->isThumb2()) {
5956 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5957 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5960 .addMemOperand(FIMMOLd));
5962 if (NumLPads < 256) {
5963 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5965 .addImm(LPadList.size()));
5967 unsigned VReg1 = MRI->createVirtualRegister(TRC);
5968 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5969 .addImm(NumLPads & 0xFFFF));
5971 unsigned VReg2 = VReg1;
5972 if ((NumLPads & 0xFFFF0000) != 0) {
5973 VReg2 = MRI->createVirtualRegister(TRC);
5974 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5976 .addImm(NumLPads >> 16));
5979 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5984 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5989 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5990 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5991 .addJumpTableIndex(MJTI)
5994 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5997 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5998 .addReg(NewVReg3, RegState::Kill)
6000 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6002 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6003 .addReg(NewVReg4, RegState::Kill)
6005 .addJumpTableIndex(MJTI)
6007 } else if (Subtarget->isThumb()) {
6008 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6009 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6012 .addMemOperand(FIMMOLd));
6014 if (NumLPads < 256) {
6015 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6019 MachineConstantPool *ConstantPool = MF->getConstantPool();
6020 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6021 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6023 // MachineConstantPool wants an explicit alignment.
6024 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6026 Align = getTargetData()->getTypeAllocSize(C->getType());
6027 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6029 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6030 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6031 .addReg(VReg1, RegState::Define)
6032 .addConstantPoolIndex(Idx));
6033 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6038 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6043 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6044 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6045 .addReg(ARM::CPSR, RegState::Define)
6049 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6050 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6051 .addJumpTableIndex(MJTI)
6054 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6055 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6056 .addReg(ARM::CPSR, RegState::Define)
6057 .addReg(NewVReg2, RegState::Kill)
6060 MachineMemOperand *JTMMOLd =
6061 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6062 MachineMemOperand::MOLoad, 4, 4);
6064 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6065 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6066 .addReg(NewVReg4, RegState::Kill)
6068 .addMemOperand(JTMMOLd));
6070 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6071 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6072 .addReg(ARM::CPSR, RegState::Define)
6073 .addReg(NewVReg5, RegState::Kill)
6076 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6077 .addReg(NewVReg6, RegState::Kill)
6078 .addJumpTableIndex(MJTI)
6081 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6082 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6085 .addMemOperand(FIMMOLd));
6087 if (NumLPads < 256) {
6088 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6091 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6092 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6093 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6094 .addImm(NumLPads & 0xFFFF));
6096 unsigned VReg2 = VReg1;
6097 if ((NumLPads & 0xFFFF0000) != 0) {
6098 VReg2 = MRI->createVirtualRegister(TRC);
6099 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6101 .addImm(NumLPads >> 16));
6104 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6108 MachineConstantPool *ConstantPool = MF->getConstantPool();
6109 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6110 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6112 // MachineConstantPool wants an explicit alignment.
6113 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6115 Align = getTargetData()->getTypeAllocSize(C->getType());
6116 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6118 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6119 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6120 .addReg(VReg1, RegState::Define)
6121 .addConstantPoolIndex(Idx)
6123 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6125 .addReg(VReg1, RegState::Kill));
6128 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6133 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6135 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6137 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6138 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6139 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6140 .addJumpTableIndex(MJTI)
6143 MachineMemOperand *JTMMOLd =
6144 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6145 MachineMemOperand::MOLoad, 4, 4);
6146 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6148 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6149 .addReg(NewVReg3, RegState::Kill)
6152 .addMemOperand(JTMMOLd));
6154 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6155 .addReg(NewVReg5, RegState::Kill)
6157 .addJumpTableIndex(MJTI)
6161 // Add the jump table entries as successors to the MBB.
6162 MachineBasicBlock *PrevMBB = 0;
6163 for (std::vector<MachineBasicBlock*>::iterator
6164 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6165 MachineBasicBlock *CurMBB = *I;
6166 if (PrevMBB != CurMBB)
6167 DispContBB->addSuccessor(CurMBB);
6171 // N.B. the order the invoke BBs are processed in doesn't matter here.
6172 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6173 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6174 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6175 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6176 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6177 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6178 MachineBasicBlock *BB = *I;
6180 // Remove the landing pad successor from the invoke block and replace it
6181 // with the new dispatch block.
6182 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6184 while (!Successors.empty()) {
6185 MachineBasicBlock *SMBB = Successors.pop_back_val();
6186 if (SMBB->isLandingPad()) {
6187 BB->removeSuccessor(SMBB);
6188 MBBLPads.push_back(SMBB);
6192 BB->addSuccessor(DispatchBB);
6194 // Find the invoke call and mark all of the callee-saved registers as
6195 // 'implicit defined' so that they're spilled. This prevents code from
6196 // moving instructions to before the EH block, where they will never be
6198 for (MachineBasicBlock::reverse_iterator
6199 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6200 if (!II->isCall()) continue;
6202 DenseMap<unsigned, bool> DefRegs;
6203 for (MachineInstr::mop_iterator
6204 OI = II->operands_begin(), OE = II->operands_end();
6206 if (!OI->isReg()) continue;
6207 DefRegs[OI->getReg()] = true;
6210 MachineInstrBuilder MIB(&*II);
6212 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6213 unsigned Reg = SavedRegs[i];
6214 if (Subtarget->isThumb2() &&
6215 !ARM::tGPRRegClass.contains(Reg) &&
6216 !ARM::hGPRRegClass.contains(Reg))
6218 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6220 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6223 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6230 // Mark all former landing pads as non-landing pads. The dispatch is the only
6232 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6233 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6234 (*I)->setIsLandingPad(false);
6236 // The instruction is gone now.
6237 MI->eraseFromParent();
6243 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6244 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6245 E = MBB->succ_end(); I != E; ++I)
6248 llvm_unreachable("Expecting a BB with two successors!");
6251 MachineBasicBlock *ARMTargetLowering::
6252 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6253 // This pseudo instruction has 3 operands: dst, src, size
6254 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6255 // Otherwise, we will generate unrolled scalar copies.
6256 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6257 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6258 MachineFunction::iterator It = BB;
6261 unsigned dest = MI->getOperand(0).getReg();
6262 unsigned src = MI->getOperand(1).getReg();
6263 unsigned SizeVal = MI->getOperand(2).getImm();
6264 unsigned Align = MI->getOperand(3).getImm();
6265 DebugLoc dl = MI->getDebugLoc();
6267 bool isThumb2 = Subtarget->isThumb2();
6268 MachineFunction *MF = BB->getParent();
6269 MachineRegisterInfo &MRI = MF->getRegInfo();
6270 unsigned ldrOpc, strOpc, UnitSize = 0;
6272 const TargetRegisterClass *TRC = isThumb2 ?
6273 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6274 (const TargetRegisterClass*)&ARM::GPRRegClass;
6275 const TargetRegisterClass *TRC_Vec = 0;
6278 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6279 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6281 } else if (Align & 2) {
6282 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6283 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6286 // Check whether we can use NEON instructions.
6287 if (!MF->getFunction()->hasFnAttr(Attribute::NoImplicitFloat) &&
6288 Subtarget->hasNEON()) {
6289 if ((Align % 16 == 0) && SizeVal >= 16) {
6290 ldrOpc = ARM::VLD1q32wb_fixed;
6291 strOpc = ARM::VST1q32wb_fixed;
6293 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6295 else if ((Align % 8 == 0) && SizeVal >= 8) {
6296 ldrOpc = ARM::VLD1d32wb_fixed;
6297 strOpc = ARM::VST1d32wb_fixed;
6299 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6302 // Can't use NEON instructions.
6303 if (UnitSize == 0) {
6304 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6305 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6310 unsigned BytesLeft = SizeVal % UnitSize;
6311 unsigned LoopSize = SizeVal - BytesLeft;
6313 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6314 // Use LDR and STR to copy.
6315 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6316 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6317 unsigned srcIn = src;
6318 unsigned destIn = dest;
6319 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6320 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6321 unsigned srcOut = MRI.createVirtualRegister(TRC);
6322 unsigned destOut = MRI.createVirtualRegister(TRC);
6323 if (UnitSize >= 8) {
6324 AddDefaultPred(BuildMI(*BB, MI, dl,
6325 TII->get(ldrOpc), scratch)
6326 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6328 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6329 .addReg(destIn).addImm(0).addReg(scratch));
6330 } else if (isThumb2) {
6331 AddDefaultPred(BuildMI(*BB, MI, dl,
6332 TII->get(ldrOpc), scratch)
6333 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6335 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6336 .addReg(scratch).addReg(destIn)
6339 AddDefaultPred(BuildMI(*BB, MI, dl,
6340 TII->get(ldrOpc), scratch)
6341 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6344 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6345 .addReg(scratch).addReg(destIn)
6346 .addReg(0).addImm(UnitSize));
6352 // Handle the leftover bytes with LDRB and STRB.
6353 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6354 // [destOut] = STRB_POST(scratch, destIn, 1)
6355 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6356 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6357 for (unsigned i = 0; i < BytesLeft; i++) {
6358 unsigned scratch = MRI.createVirtualRegister(TRC);
6359 unsigned srcOut = MRI.createVirtualRegister(TRC);
6360 unsigned destOut = MRI.createVirtualRegister(TRC);
6362 AddDefaultPred(BuildMI(*BB, MI, dl,
6363 TII->get(ldrOpc),scratch)
6364 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6366 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6367 .addReg(scratch).addReg(destIn)
6368 .addReg(0).addImm(1));
6370 AddDefaultPred(BuildMI(*BB, MI, dl,
6371 TII->get(ldrOpc),scratch)
6372 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6374 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6375 .addReg(scratch).addReg(destIn)
6376 .addReg(0).addImm(1));
6381 MI->eraseFromParent(); // The instruction is gone now.
6385 // Expand the pseudo op to a loop.
6388 // movw varEnd, # --> with thumb2
6390 // ldrcp varEnd, idx --> without thumb2
6391 // fallthrough --> loopMBB
6393 // PHI varPhi, varEnd, varLoop
6394 // PHI srcPhi, src, srcLoop
6395 // PHI destPhi, dst, destLoop
6396 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6397 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6398 // subs varLoop, varPhi, #UnitSize
6400 // fallthrough --> exitMBB
6402 // epilogue to handle left-over bytes
6403 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6404 // [destOut] = STRB_POST(scratch, destLoop, 1)
6405 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6406 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6407 MF->insert(It, loopMBB);
6408 MF->insert(It, exitMBB);
6410 // Transfer the remainder of BB and its successor edges to exitMBB.
6411 exitMBB->splice(exitMBB->begin(), BB,
6412 llvm::next(MachineBasicBlock::iterator(MI)),
6414 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6416 // Load an immediate to varEnd.
6417 unsigned varEnd = MRI.createVirtualRegister(TRC);
6419 unsigned VReg1 = varEnd;
6420 if ((LoopSize & 0xFFFF0000) != 0)
6421 VReg1 = MRI.createVirtualRegister(TRC);
6422 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6423 .addImm(LoopSize & 0xFFFF));
6425 if ((LoopSize & 0xFFFF0000) != 0)
6426 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6428 .addImm(LoopSize >> 16));
6430 MachineConstantPool *ConstantPool = MF->getConstantPool();
6431 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6432 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6434 // MachineConstantPool wants an explicit alignment.
6435 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6437 Align = getTargetData()->getTypeAllocSize(C->getType());
6438 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6440 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6441 .addReg(varEnd, RegState::Define)
6442 .addConstantPoolIndex(Idx)
6445 BB->addSuccessor(loopMBB);
6447 // Generate the loop body:
6448 // varPhi = PHI(varLoop, varEnd)
6449 // srcPhi = PHI(srcLoop, src)
6450 // destPhi = PHI(destLoop, dst)
6451 MachineBasicBlock *entryBB = BB;
6453 unsigned varLoop = MRI.createVirtualRegister(TRC);
6454 unsigned varPhi = MRI.createVirtualRegister(TRC);
6455 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6456 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6457 unsigned destLoop = MRI.createVirtualRegister(TRC);
6458 unsigned destPhi = MRI.createVirtualRegister(TRC);
6460 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6461 .addReg(varLoop).addMBB(loopMBB)
6462 .addReg(varEnd).addMBB(entryBB);
6463 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6464 .addReg(srcLoop).addMBB(loopMBB)
6465 .addReg(src).addMBB(entryBB);
6466 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6467 .addReg(destLoop).addMBB(loopMBB)
6468 .addReg(dest).addMBB(entryBB);
6470 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6471 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6472 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6473 if (UnitSize >= 8) {
6474 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6475 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6477 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6478 .addReg(destPhi).addImm(0).addReg(scratch));
6479 } else if (isThumb2) {
6480 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6481 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6483 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6484 .addReg(scratch).addReg(destPhi)
6487 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6488 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6491 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6492 .addReg(scratch).addReg(destPhi)
6493 .addReg(0).addImm(UnitSize));
6496 // Decrement loop variable by UnitSize.
6497 MachineInstrBuilder MIB = BuildMI(BB, dl,
6498 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6499 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6500 MIB->getOperand(5).setReg(ARM::CPSR);
6501 MIB->getOperand(5).setIsDef(true);
6503 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6504 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6506 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6507 BB->addSuccessor(loopMBB);
6508 BB->addSuccessor(exitMBB);
6510 // Add epilogue to handle BytesLeft.
6512 MachineInstr *StartOfExit = exitMBB->begin();
6513 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6514 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6516 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6517 // [destOut] = STRB_POST(scratch, destLoop, 1)
6518 unsigned srcIn = srcLoop;
6519 unsigned destIn = destLoop;
6520 for (unsigned i = 0; i < BytesLeft; i++) {
6521 unsigned scratch = MRI.createVirtualRegister(TRC);
6522 unsigned srcOut = MRI.createVirtualRegister(TRC);
6523 unsigned destOut = MRI.createVirtualRegister(TRC);
6525 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6526 TII->get(ldrOpc),scratch)
6527 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6529 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6530 .addReg(scratch).addReg(destIn)
6533 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6534 TII->get(ldrOpc),scratch)
6535 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6537 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6538 .addReg(scratch).addReg(destIn)
6539 .addReg(0).addImm(1));
6545 MI->eraseFromParent(); // The instruction is gone now.
6550 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6551 MachineBasicBlock *BB) const {
6552 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6553 DebugLoc dl = MI->getDebugLoc();
6554 bool isThumb2 = Subtarget->isThumb2();
6555 switch (MI->getOpcode()) {
6558 llvm_unreachable("Unexpected instr type to insert");
6560 // The Thumb2 pre-indexed stores have the same MI operands, they just
6561 // define them differently in the .td files from the isel patterns, so
6562 // they need pseudos.
6563 case ARM::t2STR_preidx:
6564 MI->setDesc(TII->get(ARM::t2STR_PRE));
6566 case ARM::t2STRB_preidx:
6567 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6569 case ARM::t2STRH_preidx:
6570 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6573 case ARM::STRi_preidx:
6574 case ARM::STRBi_preidx: {
6575 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6576 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6577 // Decode the offset.
6578 unsigned Offset = MI->getOperand(4).getImm();
6579 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6580 Offset = ARM_AM::getAM2Offset(Offset);
6584 MachineMemOperand *MMO = *MI->memoperands_begin();
6585 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6586 .addOperand(MI->getOperand(0)) // Rn_wb
6587 .addOperand(MI->getOperand(1)) // Rt
6588 .addOperand(MI->getOperand(2)) // Rn
6589 .addImm(Offset) // offset (skip GPR==zero_reg)
6590 .addOperand(MI->getOperand(5)) // pred
6591 .addOperand(MI->getOperand(6))
6592 .addMemOperand(MMO);
6593 MI->eraseFromParent();
6596 case ARM::STRr_preidx:
6597 case ARM::STRBr_preidx:
6598 case ARM::STRH_preidx: {
6600 switch (MI->getOpcode()) {
6601 default: llvm_unreachable("unexpected opcode!");
6602 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6603 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6604 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6606 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6607 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6608 MIB.addOperand(MI->getOperand(i));
6609 MI->eraseFromParent();
6612 case ARM::ATOMIC_LOAD_ADD_I8:
6613 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6614 case ARM::ATOMIC_LOAD_ADD_I16:
6615 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6616 case ARM::ATOMIC_LOAD_ADD_I32:
6617 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6619 case ARM::ATOMIC_LOAD_AND_I8:
6620 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6621 case ARM::ATOMIC_LOAD_AND_I16:
6622 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6623 case ARM::ATOMIC_LOAD_AND_I32:
6624 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6626 case ARM::ATOMIC_LOAD_OR_I8:
6627 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6628 case ARM::ATOMIC_LOAD_OR_I16:
6629 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6630 case ARM::ATOMIC_LOAD_OR_I32:
6631 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6633 case ARM::ATOMIC_LOAD_XOR_I8:
6634 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6635 case ARM::ATOMIC_LOAD_XOR_I16:
6636 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6637 case ARM::ATOMIC_LOAD_XOR_I32:
6638 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6640 case ARM::ATOMIC_LOAD_NAND_I8:
6641 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6642 case ARM::ATOMIC_LOAD_NAND_I16:
6643 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6644 case ARM::ATOMIC_LOAD_NAND_I32:
6645 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6647 case ARM::ATOMIC_LOAD_SUB_I8:
6648 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6649 case ARM::ATOMIC_LOAD_SUB_I16:
6650 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6651 case ARM::ATOMIC_LOAD_SUB_I32:
6652 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6654 case ARM::ATOMIC_LOAD_MIN_I8:
6655 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6656 case ARM::ATOMIC_LOAD_MIN_I16:
6657 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6658 case ARM::ATOMIC_LOAD_MIN_I32:
6659 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6661 case ARM::ATOMIC_LOAD_MAX_I8:
6662 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6663 case ARM::ATOMIC_LOAD_MAX_I16:
6664 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6665 case ARM::ATOMIC_LOAD_MAX_I32:
6666 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6668 case ARM::ATOMIC_LOAD_UMIN_I8:
6669 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6670 case ARM::ATOMIC_LOAD_UMIN_I16:
6671 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6672 case ARM::ATOMIC_LOAD_UMIN_I32:
6673 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6675 case ARM::ATOMIC_LOAD_UMAX_I8:
6676 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6677 case ARM::ATOMIC_LOAD_UMAX_I16:
6678 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6679 case ARM::ATOMIC_LOAD_UMAX_I32:
6680 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6682 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
6683 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6684 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6686 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
6687 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6688 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6691 case ARM::ATOMADD6432:
6692 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6693 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6694 /*NeedsCarry*/ true);
6695 case ARM::ATOMSUB6432:
6696 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6697 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6698 /*NeedsCarry*/ true);
6699 case ARM::ATOMOR6432:
6700 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6701 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6702 case ARM::ATOMXOR6432:
6703 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6704 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6705 case ARM::ATOMAND6432:
6706 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6707 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6708 case ARM::ATOMSWAP6432:
6709 return EmitAtomicBinary64(MI, BB, 0, 0, false);
6710 case ARM::ATOMCMPXCHG6432:
6711 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6712 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6713 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6715 case ARM::tMOVCCr_pseudo: {
6716 // To "insert" a SELECT_CC instruction, we actually have to insert the
6717 // diamond control-flow pattern. The incoming instruction knows the
6718 // destination vreg to set, the condition code register to branch on, the
6719 // true/false values to select between, and a branch opcode to use.
6720 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6721 MachineFunction::iterator It = BB;
6727 // cmpTY ccX, r1, r2
6729 // fallthrough --> copy0MBB
6730 MachineBasicBlock *thisMBB = BB;
6731 MachineFunction *F = BB->getParent();
6732 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6733 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6734 F->insert(It, copy0MBB);
6735 F->insert(It, sinkMBB);
6737 // Transfer the remainder of BB and its successor edges to sinkMBB.
6738 sinkMBB->splice(sinkMBB->begin(), BB,
6739 llvm::next(MachineBasicBlock::iterator(MI)),
6741 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6743 BB->addSuccessor(copy0MBB);
6744 BB->addSuccessor(sinkMBB);
6746 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6747 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6750 // %FalseValue = ...
6751 // # fallthrough to sinkMBB
6754 // Update machine-CFG edges
6755 BB->addSuccessor(sinkMBB);
6758 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6761 BuildMI(*BB, BB->begin(), dl,
6762 TII->get(ARM::PHI), MI->getOperand(0).getReg())
6763 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6764 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6766 MI->eraseFromParent(); // The pseudo instruction is gone now.
6771 case ARM::BCCZi64: {
6772 // If there is an unconditional branch to the other successor, remove it.
6773 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6775 // Compare both parts that make up the double comparison separately for
6777 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6779 unsigned LHS1 = MI->getOperand(1).getReg();
6780 unsigned LHS2 = MI->getOperand(2).getReg();
6782 AddDefaultPred(BuildMI(BB, dl,
6783 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6784 .addReg(LHS1).addImm(0));
6785 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6786 .addReg(LHS2).addImm(0)
6787 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6789 unsigned RHS1 = MI->getOperand(3).getReg();
6790 unsigned RHS2 = MI->getOperand(4).getReg();
6791 AddDefaultPred(BuildMI(BB, dl,
6792 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6793 .addReg(LHS1).addReg(RHS1));
6794 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6795 .addReg(LHS2).addReg(RHS2)
6796 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6799 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6800 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6801 if (MI->getOperand(0).getImm() == ARMCC::NE)
6802 std::swap(destMBB, exitMBB);
6804 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6805 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6807 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6809 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6811 MI->eraseFromParent(); // The pseudo instruction is gone now.
6815 case ARM::Int_eh_sjlj_setjmp:
6816 case ARM::Int_eh_sjlj_setjmp_nofp:
6817 case ARM::tInt_eh_sjlj_setjmp:
6818 case ARM::t2Int_eh_sjlj_setjmp:
6819 case ARM::t2Int_eh_sjlj_setjmp_nofp:
6820 EmitSjLjDispatchBlock(MI, BB);
6825 // To insert an ABS instruction, we have to insert the
6826 // diamond control-flow pattern. The incoming instruction knows the
6827 // source vreg to test against 0, the destination vreg to set,
6828 // the condition code register to branch on, the
6829 // true/false values to select between, and a branch opcode to use.
6834 // BCC (branch to SinkBB if V0 >= 0)
6835 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
6836 // SinkBB: V1 = PHI(V2, V3)
6837 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6838 MachineFunction::iterator BBI = BB;
6840 MachineFunction *Fn = BB->getParent();
6841 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6842 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6843 Fn->insert(BBI, RSBBB);
6844 Fn->insert(BBI, SinkBB);
6846 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6847 unsigned int ABSDstReg = MI->getOperand(0).getReg();
6848 bool isThumb2 = Subtarget->isThumb2();
6849 MachineRegisterInfo &MRI = Fn->getRegInfo();
6850 // In Thumb mode S must not be specified if source register is the SP or
6851 // PC and if destination register is the SP, so restrict register class
6852 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6853 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6854 (const TargetRegisterClass*)&ARM::GPRRegClass);
6856 // Transfer the remainder of BB and its successor edges to sinkMBB.
6857 SinkBB->splice(SinkBB->begin(), BB,
6858 llvm::next(MachineBasicBlock::iterator(MI)),
6860 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6862 BB->addSuccessor(RSBBB);
6863 BB->addSuccessor(SinkBB);
6865 // fall through to SinkMBB
6866 RSBBB->addSuccessor(SinkBB);
6868 // insert a cmp at the end of BB
6869 AddDefaultPred(BuildMI(BB, dl,
6870 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6871 .addReg(ABSSrcReg).addImm(0));
6873 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6875 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6876 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6878 // insert rsbri in RSBBB
6879 // Note: BCC and rsbri will be converted into predicated rsbmi
6880 // by if-conversion pass
6881 BuildMI(*RSBBB, RSBBB->begin(), dl,
6882 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6883 .addReg(ABSSrcReg, RegState::Kill)
6884 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6886 // insert PHI in SinkBB,
6887 // reuse ABSDstReg to not change uses of ABS instruction
6888 BuildMI(*SinkBB, SinkBB->begin(), dl,
6889 TII->get(ARM::PHI), ABSDstReg)
6890 .addReg(NewRsbDstReg).addMBB(RSBBB)
6891 .addReg(ABSSrcReg).addMBB(BB);
6893 // remove ABS instruction
6894 MI->eraseFromParent();
6896 // return last added BB
6899 case ARM::COPY_STRUCT_BYVAL_I32:
6901 return EmitStructByval(MI, BB);
6905 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6906 SDNode *Node) const {
6907 if (!MI->hasPostISelHook()) {
6908 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6909 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6913 const MCInstrDesc *MCID = &MI->getDesc();
6914 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6915 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6916 // operand is still set to noreg. If needed, set the optional operand's
6917 // register to CPSR, and remove the redundant implicit def.
6919 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6921 // Rename pseudo opcodes.
6922 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6924 const ARMBaseInstrInfo *TII =
6925 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6926 MCID = &TII->get(NewOpc);
6928 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6929 "converted opcode should be the same except for cc_out");
6933 // Add the optional cc_out operand
6934 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6936 unsigned ccOutIdx = MCID->getNumOperands() - 1;
6938 // Any ARM instruction that sets the 's' bit should specify an optional
6939 // "cc_out" operand in the last operand position.
6940 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6941 assert(!NewOpc && "Optional cc_out operand required");
6944 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6945 // since we already have an optional CPSR def.
6946 bool definesCPSR = false;
6947 bool deadCPSR = false;
6948 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6950 const MachineOperand &MO = MI->getOperand(i);
6951 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6955 MI->RemoveOperand(i);
6960 assert(!NewOpc && "Optional cc_out operand required");
6963 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6965 assert(!MI->getOperand(ccOutIdx).getReg() &&
6966 "expect uninitialized optional cc_out operand");
6970 // If this instruction was defined with an optional CPSR def and its dag node
6971 // had a live implicit CPSR def, then activate the optional CPSR def.
6972 MachineOperand &MO = MI->getOperand(ccOutIdx);
6973 MO.setReg(ARM::CPSR);
6977 //===----------------------------------------------------------------------===//
6978 // ARM Optimization Hooks
6979 //===----------------------------------------------------------------------===//
6982 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6983 TargetLowering::DAGCombinerInfo &DCI) {
6984 SelectionDAG &DAG = DCI.DAG;
6985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6986 EVT VT = N->getValueType(0);
6987 unsigned Opc = N->getOpcode();
6988 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6989 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6990 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6991 ISD::CondCode CC = ISD::SETCC_INVALID;
6994 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6996 SDValue CCOp = Slct.getOperand(0);
6997 if (CCOp.getOpcode() == ISD::SETCC)
6998 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
7001 bool DoXform = false;
7003 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
7006 if (LHS.getOpcode() == ISD::Constant &&
7007 cast<ConstantSDNode>(LHS)->isNullValue()) {
7009 } else if (CC != ISD::SETCC_INVALID &&
7010 RHS.getOpcode() == ISD::Constant &&
7011 cast<ConstantSDNode>(RHS)->isNullValue()) {
7012 std::swap(LHS, RHS);
7013 SDValue Op0 = Slct.getOperand(0);
7014 EVT OpVT = isSlctCC ? Op0.getValueType() :
7015 Op0.getOperand(0).getValueType();
7016 bool isInt = OpVT.isInteger();
7017 CC = ISD::getSetCCInverse(CC, isInt);
7019 if (!TLI.isCondCodeLegal(CC, OpVT))
7020 return SDValue(); // Inverse operator isn't legal.
7027 SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
7029 return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
7030 Slct.getOperand(0), Slct.getOperand(1), CC);
7031 SDValue CCOp = Slct.getOperand(0);
7033 CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
7034 CCOp.getOperand(0), CCOp.getOperand(1), CC);
7035 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7036 CCOp, OtherOp, Result);
7041 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7042 // (only after legalization).
7043 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7044 TargetLowering::DAGCombinerInfo &DCI,
7045 const ARMSubtarget *Subtarget) {
7047 // Only perform optimization if after legalize, and if NEON is available. We
7048 // also expected both operands to be BUILD_VECTORs.
7049 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7050 || N0.getOpcode() != ISD::BUILD_VECTOR
7051 || N1.getOpcode() != ISD::BUILD_VECTOR)
7054 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7055 EVT VT = N->getValueType(0);
7056 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7059 // Check that the vector operands are of the right form.
7060 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7061 // operands, where N is the size of the formed vector.
7062 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7063 // index such that we have a pair wise add pattern.
7065 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7066 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7068 SDValue Vec = N0->getOperand(0)->getOperand(0);
7069 SDNode *V = Vec.getNode();
7070 unsigned nextIndex = 0;
7072 // For each operands to the ADD which are BUILD_VECTORs,
7073 // check to see if each of their operands are an EXTRACT_VECTOR with
7074 // the same vector and appropriate index.
7075 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7076 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7077 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7079 SDValue ExtVec0 = N0->getOperand(i);
7080 SDValue ExtVec1 = N1->getOperand(i);
7082 // First operand is the vector, verify its the same.
7083 if (V != ExtVec0->getOperand(0).getNode() ||
7084 V != ExtVec1->getOperand(0).getNode())
7087 // Second is the constant, verify its correct.
7088 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7089 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7091 // For the constant, we want to see all the even or all the odd.
7092 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7093 || C1->getZExtValue() != nextIndex+1)
7102 // Create VPADDL node.
7103 SelectionDAG &DAG = DCI.DAG;
7104 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7106 // Build operand list.
7107 SmallVector<SDValue, 8> Ops;
7108 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7109 TLI.getPointerTy()));
7111 // Input is the vector.
7114 // Get widened type and narrowed type.
7116 unsigned numElem = VT.getVectorNumElements();
7117 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7118 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7119 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7120 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7122 llvm_unreachable("Invalid vector element type for padd optimization.");
7125 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7126 widenType, &Ops[0], Ops.size());
7127 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7130 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7131 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7132 /// called with the default operands, and if that fails, with commuted
7134 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7135 TargetLowering::DAGCombinerInfo &DCI,
7136 const ARMSubtarget *Subtarget){
7138 // Attempt to create vpaddl for this add.
7139 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7140 if (Result.getNode())
7143 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7144 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
7145 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7146 if (Result.getNode()) return Result;
7151 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7153 static SDValue PerformADDCombine(SDNode *N,
7154 TargetLowering::DAGCombinerInfo &DCI,
7155 const ARMSubtarget *Subtarget) {
7156 SDValue N0 = N->getOperand(0);
7157 SDValue N1 = N->getOperand(1);
7159 // First try with the default operand order.
7160 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7161 if (Result.getNode())
7164 // If that didn't work, try again with the operands commuted.
7165 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7168 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7170 static SDValue PerformSUBCombine(SDNode *N,
7171 TargetLowering::DAGCombinerInfo &DCI) {
7172 SDValue N0 = N->getOperand(0);
7173 SDValue N1 = N->getOperand(1);
7175 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7176 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
7177 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7178 if (Result.getNode()) return Result;
7184 /// PerformVMULCombine
7185 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7186 /// special multiplier accumulator forwarding.
7192 static SDValue PerformVMULCombine(SDNode *N,
7193 TargetLowering::DAGCombinerInfo &DCI,
7194 const ARMSubtarget *Subtarget) {
7195 if (!Subtarget->hasVMLxForwarding())
7198 SelectionDAG &DAG = DCI.DAG;
7199 SDValue N0 = N->getOperand(0);
7200 SDValue N1 = N->getOperand(1);
7201 unsigned Opcode = N0.getOpcode();
7202 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7203 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7204 Opcode = N1.getOpcode();
7205 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7206 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7211 EVT VT = N->getValueType(0);
7212 DebugLoc DL = N->getDebugLoc();
7213 SDValue N00 = N0->getOperand(0);
7214 SDValue N01 = N0->getOperand(1);
7215 return DAG.getNode(Opcode, DL, VT,
7216 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7217 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7220 static SDValue PerformMULCombine(SDNode *N,
7221 TargetLowering::DAGCombinerInfo &DCI,
7222 const ARMSubtarget *Subtarget) {
7223 SelectionDAG &DAG = DCI.DAG;
7225 if (Subtarget->isThumb1Only())
7228 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7231 EVT VT = N->getValueType(0);
7232 if (VT.is64BitVector() || VT.is128BitVector())
7233 return PerformVMULCombine(N, DCI, Subtarget);
7237 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7241 int64_t MulAmt = C->getSExtValue();
7242 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7244 ShiftAmt = ShiftAmt & (32 - 1);
7245 SDValue V = N->getOperand(0);
7246 DebugLoc DL = N->getDebugLoc();
7249 MulAmt >>= ShiftAmt;
7252 if (isPowerOf2_32(MulAmt - 1)) {
7253 // (mul x, 2^N + 1) => (add (shl x, N), x)
7254 Res = DAG.getNode(ISD::ADD, DL, VT,
7256 DAG.getNode(ISD::SHL, DL, VT,
7258 DAG.getConstant(Log2_32(MulAmt - 1),
7260 } else if (isPowerOf2_32(MulAmt + 1)) {
7261 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7262 Res = DAG.getNode(ISD::SUB, DL, VT,
7263 DAG.getNode(ISD::SHL, DL, VT,
7265 DAG.getConstant(Log2_32(MulAmt + 1),
7271 uint64_t MulAmtAbs = -MulAmt;
7272 if (isPowerOf2_32(MulAmtAbs + 1)) {
7273 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7274 Res = DAG.getNode(ISD::SUB, DL, VT,
7276 DAG.getNode(ISD::SHL, DL, VT,
7278 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7280 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7281 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7282 Res = DAG.getNode(ISD::ADD, DL, VT,
7284 DAG.getNode(ISD::SHL, DL, VT,
7286 DAG.getConstant(Log2_32(MulAmtAbs-1),
7288 Res = DAG.getNode(ISD::SUB, DL, VT,
7289 DAG.getConstant(0, MVT::i32),Res);
7296 Res = DAG.getNode(ISD::SHL, DL, VT,
7297 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7299 // Do not add new nodes to DAG combiner worklist.
7300 DCI.CombineTo(N, Res, false);
7304 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
7305 if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
7308 SDValue FalseVal = N.getOperand(0);
7309 ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
7313 return C->isAllOnesValue();
7314 return C->isNullValue();
7317 /// formConditionalOp - Combine an operation with a conditional move operand
7318 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7319 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7320 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7322 SDValue N0 = N->getOperand(0);
7323 SDValue N1 = N->getOperand(1);
7325 bool isAND = N->getOpcode() == ISD::AND;
7326 bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7327 if (!isCand && Commutable) {
7328 isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7336 switch (N->getOpcode()) {
7337 default: llvm_unreachable("Unexpected node");
7338 case ISD::AND: Opc = ARMISD::CAND; break;
7339 case ISD::OR: Opc = ARMISD::COR; break;
7340 case ISD::XOR: Opc = ARMISD::CXOR; break;
7342 return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7343 N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7347 static SDValue PerformANDCombine(SDNode *N,
7348 TargetLowering::DAGCombinerInfo &DCI,
7349 const ARMSubtarget *Subtarget) {
7351 // Attempt to use immediate-form VBIC
7352 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7353 DebugLoc dl = N->getDebugLoc();
7354 EVT VT = N->getValueType(0);
7355 SelectionDAG &DAG = DCI.DAG;
7357 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7360 APInt SplatBits, SplatUndef;
7361 unsigned SplatBitSize;
7364 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7365 if (SplatBitSize <= 64) {
7367 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7368 SplatUndef.getZExtValue(), SplatBitSize,
7369 DAG, VbicVT, VT.is128BitVector(),
7371 if (Val.getNode()) {
7373 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7374 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7375 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7380 if (!Subtarget->isThumb1Only()) {
7381 // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7382 SDValue CAND = formConditionalOp(N, DAG, true);
7390 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7391 static SDValue PerformORCombine(SDNode *N,
7392 TargetLowering::DAGCombinerInfo &DCI,
7393 const ARMSubtarget *Subtarget) {
7394 // Attempt to use immediate-form VORR
7395 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7396 DebugLoc dl = N->getDebugLoc();
7397 EVT VT = N->getValueType(0);
7398 SelectionDAG &DAG = DCI.DAG;
7400 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7403 APInt SplatBits, SplatUndef;
7404 unsigned SplatBitSize;
7406 if (BVN && Subtarget->hasNEON() &&
7407 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7408 if (SplatBitSize <= 64) {
7410 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7411 SplatUndef.getZExtValue(), SplatBitSize,
7412 DAG, VorrVT, VT.is128BitVector(),
7414 if (Val.getNode()) {
7416 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7417 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7418 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7423 if (!Subtarget->isThumb1Only()) {
7424 // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7425 SDValue COR = formConditionalOp(N, DAG, true);
7430 SDValue N0 = N->getOperand(0);
7431 if (N0.getOpcode() != ISD::AND)
7433 SDValue N1 = N->getOperand(1);
7435 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7436 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7437 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7439 unsigned SplatBitSize;
7442 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7444 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7445 HasAnyUndefs) && !HasAnyUndefs) {
7446 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7448 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7449 HasAnyUndefs) && !HasAnyUndefs &&
7450 SplatBits0 == ~SplatBits1) {
7451 // Canonicalize the vector type to make instruction selection simpler.
7452 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7453 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7454 N0->getOperand(1), N0->getOperand(0),
7456 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7461 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7464 // BFI is only available on V6T2+
7465 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7468 DebugLoc DL = N->getDebugLoc();
7469 // 1) or (and A, mask), val => ARMbfi A, val, mask
7470 // iff (val & mask) == val
7472 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7473 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7474 // && mask == ~mask2
7475 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7476 // && ~mask == mask2
7477 // (i.e., copy a bitfield value into another bitfield of the same width)
7482 SDValue N00 = N0.getOperand(0);
7484 // The value and the mask need to be constants so we can verify this is
7485 // actually a bitfield set. If the mask is 0xffff, we can do better
7486 // via a movt instruction, so don't use BFI in that case.
7487 SDValue MaskOp = N0.getOperand(1);
7488 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7491 unsigned Mask = MaskC->getZExtValue();
7495 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7496 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7498 unsigned Val = N1C->getZExtValue();
7499 if ((Val & ~Mask) != Val)
7502 if (ARM::isBitFieldInvertedMask(Mask)) {
7503 Val >>= CountTrailingZeros_32(~Mask);
7505 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7506 DAG.getConstant(Val, MVT::i32),
7507 DAG.getConstant(Mask, MVT::i32));
7509 // Do not add new nodes to DAG combiner worklist.
7510 DCI.CombineTo(N, Res, false);
7513 } else if (N1.getOpcode() == ISD::AND) {
7514 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7515 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7518 unsigned Mask2 = N11C->getZExtValue();
7520 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7522 if (ARM::isBitFieldInvertedMask(Mask) &&
7524 // The pack halfword instruction works better for masks that fit it,
7525 // so use that when it's available.
7526 if (Subtarget->hasT2ExtractPack() &&
7527 (Mask == 0xffff || Mask == 0xffff0000))
7530 unsigned amt = CountTrailingZeros_32(Mask2);
7531 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7532 DAG.getConstant(amt, MVT::i32));
7533 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7534 DAG.getConstant(Mask, MVT::i32));
7535 // Do not add new nodes to DAG combiner worklist.
7536 DCI.CombineTo(N, Res, false);
7538 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7540 // The pack halfword instruction works better for masks that fit it,
7541 // so use that when it's available.
7542 if (Subtarget->hasT2ExtractPack() &&
7543 (Mask2 == 0xffff || Mask2 == 0xffff0000))
7546 unsigned lsb = CountTrailingZeros_32(Mask);
7547 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7548 DAG.getConstant(lsb, MVT::i32));
7549 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7550 DAG.getConstant(Mask2, MVT::i32));
7551 // Do not add new nodes to DAG combiner worklist.
7552 DCI.CombineTo(N, Res, false);
7557 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7558 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7559 ARM::isBitFieldInvertedMask(~Mask)) {
7560 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7561 // where lsb(mask) == #shamt and masked bits of B are known zero.
7562 SDValue ShAmt = N00.getOperand(1);
7563 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7564 unsigned LSB = CountTrailingZeros_32(Mask);
7568 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7569 DAG.getConstant(~Mask, MVT::i32));
7571 // Do not add new nodes to DAG combiner worklist.
7572 DCI.CombineTo(N, Res, false);
7578 static SDValue PerformXORCombine(SDNode *N,
7579 TargetLowering::DAGCombinerInfo &DCI,
7580 const ARMSubtarget *Subtarget) {
7581 EVT VT = N->getValueType(0);
7582 SelectionDAG &DAG = DCI.DAG;
7584 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7587 if (!Subtarget->isThumb1Only()) {
7588 // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7589 SDValue CXOR = formConditionalOp(N, DAG, true);
7597 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7598 /// the bits being cleared by the AND are not demanded by the BFI.
7599 static SDValue PerformBFICombine(SDNode *N,
7600 TargetLowering::DAGCombinerInfo &DCI) {
7601 SDValue N1 = N->getOperand(1);
7602 if (N1.getOpcode() == ISD::AND) {
7603 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7606 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7607 unsigned LSB = CountTrailingZeros_32(~InvMask);
7608 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7609 unsigned Mask = (1 << Width)-1;
7610 unsigned Mask2 = N11C->getZExtValue();
7611 if ((Mask & (~Mask2)) == 0)
7612 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7613 N->getOperand(0), N1.getOperand(0),
7619 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7620 /// ARMISD::VMOVRRD.
7621 static SDValue PerformVMOVRRDCombine(SDNode *N,
7622 TargetLowering::DAGCombinerInfo &DCI) {
7623 // vmovrrd(vmovdrr x, y) -> x,y
7624 SDValue InDouble = N->getOperand(0);
7625 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7626 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7628 // vmovrrd(load f64) -> (load i32), (load i32)
7629 SDNode *InNode = InDouble.getNode();
7630 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7631 InNode->getValueType(0) == MVT::f64 &&
7632 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7633 !cast<LoadSDNode>(InNode)->isVolatile()) {
7634 // TODO: Should this be done for non-FrameIndex operands?
7635 LoadSDNode *LD = cast<LoadSDNode>(InNode);
7637 SelectionDAG &DAG = DCI.DAG;
7638 DebugLoc DL = LD->getDebugLoc();
7639 SDValue BasePtr = LD->getBasePtr();
7640 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7641 LD->getPointerInfo(), LD->isVolatile(),
7642 LD->isNonTemporal(), LD->isInvariant(),
7643 LD->getAlignment());
7645 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7646 DAG.getConstant(4, MVT::i32));
7647 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7648 LD->getPointerInfo(), LD->isVolatile(),
7649 LD->isNonTemporal(), LD->isInvariant(),
7650 std::min(4U, LD->getAlignment() / 2));
7652 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7653 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7654 DCI.RemoveFromWorklist(LD);
7662 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7663 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
7664 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7665 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7666 SDValue Op0 = N->getOperand(0);
7667 SDValue Op1 = N->getOperand(1);
7668 if (Op0.getOpcode() == ISD::BITCAST)
7669 Op0 = Op0.getOperand(0);
7670 if (Op1.getOpcode() == ISD::BITCAST)
7671 Op1 = Op1.getOperand(0);
7672 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7673 Op0.getNode() == Op1.getNode() &&
7674 Op0.getResNo() == 0 && Op1.getResNo() == 1)
7675 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7676 N->getValueType(0), Op0.getOperand(0));
7680 /// PerformSTORECombine - Target-specific dag combine xforms for
7682 static SDValue PerformSTORECombine(SDNode *N,
7683 TargetLowering::DAGCombinerInfo &DCI) {
7684 StoreSDNode *St = cast<StoreSDNode>(N);
7685 if (St->isVolatile())
7688 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
7689 // pack all of the elements in one place. Next, store to memory in fewer
7691 SDValue StVal = St->getValue();
7692 EVT VT = StVal.getValueType();
7693 if (St->isTruncatingStore() && VT.isVector()) {
7694 SelectionDAG &DAG = DCI.DAG;
7695 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7696 EVT StVT = St->getMemoryVT();
7697 unsigned NumElems = VT.getVectorNumElements();
7698 assert(StVT != VT && "Cannot truncate to the same type");
7699 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7700 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7702 // From, To sizes and ElemCount must be pow of two
7703 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7705 // We are going to use the original vector elt for storing.
7706 // Accumulated smaller vector elements must be a multiple of the store size.
7707 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7709 unsigned SizeRatio = FromEltSz / ToEltSz;
7710 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7712 // Create a type on which we perform the shuffle.
7713 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7714 NumElems*SizeRatio);
7715 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7717 DebugLoc DL = St->getDebugLoc();
7718 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7719 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7720 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7722 // Can't shuffle using an illegal type.
7723 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7725 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7726 DAG.getUNDEF(WideVec.getValueType()),
7728 // At this point all of the data is stored at the bottom of the
7729 // register. We now need to save it to mem.
7731 // Find the largest store unit
7732 MVT StoreType = MVT::i8;
7733 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7734 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7735 MVT Tp = (MVT::SimpleValueType)tp;
7736 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7739 // Didn't find a legal store type.
7740 if (!TLI.isTypeLegal(StoreType))
7743 // Bitcast the original vector into a vector of store-size units
7744 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7745 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7746 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7747 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7748 SmallVector<SDValue, 8> Chains;
7749 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7750 TLI.getPointerTy());
7751 SDValue BasePtr = St->getBasePtr();
7753 // Perform one or more big stores into memory.
7754 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7755 for (unsigned I = 0; I < E; I++) {
7756 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7757 StoreType, ShuffWide,
7758 DAG.getIntPtrConstant(I));
7759 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7760 St->getPointerInfo(), St->isVolatile(),
7761 St->isNonTemporal(), St->getAlignment());
7762 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7764 Chains.push_back(Ch);
7766 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7770 if (!ISD::isNormalStore(St))
7773 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7774 // ARM stores of arguments in the same cache line.
7775 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7776 StVal.getNode()->hasOneUse()) {
7777 SelectionDAG &DAG = DCI.DAG;
7778 DebugLoc DL = St->getDebugLoc();
7779 SDValue BasePtr = St->getBasePtr();
7780 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7781 StVal.getNode()->getOperand(0), BasePtr,
7782 St->getPointerInfo(), St->isVolatile(),
7783 St->isNonTemporal(), St->getAlignment());
7785 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7786 DAG.getConstant(4, MVT::i32));
7787 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7788 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7789 St->isNonTemporal(),
7790 std::min(4U, St->getAlignment() / 2));
7793 if (StVal.getValueType() != MVT::i64 ||
7794 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7797 // Bitcast an i64 store extracted from a vector to f64.
7798 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7799 SelectionDAG &DAG = DCI.DAG;
7800 DebugLoc dl = StVal.getDebugLoc();
7801 SDValue IntVec = StVal.getOperand(0);
7802 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7803 IntVec.getValueType().getVectorNumElements());
7804 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7805 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7806 Vec, StVal.getOperand(1));
7807 dl = N->getDebugLoc();
7808 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7809 // Make the DAGCombiner fold the bitcasts.
7810 DCI.AddToWorklist(Vec.getNode());
7811 DCI.AddToWorklist(ExtElt.getNode());
7812 DCI.AddToWorklist(V.getNode());
7813 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7814 St->getPointerInfo(), St->isVolatile(),
7815 St->isNonTemporal(), St->getAlignment(),
7819 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7820 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
7821 /// i64 vector to have f64 elements, since the value can then be loaded
7822 /// directly into a VFP register.
7823 static bool hasNormalLoadOperand(SDNode *N) {
7824 unsigned NumElts = N->getValueType(0).getVectorNumElements();
7825 for (unsigned i = 0; i < NumElts; ++i) {
7826 SDNode *Elt = N->getOperand(i).getNode();
7827 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7833 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7834 /// ISD::BUILD_VECTOR.
7835 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7836 TargetLowering::DAGCombinerInfo &DCI){
7837 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7838 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
7839 // into a pair of GPRs, which is fine when the value is used as a scalar,
7840 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7841 SelectionDAG &DAG = DCI.DAG;
7842 if (N->getNumOperands() == 2) {
7843 SDValue RV = PerformVMOVDRRCombine(N, DAG);
7848 // Load i64 elements as f64 values so that type legalization does not split
7849 // them up into i32 values.
7850 EVT VT = N->getValueType(0);
7851 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7853 DebugLoc dl = N->getDebugLoc();
7854 SmallVector<SDValue, 8> Ops;
7855 unsigned NumElts = VT.getVectorNumElements();
7856 for (unsigned i = 0; i < NumElts; ++i) {
7857 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7859 // Make the DAGCombiner fold the bitcast.
7860 DCI.AddToWorklist(V.getNode());
7862 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7863 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7864 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7867 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7868 /// ISD::INSERT_VECTOR_ELT.
7869 static SDValue PerformInsertEltCombine(SDNode *N,
7870 TargetLowering::DAGCombinerInfo &DCI) {
7871 // Bitcast an i64 load inserted into a vector to f64.
7872 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7873 EVT VT = N->getValueType(0);
7874 SDNode *Elt = N->getOperand(1).getNode();
7875 if (VT.getVectorElementType() != MVT::i64 ||
7876 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7879 SelectionDAG &DAG = DCI.DAG;
7880 DebugLoc dl = N->getDebugLoc();
7881 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7882 VT.getVectorNumElements());
7883 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7884 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7885 // Make the DAGCombiner fold the bitcasts.
7886 DCI.AddToWorklist(Vec.getNode());
7887 DCI.AddToWorklist(V.getNode());
7888 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7889 Vec, V, N->getOperand(2));
7890 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7893 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7894 /// ISD::VECTOR_SHUFFLE.
7895 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7896 // The LLVM shufflevector instruction does not require the shuffle mask
7897 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7898 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
7899 // operands do not match the mask length, they are extended by concatenating
7900 // them with undef vectors. That is probably the right thing for other
7901 // targets, but for NEON it is better to concatenate two double-register
7902 // size vector operands into a single quad-register size vector. Do that
7903 // transformation here:
7904 // shuffle(concat(v1, undef), concat(v2, undef)) ->
7905 // shuffle(concat(v1, v2), undef)
7906 SDValue Op0 = N->getOperand(0);
7907 SDValue Op1 = N->getOperand(1);
7908 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7909 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7910 Op0.getNumOperands() != 2 ||
7911 Op1.getNumOperands() != 2)
7913 SDValue Concat0Op1 = Op0.getOperand(1);
7914 SDValue Concat1Op1 = Op1.getOperand(1);
7915 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7916 Concat1Op1.getOpcode() != ISD::UNDEF)
7918 // Skip the transformation if any of the types are illegal.
7919 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7920 EVT VT = N->getValueType(0);
7921 if (!TLI.isTypeLegal(VT) ||
7922 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7923 !TLI.isTypeLegal(Concat1Op1.getValueType()))
7926 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7927 Op0.getOperand(0), Op1.getOperand(0));
7928 // Translate the shuffle mask.
7929 SmallVector<int, 16> NewMask;
7930 unsigned NumElts = VT.getVectorNumElements();
7931 unsigned HalfElts = NumElts/2;
7932 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7933 for (unsigned n = 0; n < NumElts; ++n) {
7934 int MaskElt = SVN->getMaskElt(n);
7936 if (MaskElt < (int)HalfElts)
7938 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7939 NewElt = HalfElts + MaskElt - NumElts;
7940 NewMask.push_back(NewElt);
7942 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7943 DAG.getUNDEF(VT), NewMask.data());
7946 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7947 /// NEON load/store intrinsics to merge base address updates.
7948 static SDValue CombineBaseUpdate(SDNode *N,
7949 TargetLowering::DAGCombinerInfo &DCI) {
7950 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7953 SelectionDAG &DAG = DCI.DAG;
7954 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7955 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7956 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7957 SDValue Addr = N->getOperand(AddrOpIdx);
7959 // Search for a use of the address operand that is an increment.
7960 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7961 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7963 if (User->getOpcode() != ISD::ADD ||
7964 UI.getUse().getResNo() != Addr.getResNo())
7967 // Check that the add is independent of the load/store. Otherwise, folding
7968 // it would create a cycle.
7969 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7972 // Find the new opcode for the updating load/store.
7974 bool isLaneOp = false;
7975 unsigned NewOpc = 0;
7976 unsigned NumVecs = 0;
7978 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7980 default: llvm_unreachable("unexpected intrinsic for Neon base update");
7981 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
7983 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
7985 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
7987 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
7989 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7990 NumVecs = 2; isLaneOp = true; break;
7991 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7992 NumVecs = 3; isLaneOp = true; break;
7993 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7994 NumVecs = 4; isLaneOp = true; break;
7995 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
7996 NumVecs = 1; isLoad = false; break;
7997 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
7998 NumVecs = 2; isLoad = false; break;
7999 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8000 NumVecs = 3; isLoad = false; break;
8001 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8002 NumVecs = 4; isLoad = false; break;
8003 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8004 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8005 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8006 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8007 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8008 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8012 switch (N->getOpcode()) {
8013 default: llvm_unreachable("unexpected opcode for Neon base update");
8014 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8015 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8016 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8020 // Find the size of memory referenced by the load/store.
8023 VecTy = N->getValueType(0);
8025 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8026 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8028 NumBytes /= VecTy.getVectorNumElements();
8030 // If the increment is a constant, it must match the memory ref size.
8031 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8032 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8033 uint64_t IncVal = CInc->getZExtValue();
8034 if (IncVal != NumBytes)
8036 } else if (NumBytes >= 3 * 16) {
8037 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8038 // separate instructions that make it harder to use a non-constant update.
8042 // Create the new updating load/store node.
8044 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8046 for (n = 0; n < NumResultVecs; ++n)
8048 Tys[n++] = MVT::i32;
8049 Tys[n] = MVT::Other;
8050 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8051 SmallVector<SDValue, 8> Ops;
8052 Ops.push_back(N->getOperand(0)); // incoming chain
8053 Ops.push_back(N->getOperand(AddrOpIdx));
8055 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8056 Ops.push_back(N->getOperand(i));
8058 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8059 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8060 Ops.data(), Ops.size(),
8061 MemInt->getMemoryVT(),
8062 MemInt->getMemOperand());
8065 std::vector<SDValue> NewResults;
8066 for (unsigned i = 0; i < NumResultVecs; ++i) {
8067 NewResults.push_back(SDValue(UpdN.getNode(), i));
8069 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8070 DCI.CombineTo(N, NewResults);
8071 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8078 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8079 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8080 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8082 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8083 SelectionDAG &DAG = DCI.DAG;
8084 EVT VT = N->getValueType(0);
8085 // vldN-dup instructions only support 64-bit vectors for N > 1.
8086 if (!VT.is64BitVector())
8089 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8090 SDNode *VLD = N->getOperand(0).getNode();
8091 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8093 unsigned NumVecs = 0;
8094 unsigned NewOpc = 0;
8095 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8096 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8098 NewOpc = ARMISD::VLD2DUP;
8099 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8101 NewOpc = ARMISD::VLD3DUP;
8102 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8104 NewOpc = ARMISD::VLD4DUP;
8109 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8110 // numbers match the load.
8111 unsigned VLDLaneNo =
8112 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8113 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8115 // Ignore uses of the chain result.
8116 if (UI.getUse().getResNo() == NumVecs)
8119 if (User->getOpcode() != ARMISD::VDUPLANE ||
8120 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8124 // Create the vldN-dup node.
8127 for (n = 0; n < NumVecs; ++n)
8129 Tys[n] = MVT::Other;
8130 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8131 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8132 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8133 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8134 Ops, 2, VLDMemInt->getMemoryVT(),
8135 VLDMemInt->getMemOperand());
8138 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8140 unsigned ResNo = UI.getUse().getResNo();
8141 // Ignore uses of the chain result.
8142 if (ResNo == NumVecs)
8145 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8148 // Now the vldN-lane intrinsic is dead except for its chain result.
8149 // Update uses of the chain.
8150 std::vector<SDValue> VLDDupResults;
8151 for (unsigned n = 0; n < NumVecs; ++n)
8152 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8153 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8154 DCI.CombineTo(VLD, VLDDupResults);
8159 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8160 /// ARMISD::VDUPLANE.
8161 static SDValue PerformVDUPLANECombine(SDNode *N,
8162 TargetLowering::DAGCombinerInfo &DCI) {
8163 SDValue Op = N->getOperand(0);
8165 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8166 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8167 if (CombineVLDDUP(N, DCI))
8168 return SDValue(N, 0);
8170 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8171 // redundant. Ignore bit_converts for now; element sizes are checked below.
8172 while (Op.getOpcode() == ISD::BITCAST)
8173 Op = Op.getOperand(0);
8174 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8177 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8178 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8179 // The canonical VMOV for a zero vector uses a 32-bit element size.
8180 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8182 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8184 EVT VT = N->getValueType(0);
8185 if (EltSize > VT.getVectorElementType().getSizeInBits())
8188 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8191 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8192 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8193 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8197 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8199 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8204 APFloat APF = C->getValueAPF();
8205 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8206 != APFloat::opOK || !isExact)
8209 c0 = (I == 0) ? cN : c0;
8210 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8217 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8218 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8219 /// when the VMUL has a constant operand that is a power of 2.
8221 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8222 /// vmul.f32 d16, d17, d16
8223 /// vcvt.s32.f32 d16, d16
8225 /// vcvt.s32.f32 d16, d16, #3
8226 static SDValue PerformVCVTCombine(SDNode *N,
8227 TargetLowering::DAGCombinerInfo &DCI,
8228 const ARMSubtarget *Subtarget) {
8229 SelectionDAG &DAG = DCI.DAG;
8230 SDValue Op = N->getOperand(0);
8232 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8233 Op.getOpcode() != ISD::FMUL)
8237 SDValue N0 = Op->getOperand(0);
8238 SDValue ConstVec = Op->getOperand(1);
8239 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8241 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8242 !isConstVecPow2(ConstVec, isSigned, C))
8245 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8246 Intrinsic::arm_neon_vcvtfp2fxu;
8247 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8249 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8250 DAG.getConstant(Log2_64(C), MVT::i32));
8253 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8254 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8255 /// when the VDIV has a constant operand that is a power of 2.
8257 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8258 /// vcvt.f32.s32 d16, d16
8259 /// vdiv.f32 d16, d17, d16
8261 /// vcvt.f32.s32 d16, d16, #3
8262 static SDValue PerformVDIVCombine(SDNode *N,
8263 TargetLowering::DAGCombinerInfo &DCI,
8264 const ARMSubtarget *Subtarget) {
8265 SelectionDAG &DAG = DCI.DAG;
8266 SDValue Op = N->getOperand(0);
8267 unsigned OpOpcode = Op.getNode()->getOpcode();
8269 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8270 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8274 SDValue ConstVec = N->getOperand(1);
8275 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8277 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8278 !isConstVecPow2(ConstVec, isSigned, C))
8281 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8282 Intrinsic::arm_neon_vcvtfxu2fp;
8283 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8285 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8286 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8289 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8290 /// operand of a vector shift operation, where all the elements of the
8291 /// build_vector must have the same constant integer value.
8292 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8293 // Ignore bit_converts.
8294 while (Op.getOpcode() == ISD::BITCAST)
8295 Op = Op.getOperand(0);
8296 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8297 APInt SplatBits, SplatUndef;
8298 unsigned SplatBitSize;
8300 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8301 HasAnyUndefs, ElementBits) ||
8302 SplatBitSize > ElementBits)
8304 Cnt = SplatBits.getSExtValue();
8308 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8309 /// operand of a vector shift left operation. That value must be in the range:
8310 /// 0 <= Value < ElementBits for a left shift; or
8311 /// 0 <= Value <= ElementBits for a long left shift.
8312 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8313 assert(VT.isVector() && "vector shift count is not a vector type");
8314 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8315 if (! getVShiftImm(Op, ElementBits, Cnt))
8317 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8320 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8321 /// operand of a vector shift right operation. For a shift opcode, the value
8322 /// is positive, but for an intrinsic the value count must be negative. The
8323 /// absolute value must be in the range:
8324 /// 1 <= |Value| <= ElementBits for a right shift; or
8325 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8326 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8328 assert(VT.isVector() && "vector shift count is not a vector type");
8329 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8330 if (! getVShiftImm(Op, ElementBits, Cnt))
8334 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8337 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8338 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8339 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8342 // Don't do anything for most intrinsics.
8345 // Vector shifts: check for immediate versions and lower them.
8346 // Note: This is done during DAG combining instead of DAG legalizing because
8347 // the build_vectors for 64-bit vector element shift counts are generally
8348 // not legal, and it is hard to see their values after they get legalized to
8349 // loads from a constant pool.
8350 case Intrinsic::arm_neon_vshifts:
8351 case Intrinsic::arm_neon_vshiftu:
8352 case Intrinsic::arm_neon_vshiftls:
8353 case Intrinsic::arm_neon_vshiftlu:
8354 case Intrinsic::arm_neon_vshiftn:
8355 case Intrinsic::arm_neon_vrshifts:
8356 case Intrinsic::arm_neon_vrshiftu:
8357 case Intrinsic::arm_neon_vrshiftn:
8358 case Intrinsic::arm_neon_vqshifts:
8359 case Intrinsic::arm_neon_vqshiftu:
8360 case Intrinsic::arm_neon_vqshiftsu:
8361 case Intrinsic::arm_neon_vqshiftns:
8362 case Intrinsic::arm_neon_vqshiftnu:
8363 case Intrinsic::arm_neon_vqshiftnsu:
8364 case Intrinsic::arm_neon_vqrshiftns:
8365 case Intrinsic::arm_neon_vqrshiftnu:
8366 case Intrinsic::arm_neon_vqrshiftnsu: {
8367 EVT VT = N->getOperand(1).getValueType();
8369 unsigned VShiftOpc = 0;
8372 case Intrinsic::arm_neon_vshifts:
8373 case Intrinsic::arm_neon_vshiftu:
8374 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8375 VShiftOpc = ARMISD::VSHL;
8378 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8379 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8380 ARMISD::VSHRs : ARMISD::VSHRu);
8385 case Intrinsic::arm_neon_vshiftls:
8386 case Intrinsic::arm_neon_vshiftlu:
8387 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8389 llvm_unreachable("invalid shift count for vshll intrinsic");
8391 case Intrinsic::arm_neon_vrshifts:
8392 case Intrinsic::arm_neon_vrshiftu:
8393 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8397 case Intrinsic::arm_neon_vqshifts:
8398 case Intrinsic::arm_neon_vqshiftu:
8399 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8403 case Intrinsic::arm_neon_vqshiftsu:
8404 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8406 llvm_unreachable("invalid shift count for vqshlu intrinsic");
8408 case Intrinsic::arm_neon_vshiftn:
8409 case Intrinsic::arm_neon_vrshiftn:
8410 case Intrinsic::arm_neon_vqshiftns:
8411 case Intrinsic::arm_neon_vqshiftnu:
8412 case Intrinsic::arm_neon_vqshiftnsu:
8413 case Intrinsic::arm_neon_vqrshiftns:
8414 case Intrinsic::arm_neon_vqrshiftnu:
8415 case Intrinsic::arm_neon_vqrshiftnsu:
8416 // Narrowing shifts require an immediate right shift.
8417 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8419 llvm_unreachable("invalid shift count for narrowing vector shift "
8423 llvm_unreachable("unhandled vector shift");
8427 case Intrinsic::arm_neon_vshifts:
8428 case Intrinsic::arm_neon_vshiftu:
8429 // Opcode already set above.
8431 case Intrinsic::arm_neon_vshiftls:
8432 case Intrinsic::arm_neon_vshiftlu:
8433 if (Cnt == VT.getVectorElementType().getSizeInBits())
8434 VShiftOpc = ARMISD::VSHLLi;
8436 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8437 ARMISD::VSHLLs : ARMISD::VSHLLu);
8439 case Intrinsic::arm_neon_vshiftn:
8440 VShiftOpc = ARMISD::VSHRN; break;
8441 case Intrinsic::arm_neon_vrshifts:
8442 VShiftOpc = ARMISD::VRSHRs; break;
8443 case Intrinsic::arm_neon_vrshiftu:
8444 VShiftOpc = ARMISD::VRSHRu; break;
8445 case Intrinsic::arm_neon_vrshiftn:
8446 VShiftOpc = ARMISD::VRSHRN; break;
8447 case Intrinsic::arm_neon_vqshifts:
8448 VShiftOpc = ARMISD::VQSHLs; break;
8449 case Intrinsic::arm_neon_vqshiftu:
8450 VShiftOpc = ARMISD::VQSHLu; break;
8451 case Intrinsic::arm_neon_vqshiftsu:
8452 VShiftOpc = ARMISD::VQSHLsu; break;
8453 case Intrinsic::arm_neon_vqshiftns:
8454 VShiftOpc = ARMISD::VQSHRNs; break;
8455 case Intrinsic::arm_neon_vqshiftnu:
8456 VShiftOpc = ARMISD::VQSHRNu; break;
8457 case Intrinsic::arm_neon_vqshiftnsu:
8458 VShiftOpc = ARMISD::VQSHRNsu; break;
8459 case Intrinsic::arm_neon_vqrshiftns:
8460 VShiftOpc = ARMISD::VQRSHRNs; break;
8461 case Intrinsic::arm_neon_vqrshiftnu:
8462 VShiftOpc = ARMISD::VQRSHRNu; break;
8463 case Intrinsic::arm_neon_vqrshiftnsu:
8464 VShiftOpc = ARMISD::VQRSHRNsu; break;
8467 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8468 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8471 case Intrinsic::arm_neon_vshiftins: {
8472 EVT VT = N->getOperand(1).getValueType();
8474 unsigned VShiftOpc = 0;
8476 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8477 VShiftOpc = ARMISD::VSLI;
8478 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8479 VShiftOpc = ARMISD::VSRI;
8481 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8484 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8485 N->getOperand(1), N->getOperand(2),
8486 DAG.getConstant(Cnt, MVT::i32));
8489 case Intrinsic::arm_neon_vqrshifts:
8490 case Intrinsic::arm_neon_vqrshiftu:
8491 // No immediate versions of these to check for.
8498 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8499 /// lowers them. As with the vector shift intrinsics, this is done during DAG
8500 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8501 /// vector element shift counts are generally not legal, and it is hard to see
8502 /// their values after they get legalized to loads from a constant pool.
8503 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8504 const ARMSubtarget *ST) {
8505 EVT VT = N->getValueType(0);
8506 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8507 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8508 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8509 SDValue N1 = N->getOperand(1);
8510 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8511 SDValue N0 = N->getOperand(0);
8512 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8513 DAG.MaskedValueIsZero(N0.getOperand(0),
8514 APInt::getHighBitsSet(32, 16)))
8515 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8519 // Nothing to be done for scalar shifts.
8520 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8521 if (!VT.isVector() || !TLI.isTypeLegal(VT))
8524 assert(ST->hasNEON() && "unexpected vector shift");
8527 switch (N->getOpcode()) {
8528 default: llvm_unreachable("unexpected shift opcode");
8531 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8532 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8533 DAG.getConstant(Cnt, MVT::i32));
8538 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8539 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8540 ARMISD::VSHRs : ARMISD::VSHRu);
8541 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8542 DAG.getConstant(Cnt, MVT::i32));
8548 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8549 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8550 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8551 const ARMSubtarget *ST) {
8552 SDValue N0 = N->getOperand(0);
8554 // Check for sign- and zero-extensions of vector extract operations of 8-
8555 // and 16-bit vector elements. NEON supports these directly. They are
8556 // handled during DAG combining because type legalization will promote them
8557 // to 32-bit types and it is messy to recognize the operations after that.
8558 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8559 SDValue Vec = N0.getOperand(0);
8560 SDValue Lane = N0.getOperand(1);
8561 EVT VT = N->getValueType(0);
8562 EVT EltVT = N0.getValueType();
8563 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8565 if (VT == MVT::i32 &&
8566 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8567 TLI.isTypeLegal(Vec.getValueType()) &&
8568 isa<ConstantSDNode>(Lane)) {
8571 switch (N->getOpcode()) {
8572 default: llvm_unreachable("unexpected opcode");
8573 case ISD::SIGN_EXTEND:
8574 Opc = ARMISD::VGETLANEs;
8576 case ISD::ZERO_EXTEND:
8577 case ISD::ANY_EXTEND:
8578 Opc = ARMISD::VGETLANEu;
8581 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8588 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8589 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8590 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8591 const ARMSubtarget *ST) {
8592 // If the target supports NEON, try to use vmax/vmin instructions for f32
8593 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
8594 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
8595 // a NaN; only do the transformation when it matches that behavior.
8597 // For now only do this when using NEON for FP operations; if using VFP, it
8598 // is not obvious that the benefit outweighs the cost of switching to the
8600 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8601 N->getValueType(0) != MVT::f32)
8604 SDValue CondLHS = N->getOperand(0);
8605 SDValue CondRHS = N->getOperand(1);
8606 SDValue LHS = N->getOperand(2);
8607 SDValue RHS = N->getOperand(3);
8608 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8610 unsigned Opcode = 0;
8612 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8613 IsReversed = false; // x CC y ? x : y
8614 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8615 IsReversed = true ; // x CC y ? y : x
8629 // If LHS is NaN, an ordered comparison will be false and the result will
8630 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
8631 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8632 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8633 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8635 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8636 // will return -0, so vmin can only be used for unsafe math or if one of
8637 // the operands is known to be nonzero.
8638 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8639 !DAG.getTarget().Options.UnsafeFPMath &&
8640 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8642 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8651 // If LHS is NaN, an ordered comparison will be false and the result will
8652 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
8653 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8654 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8655 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8657 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8658 // will return +0, so vmax can only be used for unsafe math or if one of
8659 // the operands is known to be nonzero.
8660 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8661 !DAG.getTarget().Options.UnsafeFPMath &&
8662 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8664 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8670 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8673 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8675 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8676 SDValue Cmp = N->getOperand(4);
8677 if (Cmp.getOpcode() != ARMISD::CMPZ)
8678 // Only looking at EQ and NE cases.
8681 EVT VT = N->getValueType(0);
8682 DebugLoc dl = N->getDebugLoc();
8683 SDValue LHS = Cmp.getOperand(0);
8684 SDValue RHS = Cmp.getOperand(1);
8685 SDValue FalseVal = N->getOperand(0);
8686 SDValue TrueVal = N->getOperand(1);
8687 SDValue ARMcc = N->getOperand(2);
8688 ARMCC::CondCodes CC =
8689 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8707 /// FIXME: Turn this into a target neutral optimization?
8709 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8710 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8711 N->getOperand(3), Cmp);
8712 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8714 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8715 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8716 N->getOperand(3), NewCmp);
8719 if (Res.getNode()) {
8720 APInt KnownZero, KnownOne;
8721 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8722 // Capture demanded bits information that would be otherwise lost.
8723 if (KnownZero == 0xfffffffe)
8724 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8725 DAG.getValueType(MVT::i1));
8726 else if (KnownZero == 0xffffff00)
8727 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8728 DAG.getValueType(MVT::i8));
8729 else if (KnownZero == 0xffff0000)
8730 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8731 DAG.getValueType(MVT::i16));
8737 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8738 DAGCombinerInfo &DCI) const {
8739 switch (N->getOpcode()) {
8741 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
8742 case ISD::SUB: return PerformSUBCombine(N, DCI);
8743 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
8744 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
8745 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
8746 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
8747 case ARMISD::BFI: return PerformBFICombine(N, DCI);
8748 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8749 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8750 case ISD::STORE: return PerformSTORECombine(N, DCI);
8751 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8752 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8753 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8754 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8755 case ISD::FP_TO_SINT:
8756 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8757 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
8758 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8761 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
8762 case ISD::SIGN_EXTEND:
8763 case ISD::ZERO_EXTEND:
8764 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8765 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8766 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8767 case ARMISD::VLD2DUP:
8768 case ARMISD::VLD3DUP:
8769 case ARMISD::VLD4DUP:
8770 return CombineBaseUpdate(N, DCI);
8771 case ISD::INTRINSIC_VOID:
8772 case ISD::INTRINSIC_W_CHAIN:
8773 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8774 case Intrinsic::arm_neon_vld1:
8775 case Intrinsic::arm_neon_vld2:
8776 case Intrinsic::arm_neon_vld3:
8777 case Intrinsic::arm_neon_vld4:
8778 case Intrinsic::arm_neon_vld2lane:
8779 case Intrinsic::arm_neon_vld3lane:
8780 case Intrinsic::arm_neon_vld4lane:
8781 case Intrinsic::arm_neon_vst1:
8782 case Intrinsic::arm_neon_vst2:
8783 case Intrinsic::arm_neon_vst3:
8784 case Intrinsic::arm_neon_vst4:
8785 case Intrinsic::arm_neon_vst2lane:
8786 case Intrinsic::arm_neon_vst3lane:
8787 case Intrinsic::arm_neon_vst4lane:
8788 return CombineBaseUpdate(N, DCI);
8796 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8798 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8801 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8802 if (!Subtarget->allowsUnalignedMem())
8805 switch (VT.getSimpleVT().SimpleTy) {
8812 // FIXME: VLD1 etc with standard alignment is legal.
8816 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8817 unsigned AlignCheck) {
8818 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8819 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8822 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8823 unsigned DstAlign, unsigned SrcAlign,
8826 MachineFunction &MF) const {
8827 const Function *F = MF.getFunction();
8829 // See if we can use NEON instructions for this...
8831 !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8832 Subtarget->hasNEON()) {
8833 if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8835 } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8840 // Lowering to i32/i16 if the size permits.
8843 } else if (Size >= 2) {
8847 // Let the target-independent logic figure it out.
8851 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8856 switch (VT.getSimpleVT().SimpleTy) {
8857 default: return false;
8872 if ((V & (Scale - 1)) != 0)
8875 return V == (V & ((1LL << 5) - 1));
8878 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8879 const ARMSubtarget *Subtarget) {
8886 switch (VT.getSimpleVT().SimpleTy) {
8887 default: return false;
8892 // + imm12 or - imm8
8894 return V == (V & ((1LL << 8) - 1));
8895 return V == (V & ((1LL << 12) - 1));
8898 // Same as ARM mode. FIXME: NEON?
8899 if (!Subtarget->hasVFP2())
8904 return V == (V & ((1LL << 8) - 1));
8908 /// isLegalAddressImmediate - Return true if the integer value can be used
8909 /// as the offset of the target addressing mode for load / store of the
8911 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8912 const ARMSubtarget *Subtarget) {
8919 if (Subtarget->isThumb1Only())
8920 return isLegalT1AddressImmediate(V, VT);
8921 else if (Subtarget->isThumb2())
8922 return isLegalT2AddressImmediate(V, VT, Subtarget);
8927 switch (VT.getSimpleVT().SimpleTy) {
8928 default: return false;
8933 return V == (V & ((1LL << 12) - 1));
8936 return V == (V & ((1LL << 8) - 1));
8939 if (!Subtarget->hasVFP2()) // FIXME: NEON?
8944 return V == (V & ((1LL << 8) - 1));
8948 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8950 int Scale = AM.Scale;
8954 switch (VT.getSimpleVT().SimpleTy) {
8955 default: return false;
8964 return Scale == 2 || Scale == 4 || Scale == 8;
8967 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8971 // Note, we allow "void" uses (basically, uses that aren't loads or
8972 // stores), because arm allows folding a scale into many arithmetic
8973 // operations. This should be made more precise and revisited later.
8975 // Allow r << imm, but the imm has to be a multiple of two.
8976 if (Scale & 1) return false;
8977 return isPowerOf2_32(Scale);
8981 /// isLegalAddressingMode - Return true if the addressing mode represented
8982 /// by AM is legal for this target, for a load/store of the specified type.
8983 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8985 EVT VT = getValueType(Ty, true);
8986 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8989 // Can never fold addr of global into load/store.
8994 case 0: // no scale reg, must be "r+i" or "r", or "i".
8997 if (Subtarget->isThumb1Only())
9001 // ARM doesn't support any R+R*scale+imm addr modes.
9008 if (Subtarget->isThumb2())
9009 return isLegalT2ScaledAddressingMode(AM, VT);
9011 int Scale = AM.Scale;
9012 switch (VT.getSimpleVT().SimpleTy) {
9013 default: return false;
9017 if (Scale < 0) Scale = -Scale;
9021 return isPowerOf2_32(Scale & ~1);
9025 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9030 // Note, we allow "void" uses (basically, uses that aren't loads or
9031 // stores), because arm allows folding a scale into many arithmetic
9032 // operations. This should be made more precise and revisited later.
9034 // Allow r << imm, but the imm has to be a multiple of two.
9035 if (Scale & 1) return false;
9036 return isPowerOf2_32(Scale);
9042 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9043 /// icmp immediate, that is the target has icmp instructions which can compare
9044 /// a register against the immediate without having to materialize the
9045 /// immediate into a register.
9046 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9047 // Thumb2 and ARM modes can use cmn for negative immediates.
9048 if (!Subtarget->isThumb())
9049 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9050 if (Subtarget->isThumb2())
9051 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9052 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9053 return Imm >= 0 && Imm <= 255;
9056 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9057 /// *or sub* immediate, that is the target has add or sub instructions which can
9058 /// add a register with the immediate without having to materialize the
9059 /// immediate into a register.
9060 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9061 // Same encoding for add/sub, just flip the sign.
9062 int64_t AbsImm = llvm::abs64(Imm);
9063 if (!Subtarget->isThumb())
9064 return ARM_AM::getSOImmVal(AbsImm) != -1;
9065 if (Subtarget->isThumb2())
9066 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9067 // Thumb1 only has 8-bit unsigned immediate.
9068 return AbsImm >= 0 && AbsImm <= 255;
9071 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9072 bool isSEXTLoad, SDValue &Base,
9073 SDValue &Offset, bool &isInc,
9074 SelectionDAG &DAG) {
9075 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9078 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9080 Base = Ptr->getOperand(0);
9081 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9082 int RHSC = (int)RHS->getZExtValue();
9083 if (RHSC < 0 && RHSC > -256) {
9084 assert(Ptr->getOpcode() == ISD::ADD);
9086 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9090 isInc = (Ptr->getOpcode() == ISD::ADD);
9091 Offset = Ptr->getOperand(1);
9093 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9095 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9096 int RHSC = (int)RHS->getZExtValue();
9097 if (RHSC < 0 && RHSC > -0x1000) {
9098 assert(Ptr->getOpcode() == ISD::ADD);
9100 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9101 Base = Ptr->getOperand(0);
9106 if (Ptr->getOpcode() == ISD::ADD) {
9108 ARM_AM::ShiftOpc ShOpcVal=
9109 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9110 if (ShOpcVal != ARM_AM::no_shift) {
9111 Base = Ptr->getOperand(1);
9112 Offset = Ptr->getOperand(0);
9114 Base = Ptr->getOperand(0);
9115 Offset = Ptr->getOperand(1);
9120 isInc = (Ptr->getOpcode() == ISD::ADD);
9121 Base = Ptr->getOperand(0);
9122 Offset = Ptr->getOperand(1);
9126 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9130 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9131 bool isSEXTLoad, SDValue &Base,
9132 SDValue &Offset, bool &isInc,
9133 SelectionDAG &DAG) {
9134 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9137 Base = Ptr->getOperand(0);
9138 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9139 int RHSC = (int)RHS->getZExtValue();
9140 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9141 assert(Ptr->getOpcode() == ISD::ADD);
9143 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9145 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9146 isInc = Ptr->getOpcode() == ISD::ADD;
9147 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9155 /// getPreIndexedAddressParts - returns true by value, base pointer and
9156 /// offset pointer and addressing mode by reference if the node's address
9157 /// can be legally represented as pre-indexed load / store address.
9159 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9161 ISD::MemIndexedMode &AM,
9162 SelectionDAG &DAG) const {
9163 if (Subtarget->isThumb1Only())
9168 bool isSEXTLoad = false;
9169 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9170 Ptr = LD->getBasePtr();
9171 VT = LD->getMemoryVT();
9172 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9173 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9174 Ptr = ST->getBasePtr();
9175 VT = ST->getMemoryVT();
9180 bool isLegal = false;
9181 if (Subtarget->isThumb2())
9182 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9183 Offset, isInc, DAG);
9185 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9186 Offset, isInc, DAG);
9190 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9194 /// getPostIndexedAddressParts - returns true by value, base pointer and
9195 /// offset pointer and addressing mode by reference if this node can be
9196 /// combined with a load / store to form a post-indexed load / store.
9197 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9200 ISD::MemIndexedMode &AM,
9201 SelectionDAG &DAG) const {
9202 if (Subtarget->isThumb1Only())
9207 bool isSEXTLoad = false;
9208 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9209 VT = LD->getMemoryVT();
9210 Ptr = LD->getBasePtr();
9211 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9212 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9213 VT = ST->getMemoryVT();
9214 Ptr = ST->getBasePtr();
9219 bool isLegal = false;
9220 if (Subtarget->isThumb2())
9221 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9224 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9230 // Swap base ptr and offset to catch more post-index load / store when
9231 // it's legal. In Thumb2 mode, offset must be an immediate.
9232 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9233 !Subtarget->isThumb2())
9234 std::swap(Base, Offset);
9236 // Post-indexed load / store update the base pointer.
9241 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9245 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9248 const SelectionDAG &DAG,
9249 unsigned Depth) const {
9250 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9251 switch (Op.getOpcode()) {
9253 case ARMISD::CMOV: {
9254 // Bits are known zero/one if known on the LHS and RHS.
9255 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9256 if (KnownZero == 0 && KnownOne == 0) return;
9258 APInt KnownZeroRHS, KnownOneRHS;
9259 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9260 KnownZero &= KnownZeroRHS;
9261 KnownOne &= KnownOneRHS;
9267 //===----------------------------------------------------------------------===//
9268 // ARM Inline Assembly Support
9269 //===----------------------------------------------------------------------===//
9271 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9272 // Looking for "rev" which is V6+.
9273 if (!Subtarget->hasV6Ops())
9276 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9277 std::string AsmStr = IA->getAsmString();
9278 SmallVector<StringRef, 4> AsmPieces;
9279 SplitString(AsmStr, AsmPieces, ";\n");
9281 switch (AsmPieces.size()) {
9282 default: return false;
9284 AsmStr = AsmPieces[0];
9286 SplitString(AsmStr, AsmPieces, " \t,");
9289 if (AsmPieces.size() == 3 &&
9290 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9291 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9292 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9293 if (Ty && Ty->getBitWidth() == 32)
9294 return IntrinsicLowering::LowerToByteSwap(CI);
9302 /// getConstraintType - Given a constraint letter, return the type of
9303 /// constraint it is for this target.
9304 ARMTargetLowering::ConstraintType
9305 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9306 if (Constraint.size() == 1) {
9307 switch (Constraint[0]) {
9309 case 'l': return C_RegisterClass;
9310 case 'w': return C_RegisterClass;
9311 case 'h': return C_RegisterClass;
9312 case 'x': return C_RegisterClass;
9313 case 't': return C_RegisterClass;
9314 case 'j': return C_Other; // Constant for movw.
9315 // An address with a single base register. Due to the way we
9316 // currently handle addresses it is the same as an 'r' memory constraint.
9317 case 'Q': return C_Memory;
9319 } else if (Constraint.size() == 2) {
9320 switch (Constraint[0]) {
9322 // All 'U+' constraints are addresses.
9323 case 'U': return C_Memory;
9326 return TargetLowering::getConstraintType(Constraint);
9329 /// Examine constraint type and operand type and determine a weight value.
9330 /// This object must already have been set up with the operand type
9331 /// and the current alternative constraint selected.
9332 TargetLowering::ConstraintWeight
9333 ARMTargetLowering::getSingleConstraintMatchWeight(
9334 AsmOperandInfo &info, const char *constraint) const {
9335 ConstraintWeight weight = CW_Invalid;
9336 Value *CallOperandVal = info.CallOperandVal;
9337 // If we don't have a value, we can't do a match,
9338 // but allow it at the lowest weight.
9339 if (CallOperandVal == NULL)
9341 Type *type = CallOperandVal->getType();
9342 // Look at the constraint type.
9343 switch (*constraint) {
9345 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9348 if (type->isIntegerTy()) {
9349 if (Subtarget->isThumb())
9350 weight = CW_SpecificReg;
9352 weight = CW_Register;
9356 if (type->isFloatingPointTy())
9357 weight = CW_Register;
9363 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9365 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9367 if (Constraint.size() == 1) {
9368 // GCC ARM Constraint Letters
9369 switch (Constraint[0]) {
9370 case 'l': // Low regs or general regs.
9371 if (Subtarget->isThumb())
9372 return RCPair(0U, &ARM::tGPRRegClass);
9373 return RCPair(0U, &ARM::GPRRegClass);
9374 case 'h': // High regs or no regs.
9375 if (Subtarget->isThumb())
9376 return RCPair(0U, &ARM::hGPRRegClass);
9379 return RCPair(0U, &ARM::GPRRegClass);
9382 return RCPair(0U, &ARM::SPRRegClass);
9383 if (VT.getSizeInBits() == 64)
9384 return RCPair(0U, &ARM::DPRRegClass);
9385 if (VT.getSizeInBits() == 128)
9386 return RCPair(0U, &ARM::QPRRegClass);
9390 return RCPair(0U, &ARM::SPR_8RegClass);
9391 if (VT.getSizeInBits() == 64)
9392 return RCPair(0U, &ARM::DPR_8RegClass);
9393 if (VT.getSizeInBits() == 128)
9394 return RCPair(0U, &ARM::QPR_8RegClass);
9398 return RCPair(0U, &ARM::SPRRegClass);
9402 if (StringRef("{cc}").equals_lower(Constraint))
9403 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9405 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9408 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9409 /// vector. If it is invalid, don't add anything to Ops.
9410 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9411 std::string &Constraint,
9412 std::vector<SDValue>&Ops,
9413 SelectionDAG &DAG) const {
9414 SDValue Result(0, 0);
9416 // Currently only support length 1 constraints.
9417 if (Constraint.length() != 1) return;
9419 char ConstraintLetter = Constraint[0];
9420 switch (ConstraintLetter) {
9423 case 'I': case 'J': case 'K': case 'L':
9424 case 'M': case 'N': case 'O':
9425 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9429 int64_t CVal64 = C->getSExtValue();
9430 int CVal = (int) CVal64;
9431 // None of these constraints allow values larger than 32 bits. Check
9432 // that the value fits in an int.
9436 switch (ConstraintLetter) {
9438 // Constant suitable for movw, must be between 0 and
9440 if (Subtarget->hasV6T2Ops())
9441 if (CVal >= 0 && CVal <= 65535)
9445 if (Subtarget->isThumb1Only()) {
9446 // This must be a constant between 0 and 255, for ADD
9448 if (CVal >= 0 && CVal <= 255)
9450 } else if (Subtarget->isThumb2()) {
9451 // A constant that can be used as an immediate value in a
9452 // data-processing instruction.
9453 if (ARM_AM::getT2SOImmVal(CVal) != -1)
9456 // A constant that can be used as an immediate value in a
9457 // data-processing instruction.
9458 if (ARM_AM::getSOImmVal(CVal) != -1)
9464 if (Subtarget->isThumb()) { // FIXME thumb2
9465 // This must be a constant between -255 and -1, for negated ADD
9466 // immediates. This can be used in GCC with an "n" modifier that
9467 // prints the negated value, for use with SUB instructions. It is
9468 // not useful otherwise but is implemented for compatibility.
9469 if (CVal >= -255 && CVal <= -1)
9472 // This must be a constant between -4095 and 4095. It is not clear
9473 // what this constraint is intended for. Implemented for
9474 // compatibility with GCC.
9475 if (CVal >= -4095 && CVal <= 4095)
9481 if (Subtarget->isThumb1Only()) {
9482 // A 32-bit value where only one byte has a nonzero value. Exclude
9483 // zero to match GCC. This constraint is used by GCC internally for
9484 // constants that can be loaded with a move/shift combination.
9485 // It is not useful otherwise but is implemented for compatibility.
9486 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9488 } else if (Subtarget->isThumb2()) {
9489 // A constant whose bitwise inverse can be used as an immediate
9490 // value in a data-processing instruction. This can be used in GCC
9491 // with a "B" modifier that prints the inverted value, for use with
9492 // BIC and MVN instructions. It is not useful otherwise but is
9493 // implemented for compatibility.
9494 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9497 // A constant whose bitwise inverse can be used as an immediate
9498 // value in a data-processing instruction. This can be used in GCC
9499 // with a "B" modifier that prints the inverted value, for use with
9500 // BIC and MVN instructions. It is not useful otherwise but is
9501 // implemented for compatibility.
9502 if (ARM_AM::getSOImmVal(~CVal) != -1)
9508 if (Subtarget->isThumb1Only()) {
9509 // This must be a constant between -7 and 7,
9510 // for 3-operand ADD/SUB immediate instructions.
9511 if (CVal >= -7 && CVal < 7)
9513 } else if (Subtarget->isThumb2()) {
9514 // A constant whose negation can be used as an immediate value in a
9515 // data-processing instruction. This can be used in GCC with an "n"
9516 // modifier that prints the negated value, for use with SUB
9517 // instructions. It is not useful otherwise but is implemented for
9519 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9522 // A constant whose negation can be used as an immediate value in a
9523 // data-processing instruction. This can be used in GCC with an "n"
9524 // modifier that prints the negated value, for use with SUB
9525 // instructions. It is not useful otherwise but is implemented for
9527 if (ARM_AM::getSOImmVal(-CVal) != -1)
9533 if (Subtarget->isThumb()) { // FIXME thumb2
9534 // This must be a multiple of 4 between 0 and 1020, for
9535 // ADD sp + immediate.
9536 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9539 // A power of two or a constant between 0 and 32. This is used in
9540 // GCC for the shift amount on shifted register operands, but it is
9541 // useful in general for any shift amounts.
9542 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9548 if (Subtarget->isThumb()) { // FIXME thumb2
9549 // This must be a constant between 0 and 31, for shift amounts.
9550 if (CVal >= 0 && CVal <= 31)
9556 if (Subtarget->isThumb()) { // FIXME thumb2
9557 // This must be a multiple of 4 between -508 and 508, for
9558 // ADD/SUB sp = sp + immediate.
9559 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9564 Result = DAG.getTargetConstant(CVal, Op.getValueType());
9568 if (Result.getNode()) {
9569 Ops.push_back(Result);
9572 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9576 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9577 // The ARM target isn't yet aware of offsets.
9581 bool ARM::isBitFieldInvertedMask(unsigned v) {
9582 if (v == 0xffffffff)
9584 // there can be 1's on either or both "outsides", all the "inside"
9586 unsigned int lsb = 0, msb = 31;
9587 while (v & (1 << msb)) --msb;
9588 while (v & (1 << lsb)) ++lsb;
9589 for (unsigned int i = lsb; i <= msb; ++i) {
9596 /// isFPImmLegal - Returns true if the target can instruction select the
9597 /// specified FP immediate natively. If false, the legalizer will
9598 /// materialize the FP immediate as a load from a constant pool.
9599 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9600 if (!Subtarget->hasVFP3())
9603 return ARM_AM::getFP32Imm(Imm) != -1;
9605 return ARM_AM::getFP64Imm(Imm) != -1;
9609 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9610 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9611 /// specified in the intrinsic calls.
9612 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9614 unsigned Intrinsic) const {
9615 switch (Intrinsic) {
9616 case Intrinsic::arm_neon_vld1:
9617 case Intrinsic::arm_neon_vld2:
9618 case Intrinsic::arm_neon_vld3:
9619 case Intrinsic::arm_neon_vld4:
9620 case Intrinsic::arm_neon_vld2lane:
9621 case Intrinsic::arm_neon_vld3lane:
9622 case Intrinsic::arm_neon_vld4lane: {
9623 Info.opc = ISD::INTRINSIC_W_CHAIN;
9624 // Conservatively set memVT to the entire set of vectors loaded.
9625 uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9626 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9627 Info.ptrVal = I.getArgOperand(0);
9629 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9630 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9631 Info.vol = false; // volatile loads with NEON intrinsics not supported
9632 Info.readMem = true;
9633 Info.writeMem = false;
9636 case Intrinsic::arm_neon_vst1:
9637 case Intrinsic::arm_neon_vst2:
9638 case Intrinsic::arm_neon_vst3:
9639 case Intrinsic::arm_neon_vst4:
9640 case Intrinsic::arm_neon_vst2lane:
9641 case Intrinsic::arm_neon_vst3lane:
9642 case Intrinsic::arm_neon_vst4lane: {
9643 Info.opc = ISD::INTRINSIC_VOID;
9644 // Conservatively set memVT to the entire set of vectors stored.
9645 unsigned NumElts = 0;
9646 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9647 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9648 if (!ArgTy->isVectorTy())
9650 NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9652 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9653 Info.ptrVal = I.getArgOperand(0);
9655 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9656 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9657 Info.vol = false; // volatile stores with NEON intrinsics not supported
9658 Info.readMem = false;
9659 Info.writeMem = true;
9662 case Intrinsic::arm_strexd: {
9663 Info.opc = ISD::INTRINSIC_W_CHAIN;
9664 Info.memVT = MVT::i64;
9665 Info.ptrVal = I.getArgOperand(2);
9669 Info.readMem = false;
9670 Info.writeMem = true;
9673 case Intrinsic::arm_ldrexd: {
9674 Info.opc = ISD::INTRINSIC_W_CHAIN;
9675 Info.memVT = MVT::i64;
9676 Info.ptrVal = I.getArgOperand(0);
9680 Info.readMem = true;
9681 Info.writeMem = false;