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");
56 // This option should go away when tail calls fully work.
58 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
59 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
63 EnableARMLongCalls("arm-long-calls", cl::Hidden,
64 cl::desc("Generate calls via indirect call instructions"),
68 ARMInterworking("arm-interworking", cl::Hidden,
69 cl::desc("Enable / disable ARM interworking (for debugging only)"),
73 class ARMCCState : public CCState {
75 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
76 const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
77 LLVMContext &C, ParmContext PC)
78 : CCState(CC, isVarArg, MF, TM, locs, C) {
79 assert(((PC == Call) || (PC == Prologue)) &&
80 "ARMCCState users must specify whether their context is call"
81 "or prologue generation.");
87 // The APCS parameter registers.
88 static const uint16_t GPRArgRegs[] = {
89 ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
93 EVT PromotedBitwiseVT) {
94 if (VT != PromotedLdStVT) {
95 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
96 AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
97 PromotedLdStVT.getSimpleVT());
99 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
100 AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
101 PromotedLdStVT.getSimpleVT());
104 EVT ElemTy = VT.getVectorElementType();
105 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
107 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
108 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
109 if (ElemTy == MVT::i32) {
110 setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
111 setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
112 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
113 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
115 setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
116 setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
117 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
118 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
120 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
121 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
122 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
123 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
124 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
125 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
127 if (VT.isInteger()) {
128 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
129 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
130 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
133 // Promote all bit-wise operations.
134 if (VT.isInteger() && VT != PromotedBitwiseVT) {
135 setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
136 AddPromotedToType (ISD::AND, VT.getSimpleVT(),
137 PromotedBitwiseVT.getSimpleVT());
138 setOperationAction(ISD::OR, VT.getSimpleVT(), Promote);
139 AddPromotedToType (ISD::OR, VT.getSimpleVT(),
140 PromotedBitwiseVT.getSimpleVT());
141 setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
142 AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
143 PromotedBitwiseVT.getSimpleVT());
146 // Neon does not support vector divide/remainder operations.
147 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
148 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
149 setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
150 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
151 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
152 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
155 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
156 addRegisterClass(VT, ARM::DPRRegisterClass);
157 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
161 addRegisterClass(VT, ARM::QPRRegisterClass);
162 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
166 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
167 return new TargetLoweringObjectFileMachO();
169 return new ARMElfTargetObjectFile();
172 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
173 : TargetLowering(TM, createTLOF(TM)) {
174 Subtarget = &TM.getSubtarget<ARMSubtarget>();
175 RegInfo = TM.getRegisterInfo();
176 Itins = TM.getInstrItineraryData();
178 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
180 if (Subtarget->isTargetDarwin()) {
181 // Uses VFP for Thumb libfuncs if available.
182 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
183 // Single-precision floating-point arithmetic.
184 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
185 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
186 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
187 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
189 // Double-precision floating-point arithmetic.
190 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
191 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
192 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
193 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
195 // Single-precision comparisons.
196 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
197 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
198 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
199 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
200 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
201 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
202 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
203 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
205 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
210 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
211 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
212 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
214 // Double-precision comparisons.
215 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
216 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
217 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
218 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
219 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
220 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
221 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
222 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
224 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
229 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
230 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
231 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
233 // Floating-point to integer conversions.
234 // i64 conversions are done via library routines even when generating VFP
235 // instructions, so use the same ones.
236 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
237 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
238 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
239 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
241 // Conversions between floating types.
242 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
243 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
245 // Integer to floating-point conversions.
246 // i64 conversions are done via library routines even when generating VFP
247 // instructions, so use the same ones.
248 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
249 // e.g., __floatunsidf vs. __floatunssidfvfp.
250 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
251 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
252 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
253 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
257 // These libcalls are not available in 32-bit.
258 setLibcallName(RTLIB::SHL_I128, 0);
259 setLibcallName(RTLIB::SRL_I128, 0);
260 setLibcallName(RTLIB::SRA_I128, 0);
262 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
263 // Double-precision floating-point arithmetic helper functions
264 // RTABI chapter 4.1.2, Table 2
265 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
266 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
267 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
268 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
269 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
270 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
271 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
272 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
274 // Double-precision floating-point comparison helper functions
275 // RTABI chapter 4.1.2, Table 3
276 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
277 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
278 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
279 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
280 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
281 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
282 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
283 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
284 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
285 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
286 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
287 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
288 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
289 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
290 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
291 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
292 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
297 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
298 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
299 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
301 // Single-precision floating-point arithmetic helper functions
302 // RTABI chapter 4.1.2, Table 4
303 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
304 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
305 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
306 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
307 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
308 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
309 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
310 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
312 // Single-precision floating-point comparison helper functions
313 // RTABI chapter 4.1.2, Table 5
314 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
315 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
316 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
317 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
318 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
319 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
320 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
321 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
322 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
323 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
324 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
325 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
326 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
327 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
328 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
329 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
330 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
335 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
336 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
337 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
339 // Floating-point to integer conversions.
340 // RTABI chapter 4.1.2, Table 6
341 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
342 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
343 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
344 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
345 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
346 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
347 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
348 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
349 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
354 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
355 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
356 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
358 // Conversions between floating types.
359 // RTABI chapter 4.1.2, Table 7
360 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
361 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
362 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
363 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
365 // Integer to floating-point conversions.
366 // RTABI chapter 4.1.2, Table 8
367 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
368 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
369 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
370 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
371 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
372 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
373 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
374 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
375 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
381 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384 // Long long helper functions
385 // RTABI chapter 4.2, Table 9
386 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
387 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
388 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
389 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
390 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
395 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
397 // Integer division functions
398 // RTABI chapter 4.3.1
399 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
400 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
401 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
402 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
403 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
404 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
405 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
406 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
407 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
412 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
413 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
414 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
417 // RTABI chapter 4.3.4
418 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
419 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
420 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
421 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
422 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
423 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
426 // Use divmod compiler-rt calls for iOS 5.0 and later.
427 if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
428 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
429 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
430 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
433 if (Subtarget->isThumb1Only())
434 addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
436 addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
437 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
438 !Subtarget->isThumb1Only()) {
439 addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
440 if (!Subtarget->isFPOnlySP())
441 addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
443 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
446 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
447 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
448 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
449 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
450 setTruncStoreAction((MVT::SimpleValueType)VT,
451 (MVT::SimpleValueType)InnerVT, Expand);
452 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
454 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
457 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
459 if (Subtarget->hasNEON()) {
460 addDRTypeForNEON(MVT::v2f32);
461 addDRTypeForNEON(MVT::v8i8);
462 addDRTypeForNEON(MVT::v4i16);
463 addDRTypeForNEON(MVT::v2i32);
464 addDRTypeForNEON(MVT::v1i64);
466 addQRTypeForNEON(MVT::v4f32);
467 addQRTypeForNEON(MVT::v2f64);
468 addQRTypeForNEON(MVT::v16i8);
469 addQRTypeForNEON(MVT::v8i16);
470 addQRTypeForNEON(MVT::v4i32);
471 addQRTypeForNEON(MVT::v2i64);
473 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474 // neither Neon nor VFP support any arithmetic operations on it.
475 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476 // supported for v4f32.
477 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480 // FIXME: Code duplication: FDIV and FREM are expanded always, see
481 // ARMTargetLowering::addTypeForNEON method for details.
482 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484 // FIXME: Create unittest.
485 // In another words, find a way when "copysign" appears in DAG with vector
487 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488 // FIXME: Code duplication: SETCC has custom operation action, see
489 // ARMTargetLowering::addTypeForNEON method for details.
490 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491 // FIXME: Create unittest for FNEG and for FABS.
492 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
511 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
512 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
513 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
514 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
515 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
516 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
518 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
519 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
520 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522 // Neon does not support some operations on v1i64 and v2i64 types.
523 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524 // Custom handling for some quad-vector types to detect VMULL.
525 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528 // Custom handling for some vector types to avoid expensive expansions
529 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536 // a destination type that is wider than the source, and nor does
537 // it have a FP_TO_[SU]INT instruction with a narrower destination than
539 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
544 setTargetDAGCombine(ISD::INTRINSIC_VOID);
545 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
546 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
547 setTargetDAGCombine(ISD::SHL);
548 setTargetDAGCombine(ISD::SRL);
549 setTargetDAGCombine(ISD::SRA);
550 setTargetDAGCombine(ISD::SIGN_EXTEND);
551 setTargetDAGCombine(ISD::ZERO_EXTEND);
552 setTargetDAGCombine(ISD::ANY_EXTEND);
553 setTargetDAGCombine(ISD::SELECT_CC);
554 setTargetDAGCombine(ISD::BUILD_VECTOR);
555 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
556 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
557 setTargetDAGCombine(ISD::STORE);
558 setTargetDAGCombine(ISD::FP_TO_SINT);
559 setTargetDAGCombine(ISD::FP_TO_UINT);
560 setTargetDAGCombine(ISD::FDIV);
562 // It is legal to extload from v4i8 to v4i16 or v4i32.
563 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
564 MVT::v4i16, MVT::v2i16,
566 for (unsigned i = 0; i < 6; ++i) {
567 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
568 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
569 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
573 computeRegisterProperties();
575 // ARM does not have f32 extending load.
576 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
578 // ARM does not have i1 sign extending load.
579 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
581 // ARM supports all 4 flavors of integer indexed load / store.
582 if (!Subtarget->isThumb1Only()) {
583 for (unsigned im = (unsigned)ISD::PRE_INC;
584 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
585 setIndexedLoadAction(im, MVT::i1, Legal);
586 setIndexedLoadAction(im, MVT::i8, Legal);
587 setIndexedLoadAction(im, MVT::i16, Legal);
588 setIndexedLoadAction(im, MVT::i32, Legal);
589 setIndexedStoreAction(im, MVT::i1, Legal);
590 setIndexedStoreAction(im, MVT::i8, Legal);
591 setIndexedStoreAction(im, MVT::i16, Legal);
592 setIndexedStoreAction(im, MVT::i32, Legal);
596 // i64 operation support.
597 setOperationAction(ISD::MUL, MVT::i64, Expand);
598 setOperationAction(ISD::MULHU, MVT::i32, Expand);
599 if (Subtarget->isThumb1Only()) {
600 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
601 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
603 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
604 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
605 setOperationAction(ISD::MULHS, MVT::i32, Expand);
607 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
608 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
609 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
610 setOperationAction(ISD::SRL, MVT::i64, Custom);
611 setOperationAction(ISD::SRA, MVT::i64, Custom);
613 if (!Subtarget->isThumb1Only()) {
614 // FIXME: We should do this for Thumb1 as well.
615 setOperationAction(ISD::ADDC, MVT::i32, Custom);
616 setOperationAction(ISD::ADDE, MVT::i32, Custom);
617 setOperationAction(ISD::SUBC, MVT::i32, Custom);
618 setOperationAction(ISD::SUBE, MVT::i32, Custom);
621 // ARM does not have ROTL.
622 setOperationAction(ISD::ROTL, MVT::i32, Expand);
623 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
624 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
625 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
626 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
628 // These just redirect to CTTZ and CTLZ on ARM.
629 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
630 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
632 // Only ARMv6 has BSWAP.
633 if (!Subtarget->hasV6Ops())
634 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
636 // These are expanded into libcalls.
637 if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
638 // v7M has a hardware divider
639 setOperationAction(ISD::SDIV, MVT::i32, Expand);
640 setOperationAction(ISD::UDIV, MVT::i32, Expand);
642 setOperationAction(ISD::SREM, MVT::i32, Expand);
643 setOperationAction(ISD::UREM, MVT::i32, Expand);
644 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
645 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
647 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
648 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
649 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
650 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
651 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
653 setOperationAction(ISD::TRAP, MVT::Other, Legal);
655 // Use the default implementation.
656 setOperationAction(ISD::VASTART, MVT::Other, Custom);
657 setOperationAction(ISD::VAARG, MVT::Other, Expand);
658 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
659 setOperationAction(ISD::VAEND, MVT::Other, Expand);
660 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
661 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
663 if (!Subtarget->isTargetDarwin()) {
664 // Non-Darwin platforms may return values in these registers via the
665 // personality function.
666 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
667 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
668 setExceptionPointerRegister(ARM::R0);
669 setExceptionSelectorRegister(ARM::R1);
672 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
673 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
674 // the default expansion.
675 // FIXME: This should be checking for v6k, not just v6.
676 if (Subtarget->hasDataBarrier() ||
677 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
678 // membarrier needs custom lowering; the rest are legal and handled
680 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
681 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
682 // Custom lowering for 64-bit ops
683 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
684 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
685 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
686 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
687 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
688 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
689 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
690 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
691 setInsertFencesForAtomic(true);
693 // Set them all for expansion, which will force libcalls.
694 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
695 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
696 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
697 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
698 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
699 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
700 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
701 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
702 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
703 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
704 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
705 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
706 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
707 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
708 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
709 // Unordered/Monotonic case.
710 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
711 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
712 // Since the libcalls include locking, fold in the fences
713 setShouldFoldAtomicFences(true);
716 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
718 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
719 if (!Subtarget->hasV6Ops()) {
720 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
721 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
723 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
725 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
726 !Subtarget->isThumb1Only()) {
727 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
728 // iff target supports vfp2.
729 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
730 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
733 // We want to custom lower some of our intrinsics.
734 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
735 if (Subtarget->isTargetDarwin()) {
736 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
737 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
738 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
741 setOperationAction(ISD::SETCC, MVT::i32, Expand);
742 setOperationAction(ISD::SETCC, MVT::f32, Expand);
743 setOperationAction(ISD::SETCC, MVT::f64, Expand);
744 setOperationAction(ISD::SELECT, MVT::i32, Custom);
745 setOperationAction(ISD::SELECT, MVT::f32, Custom);
746 setOperationAction(ISD::SELECT, MVT::f64, Custom);
747 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
748 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
749 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
751 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
752 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
753 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
754 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
755 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
757 // We don't support sin/cos/fmod/copysign/pow
758 setOperationAction(ISD::FSIN, MVT::f64, Expand);
759 setOperationAction(ISD::FSIN, MVT::f32, Expand);
760 setOperationAction(ISD::FCOS, MVT::f32, Expand);
761 setOperationAction(ISD::FCOS, MVT::f64, Expand);
762 setOperationAction(ISD::FREM, MVT::f64, Expand);
763 setOperationAction(ISD::FREM, MVT::f32, Expand);
764 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
765 !Subtarget->isThumb1Only()) {
766 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
767 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
769 setOperationAction(ISD::FPOW, MVT::f64, Expand);
770 setOperationAction(ISD::FPOW, MVT::f32, Expand);
772 setOperationAction(ISD::FMA, MVT::f64, Expand);
773 setOperationAction(ISD::FMA, MVT::f32, Expand);
775 // Various VFP goodness
776 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
777 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
778 if (Subtarget->hasVFP2()) {
779 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
780 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
781 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
782 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
784 // Special handling for half-precision FP.
785 if (!Subtarget->hasFP16()) {
786 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
787 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
791 // We have target-specific dag combine patterns for the following nodes:
792 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
793 setTargetDAGCombine(ISD::ADD);
794 setTargetDAGCombine(ISD::SUB);
795 setTargetDAGCombine(ISD::MUL);
797 if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
798 setTargetDAGCombine(ISD::AND);
799 setTargetDAGCombine(ISD::OR);
800 setTargetDAGCombine(ISD::XOR);
803 if (Subtarget->hasV6Ops())
804 setTargetDAGCombine(ISD::SRL);
806 setStackPointerRegisterToSaveRestore(ARM::SP);
808 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
809 !Subtarget->hasVFP2())
810 setSchedulingPreference(Sched::RegPressure);
812 setSchedulingPreference(Sched::Hybrid);
814 //// temporary - rewrite interface to use type
815 maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
816 maxStoresPerMemset = 16;
817 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
819 // On ARM arguments smaller than 4 bytes are extended, so all arguments
820 // are at least 4 bytes aligned.
821 setMinStackArgumentAlignment(4);
823 benefitFromCodePlacementOpt = true;
825 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
828 // FIXME: It might make sense to define the representative register class as the
829 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
830 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
831 // SPR's representative would be DPR_VFP2. This should work well if register
832 // pressure tracking were modified such that a register use would increment the
833 // pressure of the register class's representative and all of it's super
834 // classes' representatives transitively. We have not implemented this because
835 // of the difficulty prior to coalescing of modeling operand register classes
836 // due to the common occurrence of cross class copies and subregister insertions
838 std::pair<const TargetRegisterClass*, uint8_t>
839 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
840 const TargetRegisterClass *RRC = 0;
842 switch (VT.getSimpleVT().SimpleTy) {
844 return TargetLowering::findRepresentativeClass(VT);
845 // Use DPR as representative register class for all floating point
846 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
847 // the cost is 1 for both f32 and f64.
848 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
849 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
850 RRC = ARM::DPRRegisterClass;
851 // When NEON is used for SP, only half of the register file is available
852 // because operations that define both SP and DP results will be constrained
853 // to the VFP2 class (D0-D15). We currently model this constraint prior to
854 // coalescing by double-counting the SP regs. See the FIXME above.
855 if (Subtarget->useNEONForSinglePrecisionFP())
858 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
859 case MVT::v4f32: case MVT::v2f64:
860 RRC = ARM::DPRRegisterClass;
864 RRC = ARM::DPRRegisterClass;
868 RRC = ARM::DPRRegisterClass;
872 return std::make_pair(RRC, Cost);
875 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
878 case ARMISD::Wrapper: return "ARMISD::Wrapper";
879 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
880 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
881 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
882 case ARMISD::CALL: return "ARMISD::CALL";
883 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
884 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
885 case ARMISD::tCALL: return "ARMISD::tCALL";
886 case ARMISD::BRCOND: return "ARMISD::BRCOND";
887 case ARMISD::BR_JT: return "ARMISD::BR_JT";
888 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
889 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
890 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
891 case ARMISD::CMP: return "ARMISD::CMP";
892 case ARMISD::CMPZ: return "ARMISD::CMPZ";
893 case ARMISD::CMPFP: return "ARMISD::CMPFP";
894 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
895 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
896 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
898 case ARMISD::CMOV: return "ARMISD::CMOV";
899 case ARMISD::CAND: return "ARMISD::CAND";
900 case ARMISD::COR: return "ARMISD::COR";
901 case ARMISD::CXOR: return "ARMISD::CXOR";
903 case ARMISD::RBIT: return "ARMISD::RBIT";
905 case ARMISD::FTOSI: return "ARMISD::FTOSI";
906 case ARMISD::FTOUI: return "ARMISD::FTOUI";
907 case ARMISD::SITOF: return "ARMISD::SITOF";
908 case ARMISD::UITOF: return "ARMISD::UITOF";
910 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
911 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
912 case ARMISD::RRX: return "ARMISD::RRX";
914 case ARMISD::ADDC: return "ARMISD::ADDC";
915 case ARMISD::ADDE: return "ARMISD::ADDE";
916 case ARMISD::SUBC: return "ARMISD::SUBC";
917 case ARMISD::SUBE: return "ARMISD::SUBE";
919 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
920 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
922 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
923 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
925 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
927 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
929 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
931 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
932 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
934 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
936 case ARMISD::VCEQ: return "ARMISD::VCEQ";
937 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
938 case ARMISD::VCGE: return "ARMISD::VCGE";
939 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
940 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
941 case ARMISD::VCGEU: return "ARMISD::VCGEU";
942 case ARMISD::VCGT: return "ARMISD::VCGT";
943 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
944 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
945 case ARMISD::VCGTU: return "ARMISD::VCGTU";
946 case ARMISD::VTST: return "ARMISD::VTST";
948 case ARMISD::VSHL: return "ARMISD::VSHL";
949 case ARMISD::VSHRs: return "ARMISD::VSHRs";
950 case ARMISD::VSHRu: return "ARMISD::VSHRu";
951 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
952 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
953 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
954 case ARMISD::VSHRN: return "ARMISD::VSHRN";
955 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
956 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
957 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
958 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
959 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
960 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
961 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
962 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
963 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
964 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
965 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
966 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
967 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
968 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
969 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
970 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
971 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
972 case ARMISD::VDUP: return "ARMISD::VDUP";
973 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
974 case ARMISD::VEXT: return "ARMISD::VEXT";
975 case ARMISD::VREV64: return "ARMISD::VREV64";
976 case ARMISD::VREV32: return "ARMISD::VREV32";
977 case ARMISD::VREV16: return "ARMISD::VREV16";
978 case ARMISD::VZIP: return "ARMISD::VZIP";
979 case ARMISD::VUZP: return "ARMISD::VUZP";
980 case ARMISD::VTRN: return "ARMISD::VTRN";
981 case ARMISD::VTBL1: return "ARMISD::VTBL1";
982 case ARMISD::VTBL2: return "ARMISD::VTBL2";
983 case ARMISD::VMULLs: return "ARMISD::VMULLs";
984 case ARMISD::VMULLu: return "ARMISD::VMULLu";
985 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
986 case ARMISD::FMAX: return "ARMISD::FMAX";
987 case ARMISD::FMIN: return "ARMISD::FMIN";
988 case ARMISD::BFI: return "ARMISD::BFI";
989 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
990 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
991 case ARMISD::VBSL: return "ARMISD::VBSL";
992 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
993 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
994 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
995 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
996 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
997 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
998 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
999 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1000 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1001 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1002 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1003 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1004 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1005 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1006 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1007 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1008 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1009 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1010 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1011 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1015 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1016 if (!VT.isVector()) return getPointerTy();
1017 return VT.changeVectorElementTypeToInteger();
1020 /// getRegClassFor - Return the register class that should be used for the
1021 /// specified value type.
1022 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1023 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1024 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1025 // load / store 4 to 8 consecutive D registers.
1026 if (Subtarget->hasNEON()) {
1027 if (VT == MVT::v4i64)
1028 return ARM::QQPRRegisterClass;
1029 else if (VT == MVT::v8i64)
1030 return ARM::QQQQPRRegisterClass;
1032 return TargetLowering::getRegClassFor(VT);
1035 // Create a fast isel object.
1037 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1038 return ARM::createFastISel(funcInfo);
1041 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1042 /// be used for loads / stores from the global.
1043 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1044 return (Subtarget->isThumb1Only() ? 127 : 4095);
1047 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1048 unsigned NumVals = N->getNumValues();
1050 return Sched::RegPressure;
1052 for (unsigned i = 0; i != NumVals; ++i) {
1053 EVT VT = N->getValueType(i);
1054 if (VT == MVT::Glue || VT == MVT::Other)
1056 if (VT.isFloatingPoint() || VT.isVector())
1060 if (!N->isMachineOpcode())
1061 return Sched::RegPressure;
1063 // Load are scheduled for latency even if there instruction itinerary
1064 // is not available.
1065 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1066 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1068 if (MCID.getNumDefs() == 0)
1069 return Sched::RegPressure;
1070 if (!Itins->isEmpty() &&
1071 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1074 return Sched::RegPressure;
1077 //===----------------------------------------------------------------------===//
1079 //===----------------------------------------------------------------------===//
1081 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1082 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1084 default: llvm_unreachable("Unknown condition code!");
1085 case ISD::SETNE: return ARMCC::NE;
1086 case ISD::SETEQ: return ARMCC::EQ;
1087 case ISD::SETGT: return ARMCC::GT;
1088 case ISD::SETGE: return ARMCC::GE;
1089 case ISD::SETLT: return ARMCC::LT;
1090 case ISD::SETLE: return ARMCC::LE;
1091 case ISD::SETUGT: return ARMCC::HI;
1092 case ISD::SETUGE: return ARMCC::HS;
1093 case ISD::SETULT: return ARMCC::LO;
1094 case ISD::SETULE: return ARMCC::LS;
1098 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1099 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1100 ARMCC::CondCodes &CondCode2) {
1101 CondCode2 = ARMCC::AL;
1103 default: llvm_unreachable("Unknown FP condition!");
1105 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1107 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1109 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1110 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1111 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1112 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1113 case ISD::SETO: CondCode = ARMCC::VC; break;
1114 case ISD::SETUO: CondCode = ARMCC::VS; break;
1115 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1116 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1117 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1119 case ISD::SETULT: CondCode = ARMCC::LT; break;
1121 case ISD::SETULE: CondCode = ARMCC::LE; break;
1123 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1127 //===----------------------------------------------------------------------===//
1128 // Calling Convention Implementation
1129 //===----------------------------------------------------------------------===//
1131 #include "ARMGenCallingConv.inc"
1133 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1134 /// given CallingConvention value.
1135 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1137 bool isVarArg) const {
1140 llvm_unreachable("Unsupported calling convention");
1141 case CallingConv::Fast:
1142 if (Subtarget->hasVFP2() && !isVarArg) {
1143 if (!Subtarget->isAAPCS_ABI())
1144 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1145 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1146 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1149 case CallingConv::C: {
1150 // Use target triple & subtarget features to do actual dispatch.
1151 if (!Subtarget->isAAPCS_ABI())
1152 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1153 else if (Subtarget->hasVFP2() &&
1154 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1156 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1157 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1159 case CallingConv::ARM_AAPCS_VFP:
1161 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1163 case CallingConv::ARM_AAPCS:
1164 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1165 case CallingConv::ARM_APCS:
1166 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1170 /// LowerCallResult - Lower the result values of a call into the
1171 /// appropriate copies out of appropriate physical registers.
1173 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1174 CallingConv::ID CallConv, bool isVarArg,
1175 const SmallVectorImpl<ISD::InputArg> &Ins,
1176 DebugLoc dl, SelectionDAG &DAG,
1177 SmallVectorImpl<SDValue> &InVals) const {
1179 // Assign locations to each value returned by this call.
1180 SmallVector<CCValAssign, 16> RVLocs;
1181 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1182 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1183 CCInfo.AnalyzeCallResult(Ins,
1184 CCAssignFnForNode(CallConv, /* Return*/ true,
1187 // Copy all of the result registers out of their specified physreg.
1188 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1189 CCValAssign VA = RVLocs[i];
1192 if (VA.needsCustom()) {
1193 // Handle f64 or half of a v2f64.
1194 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1196 Chain = Lo.getValue(1);
1197 InFlag = Lo.getValue(2);
1198 VA = RVLocs[++i]; // skip ahead to next loc
1199 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1201 Chain = Hi.getValue(1);
1202 InFlag = Hi.getValue(2);
1203 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1205 if (VA.getLocVT() == MVT::v2f64) {
1206 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1207 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1208 DAG.getConstant(0, MVT::i32));
1210 VA = RVLocs[++i]; // skip ahead to next loc
1211 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1212 Chain = Lo.getValue(1);
1213 InFlag = Lo.getValue(2);
1214 VA = RVLocs[++i]; // skip ahead to next loc
1215 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1216 Chain = Hi.getValue(1);
1217 InFlag = Hi.getValue(2);
1218 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1219 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1220 DAG.getConstant(1, MVT::i32));
1223 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1225 Chain = Val.getValue(1);
1226 InFlag = Val.getValue(2);
1229 switch (VA.getLocInfo()) {
1230 default: llvm_unreachable("Unknown loc info!");
1231 case CCValAssign::Full: break;
1232 case CCValAssign::BCvt:
1233 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1237 InVals.push_back(Val);
1243 /// LowerMemOpCallTo - Store the argument to the stack.
1245 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1246 SDValue StackPtr, SDValue Arg,
1247 DebugLoc dl, SelectionDAG &DAG,
1248 const CCValAssign &VA,
1249 ISD::ArgFlagsTy Flags) const {
1250 unsigned LocMemOffset = VA.getLocMemOffset();
1251 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1252 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1253 return DAG.getStore(Chain, dl, Arg, PtrOff,
1254 MachinePointerInfo::getStack(LocMemOffset),
1258 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1259 SDValue Chain, SDValue &Arg,
1260 RegsToPassVector &RegsToPass,
1261 CCValAssign &VA, CCValAssign &NextVA,
1263 SmallVector<SDValue, 8> &MemOpChains,
1264 ISD::ArgFlagsTy Flags) const {
1266 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1267 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1268 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1270 if (NextVA.isRegLoc())
1271 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1273 assert(NextVA.isMemLoc());
1274 if (StackPtr.getNode() == 0)
1275 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1277 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1283 /// LowerCall - Lowering a call into a callseq_start <-
1284 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1287 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1288 CallingConv::ID CallConv, bool isVarArg,
1289 bool doesNotRet, bool &isTailCall,
1290 const SmallVectorImpl<ISD::OutputArg> &Outs,
1291 const SmallVectorImpl<SDValue> &OutVals,
1292 const SmallVectorImpl<ISD::InputArg> &Ins,
1293 DebugLoc dl, SelectionDAG &DAG,
1294 SmallVectorImpl<SDValue> &InVals) const {
1295 MachineFunction &MF = DAG.getMachineFunction();
1296 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1297 bool IsSibCall = false;
1298 // Disable tail calls if they're not supported.
1299 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1302 // Check if it's really possible to do a tail call.
1303 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1304 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1305 Outs, OutVals, Ins, DAG);
1306 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1307 // detected sibcalls.
1314 // Analyze operands of the call, assigning locations to each operand.
1315 SmallVector<CCValAssign, 16> ArgLocs;
1316 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1317 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1318 CCInfo.AnalyzeCallOperands(Outs,
1319 CCAssignFnForNode(CallConv, /* Return*/ false,
1322 // Get a count of how many bytes are to be pushed on the stack.
1323 unsigned NumBytes = CCInfo.getNextStackOffset();
1325 // For tail calls, memory operands are available in our caller's stack.
1329 // Adjust the stack pointer for the new arguments...
1330 // These operations are automatically eliminated by the prolog/epilog pass
1332 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1334 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1336 RegsToPassVector RegsToPass;
1337 SmallVector<SDValue, 8> MemOpChains;
1339 // Walk the register/memloc assignments, inserting copies/loads. In the case
1340 // of tail call optimization, arguments are handled later.
1341 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1343 ++i, ++realArgIdx) {
1344 CCValAssign &VA = ArgLocs[i];
1345 SDValue Arg = OutVals[realArgIdx];
1346 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1347 bool isByVal = Flags.isByVal();
1349 // Promote the value if needed.
1350 switch (VA.getLocInfo()) {
1351 default: llvm_unreachable("Unknown loc info!");
1352 case CCValAssign::Full: break;
1353 case CCValAssign::SExt:
1354 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1356 case CCValAssign::ZExt:
1357 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1359 case CCValAssign::AExt:
1360 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1362 case CCValAssign::BCvt:
1363 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1367 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1368 if (VA.needsCustom()) {
1369 if (VA.getLocVT() == MVT::v2f64) {
1370 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1371 DAG.getConstant(0, MVT::i32));
1372 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1373 DAG.getConstant(1, MVT::i32));
1375 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1376 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1378 VA = ArgLocs[++i]; // skip ahead to next loc
1379 if (VA.isRegLoc()) {
1380 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1381 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1383 assert(VA.isMemLoc());
1385 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1386 dl, DAG, VA, Flags));
1389 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1390 StackPtr, MemOpChains, Flags);
1392 } else if (VA.isRegLoc()) {
1393 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1394 } else if (isByVal) {
1395 assert(VA.isMemLoc());
1396 unsigned offset = 0;
1398 // True if this byval aggregate will be split between registers
1400 if (CCInfo.isFirstByValRegValid()) {
1401 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1403 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1404 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1405 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1406 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1407 MachinePointerInfo(),
1408 false, false, false, 0);
1409 MemOpChains.push_back(Load.getValue(1));
1410 RegsToPass.push_back(std::make_pair(j, Load));
1412 offset = ARM::R4 - CCInfo.getFirstByValReg();
1413 CCInfo.clearFirstByValReg();
1416 unsigned LocMemOffset = VA.getLocMemOffset();
1417 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1420 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1421 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1422 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1424 MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1425 Flags.getByValAlign(),
1426 /*isVolatile=*/false,
1427 /*AlwaysInline=*/false,
1428 MachinePointerInfo(0),
1429 MachinePointerInfo(0)));
1431 } else if (!IsSibCall) {
1432 assert(VA.isMemLoc());
1434 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1435 dl, DAG, VA, Flags));
1439 if (!MemOpChains.empty())
1440 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1441 &MemOpChains[0], MemOpChains.size());
1443 // Build a sequence of copy-to-reg nodes chained together with token chain
1444 // and flag operands which copy the outgoing args into the appropriate regs.
1446 // Tail call byval lowering might overwrite argument registers so in case of
1447 // tail call optimization the copies to registers are lowered later.
1449 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1450 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1451 RegsToPass[i].second, InFlag);
1452 InFlag = Chain.getValue(1);
1455 // For tail calls lower the arguments to the 'real' stack slot.
1457 // Force all the incoming stack arguments to be loaded from the stack
1458 // before any new outgoing arguments are stored to the stack, because the
1459 // outgoing stack slots may alias the incoming argument stack slots, and
1460 // the alias isn't otherwise explicit. This is slightly more conservative
1461 // than necessary, because it means that each store effectively depends
1462 // on every argument instead of just those arguments it would clobber.
1464 // Do not flag preceding copytoreg stuff together with the following stuff.
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);
1474 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1475 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1476 // node so that legalize doesn't hack it.
1477 bool isDirect = false;
1478 bool isARMFunc = false;
1479 bool isLocalARMFunc = false;
1480 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1482 if (EnableARMLongCalls) {
1483 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1484 && "long-calls with non-static relocation model!");
1485 // Handle a global address or an external symbol. If it's not one of
1486 // those, the target's already in a register, so we don't need to do
1488 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1489 const GlobalValue *GV = G->getGlobal();
1490 // Create a constant pool entry for the callee address
1491 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1492 ARMConstantPoolValue *CPV =
1493 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1495 // Get the address of the callee into a register
1496 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1497 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1498 Callee = DAG.getLoad(getPointerTy(), dl,
1499 DAG.getEntryNode(), CPAddr,
1500 MachinePointerInfo::getConstantPool(),
1501 false, false, false, 0);
1502 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1503 const char *Sym = S->getSymbol();
1505 // Create a constant pool entry for the callee address
1506 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1507 ARMConstantPoolValue *CPV =
1508 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1509 ARMPCLabelIndex, 0);
1510 // Get the address of the callee into a register
1511 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1512 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1513 Callee = DAG.getLoad(getPointerTy(), dl,
1514 DAG.getEntryNode(), CPAddr,
1515 MachinePointerInfo::getConstantPool(),
1516 false, false, false, 0);
1518 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1519 const GlobalValue *GV = G->getGlobal();
1521 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1522 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1523 getTargetMachine().getRelocationModel() != Reloc::Static;
1524 isARMFunc = !Subtarget->isThumb() || isStub;
1525 // ARM call to a local ARM function is predicable.
1526 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1527 // tBX takes a register source operand.
1528 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1529 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1530 ARMConstantPoolValue *CPV =
1531 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1532 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1533 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1534 Callee = DAG.getLoad(getPointerTy(), dl,
1535 DAG.getEntryNode(), CPAddr,
1536 MachinePointerInfo::getConstantPool(),
1537 false, false, false, 0);
1538 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1539 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1540 getPointerTy(), Callee, PICLabel);
1542 // On ELF targets for PIC code, direct calls should go through the PLT
1543 unsigned OpFlags = 0;
1544 if (Subtarget->isTargetELF() &&
1545 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1546 OpFlags = ARMII::MO_PLT;
1547 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1549 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1551 bool isStub = Subtarget->isTargetDarwin() &&
1552 getTargetMachine().getRelocationModel() != Reloc::Static;
1553 isARMFunc = !Subtarget->isThumb() || isStub;
1554 // tBX takes a register source operand.
1555 const char *Sym = S->getSymbol();
1556 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1557 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1558 ARMConstantPoolValue *CPV =
1559 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1560 ARMPCLabelIndex, 4);
1561 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1562 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1563 Callee = DAG.getLoad(getPointerTy(), dl,
1564 DAG.getEntryNode(), CPAddr,
1565 MachinePointerInfo::getConstantPool(),
1566 false, false, false, 0);
1567 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1568 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1569 getPointerTy(), Callee, PICLabel);
1571 unsigned OpFlags = 0;
1572 // On ELF targets for PIC code, direct calls should go through the PLT
1573 if (Subtarget->isTargetELF() &&
1574 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1575 OpFlags = ARMII::MO_PLT;
1576 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1580 // FIXME: handle tail calls differently.
1582 if (Subtarget->isThumb()) {
1583 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1584 CallOpc = ARMISD::CALL_NOLINK;
1585 else if (doesNotRet && isDirect && !isARMFunc &&
1586 Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1587 // "mov lr, pc; b _foo" to avoid confusing the RSP
1588 CallOpc = ARMISD::CALL_NOLINK;
1590 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1592 if (!isDirect && !Subtarget->hasV5TOps()) {
1593 CallOpc = ARMISD::CALL_NOLINK;
1594 } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1595 // "mov lr, pc; b _foo" to avoid confusing the RSP
1596 CallOpc = ARMISD::CALL_NOLINK;
1598 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1601 std::vector<SDValue> Ops;
1602 Ops.push_back(Chain);
1603 Ops.push_back(Callee);
1605 // Add argument registers to the end of the list so that they are known live
1607 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1608 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1609 RegsToPass[i].second.getValueType()));
1611 // Add a register mask operand representing the call-preserved registers.
1612 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1613 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1614 assert(Mask && "Missing call preserved mask for calling convention");
1615 Ops.push_back(DAG.getRegisterMask(Mask));
1617 if (InFlag.getNode())
1618 Ops.push_back(InFlag);
1620 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1622 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1624 // Returns a chain and a flag for retval copy to use.
1625 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1626 InFlag = Chain.getValue(1);
1628 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1629 DAG.getIntPtrConstant(0, true), InFlag);
1631 InFlag = Chain.getValue(1);
1633 // Handle result values, copying them out of physregs into vregs that we
1635 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1639 /// HandleByVal - Every parameter *after* a byval parameter is passed
1640 /// on the stack. Remember the next parameter register to allocate,
1641 /// and then confiscate the rest of the parameter registers to insure
1644 llvm::ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1645 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1646 assert((State->getCallOrPrologue() == Prologue ||
1647 State->getCallOrPrologue() == Call) &&
1648 "unhandled ParmContext");
1649 if ((!State->isFirstByValRegValid()) &&
1650 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1651 State->setFirstByValReg(reg);
1652 // At a call site, a byval parameter that is split between
1653 // registers and memory needs its size truncated here. In a
1654 // function prologue, such byval parameters are reassembled in
1655 // memory, and are not truncated.
1656 if (State->getCallOrPrologue() == Call) {
1657 unsigned excess = 4 * (ARM::R4 - reg);
1658 assert(size >= excess && "expected larger existing stack allocation");
1662 // Confiscate any remaining parameter registers to preclude their
1663 // assignment to subsequent parameters.
1664 while (State->AllocateReg(GPRArgRegs, 4))
1668 /// MatchingStackOffset - Return true if the given stack call argument is
1669 /// already available in the same position (relatively) of the caller's
1670 /// incoming argument stack.
1672 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1673 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1674 const TargetInstrInfo *TII) {
1675 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1677 if (Arg.getOpcode() == ISD::CopyFromReg) {
1678 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1679 if (!TargetRegisterInfo::isVirtualRegister(VR))
1681 MachineInstr *Def = MRI->getVRegDef(VR);
1684 if (!Flags.isByVal()) {
1685 if (!TII->isLoadFromStackSlot(Def, FI))
1690 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1691 if (Flags.isByVal())
1692 // ByVal argument is passed in as a pointer but it's now being
1693 // dereferenced. e.g.
1694 // define @foo(%struct.X* %A) {
1695 // tail call @bar(%struct.X* byval %A)
1698 SDValue Ptr = Ld->getBasePtr();
1699 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1702 FI = FINode->getIndex();
1706 assert(FI != INT_MAX);
1707 if (!MFI->isFixedObjectIndex(FI))
1709 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1712 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1713 /// for tail call optimization. Targets which want to do tail call
1714 /// optimization should implement this function.
1716 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1717 CallingConv::ID CalleeCC,
1719 bool isCalleeStructRet,
1720 bool isCallerStructRet,
1721 const SmallVectorImpl<ISD::OutputArg> &Outs,
1722 const SmallVectorImpl<SDValue> &OutVals,
1723 const SmallVectorImpl<ISD::InputArg> &Ins,
1724 SelectionDAG& DAG) const {
1725 const Function *CallerF = DAG.getMachineFunction().getFunction();
1726 CallingConv::ID CallerCC = CallerF->getCallingConv();
1727 bool CCMatch = CallerCC == CalleeCC;
1729 // Look for obvious safe cases to perform tail call optimization that do not
1730 // require ABI changes. This is what gcc calls sibcall.
1732 // Do not sibcall optimize vararg calls unless the call site is not passing
1734 if (isVarArg && !Outs.empty())
1737 // Also avoid sibcall optimization if either caller or callee uses struct
1738 // return semantics.
1739 if (isCalleeStructRet || isCallerStructRet)
1742 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1743 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1744 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1745 // support in the assembler and linker to be used. This would need to be
1746 // fixed to fully support tail calls in Thumb1.
1748 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1749 // LR. This means if we need to reload LR, it takes an extra instructions,
1750 // which outweighs the value of the tail call; but here we don't know yet
1751 // whether LR is going to be used. Probably the right approach is to
1752 // generate the tail call here and turn it back into CALL/RET in
1753 // emitEpilogue if LR is used.
1755 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1756 // but we need to make sure there are enough registers; the only valid
1757 // registers are the 4 used for parameters. We don't currently do this
1759 if (Subtarget->isThumb1Only())
1762 // If the calling conventions do not match, then we'd better make sure the
1763 // results are returned in the same way as what the caller expects.
1765 SmallVector<CCValAssign, 16> RVLocs1;
1766 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1767 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1768 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1770 SmallVector<CCValAssign, 16> RVLocs2;
1771 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1772 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1773 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1775 if (RVLocs1.size() != RVLocs2.size())
1777 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1778 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1780 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1782 if (RVLocs1[i].isRegLoc()) {
1783 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1786 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1792 // If the callee takes no arguments then go on to check the results of the
1794 if (!Outs.empty()) {
1795 // Check if stack adjustment is needed. For now, do not do this if any
1796 // argument is passed on the stack.
1797 SmallVector<CCValAssign, 16> ArgLocs;
1798 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1799 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1800 CCInfo.AnalyzeCallOperands(Outs,
1801 CCAssignFnForNode(CalleeCC, false, isVarArg));
1802 if (CCInfo.getNextStackOffset()) {
1803 MachineFunction &MF = DAG.getMachineFunction();
1805 // Check if the arguments are already laid out in the right way as
1806 // the caller's fixed stack objects.
1807 MachineFrameInfo *MFI = MF.getFrameInfo();
1808 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1809 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1810 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1812 ++i, ++realArgIdx) {
1813 CCValAssign &VA = ArgLocs[i];
1814 EVT RegVT = VA.getLocVT();
1815 SDValue Arg = OutVals[realArgIdx];
1816 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1817 if (VA.getLocInfo() == CCValAssign::Indirect)
1819 if (VA.needsCustom()) {
1820 // f64 and vector types are split into multiple registers or
1821 // register/stack-slot combinations. The types will not match
1822 // the registers; give up on memory f64 refs until we figure
1823 // out what to do about this.
1826 if (!ArgLocs[++i].isRegLoc())
1828 if (RegVT == MVT::v2f64) {
1829 if (!ArgLocs[++i].isRegLoc())
1831 if (!ArgLocs[++i].isRegLoc())
1834 } else if (!VA.isRegLoc()) {
1835 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1847 ARMTargetLowering::LowerReturn(SDValue Chain,
1848 CallingConv::ID CallConv, bool isVarArg,
1849 const SmallVectorImpl<ISD::OutputArg> &Outs,
1850 const SmallVectorImpl<SDValue> &OutVals,
1851 DebugLoc dl, SelectionDAG &DAG) const {
1853 // CCValAssign - represent the assignment of the return value to a location.
1854 SmallVector<CCValAssign, 16> RVLocs;
1856 // CCState - Info about the registers and stack slots.
1857 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1858 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1860 // Analyze outgoing return values.
1861 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1864 // If this is the first return lowered for this function, add
1865 // the regs to the liveout set for the function.
1866 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1867 for (unsigned i = 0; i != RVLocs.size(); ++i)
1868 if (RVLocs[i].isRegLoc())
1869 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1874 // Copy the result values into the output registers.
1875 for (unsigned i = 0, realRVLocIdx = 0;
1877 ++i, ++realRVLocIdx) {
1878 CCValAssign &VA = RVLocs[i];
1879 assert(VA.isRegLoc() && "Can only return in registers!");
1881 SDValue Arg = OutVals[realRVLocIdx];
1883 switch (VA.getLocInfo()) {
1884 default: llvm_unreachable("Unknown loc info!");
1885 case CCValAssign::Full: break;
1886 case CCValAssign::BCvt:
1887 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1891 if (VA.needsCustom()) {
1892 if (VA.getLocVT() == MVT::v2f64) {
1893 // Extract the first half and return it in two registers.
1894 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1895 DAG.getConstant(0, MVT::i32));
1896 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1897 DAG.getVTList(MVT::i32, MVT::i32), Half);
1899 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1900 Flag = Chain.getValue(1);
1901 VA = RVLocs[++i]; // skip ahead to next loc
1902 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1903 HalfGPRs.getValue(1), Flag);
1904 Flag = Chain.getValue(1);
1905 VA = RVLocs[++i]; // skip ahead to next loc
1907 // Extract the 2nd half and fall through to handle it as an f64 value.
1908 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1909 DAG.getConstant(1, MVT::i32));
1911 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1913 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1914 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1915 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1916 Flag = Chain.getValue(1);
1917 VA = RVLocs[++i]; // skip ahead to next loc
1918 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1921 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1923 // Guarantee that all emitted copies are
1924 // stuck together, avoiding something bad.
1925 Flag = Chain.getValue(1);
1930 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1932 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1937 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N) const {
1938 if (N->getNumValues() != 1)
1940 if (!N->hasNUsesOfValue(1, 0))
1943 unsigned NumCopies = 0;
1944 SDNode* Copies[2] = { 0, 0 };
1945 SDNode *Use = *N->use_begin();
1946 if (Use->getOpcode() == ISD::CopyToReg) {
1947 Copies[NumCopies++] = Use;
1948 } else if (Use->getOpcode() == ARMISD::VMOVRRD) {
1949 // f64 returned in a pair of GPRs.
1950 for (SDNode::use_iterator UI = Use->use_begin(), UE = Use->use_end();
1952 if (UI->getOpcode() != ISD::CopyToReg)
1954 Copies[UI.getUse().getResNo()] = *UI;
1957 } else if (Use->getOpcode() == ISD::BITCAST) {
1958 // f32 returned in a single GPR.
1959 if (!Use->hasNUsesOfValue(1, 0))
1961 Use = *Use->use_begin();
1962 if (Use->getOpcode() != ISD::CopyToReg || !Use->hasNUsesOfValue(1, 0))
1964 Copies[NumCopies++] = Use;
1969 if (NumCopies != 1 && NumCopies != 2)
1972 bool HasRet = false;
1973 for (unsigned i = 0; i < NumCopies; ++i) {
1974 SDNode *Copy = Copies[i];
1975 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1977 if (UI->getOpcode() == ISD::CopyToReg) {
1979 if (Use == Copies[0] || ((NumCopies == 2) && (Use == Copies[1])))
1983 if (UI->getOpcode() != ARMISD::RET_FLAG)
1992 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1993 if (!EnableARMTailCalls)
1996 if (!CI->isTailCall())
1999 return !Subtarget->isThumb1Only();
2002 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2003 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2004 // one of the above mentioned nodes. It has to be wrapped because otherwise
2005 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2006 // be used to form addressing mode. These wrapped nodes will be selected
2008 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2009 EVT PtrVT = Op.getValueType();
2010 // FIXME there is no actual debug info here
2011 DebugLoc dl = Op.getDebugLoc();
2012 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2014 if (CP->isMachineConstantPoolEntry())
2015 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2016 CP->getAlignment());
2018 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2019 CP->getAlignment());
2020 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2023 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2024 return MachineJumpTableInfo::EK_Inline;
2027 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2028 SelectionDAG &DAG) const {
2029 MachineFunction &MF = DAG.getMachineFunction();
2030 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2031 unsigned ARMPCLabelIndex = 0;
2032 DebugLoc DL = Op.getDebugLoc();
2033 EVT PtrVT = getPointerTy();
2034 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2035 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2037 if (RelocM == Reloc::Static) {
2038 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2040 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2041 ARMPCLabelIndex = AFI->createPICLabelUId();
2042 ARMConstantPoolValue *CPV =
2043 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2044 ARMCP::CPBlockAddress, PCAdj);
2045 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2047 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2048 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2049 MachinePointerInfo::getConstantPool(),
2050 false, false, false, 0);
2051 if (RelocM == Reloc::Static)
2053 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2054 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2057 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2059 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2060 SelectionDAG &DAG) const {
2061 DebugLoc dl = GA->getDebugLoc();
2062 EVT PtrVT = getPointerTy();
2063 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2064 MachineFunction &MF = DAG.getMachineFunction();
2065 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2066 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2067 ARMConstantPoolValue *CPV =
2068 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2069 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2070 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2071 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2072 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2073 MachinePointerInfo::getConstantPool(),
2074 false, false, false, 0);
2075 SDValue Chain = Argument.getValue(1);
2077 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2078 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2080 // call __tls_get_addr.
2083 Entry.Node = Argument;
2084 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2085 Args.push_back(Entry);
2086 // FIXME: is there useful debug info available here?
2087 std::pair<SDValue, SDValue> CallResult =
2088 LowerCallTo(Chain, (Type *) Type::getInt32Ty(*DAG.getContext()),
2089 false, false, false, false,
2090 0, CallingConv::C, /*isTailCall=*/false,
2091 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2092 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2093 return CallResult.first;
2096 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2097 // "local exec" model.
2099 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2100 SelectionDAG &DAG) const {
2101 const GlobalValue *GV = GA->getGlobal();
2102 DebugLoc dl = GA->getDebugLoc();
2104 SDValue Chain = DAG.getEntryNode();
2105 EVT PtrVT = getPointerTy();
2106 // Get the Thread Pointer
2107 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2109 if (GV->isDeclaration()) {
2110 MachineFunction &MF = DAG.getMachineFunction();
2111 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2112 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2113 // Initial exec model.
2114 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2115 ARMConstantPoolValue *CPV =
2116 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2117 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2119 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2120 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2121 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2122 MachinePointerInfo::getConstantPool(),
2123 false, false, false, 0);
2124 Chain = Offset.getValue(1);
2126 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2127 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2129 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2130 MachinePointerInfo::getConstantPool(),
2131 false, false, false, 0);
2134 ARMConstantPoolValue *CPV =
2135 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2136 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2137 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2138 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2139 MachinePointerInfo::getConstantPool(),
2140 false, false, false, 0);
2143 // The address of the thread local variable is the add of the thread
2144 // pointer with the offset of the variable.
2145 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2149 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2150 // TODO: implement the "local dynamic" model
2151 assert(Subtarget->isTargetELF() &&
2152 "TLS not implemented for non-ELF targets");
2153 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2154 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
2155 // otherwise use the "Local Exec" TLS Model
2156 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
2157 return LowerToTLSGeneralDynamicModel(GA, DAG);
2159 return LowerToTLSExecModels(GA, DAG);
2162 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2163 SelectionDAG &DAG) const {
2164 EVT PtrVT = getPointerTy();
2165 DebugLoc dl = Op.getDebugLoc();
2166 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2167 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2168 if (RelocM == Reloc::PIC_) {
2169 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2170 ARMConstantPoolValue *CPV =
2171 ARMConstantPoolConstant::Create(GV,
2172 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2173 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2174 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2175 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2177 MachinePointerInfo::getConstantPool(),
2178 false, false, false, 0);
2179 SDValue Chain = Result.getValue(1);
2180 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2181 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2183 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2184 MachinePointerInfo::getGOT(),
2185 false, false, false, 0);
2189 // If we have T2 ops, we can materialize the address directly via movt/movw
2190 // pair. This is always cheaper.
2191 if (Subtarget->useMovt()) {
2193 // FIXME: Once remat is capable of dealing with instructions with register
2194 // operands, expand this into two nodes.
2195 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2196 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2198 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2199 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2200 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2201 MachinePointerInfo::getConstantPool(),
2202 false, false, false, 0);
2206 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2207 SelectionDAG &DAG) const {
2208 EVT PtrVT = getPointerTy();
2209 DebugLoc dl = Op.getDebugLoc();
2210 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2211 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2212 MachineFunction &MF = DAG.getMachineFunction();
2213 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2215 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2216 // update ARMFastISel::ARMMaterializeGV.
2217 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2219 // FIXME: Once remat is capable of dealing with instructions with register
2220 // operands, expand this into two nodes.
2221 if (RelocM == Reloc::Static)
2222 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2223 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2225 unsigned Wrapper = (RelocM == Reloc::PIC_)
2226 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2227 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2228 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2229 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2230 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2231 MachinePointerInfo::getGOT(),
2232 false, false, false, 0);
2236 unsigned ARMPCLabelIndex = 0;
2238 if (RelocM == Reloc::Static) {
2239 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2241 ARMPCLabelIndex = AFI->createPICLabelUId();
2242 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2243 ARMConstantPoolValue *CPV =
2244 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2246 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2248 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2250 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2251 MachinePointerInfo::getConstantPool(),
2252 false, false, false, 0);
2253 SDValue Chain = Result.getValue(1);
2255 if (RelocM == Reloc::PIC_) {
2256 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2257 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2260 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2261 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2262 false, false, false, 0);
2267 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2268 SelectionDAG &DAG) const {
2269 assert(Subtarget->isTargetELF() &&
2270 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2271 MachineFunction &MF = DAG.getMachineFunction();
2272 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2273 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2274 EVT PtrVT = getPointerTy();
2275 DebugLoc dl = Op.getDebugLoc();
2276 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2277 ARMConstantPoolValue *CPV =
2278 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2279 ARMPCLabelIndex, PCAdj);
2280 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2281 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2282 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2283 MachinePointerInfo::getConstantPool(),
2284 false, false, false, 0);
2285 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2286 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2290 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2291 DebugLoc dl = Op.getDebugLoc();
2292 SDValue Val = DAG.getConstant(0, MVT::i32);
2293 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2294 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2295 Op.getOperand(1), Val);
2299 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2300 DebugLoc dl = Op.getDebugLoc();
2301 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2302 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2306 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2307 const ARMSubtarget *Subtarget) const {
2308 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2309 DebugLoc dl = Op.getDebugLoc();
2311 default: return SDValue(); // Don't custom lower most intrinsics.
2312 case Intrinsic::arm_thread_pointer: {
2313 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2314 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2316 case Intrinsic::eh_sjlj_lsda: {
2317 MachineFunction &MF = DAG.getMachineFunction();
2318 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2319 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2320 EVT PtrVT = getPointerTy();
2321 DebugLoc dl = Op.getDebugLoc();
2322 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2324 unsigned PCAdj = (RelocM != Reloc::PIC_)
2325 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2326 ARMConstantPoolValue *CPV =
2327 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2328 ARMCP::CPLSDA, PCAdj);
2329 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2330 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2332 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2333 MachinePointerInfo::getConstantPool(),
2334 false, false, false, 0);
2336 if (RelocM == Reloc::PIC_) {
2337 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2338 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2342 case Intrinsic::arm_neon_vmulls:
2343 case Intrinsic::arm_neon_vmullu: {
2344 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2345 ? ARMISD::VMULLs : ARMISD::VMULLu;
2346 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2347 Op.getOperand(1), Op.getOperand(2));
2352 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2353 const ARMSubtarget *Subtarget) {
2354 DebugLoc dl = Op.getDebugLoc();
2355 if (!Subtarget->hasDataBarrier()) {
2356 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2357 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2359 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2360 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2361 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2362 DAG.getConstant(0, MVT::i32));
2365 SDValue Op5 = Op.getOperand(5);
2366 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2367 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2368 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2369 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2371 ARM_MB::MemBOpt DMBOpt;
2372 if (isDeviceBarrier)
2373 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2375 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2376 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2377 DAG.getConstant(DMBOpt, MVT::i32));
2381 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2382 const ARMSubtarget *Subtarget) {
2383 // FIXME: handle "fence singlethread" more efficiently.
2384 DebugLoc dl = Op.getDebugLoc();
2385 if (!Subtarget->hasDataBarrier()) {
2386 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2387 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2389 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2390 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2391 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2392 DAG.getConstant(0, MVT::i32));
2395 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2396 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2399 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2400 const ARMSubtarget *Subtarget) {
2401 // ARM pre v5TE and Thumb1 does not have preload instructions.
2402 if (!(Subtarget->isThumb2() ||
2403 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2404 // Just preserve the chain.
2405 return Op.getOperand(0);
2407 DebugLoc dl = Op.getDebugLoc();
2408 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2410 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2411 // ARMv7 with MP extension has PLDW.
2412 return Op.getOperand(0);
2414 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2415 if (Subtarget->isThumb()) {
2417 isRead = ~isRead & 1;
2418 isData = ~isData & 1;
2421 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2422 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2423 DAG.getConstant(isData, MVT::i32));
2426 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2427 MachineFunction &MF = DAG.getMachineFunction();
2428 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2430 // vastart just stores the address of the VarArgsFrameIndex slot into the
2431 // memory location argument.
2432 DebugLoc dl = Op.getDebugLoc();
2433 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2434 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2435 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2436 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2437 MachinePointerInfo(SV), false, false, 0);
2441 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2442 SDValue &Root, SelectionDAG &DAG,
2443 DebugLoc dl) const {
2444 MachineFunction &MF = DAG.getMachineFunction();
2445 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2447 const TargetRegisterClass *RC;
2448 if (AFI->isThumb1OnlyFunction())
2449 RC = ARM::tGPRRegisterClass;
2451 RC = ARM::GPRRegisterClass;
2453 // Transform the arguments stored in physical registers into virtual ones.
2454 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2455 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2458 if (NextVA.isMemLoc()) {
2459 MachineFrameInfo *MFI = MF.getFrameInfo();
2460 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2462 // Create load node to retrieve arguments from the stack.
2463 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2464 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2465 MachinePointerInfo::getFixedStack(FI),
2466 false, false, false, 0);
2468 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2469 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2472 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2476 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2477 unsigned &VARegSize, unsigned &VARegSaveSize)
2480 if (CCInfo.isFirstByValRegValid())
2481 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2483 unsigned int firstUnalloced;
2484 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2485 sizeof(GPRArgRegs) /
2486 sizeof(GPRArgRegs[0]));
2487 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2490 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2491 VARegSize = NumGPRs * 4;
2492 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2495 // The remaining GPRs hold either the beginning of variable-argument
2496 // data, or the beginning of an aggregate passed by value (usuall
2497 // byval). Either way, we allocate stack slots adjacent to the data
2498 // provided by our caller, and store the unallocated registers there.
2499 // If this is a variadic function, the va_list pointer will begin with
2500 // these values; otherwise, this reassembles a (byval) structure that
2501 // was split between registers and memory.
2503 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2504 DebugLoc dl, SDValue &Chain,
2505 unsigned ArgOffset) const {
2506 MachineFunction &MF = DAG.getMachineFunction();
2507 MachineFrameInfo *MFI = MF.getFrameInfo();
2508 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2509 unsigned firstRegToSaveIndex;
2510 if (CCInfo.isFirstByValRegValid())
2511 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2513 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2514 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2517 unsigned VARegSize, VARegSaveSize;
2518 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2519 if (VARegSaveSize) {
2520 // If this function is vararg, store any remaining integer argument regs
2521 // to their spots on the stack so that they may be loaded by deferencing
2522 // the result of va_next.
2523 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2524 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2525 ArgOffset + VARegSaveSize
2528 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2531 SmallVector<SDValue, 4> MemOps;
2532 for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2533 const TargetRegisterClass *RC;
2534 if (AFI->isThumb1OnlyFunction())
2535 RC = ARM::tGPRRegisterClass;
2537 RC = ARM::GPRRegisterClass;
2539 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2540 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2542 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2543 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2545 MemOps.push_back(Store);
2546 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2547 DAG.getConstant(4, getPointerTy()));
2549 if (!MemOps.empty())
2550 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2551 &MemOps[0], MemOps.size());
2553 // This will point to the next argument passed via stack.
2554 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2558 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2559 CallingConv::ID CallConv, bool isVarArg,
2560 const SmallVectorImpl<ISD::InputArg>
2562 DebugLoc dl, SelectionDAG &DAG,
2563 SmallVectorImpl<SDValue> &InVals)
2565 MachineFunction &MF = DAG.getMachineFunction();
2566 MachineFrameInfo *MFI = MF.getFrameInfo();
2568 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2570 // Assign locations to all of the incoming arguments.
2571 SmallVector<CCValAssign, 16> ArgLocs;
2572 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2573 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2574 CCInfo.AnalyzeFormalArguments(Ins,
2575 CCAssignFnForNode(CallConv, /* Return*/ false,
2578 SmallVector<SDValue, 16> ArgValues;
2579 int lastInsIndex = -1;
2582 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2583 CCValAssign &VA = ArgLocs[i];
2585 // Arguments stored in registers.
2586 if (VA.isRegLoc()) {
2587 EVT RegVT = VA.getLocVT();
2589 if (VA.needsCustom()) {
2590 // f64 and vector types are split up into multiple registers or
2591 // combinations of registers and stack slots.
2592 if (VA.getLocVT() == MVT::v2f64) {
2593 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2595 VA = ArgLocs[++i]; // skip ahead to next loc
2597 if (VA.isMemLoc()) {
2598 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2599 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2600 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2601 MachinePointerInfo::getFixedStack(FI),
2602 false, false, false, 0);
2604 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2607 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2608 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2609 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2610 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2611 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2613 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2616 const TargetRegisterClass *RC;
2618 if (RegVT == MVT::f32)
2619 RC = ARM::SPRRegisterClass;
2620 else if (RegVT == MVT::f64)
2621 RC = ARM::DPRRegisterClass;
2622 else if (RegVT == MVT::v2f64)
2623 RC = ARM::QPRRegisterClass;
2624 else if (RegVT == MVT::i32)
2625 RC = (AFI->isThumb1OnlyFunction() ?
2626 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
2628 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2630 // Transform the arguments in physical registers into virtual ones.
2631 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2632 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2635 // If this is an 8 or 16-bit value, it is really passed promoted
2636 // to 32 bits. Insert an assert[sz]ext to capture this, then
2637 // truncate to the right size.
2638 switch (VA.getLocInfo()) {
2639 default: llvm_unreachable("Unknown loc info!");
2640 case CCValAssign::Full: break;
2641 case CCValAssign::BCvt:
2642 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2644 case CCValAssign::SExt:
2645 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2646 DAG.getValueType(VA.getValVT()));
2647 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2649 case CCValAssign::ZExt:
2650 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2651 DAG.getValueType(VA.getValVT()));
2652 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2656 InVals.push_back(ArgValue);
2658 } else { // VA.isRegLoc()
2661 assert(VA.isMemLoc());
2662 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2664 int index = ArgLocs[i].getValNo();
2666 // Some Ins[] entries become multiple ArgLoc[] entries.
2667 // Process them only once.
2668 if (index != lastInsIndex)
2670 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2671 // FIXME: For now, all byval parameter objects are marked mutable.
2672 // This can be changed with more analysis.
2673 // In case of tail call optimization mark all arguments mutable.
2674 // Since they could be overwritten by lowering of arguments in case of
2676 if (Flags.isByVal()) {
2677 unsigned VARegSize, VARegSaveSize;
2678 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2679 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2680 unsigned Bytes = Flags.getByValSize() - VARegSize;
2681 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2682 int FI = MFI->CreateFixedObject(Bytes,
2683 VA.getLocMemOffset(), false);
2684 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2686 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2687 VA.getLocMemOffset(), true);
2689 // Create load nodes to retrieve arguments from the stack.
2690 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2691 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2692 MachinePointerInfo::getFixedStack(FI),
2693 false, false, false, 0));
2695 lastInsIndex = index;
2702 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2707 /// isFloatingPointZero - Return true if this is +0.0.
2708 static bool isFloatingPointZero(SDValue Op) {
2709 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2710 return CFP->getValueAPF().isPosZero();
2711 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2712 // Maybe this has already been legalized into the constant pool?
2713 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2714 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2715 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2716 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2717 return CFP->getValueAPF().isPosZero();
2723 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2724 /// the given operands.
2726 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2727 SDValue &ARMcc, SelectionDAG &DAG,
2728 DebugLoc dl) const {
2729 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2730 unsigned C = RHSC->getZExtValue();
2731 if (!isLegalICmpImmediate(C)) {
2732 // Constant does not fit, try adjusting it by one?
2737 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2738 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2739 RHS = DAG.getConstant(C-1, MVT::i32);
2744 if (C != 0 && isLegalICmpImmediate(C-1)) {
2745 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2746 RHS = DAG.getConstant(C-1, MVT::i32);
2751 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2752 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2753 RHS = DAG.getConstant(C+1, MVT::i32);
2758 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2759 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2760 RHS = DAG.getConstant(C+1, MVT::i32);
2767 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2768 ARMISD::NodeType CompareType;
2771 CompareType = ARMISD::CMP;
2776 CompareType = ARMISD::CMPZ;
2779 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2780 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2783 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2785 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2786 DebugLoc dl) const {
2788 if (!isFloatingPointZero(RHS))
2789 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2791 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2792 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2795 /// duplicateCmp - Glue values can have only one use, so this function
2796 /// duplicates a comparison node.
2798 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2799 unsigned Opc = Cmp.getOpcode();
2800 DebugLoc DL = Cmp.getDebugLoc();
2801 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2802 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2804 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2805 Cmp = Cmp.getOperand(0);
2806 Opc = Cmp.getOpcode();
2807 if (Opc == ARMISD::CMPFP)
2808 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2810 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2811 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2813 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2816 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2817 SDValue Cond = Op.getOperand(0);
2818 SDValue SelectTrue = Op.getOperand(1);
2819 SDValue SelectFalse = Op.getOperand(2);
2820 DebugLoc dl = Op.getDebugLoc();
2824 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2825 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2827 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2828 const ConstantSDNode *CMOVTrue =
2829 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2830 const ConstantSDNode *CMOVFalse =
2831 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2833 if (CMOVTrue && CMOVFalse) {
2834 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2835 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2839 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2841 False = SelectFalse;
2842 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2847 if (True.getNode() && False.getNode()) {
2848 EVT VT = Op.getValueType();
2849 SDValue ARMcc = Cond.getOperand(2);
2850 SDValue CCR = Cond.getOperand(3);
2851 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2852 assert(True.getValueType() == VT);
2853 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2858 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2859 // undefined bits before doing a full-word comparison with zero.
2860 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2861 DAG.getConstant(1, Cond.getValueType()));
2863 return DAG.getSelectCC(dl, Cond,
2864 DAG.getConstant(0, Cond.getValueType()),
2865 SelectTrue, SelectFalse, ISD::SETNE);
2868 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2869 EVT VT = Op.getValueType();
2870 SDValue LHS = Op.getOperand(0);
2871 SDValue RHS = Op.getOperand(1);
2872 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2873 SDValue TrueVal = Op.getOperand(2);
2874 SDValue FalseVal = Op.getOperand(3);
2875 DebugLoc dl = Op.getDebugLoc();
2877 if (LHS.getValueType() == MVT::i32) {
2879 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2880 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2881 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2884 ARMCC::CondCodes CondCode, CondCode2;
2885 FPCCToARMCC(CC, CondCode, CondCode2);
2887 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2888 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2889 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2890 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2892 if (CondCode2 != ARMCC::AL) {
2893 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2894 // FIXME: Needs another CMP because flag can have but one use.
2895 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2896 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2897 Result, TrueVal, ARMcc2, CCR, Cmp2);
2902 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2903 /// to morph to an integer compare sequence.
2904 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2905 const ARMSubtarget *Subtarget) {
2906 SDNode *N = Op.getNode();
2907 if (!N->hasOneUse())
2908 // Otherwise it requires moving the value from fp to integer registers.
2910 if (!N->getNumValues())
2912 EVT VT = Op.getValueType();
2913 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2914 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2915 // vmrs are very slow, e.g. cortex-a8.
2918 if (isFloatingPointZero(Op)) {
2922 return ISD::isNormalLoad(N);
2925 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2926 if (isFloatingPointZero(Op))
2927 return DAG.getConstant(0, MVT::i32);
2929 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2930 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2931 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2932 Ld->isVolatile(), Ld->isNonTemporal(),
2933 Ld->isInvariant(), Ld->getAlignment());
2935 llvm_unreachable("Unknown VFP cmp argument!");
2938 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2939 SDValue &RetVal1, SDValue &RetVal2) {
2940 if (isFloatingPointZero(Op)) {
2941 RetVal1 = DAG.getConstant(0, MVT::i32);
2942 RetVal2 = DAG.getConstant(0, MVT::i32);
2946 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2947 SDValue Ptr = Ld->getBasePtr();
2948 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2949 Ld->getChain(), Ptr,
2950 Ld->getPointerInfo(),
2951 Ld->isVolatile(), Ld->isNonTemporal(),
2952 Ld->isInvariant(), Ld->getAlignment());
2954 EVT PtrType = Ptr.getValueType();
2955 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2956 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2957 PtrType, Ptr, DAG.getConstant(4, PtrType));
2958 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2959 Ld->getChain(), NewPtr,
2960 Ld->getPointerInfo().getWithOffset(4),
2961 Ld->isVolatile(), Ld->isNonTemporal(),
2962 Ld->isInvariant(), NewAlign);
2966 llvm_unreachable("Unknown VFP cmp argument!");
2969 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2970 /// f32 and even f64 comparisons to integer ones.
2972 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2973 SDValue Chain = Op.getOperand(0);
2974 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2975 SDValue LHS = Op.getOperand(2);
2976 SDValue RHS = Op.getOperand(3);
2977 SDValue Dest = Op.getOperand(4);
2978 DebugLoc dl = Op.getDebugLoc();
2980 bool LHSSeenZero = false;
2981 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
2982 bool RHSSeenZero = false;
2983 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
2984 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
2985 // If unsafe fp math optimization is enabled and there are no other uses of
2986 // the CMP operands, and the condition code is EQ or NE, we can optimize it
2987 // to an integer comparison.
2988 if (CC == ISD::SETOEQ)
2990 else if (CC == ISD::SETUNE)
2993 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
2995 if (LHS.getValueType() == MVT::f32) {
2996 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
2997 bitcastf32Toi32(LHS, DAG), Mask);
2998 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
2999 bitcastf32Toi32(RHS, DAG), Mask);
3000 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3001 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3002 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3003 Chain, Dest, ARMcc, CCR, Cmp);
3008 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3009 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3010 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3011 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3012 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3013 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3014 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3015 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3016 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3022 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3023 SDValue Chain = Op.getOperand(0);
3024 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3025 SDValue LHS = Op.getOperand(2);
3026 SDValue RHS = Op.getOperand(3);
3027 SDValue Dest = Op.getOperand(4);
3028 DebugLoc dl = Op.getDebugLoc();
3030 if (LHS.getValueType() == MVT::i32) {
3032 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3033 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3034 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3035 Chain, Dest, ARMcc, CCR, Cmp);
3038 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3040 if (getTargetMachine().Options.UnsafeFPMath &&
3041 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3042 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3043 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3044 if (Result.getNode())
3048 ARMCC::CondCodes CondCode, CondCode2;
3049 FPCCToARMCC(CC, CondCode, CondCode2);
3051 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3052 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3053 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3054 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3055 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3056 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3057 if (CondCode2 != ARMCC::AL) {
3058 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3059 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3060 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3065 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3066 SDValue Chain = Op.getOperand(0);
3067 SDValue Table = Op.getOperand(1);
3068 SDValue Index = Op.getOperand(2);
3069 DebugLoc dl = Op.getDebugLoc();
3071 EVT PTy = getPointerTy();
3072 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3073 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3074 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3075 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3076 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3077 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3078 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3079 if (Subtarget->isThumb2()) {
3080 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3081 // which does another jump to the destination. This also makes it easier
3082 // to translate it to TBB / TBH later.
3083 // FIXME: This might not work if the function is extremely large.
3084 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3085 Addr, Op.getOperand(2), JTI, UId);
3087 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3088 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3089 MachinePointerInfo::getJumpTable(),
3090 false, false, false, 0);
3091 Chain = Addr.getValue(1);
3092 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3093 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3095 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3096 MachinePointerInfo::getJumpTable(),
3097 false, false, false, 0);
3098 Chain = Addr.getValue(1);
3099 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3103 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3104 EVT VT = Op.getValueType();
3105 DebugLoc dl = Op.getDebugLoc();
3107 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3108 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3110 return DAG.UnrollVectorOp(Op.getNode());
3113 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3114 "Invalid type for custom lowering!");
3115 if (VT != MVT::v4i16)
3116 return DAG.UnrollVectorOp(Op.getNode());
3118 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3119 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3122 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3123 EVT VT = Op.getValueType();
3125 return LowerVectorFP_TO_INT(Op, DAG);
3127 DebugLoc dl = Op.getDebugLoc();
3130 switch (Op.getOpcode()) {
3131 default: llvm_unreachable("Invalid opcode!");
3132 case ISD::FP_TO_SINT:
3133 Opc = ARMISD::FTOSI;
3135 case ISD::FP_TO_UINT:
3136 Opc = ARMISD::FTOUI;
3139 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3140 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3143 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3144 EVT VT = Op.getValueType();
3145 DebugLoc dl = Op.getDebugLoc();
3147 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3148 if (VT.getVectorElementType() == MVT::f32)
3150 return DAG.UnrollVectorOp(Op.getNode());
3153 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3154 "Invalid type for custom lowering!");
3155 if (VT != MVT::v4f32)
3156 return DAG.UnrollVectorOp(Op.getNode());
3160 switch (Op.getOpcode()) {
3161 default: llvm_unreachable("Invalid opcode!");
3162 case ISD::SINT_TO_FP:
3163 CastOpc = ISD::SIGN_EXTEND;
3164 Opc = ISD::SINT_TO_FP;
3166 case ISD::UINT_TO_FP:
3167 CastOpc = ISD::ZERO_EXTEND;
3168 Opc = ISD::UINT_TO_FP;
3172 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3173 return DAG.getNode(Opc, dl, VT, Op);
3176 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3177 EVT VT = Op.getValueType();
3179 return LowerVectorINT_TO_FP(Op, DAG);
3181 DebugLoc dl = Op.getDebugLoc();
3184 switch (Op.getOpcode()) {
3185 default: llvm_unreachable("Invalid opcode!");
3186 case ISD::SINT_TO_FP:
3187 Opc = ARMISD::SITOF;
3189 case ISD::UINT_TO_FP:
3190 Opc = ARMISD::UITOF;
3194 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3195 return DAG.getNode(Opc, dl, VT, Op);
3198 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3199 // Implement fcopysign with a fabs and a conditional fneg.
3200 SDValue Tmp0 = Op.getOperand(0);
3201 SDValue Tmp1 = Op.getOperand(1);
3202 DebugLoc dl = Op.getDebugLoc();
3203 EVT VT = Op.getValueType();
3204 EVT SrcVT = Tmp1.getValueType();
3205 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3206 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3207 bool UseNEON = !InGPR && Subtarget->hasNEON();
3210 // Use VBSL to copy the sign bit.
3211 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3212 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3213 DAG.getTargetConstant(EncodedVal, MVT::i32));
3214 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3216 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3217 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3218 DAG.getConstant(32, MVT::i32));
3219 else /*if (VT == MVT::f32)*/
3220 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3221 if (SrcVT == MVT::f32) {
3222 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3224 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3225 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3226 DAG.getConstant(32, MVT::i32));
3227 } else if (VT == MVT::f32)
3228 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3229 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3230 DAG.getConstant(32, MVT::i32));
3231 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3232 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3234 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3236 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3237 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3238 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3240 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3241 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3242 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3243 if (VT == MVT::f32) {
3244 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3245 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3246 DAG.getConstant(0, MVT::i32));
3248 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3254 // Bitcast operand 1 to i32.
3255 if (SrcVT == MVT::f64)
3256 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3257 &Tmp1, 1).getValue(1);
3258 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3260 // Or in the signbit with integer operations.
3261 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3262 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3263 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3264 if (VT == MVT::f32) {
3265 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3266 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3267 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3268 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3271 // f64: Or the high part with signbit and then combine two parts.
3272 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3274 SDValue Lo = Tmp0.getValue(0);
3275 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3276 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3277 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3280 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3281 MachineFunction &MF = DAG.getMachineFunction();
3282 MachineFrameInfo *MFI = MF.getFrameInfo();
3283 MFI->setReturnAddressIsTaken(true);
3285 EVT VT = Op.getValueType();
3286 DebugLoc dl = Op.getDebugLoc();
3287 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3289 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3290 SDValue Offset = DAG.getConstant(4, MVT::i32);
3291 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3292 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3293 MachinePointerInfo(), false, false, false, 0);
3296 // Return LR, which contains the return address. Mark it an implicit live-in.
3297 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3298 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3301 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3302 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3303 MFI->setFrameAddressIsTaken(true);
3305 EVT VT = Op.getValueType();
3306 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3307 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3308 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3309 ? ARM::R7 : ARM::R11;
3310 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3312 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3313 MachinePointerInfo(),
3314 false, false, false, 0);
3318 /// ExpandBITCAST - If the target supports VFP, this function is called to
3319 /// expand a bit convert where either the source or destination type is i64 to
3320 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3321 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3322 /// vectors), since the legalizer won't know what to do with that.
3323 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3324 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3325 DebugLoc dl = N->getDebugLoc();
3326 SDValue Op = N->getOperand(0);
3328 // This function is only supposed to be called for i64 types, either as the
3329 // source or destination of the bit convert.
3330 EVT SrcVT = Op.getValueType();
3331 EVT DstVT = N->getValueType(0);
3332 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3333 "ExpandBITCAST called for non-i64 type");
3335 // Turn i64->f64 into VMOVDRR.
3336 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3337 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3338 DAG.getConstant(0, MVT::i32));
3339 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3340 DAG.getConstant(1, MVT::i32));
3341 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3342 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3345 // Turn f64->i64 into VMOVRRD.
3346 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3347 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3348 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3349 // Merge the pieces into a single i64 value.
3350 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3356 /// getZeroVector - Returns a vector of specified type with all zero elements.
3357 /// Zero vectors are used to represent vector negation and in those cases
3358 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3359 /// not support i64 elements, so sometimes the zero vectors will need to be
3360 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3362 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3363 assert(VT.isVector() && "Expected a vector type");
3364 // The canonical modified immediate encoding of a zero vector is....0!
3365 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3366 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3367 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3368 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3371 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3372 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3373 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3374 SelectionDAG &DAG) const {
3375 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3376 EVT VT = Op.getValueType();
3377 unsigned VTBits = VT.getSizeInBits();
3378 DebugLoc dl = Op.getDebugLoc();
3379 SDValue ShOpLo = Op.getOperand(0);
3380 SDValue ShOpHi = Op.getOperand(1);
3381 SDValue ShAmt = Op.getOperand(2);
3383 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3385 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3387 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3388 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3389 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3390 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3391 DAG.getConstant(VTBits, MVT::i32));
3392 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3393 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3394 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3396 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3397 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3399 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3400 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3403 SDValue Ops[2] = { Lo, Hi };
3404 return DAG.getMergeValues(Ops, 2, dl);
3407 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3408 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3409 SDValue ARMTargetLowering::LowerShiftLeftParts(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);
3420 assert(Op.getOpcode() == ISD::SHL_PARTS);
3421 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3422 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3423 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3424 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3425 DAG.getConstant(VTBits, MVT::i32));
3426 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3427 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3429 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3430 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3431 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3433 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3434 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3437 SDValue Ops[2] = { Lo, Hi };
3438 return DAG.getMergeValues(Ops, 2, dl);
3441 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3442 SelectionDAG &DAG) const {
3443 // The rounding mode is in bits 23:22 of the FPSCR.
3444 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3445 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3446 // so that the shift + and get folded into a bitfield extract.
3447 DebugLoc dl = Op.getDebugLoc();
3448 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3449 DAG.getConstant(Intrinsic::arm_get_fpscr,
3451 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3452 DAG.getConstant(1U << 22, MVT::i32));
3453 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3454 DAG.getConstant(22, MVT::i32));
3455 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3456 DAG.getConstant(3, MVT::i32));
3459 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3460 const ARMSubtarget *ST) {
3461 EVT VT = N->getValueType(0);
3462 DebugLoc dl = N->getDebugLoc();
3464 if (!ST->hasV6T2Ops())
3467 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3468 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3471 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3472 const ARMSubtarget *ST) {
3473 EVT VT = N->getValueType(0);
3474 DebugLoc dl = N->getDebugLoc();
3479 // Lower vector shifts on NEON to use VSHL.
3480 assert(ST->hasNEON() && "unexpected vector shift");
3482 // Left shifts translate directly to the vshiftu intrinsic.
3483 if (N->getOpcode() == ISD::SHL)
3484 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3485 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3486 N->getOperand(0), N->getOperand(1));
3488 assert((N->getOpcode() == ISD::SRA ||
3489 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3491 // NEON uses the same intrinsics for both left and right shifts. For
3492 // right shifts, the shift amounts are negative, so negate the vector of
3494 EVT ShiftVT = N->getOperand(1).getValueType();
3495 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3496 getZeroVector(ShiftVT, DAG, dl),
3498 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3499 Intrinsic::arm_neon_vshifts :
3500 Intrinsic::arm_neon_vshiftu);
3501 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3502 DAG.getConstant(vshiftInt, MVT::i32),
3503 N->getOperand(0), NegatedCount);
3506 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3507 const ARMSubtarget *ST) {
3508 EVT VT = N->getValueType(0);
3509 DebugLoc dl = N->getDebugLoc();
3511 // We can get here for a node like i32 = ISD::SHL i32, i64
3515 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3516 "Unknown shift to lower!");
3518 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3519 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3520 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3523 // If we are in thumb mode, we don't have RRX.
3524 if (ST->isThumb1Only()) return SDValue();
3526 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3527 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3528 DAG.getConstant(0, MVT::i32));
3529 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3530 DAG.getConstant(1, MVT::i32));
3532 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3533 // captures the result into a carry flag.
3534 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3535 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3537 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3538 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3540 // Merge the pieces into a single i64 value.
3541 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3544 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3545 SDValue TmpOp0, TmpOp1;
3546 bool Invert = false;
3550 SDValue Op0 = Op.getOperand(0);
3551 SDValue Op1 = Op.getOperand(1);
3552 SDValue CC = Op.getOperand(2);
3553 EVT VT = Op.getValueType();
3554 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3555 DebugLoc dl = Op.getDebugLoc();
3557 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3558 switch (SetCCOpcode) {
3559 default: llvm_unreachable("Illegal FP comparison");
3561 case ISD::SETNE: Invert = true; // Fallthrough
3563 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3565 case ISD::SETLT: Swap = true; // Fallthrough
3567 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3569 case ISD::SETLE: Swap = true; // Fallthrough
3571 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3572 case ISD::SETUGE: Swap = true; // Fallthrough
3573 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3574 case ISD::SETUGT: Swap = true; // Fallthrough
3575 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3576 case ISD::SETUEQ: Invert = true; // Fallthrough
3578 // Expand this to (OLT | OGT).
3582 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3583 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3585 case ISD::SETUO: Invert = true; // Fallthrough
3587 // Expand this to (OLT | OGE).
3591 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3592 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3596 // Integer comparisons.
3597 switch (SetCCOpcode) {
3598 default: llvm_unreachable("Illegal integer comparison");
3599 case ISD::SETNE: Invert = true;
3600 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3601 case ISD::SETLT: Swap = true;
3602 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3603 case ISD::SETLE: Swap = true;
3604 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3605 case ISD::SETULT: Swap = true;
3606 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3607 case ISD::SETULE: Swap = true;
3608 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3611 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3612 if (Opc == ARMISD::VCEQ) {
3615 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3617 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3620 // Ignore bitconvert.
3621 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3622 AndOp = AndOp.getOperand(0);
3624 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3626 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3627 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3634 std::swap(Op0, Op1);
3636 // If one of the operands is a constant vector zero, attempt to fold the
3637 // comparison to a specialized compare-against-zero form.
3639 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3641 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3642 if (Opc == ARMISD::VCGE)
3643 Opc = ARMISD::VCLEZ;
3644 else if (Opc == ARMISD::VCGT)
3645 Opc = ARMISD::VCLTZ;
3650 if (SingleOp.getNode()) {
3653 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3655 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3657 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3659 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3661 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3663 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3666 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3670 Result = DAG.getNOT(dl, Result, VT);
3675 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3676 const ARMSubtarget *ST) const {
3677 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3680 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3681 assert(Op.getValueType() == MVT::f32 &&
3682 "ConstantFP custom lowering should only occur for f32.");
3684 APFloat FPVal = CFP->getValueAPF();
3685 int ImmVal = ARM_AM::getFP32Imm(FPVal);
3689 DebugLoc DL = Op.getDebugLoc();
3690 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3691 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, NewVal);
3692 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3693 DAG.getConstant(0, MVT::i32));
3696 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3697 /// valid vector constant for a NEON instruction with a "modified immediate"
3698 /// operand (e.g., VMOV). If so, return the encoded value.
3699 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3700 unsigned SplatBitSize, SelectionDAG &DAG,
3701 EVT &VT, bool is128Bits, NEONModImmType type) {
3702 unsigned OpCmode, Imm;
3704 // SplatBitSize is set to the smallest size that splats the vector, so a
3705 // zero vector will always have SplatBitSize == 8. However, NEON modified
3706 // immediate instructions others than VMOV do not support the 8-bit encoding
3707 // of a zero vector, and the default encoding of zero is supposed to be the
3712 switch (SplatBitSize) {
3714 if (type != VMOVModImm)
3716 // Any 1-byte value is OK. Op=0, Cmode=1110.
3717 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3720 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3724 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3725 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3726 if ((SplatBits & ~0xff) == 0) {
3727 // Value = 0x00nn: Op=x, Cmode=100x.
3732 if ((SplatBits & ~0xff00) == 0) {
3733 // Value = 0xnn00: Op=x, Cmode=101x.
3735 Imm = SplatBits >> 8;
3741 // NEON's 32-bit VMOV supports splat values where:
3742 // * only one byte is nonzero, or
3743 // * the least significant byte is 0xff and the second byte is nonzero, or
3744 // * the least significant 2 bytes are 0xff and the third is nonzero.
3745 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3746 if ((SplatBits & ~0xff) == 0) {
3747 // Value = 0x000000nn: Op=x, Cmode=000x.
3752 if ((SplatBits & ~0xff00) == 0) {
3753 // Value = 0x0000nn00: Op=x, Cmode=001x.
3755 Imm = SplatBits >> 8;
3758 if ((SplatBits & ~0xff0000) == 0) {
3759 // Value = 0x00nn0000: Op=x, Cmode=010x.
3761 Imm = SplatBits >> 16;
3764 if ((SplatBits & ~0xff000000) == 0) {
3765 // Value = 0xnn000000: Op=x, Cmode=011x.
3767 Imm = SplatBits >> 24;
3771 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3772 if (type == OtherModImm) return SDValue();
3774 if ((SplatBits & ~0xffff) == 0 &&
3775 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3776 // Value = 0x0000nnff: Op=x, Cmode=1100.
3778 Imm = SplatBits >> 8;
3783 if ((SplatBits & ~0xffffff) == 0 &&
3784 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3785 // Value = 0x00nnffff: Op=x, Cmode=1101.
3787 Imm = SplatBits >> 16;
3788 SplatBits |= 0xffff;
3792 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3793 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3794 // VMOV.I32. A (very) minor optimization would be to replicate the value
3795 // and fall through here to test for a valid 64-bit splat. But, then the
3796 // caller would also need to check and handle the change in size.
3800 if (type != VMOVModImm)
3802 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3803 uint64_t BitMask = 0xff;
3805 unsigned ImmMask = 1;
3807 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3808 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3811 } else if ((SplatBits & BitMask) != 0) {
3817 // Op=1, Cmode=1110.
3820 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3825 llvm_unreachable("unexpected size for isNEONModifiedImm");
3828 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3829 return DAG.getTargetConstant(EncodedVal, MVT::i32);
3832 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3833 bool &ReverseVEXT, unsigned &Imm) {
3834 unsigned NumElts = VT.getVectorNumElements();
3835 ReverseVEXT = false;
3837 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3843 // If this is a VEXT shuffle, the immediate value is the index of the first
3844 // element. The other shuffle indices must be the successive elements after
3846 unsigned ExpectedElt = Imm;
3847 for (unsigned i = 1; i < NumElts; ++i) {
3848 // Increment the expected index. If it wraps around, it may still be
3849 // a VEXT but the source vectors must be swapped.
3851 if (ExpectedElt == NumElts * 2) {
3856 if (M[i] < 0) continue; // ignore UNDEF indices
3857 if (ExpectedElt != static_cast<unsigned>(M[i]))
3861 // Adjust the index value if the source operands will be swapped.
3868 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3869 /// instruction with the specified blocksize. (The order of the elements
3870 /// within each block of the vector is reversed.)
3871 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3872 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3873 "Only possible block sizes for VREV are: 16, 32, 64");
3875 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3879 unsigned NumElts = VT.getVectorNumElements();
3880 unsigned BlockElts = M[0] + 1;
3881 // If the first shuffle index is UNDEF, be optimistic.
3883 BlockElts = BlockSize / EltSz;
3885 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3888 for (unsigned i = 0; i < NumElts; ++i) {
3889 if (M[i] < 0) continue; // ignore UNDEF indices
3890 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3897 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3898 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3899 // range, then 0 is placed into the resulting vector. So pretty much any mask
3900 // of 8 elements can work here.
3901 return VT == MVT::v8i8 && M.size() == 8;
3904 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3905 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3909 unsigned NumElts = VT.getVectorNumElements();
3910 WhichResult = (M[0] == 0 ? 0 : 1);
3911 for (unsigned i = 0; i < NumElts; i += 2) {
3912 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3913 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3919 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3920 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3921 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3922 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3923 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3927 unsigned NumElts = VT.getVectorNumElements();
3928 WhichResult = (M[0] == 0 ? 0 : 1);
3929 for (unsigned i = 0; i < NumElts; i += 2) {
3930 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3931 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3937 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3938 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3942 unsigned NumElts = VT.getVectorNumElements();
3943 WhichResult = (M[0] == 0 ? 0 : 1);
3944 for (unsigned i = 0; i != NumElts; ++i) {
3945 if (M[i] < 0) continue; // ignore UNDEF indices
3946 if ((unsigned) M[i] != 2 * i + WhichResult)
3950 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3951 if (VT.is64BitVector() && EltSz == 32)
3957 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
3958 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3959 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
3960 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3961 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3965 unsigned Half = VT.getVectorNumElements() / 2;
3966 WhichResult = (M[0] == 0 ? 0 : 1);
3967 for (unsigned j = 0; j != 2; ++j) {
3968 unsigned Idx = WhichResult;
3969 for (unsigned i = 0; i != Half; ++i) {
3970 int MIdx = M[i + j * Half];
3971 if (MIdx >= 0 && (unsigned) MIdx != Idx)
3977 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3978 if (VT.is64BitVector() && EltSz == 32)
3984 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3985 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3989 unsigned NumElts = VT.getVectorNumElements();
3990 WhichResult = (M[0] == 0 ? 0 : 1);
3991 unsigned Idx = WhichResult * NumElts / 2;
3992 for (unsigned i = 0; i != NumElts; i += 2) {
3993 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3994 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
3999 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4000 if (VT.is64BitVector() && EltSz == 32)
4006 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4007 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4008 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4009 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4010 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4014 unsigned NumElts = VT.getVectorNumElements();
4015 WhichResult = (M[0] == 0 ? 0 : 1);
4016 unsigned Idx = WhichResult * NumElts / 2;
4017 for (unsigned i = 0; i != NumElts; i += 2) {
4018 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4019 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4024 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4025 if (VT.is64BitVector() && EltSz == 32)
4031 // If N is an integer constant that can be moved into a register in one
4032 // instruction, return an SDValue of such a constant (will become a MOV
4033 // instruction). Otherwise return null.
4034 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4035 const ARMSubtarget *ST, DebugLoc dl) {
4037 if (!isa<ConstantSDNode>(N))
4039 Val = cast<ConstantSDNode>(N)->getZExtValue();
4041 if (ST->isThumb1Only()) {
4042 if (Val <= 255 || ~Val <= 255)
4043 return DAG.getConstant(Val, MVT::i32);
4045 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4046 return DAG.getConstant(Val, MVT::i32);
4051 // If this is a case we can't handle, return null and let the default
4052 // expansion code take care of it.
4053 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4054 const ARMSubtarget *ST) const {
4055 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4056 DebugLoc dl = Op.getDebugLoc();
4057 EVT VT = Op.getValueType();
4059 APInt SplatBits, SplatUndef;
4060 unsigned SplatBitSize;
4062 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4063 if (SplatBitSize <= 64) {
4064 // Check if an immediate VMOV works.
4066 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4067 SplatUndef.getZExtValue(), SplatBitSize,
4068 DAG, VmovVT, VT.is128BitVector(),
4070 if (Val.getNode()) {
4071 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4072 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4075 // Try an immediate VMVN.
4076 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4077 Val = isNEONModifiedImm(NegatedImm,
4078 SplatUndef.getZExtValue(), SplatBitSize,
4079 DAG, VmovVT, VT.is128BitVector(),
4081 if (Val.getNode()) {
4082 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4083 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4086 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4087 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4088 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4090 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4091 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4097 // Scan through the operands to see if only one value is used.
4098 unsigned NumElts = VT.getVectorNumElements();
4099 bool isOnlyLowElement = true;
4100 bool usesOnlyOneValue = true;
4101 bool isConstant = true;
4103 for (unsigned i = 0; i < NumElts; ++i) {
4104 SDValue V = Op.getOperand(i);
4105 if (V.getOpcode() == ISD::UNDEF)
4108 isOnlyLowElement = false;
4109 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4112 if (!Value.getNode())
4114 else if (V != Value)
4115 usesOnlyOneValue = false;
4118 if (!Value.getNode())
4119 return DAG.getUNDEF(VT);
4121 if (isOnlyLowElement)
4122 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4124 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4126 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4127 // i32 and try again.
4128 if (usesOnlyOneValue && EltSize <= 32) {
4130 return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4131 if (VT.getVectorElementType().isFloatingPoint()) {
4132 SmallVector<SDValue, 8> Ops;
4133 for (unsigned i = 0; i < NumElts; ++i)
4134 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4136 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4137 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4138 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4140 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4142 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4144 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4147 // If all elements are constants and the case above didn't get hit, fall back
4148 // to the default expansion, which will generate a load from the constant
4153 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4155 SDValue shuffle = ReconstructShuffle(Op, DAG);
4156 if (shuffle != SDValue())
4160 // Vectors with 32- or 64-bit elements can be built by directly assigning
4161 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4162 // will be legalized.
4163 if (EltSize >= 32) {
4164 // Do the expansion with floating-point types, since that is what the VFP
4165 // registers are defined to use, and since i64 is not legal.
4166 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4167 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4168 SmallVector<SDValue, 8> Ops;
4169 for (unsigned i = 0; i < NumElts; ++i)
4170 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4171 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4172 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4178 // Gather data to see if the operation can be modelled as a
4179 // shuffle in combination with VEXTs.
4180 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4181 SelectionDAG &DAG) const {
4182 DebugLoc dl = Op.getDebugLoc();
4183 EVT VT = Op.getValueType();
4184 unsigned NumElts = VT.getVectorNumElements();
4186 SmallVector<SDValue, 2> SourceVecs;
4187 SmallVector<unsigned, 2> MinElts;
4188 SmallVector<unsigned, 2> MaxElts;
4190 for (unsigned i = 0; i < NumElts; ++i) {
4191 SDValue V = Op.getOperand(i);
4192 if (V.getOpcode() == ISD::UNDEF)
4194 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4195 // A shuffle can only come from building a vector from various
4196 // elements of other vectors.
4198 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4199 VT.getVectorElementType()) {
4200 // This code doesn't know how to handle shuffles where the vector
4201 // element types do not match (this happens because type legalization
4202 // promotes the return type of EXTRACT_VECTOR_ELT).
4203 // FIXME: It might be appropriate to extend this code to handle
4204 // mismatched types.
4208 // Record this extraction against the appropriate vector if possible...
4209 SDValue SourceVec = V.getOperand(0);
4210 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4211 bool FoundSource = false;
4212 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4213 if (SourceVecs[j] == SourceVec) {
4214 if (MinElts[j] > EltNo)
4216 if (MaxElts[j] < EltNo)
4223 // Or record a new source if not...
4225 SourceVecs.push_back(SourceVec);
4226 MinElts.push_back(EltNo);
4227 MaxElts.push_back(EltNo);
4231 // Currently only do something sane when at most two source vectors
4233 if (SourceVecs.size() > 2)
4236 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4237 int VEXTOffsets[2] = {0, 0};
4239 // This loop extracts the usage patterns of the source vectors
4240 // and prepares appropriate SDValues for a shuffle if possible.
4241 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4242 if (SourceVecs[i].getValueType() == VT) {
4243 // No VEXT necessary
4244 ShuffleSrcs[i] = SourceVecs[i];
4247 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4248 // It probably isn't worth padding out a smaller vector just to
4249 // break it down again in a shuffle.
4253 // Since only 64-bit and 128-bit vectors are legal on ARM and
4254 // we've eliminated the other cases...
4255 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4256 "unexpected vector sizes in ReconstructShuffle");
4258 if (MaxElts[i] - MinElts[i] >= NumElts) {
4259 // Span too large for a VEXT to cope
4263 if (MinElts[i] >= NumElts) {
4264 // The extraction can just take the second half
4265 VEXTOffsets[i] = NumElts;
4266 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4268 DAG.getIntPtrConstant(NumElts));
4269 } else if (MaxElts[i] < NumElts) {
4270 // The extraction can just take the first half
4272 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4274 DAG.getIntPtrConstant(0));
4276 // An actual VEXT is needed
4277 VEXTOffsets[i] = MinElts[i];
4278 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4280 DAG.getIntPtrConstant(0));
4281 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4283 DAG.getIntPtrConstant(NumElts));
4284 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4285 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4289 SmallVector<int, 8> Mask;
4291 for (unsigned i = 0; i < NumElts; ++i) {
4292 SDValue Entry = Op.getOperand(i);
4293 if (Entry.getOpcode() == ISD::UNDEF) {
4298 SDValue ExtractVec = Entry.getOperand(0);
4299 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4300 .getOperand(1))->getSExtValue();
4301 if (ExtractVec == SourceVecs[0]) {
4302 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4304 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4308 // Final check before we try to produce nonsense...
4309 if (isShuffleMaskLegal(Mask, VT))
4310 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4316 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4317 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4318 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4319 /// are assumed to be legal.
4321 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4323 if (VT.getVectorNumElements() == 4 &&
4324 (VT.is128BitVector() || VT.is64BitVector())) {
4325 unsigned PFIndexes[4];
4326 for (unsigned i = 0; i != 4; ++i) {
4330 PFIndexes[i] = M[i];
4333 // Compute the index in the perfect shuffle table.
4334 unsigned PFTableIndex =
4335 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4336 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4337 unsigned Cost = (PFEntry >> 30);
4344 unsigned Imm, WhichResult;
4346 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4347 return (EltSize >= 32 ||
4348 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4349 isVREVMask(M, VT, 64) ||
4350 isVREVMask(M, VT, 32) ||
4351 isVREVMask(M, VT, 16) ||
4352 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4353 isVTBLMask(M, VT) ||
4354 isVTRNMask(M, VT, WhichResult) ||
4355 isVUZPMask(M, VT, WhichResult) ||
4356 isVZIPMask(M, VT, WhichResult) ||
4357 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4358 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4359 isVZIP_v_undef_Mask(M, VT, WhichResult));
4362 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4363 /// the specified operations to build the shuffle.
4364 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4365 SDValue RHS, SelectionDAG &DAG,
4367 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4368 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4369 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4372 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4381 OP_VUZPL, // VUZP, left result
4382 OP_VUZPR, // VUZP, right result
4383 OP_VZIPL, // VZIP, left result
4384 OP_VZIPR, // VZIP, right result
4385 OP_VTRNL, // VTRN, left result
4386 OP_VTRNR // VTRN, right result
4389 if (OpNum == OP_COPY) {
4390 if (LHSID == (1*9+2)*9+3) return LHS;
4391 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4395 SDValue OpLHS, OpRHS;
4396 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4397 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4398 EVT VT = OpLHS.getValueType();
4401 default: llvm_unreachable("Unknown shuffle opcode!");
4403 // VREV divides the vector in half and swaps within the half.
4404 if (VT.getVectorElementType() == MVT::i32 ||
4405 VT.getVectorElementType() == MVT::f32)
4406 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4407 // vrev <4 x i16> -> VREV32
4408 if (VT.getVectorElementType() == MVT::i16)
4409 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4410 // vrev <4 x i8> -> VREV16
4411 assert(VT.getVectorElementType() == MVT::i8);
4412 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4417 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4418 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4422 return DAG.getNode(ARMISD::VEXT, dl, VT,
4424 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4427 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4428 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4431 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4432 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4435 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4436 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4440 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4441 ArrayRef<int> ShuffleMask,
4442 SelectionDAG &DAG) {
4443 // Check to see if we can use the VTBL instruction.
4444 SDValue V1 = Op.getOperand(0);
4445 SDValue V2 = Op.getOperand(1);
4446 DebugLoc DL = Op.getDebugLoc();
4448 SmallVector<SDValue, 8> VTBLMask;
4449 for (ArrayRef<int>::iterator
4450 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4451 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4453 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4454 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4455 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4458 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4459 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4463 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4464 SDValue V1 = Op.getOperand(0);
4465 SDValue V2 = Op.getOperand(1);
4466 DebugLoc dl = Op.getDebugLoc();
4467 EVT VT = Op.getValueType();
4468 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4470 // Convert shuffles that are directly supported on NEON to target-specific
4471 // DAG nodes, instead of keeping them as shuffles and matching them again
4472 // during code selection. This is more efficient and avoids the possibility
4473 // of inconsistencies between legalization and selection.
4474 // FIXME: floating-point vectors should be canonicalized to integer vectors
4475 // of the same time so that they get CSEd properly.
4476 ArrayRef<int> ShuffleMask = SVN->getMask();
4478 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4479 if (EltSize <= 32) {
4480 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4481 int Lane = SVN->getSplatIndex();
4482 // If this is undef splat, generate it via "just" vdup, if possible.
4483 if (Lane == -1) Lane = 0;
4485 // Test if V1 is a SCALAR_TO_VECTOR.
4486 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4487 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4489 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4490 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4492 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4493 !isa<ConstantSDNode>(V1.getOperand(0))) {
4494 bool IsScalarToVector = true;
4495 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4496 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4497 IsScalarToVector = false;
4500 if (IsScalarToVector)
4501 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4503 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4504 DAG.getConstant(Lane, MVT::i32));
4509 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4512 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4513 DAG.getConstant(Imm, MVT::i32));
4516 if (isVREVMask(ShuffleMask, VT, 64))
4517 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4518 if (isVREVMask(ShuffleMask, VT, 32))
4519 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4520 if (isVREVMask(ShuffleMask, VT, 16))
4521 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4523 // Check for Neon shuffles that modify both input vectors in place.
4524 // If both results are used, i.e., if there are two shuffles with the same
4525 // source operands and with masks corresponding to both results of one of
4526 // these operations, DAG memoization will ensure that a single node is
4527 // used for both shuffles.
4528 unsigned WhichResult;
4529 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4530 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4531 V1, V2).getValue(WhichResult);
4532 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4533 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4534 V1, V2).getValue(WhichResult);
4535 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4536 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4537 V1, V2).getValue(WhichResult);
4539 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4540 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4541 V1, V1).getValue(WhichResult);
4542 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4543 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4544 V1, V1).getValue(WhichResult);
4545 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4546 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4547 V1, V1).getValue(WhichResult);
4550 // If the shuffle is not directly supported and it has 4 elements, use
4551 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4552 unsigned NumElts = VT.getVectorNumElements();
4554 unsigned PFIndexes[4];
4555 for (unsigned i = 0; i != 4; ++i) {
4556 if (ShuffleMask[i] < 0)
4559 PFIndexes[i] = ShuffleMask[i];
4562 // Compute the index in the perfect shuffle table.
4563 unsigned PFTableIndex =
4564 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4565 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4566 unsigned Cost = (PFEntry >> 30);
4569 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4572 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4573 if (EltSize >= 32) {
4574 // Do the expansion with floating-point types, since that is what the VFP
4575 // registers are defined to use, and since i64 is not legal.
4576 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4577 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4578 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4579 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4580 SmallVector<SDValue, 8> Ops;
4581 for (unsigned i = 0; i < NumElts; ++i) {
4582 if (ShuffleMask[i] < 0)
4583 Ops.push_back(DAG.getUNDEF(EltVT));
4585 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4586 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4587 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4590 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4591 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4594 if (VT == MVT::v8i8) {
4595 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4596 if (NewOp.getNode())
4603 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4604 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4605 SDValue Lane = Op.getOperand(2);
4606 if (!isa<ConstantSDNode>(Lane))
4612 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4613 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4614 SDValue Lane = Op.getOperand(1);
4615 if (!isa<ConstantSDNode>(Lane))
4618 SDValue Vec = Op.getOperand(0);
4619 if (Op.getValueType() == MVT::i32 &&
4620 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4621 DebugLoc dl = Op.getDebugLoc();
4622 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4628 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4629 // The only time a CONCAT_VECTORS operation can have legal types is when
4630 // two 64-bit vectors are concatenated to a 128-bit vector.
4631 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4632 "unexpected CONCAT_VECTORS");
4633 DebugLoc dl = Op.getDebugLoc();
4634 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4635 SDValue Op0 = Op.getOperand(0);
4636 SDValue Op1 = Op.getOperand(1);
4637 if (Op0.getOpcode() != ISD::UNDEF)
4638 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4639 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4640 DAG.getIntPtrConstant(0));
4641 if (Op1.getOpcode() != ISD::UNDEF)
4642 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4643 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4644 DAG.getIntPtrConstant(1));
4645 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4648 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4649 /// element has been zero/sign-extended, depending on the isSigned parameter,
4650 /// from an integer type half its size.
4651 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4653 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4654 EVT VT = N->getValueType(0);
4655 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4656 SDNode *BVN = N->getOperand(0).getNode();
4657 if (BVN->getValueType(0) != MVT::v4i32 ||
4658 BVN->getOpcode() != ISD::BUILD_VECTOR)
4660 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4661 unsigned HiElt = 1 - LoElt;
4662 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4663 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4664 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4665 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4666 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4669 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4670 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4673 if (Hi0->isNullValue() && Hi1->isNullValue())
4679 if (N->getOpcode() != ISD::BUILD_VECTOR)
4682 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4683 SDNode *Elt = N->getOperand(i).getNode();
4684 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4685 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4686 unsigned HalfSize = EltSize / 2;
4688 if (!isIntN(HalfSize, C->getSExtValue()))
4691 if (!isUIntN(HalfSize, C->getZExtValue()))
4702 /// isSignExtended - Check if a node is a vector value that is sign-extended
4703 /// or a constant BUILD_VECTOR with sign-extended elements.
4704 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4705 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4707 if (isExtendedBUILD_VECTOR(N, DAG, true))
4712 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4713 /// or a constant BUILD_VECTOR with zero-extended elements.
4714 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4715 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4717 if (isExtendedBUILD_VECTOR(N, DAG, false))
4722 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4723 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4724 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4725 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4726 return N->getOperand(0);
4727 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4728 return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4729 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4730 LD->isNonTemporal(), LD->isInvariant(),
4731 LD->getAlignment());
4732 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
4733 // have been legalized as a BITCAST from v4i32.
4734 if (N->getOpcode() == ISD::BITCAST) {
4735 SDNode *BVN = N->getOperand(0).getNode();
4736 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4737 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4738 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4739 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4740 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4742 // Construct a new BUILD_VECTOR with elements truncated to half the size.
4743 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4744 EVT VT = N->getValueType(0);
4745 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4746 unsigned NumElts = VT.getVectorNumElements();
4747 MVT TruncVT = MVT::getIntegerVT(EltSize);
4748 SmallVector<SDValue, 8> Ops;
4749 for (unsigned i = 0; i != NumElts; ++i) {
4750 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4751 const APInt &CInt = C->getAPIntValue();
4752 Ops.push_back(DAG.getConstant(CInt.trunc(EltSize), TruncVT));
4754 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4755 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4758 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4759 unsigned Opcode = N->getOpcode();
4760 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4761 SDNode *N0 = N->getOperand(0).getNode();
4762 SDNode *N1 = N->getOperand(1).getNode();
4763 return N0->hasOneUse() && N1->hasOneUse() &&
4764 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4769 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4770 unsigned Opcode = N->getOpcode();
4771 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4772 SDNode *N0 = N->getOperand(0).getNode();
4773 SDNode *N1 = N->getOperand(1).getNode();
4774 return N0->hasOneUse() && N1->hasOneUse() &&
4775 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4780 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4781 // Multiplications are only custom-lowered for 128-bit vectors so that
4782 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
4783 EVT VT = Op.getValueType();
4784 assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4785 SDNode *N0 = Op.getOperand(0).getNode();
4786 SDNode *N1 = Op.getOperand(1).getNode();
4787 unsigned NewOpc = 0;
4789 bool isN0SExt = isSignExtended(N0, DAG);
4790 bool isN1SExt = isSignExtended(N1, DAG);
4791 if (isN0SExt && isN1SExt)
4792 NewOpc = ARMISD::VMULLs;
4794 bool isN0ZExt = isZeroExtended(N0, DAG);
4795 bool isN1ZExt = isZeroExtended(N1, DAG);
4796 if (isN0ZExt && isN1ZExt)
4797 NewOpc = ARMISD::VMULLu;
4798 else if (isN1SExt || isN1ZExt) {
4799 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4800 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4801 if (isN1SExt && isAddSubSExt(N0, DAG)) {
4802 NewOpc = ARMISD::VMULLs;
4804 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4805 NewOpc = ARMISD::VMULLu;
4807 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4809 NewOpc = ARMISD::VMULLu;
4815 if (VT == MVT::v2i64)
4816 // Fall through to expand this. It is not legal.
4819 // Other vector multiplications are legal.
4824 // Legalize to a VMULL instruction.
4825 DebugLoc DL = Op.getDebugLoc();
4827 SDValue Op1 = SkipExtension(N1, DAG);
4829 Op0 = SkipExtension(N0, DAG);
4830 assert(Op0.getValueType().is64BitVector() &&
4831 Op1.getValueType().is64BitVector() &&
4832 "unexpected types for extended operands to VMULL");
4833 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4836 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4837 // isel lowering to take advantage of no-stall back to back vmul + vmla.
4844 SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4845 SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4846 EVT Op1VT = Op1.getValueType();
4847 return DAG.getNode(N0->getOpcode(), DL, VT,
4848 DAG.getNode(NewOpc, DL, VT,
4849 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4850 DAG.getNode(NewOpc, DL, VT,
4851 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4855 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4857 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4858 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4859 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4860 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4861 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4862 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4863 // Get reciprocal estimate.
4864 // float4 recip = vrecpeq_f32(yf);
4865 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4866 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4867 // Because char has a smaller range than uchar, we can actually get away
4868 // without any newton steps. This requires that we use a weird bias
4869 // of 0xb000, however (again, this has been exhaustively tested).
4870 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4871 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4872 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4873 Y = DAG.getConstant(0xb000, MVT::i32);
4874 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4875 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4876 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4877 // Convert back to short.
4878 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4879 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4884 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4886 // Convert to float.
4887 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4888 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4889 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4890 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4891 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4892 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4894 // Use reciprocal estimate and one refinement step.
4895 // float4 recip = vrecpeq_f32(yf);
4896 // recip *= vrecpsq_f32(yf, recip);
4897 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4898 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4899 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4900 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4902 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4903 // Because short has a smaller range than ushort, we can actually get away
4904 // with only a single newton step. This requires that we use a weird bias
4905 // of 89, however (again, this has been exhaustively tested).
4906 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4907 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4908 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4909 N1 = DAG.getConstant(0x89, MVT::i32);
4910 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4911 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4912 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4913 // Convert back to integer and return.
4914 // return vmovn_s32(vcvt_s32_f32(result));
4915 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4916 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4920 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4921 EVT VT = Op.getValueType();
4922 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4923 "unexpected type for custom-lowering ISD::SDIV");
4925 DebugLoc dl = Op.getDebugLoc();
4926 SDValue N0 = Op.getOperand(0);
4927 SDValue N1 = Op.getOperand(1);
4930 if (VT == MVT::v8i8) {
4931 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4932 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4934 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4935 DAG.getIntPtrConstant(4));
4936 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4937 DAG.getIntPtrConstant(4));
4938 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4939 DAG.getIntPtrConstant(0));
4940 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4941 DAG.getIntPtrConstant(0));
4943 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
4944 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
4946 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4947 N0 = LowerCONCAT_VECTORS(N0, DAG);
4949 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
4952 return LowerSDIV_v4i16(N0, N1, dl, DAG);
4955 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
4956 EVT VT = Op.getValueType();
4957 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4958 "unexpected type for custom-lowering ISD::UDIV");
4960 DebugLoc dl = Op.getDebugLoc();
4961 SDValue N0 = Op.getOperand(0);
4962 SDValue N1 = Op.getOperand(1);
4965 if (VT == MVT::v8i8) {
4966 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
4967 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
4969 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4970 DAG.getIntPtrConstant(4));
4971 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4972 DAG.getIntPtrConstant(4));
4973 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4974 DAG.getIntPtrConstant(0));
4975 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4976 DAG.getIntPtrConstant(0));
4978 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
4979 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
4981 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4982 N0 = LowerCONCAT_VECTORS(N0, DAG);
4984 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
4985 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
4990 // v4i16 sdiv ... Convert to float.
4991 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
4992 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
4993 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
4994 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
4995 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4996 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4998 // Use reciprocal estimate and two refinement steps.
4999 // float4 recip = vrecpeq_f32(yf);
5000 // recip *= vrecpsq_f32(yf, recip);
5001 // recip *= vrecpsq_f32(yf, recip);
5002 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5003 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5004 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5005 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5007 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5008 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5009 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5011 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5012 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5013 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5014 // and that it will never cause us to return an answer too large).
5015 // float4 result = as_float4(as_int4(xf*recip) + 2);
5016 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5017 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5018 N1 = DAG.getConstant(2, MVT::i32);
5019 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5020 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5021 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5022 // Convert back to integer and return.
5023 // return vmovn_u32(vcvt_s32_f32(result));
5024 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5025 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5029 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5030 EVT VT = Op.getNode()->getValueType(0);
5031 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5034 bool ExtraOp = false;
5035 switch (Op.getOpcode()) {
5036 default: llvm_unreachable("Invalid code");
5037 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5038 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5039 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5040 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5044 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5046 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5047 Op.getOperand(1), Op.getOperand(2));
5050 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5051 // Monotonic load/store is legal for all targets
5052 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5055 // Aquire/Release load/store is not legal for targets without a
5056 // dmb or equivalent available.
5062 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5063 SelectionDAG &DAG, unsigned NewOp) {
5064 DebugLoc dl = Node->getDebugLoc();
5065 assert (Node->getValueType(0) == MVT::i64 &&
5066 "Only know how to expand i64 atomics");
5068 SmallVector<SDValue, 6> Ops;
5069 Ops.push_back(Node->getOperand(0)); // Chain
5070 Ops.push_back(Node->getOperand(1)); // Ptr
5072 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5073 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5074 // High part of Val1
5075 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5076 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5077 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5078 // High part of Val1
5079 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5080 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5081 // High part of Val2
5082 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5083 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5085 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5087 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5088 cast<MemSDNode>(Node)->getMemOperand());
5089 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5090 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5091 Results.push_back(Result.getValue(2));
5094 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5095 switch (Op.getOpcode()) {
5096 default: llvm_unreachable("Don't know how to custom lower this!");
5097 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5098 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5099 case ISD::GlobalAddress:
5100 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5101 LowerGlobalAddressELF(Op, DAG);
5102 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5103 case ISD::SELECT: return LowerSELECT(Op, DAG);
5104 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5105 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5106 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5107 case ISD::VASTART: return LowerVASTART(Op, DAG);
5108 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5109 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5110 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5111 case ISD::SINT_TO_FP:
5112 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5113 case ISD::FP_TO_SINT:
5114 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5115 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5116 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5117 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5118 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5119 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5120 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5121 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5123 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5126 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5127 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5128 case ISD::SRL_PARTS:
5129 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5130 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5131 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5132 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5133 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5134 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5135 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5136 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5137 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5138 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5139 case ISD::MUL: return LowerMUL(Op, DAG);
5140 case ISD::SDIV: return LowerSDIV(Op, DAG);
5141 case ISD::UDIV: return LowerUDIV(Op, DAG);
5145 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5146 case ISD::ATOMIC_LOAD:
5147 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5151 /// ReplaceNodeResults - Replace the results of node with an illegal result
5152 /// type with new values built out of custom code.
5153 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5154 SmallVectorImpl<SDValue>&Results,
5155 SelectionDAG &DAG) const {
5157 switch (N->getOpcode()) {
5159 llvm_unreachable("Don't know how to custom expand this!");
5161 Res = ExpandBITCAST(N, DAG);
5165 Res = Expand64BitShift(N, DAG, Subtarget);
5167 case ISD::ATOMIC_LOAD_ADD:
5168 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5170 case ISD::ATOMIC_LOAD_AND:
5171 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5173 case ISD::ATOMIC_LOAD_NAND:
5174 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5176 case ISD::ATOMIC_LOAD_OR:
5177 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5179 case ISD::ATOMIC_LOAD_SUB:
5180 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5182 case ISD::ATOMIC_LOAD_XOR:
5183 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5185 case ISD::ATOMIC_SWAP:
5186 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5188 case ISD::ATOMIC_CMP_SWAP:
5189 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5193 Results.push_back(Res);
5196 //===----------------------------------------------------------------------===//
5197 // ARM Scheduler Hooks
5198 //===----------------------------------------------------------------------===//
5201 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5202 MachineBasicBlock *BB,
5203 unsigned Size) const {
5204 unsigned dest = MI->getOperand(0).getReg();
5205 unsigned ptr = MI->getOperand(1).getReg();
5206 unsigned oldval = MI->getOperand(2).getReg();
5207 unsigned newval = MI->getOperand(3).getReg();
5208 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5209 DebugLoc dl = MI->getDebugLoc();
5210 bool isThumb2 = Subtarget->isThumb2();
5212 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5214 MRI.createVirtualRegister(isThumb2 ? ARM::rGPRRegisterClass
5215 : ARM::GPRRegisterClass);
5218 MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5219 MRI.constrainRegClass(oldval, ARM::rGPRRegisterClass);
5220 MRI.constrainRegClass(newval, ARM::rGPRRegisterClass);
5223 unsigned ldrOpc, strOpc;
5225 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5227 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5228 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5231 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5232 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5235 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5236 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5240 MachineFunction *MF = BB->getParent();
5241 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5242 MachineFunction::iterator It = BB;
5243 ++It; // insert the new blocks after the current block
5245 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5246 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5247 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5248 MF->insert(It, loop1MBB);
5249 MF->insert(It, loop2MBB);
5250 MF->insert(It, exitMBB);
5252 // Transfer the remainder of BB and its successor edges to exitMBB.
5253 exitMBB->splice(exitMBB->begin(), BB,
5254 llvm::next(MachineBasicBlock::iterator(MI)),
5256 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5260 // fallthrough --> loop1MBB
5261 BB->addSuccessor(loop1MBB);
5264 // ldrex dest, [ptr]
5268 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5269 if (ldrOpc == ARM::t2LDREX)
5271 AddDefaultPred(MIB);
5272 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5273 .addReg(dest).addReg(oldval));
5274 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5275 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5276 BB->addSuccessor(loop2MBB);
5277 BB->addSuccessor(exitMBB);
5280 // strex scratch, newval, [ptr]
5284 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5285 if (strOpc == ARM::t2STREX)
5287 AddDefaultPred(MIB);
5288 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5289 .addReg(scratch).addImm(0));
5290 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5291 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5292 BB->addSuccessor(loop1MBB);
5293 BB->addSuccessor(exitMBB);
5299 MI->eraseFromParent(); // The instruction is gone now.
5305 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5306 unsigned Size, unsigned BinOpcode) const {
5307 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5308 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5310 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5311 MachineFunction *MF = BB->getParent();
5312 MachineFunction::iterator It = BB;
5315 unsigned dest = MI->getOperand(0).getReg();
5316 unsigned ptr = MI->getOperand(1).getReg();
5317 unsigned incr = MI->getOperand(2).getReg();
5318 DebugLoc dl = MI->getDebugLoc();
5319 bool isThumb2 = Subtarget->isThumb2();
5321 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5323 MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5324 MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5327 unsigned ldrOpc, strOpc;
5329 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5331 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5332 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5335 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5336 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5339 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5340 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5344 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5345 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5346 MF->insert(It, loopMBB);
5347 MF->insert(It, exitMBB);
5349 // Transfer the remainder of BB and its successor edges to exitMBB.
5350 exitMBB->splice(exitMBB->begin(), BB,
5351 llvm::next(MachineBasicBlock::iterator(MI)),
5353 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5355 const TargetRegisterClass *TRC =
5356 isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5357 unsigned scratch = MRI.createVirtualRegister(TRC);
5358 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5362 // fallthrough --> loopMBB
5363 BB->addSuccessor(loopMBB);
5367 // <binop> scratch2, dest, incr
5368 // strex scratch, scratch2, ptr
5371 // fallthrough --> exitMBB
5373 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5374 if (ldrOpc == ARM::t2LDREX)
5376 AddDefaultPred(MIB);
5378 // operand order needs to go the other way for NAND
5379 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5380 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5381 addReg(incr).addReg(dest)).addReg(0);
5383 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5384 addReg(dest).addReg(incr)).addReg(0);
5387 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5388 if (strOpc == ARM::t2STREX)
5390 AddDefaultPred(MIB);
5391 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5392 .addReg(scratch).addImm(0));
5393 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5394 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5396 BB->addSuccessor(loopMBB);
5397 BB->addSuccessor(exitMBB);
5403 MI->eraseFromParent(); // The instruction is gone now.
5409 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5410 MachineBasicBlock *BB,
5413 ARMCC::CondCodes Cond) const {
5414 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5416 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5417 MachineFunction *MF = BB->getParent();
5418 MachineFunction::iterator It = BB;
5421 unsigned dest = MI->getOperand(0).getReg();
5422 unsigned ptr = MI->getOperand(1).getReg();
5423 unsigned incr = MI->getOperand(2).getReg();
5424 unsigned oldval = dest;
5425 DebugLoc dl = MI->getDebugLoc();
5426 bool isThumb2 = Subtarget->isThumb2();
5428 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5430 MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5431 MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5434 unsigned ldrOpc, strOpc, extendOpc;
5436 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5438 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5439 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5440 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5443 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5444 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5445 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5448 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5449 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5454 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5455 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5456 MF->insert(It, loopMBB);
5457 MF->insert(It, exitMBB);
5459 // Transfer the remainder of BB and its successor edges to exitMBB.
5460 exitMBB->splice(exitMBB->begin(), BB,
5461 llvm::next(MachineBasicBlock::iterator(MI)),
5463 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5465 const TargetRegisterClass *TRC =
5466 isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5467 unsigned scratch = MRI.createVirtualRegister(TRC);
5468 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5472 // fallthrough --> loopMBB
5473 BB->addSuccessor(loopMBB);
5477 // (sign extend dest, if required)
5479 // cmov.cond scratch2, dest, incr
5480 // strex scratch, scratch2, ptr
5483 // fallthrough --> exitMBB
5485 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5486 if (ldrOpc == ARM::t2LDREX)
5488 AddDefaultPred(MIB);
5490 // Sign extend the value, if necessary.
5491 if (signExtend && extendOpc) {
5492 oldval = MRI.createVirtualRegister(ARM::GPRRegisterClass);
5493 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5498 // Build compare and cmov instructions.
5499 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5500 .addReg(oldval).addReg(incr));
5501 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5502 .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5504 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5505 if (strOpc == ARM::t2STREX)
5507 AddDefaultPred(MIB);
5508 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5509 .addReg(scratch).addImm(0));
5510 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5511 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5513 BB->addSuccessor(loopMBB);
5514 BB->addSuccessor(exitMBB);
5520 MI->eraseFromParent(); // The instruction is gone now.
5526 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5527 unsigned Op1, unsigned Op2,
5528 bool NeedsCarry, bool IsCmpxchg) const {
5529 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5530 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5532 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5533 MachineFunction *MF = BB->getParent();
5534 MachineFunction::iterator It = BB;
5537 unsigned destlo = MI->getOperand(0).getReg();
5538 unsigned desthi = MI->getOperand(1).getReg();
5539 unsigned ptr = MI->getOperand(2).getReg();
5540 unsigned vallo = MI->getOperand(3).getReg();
5541 unsigned valhi = MI->getOperand(4).getReg();
5542 DebugLoc dl = MI->getDebugLoc();
5543 bool isThumb2 = Subtarget->isThumb2();
5545 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5547 MRI.constrainRegClass(destlo, ARM::rGPRRegisterClass);
5548 MRI.constrainRegClass(desthi, ARM::rGPRRegisterClass);
5549 MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5552 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5553 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5555 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5556 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5558 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5559 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5561 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5562 MF->insert(It, loopMBB);
5564 MF->insert(It, contBB);
5565 MF->insert(It, cont2BB);
5567 MF->insert(It, exitMBB);
5569 // Transfer the remainder of BB and its successor edges to exitMBB.
5570 exitMBB->splice(exitMBB->begin(), BB,
5571 llvm::next(MachineBasicBlock::iterator(MI)),
5573 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5575 const TargetRegisterClass *TRC =
5576 isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5577 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5581 // fallthrough --> loopMBB
5582 BB->addSuccessor(loopMBB);
5585 // ldrexd r2, r3, ptr
5586 // <binopa> r0, r2, incr
5587 // <binopb> r1, r3, incr
5588 // strexd storesuccess, r0, r1, ptr
5589 // cmp storesuccess, #0
5591 // fallthrough --> exitMBB
5593 // Note that the registers are explicitly specified because there is not any
5594 // way to force the register allocator to allocate a register pair.
5596 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5597 // need to properly enforce the restriction that the two output registers
5598 // for ldrexd must be different.
5601 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5602 .addReg(ARM::R2, RegState::Define)
5603 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5604 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
5605 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5606 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5610 for (unsigned i = 0; i < 2; i++) {
5611 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5613 .addReg(i == 0 ? destlo : desthi)
5614 .addReg(i == 0 ? vallo : valhi));
5615 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5616 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5617 BB->addSuccessor(exitMBB);
5618 BB->addSuccessor(i == 0 ? contBB : cont2BB);
5619 BB = (i == 0 ? contBB : cont2BB);
5622 // Copy to physregs for strexd
5623 unsigned setlo = MI->getOperand(5).getReg();
5624 unsigned sethi = MI->getOperand(6).getReg();
5625 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5626 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5628 // Perform binary operation
5629 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5630 .addReg(destlo).addReg(vallo))
5631 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5632 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5633 .addReg(desthi).addReg(valhi)).addReg(0);
5635 // Copy to physregs for strexd
5636 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5637 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5641 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5642 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5644 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5645 .addReg(storesuccess).addImm(0));
5646 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5647 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5649 BB->addSuccessor(loopMBB);
5650 BB->addSuccessor(exitMBB);
5656 MI->eraseFromParent(); // The instruction is gone now.
5661 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5662 /// registers the function context.
5663 void ARMTargetLowering::
5664 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5665 MachineBasicBlock *DispatchBB, int FI) const {
5666 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5667 DebugLoc dl = MI->getDebugLoc();
5668 MachineFunction *MF = MBB->getParent();
5669 MachineRegisterInfo *MRI = &MF->getRegInfo();
5670 MachineConstantPool *MCP = MF->getConstantPool();
5671 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5672 const Function *F = MF->getFunction();
5674 bool isThumb = Subtarget->isThumb();
5675 bool isThumb2 = Subtarget->isThumb2();
5677 unsigned PCLabelId = AFI->createPICLabelUId();
5678 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5679 ARMConstantPoolValue *CPV =
5680 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5681 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5683 const TargetRegisterClass *TRC =
5684 isThumb ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5686 // Grab constant pool and fixed stack memory operands.
5687 MachineMemOperand *CPMMO =
5688 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5689 MachineMemOperand::MOLoad, 4, 4);
5691 MachineMemOperand *FIMMOSt =
5692 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5693 MachineMemOperand::MOStore, 4, 4);
5695 // Load the address of the dispatch MBB into the jump buffer.
5697 // Incoming value: jbuf
5698 // ldr.n r5, LCPI1_1
5701 // str r5, [$jbuf, #+4] ; &jbuf[1]
5702 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5703 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5704 .addConstantPoolIndex(CPI)
5705 .addMemOperand(CPMMO));
5706 // Set the low bit because of thumb mode.
5707 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5709 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5710 .addReg(NewVReg1, RegState::Kill)
5712 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5713 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5714 .addReg(NewVReg2, RegState::Kill)
5716 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5717 .addReg(NewVReg3, RegState::Kill)
5719 .addImm(36) // &jbuf[1] :: pc
5720 .addMemOperand(FIMMOSt));
5721 } else if (isThumb) {
5722 // Incoming value: jbuf
5723 // ldr.n r1, LCPI1_4
5727 // add r2, $jbuf, #+4 ; &jbuf[1]
5729 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5730 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5731 .addConstantPoolIndex(CPI)
5732 .addMemOperand(CPMMO));
5733 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5734 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5735 .addReg(NewVReg1, RegState::Kill)
5737 // Set the low bit because of thumb mode.
5738 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5739 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5740 .addReg(ARM::CPSR, RegState::Define)
5742 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5743 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5744 .addReg(ARM::CPSR, RegState::Define)
5745 .addReg(NewVReg2, RegState::Kill)
5746 .addReg(NewVReg3, RegState::Kill));
5747 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5748 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5750 .addImm(36)); // &jbuf[1] :: pc
5751 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5752 .addReg(NewVReg4, RegState::Kill)
5753 .addReg(NewVReg5, RegState::Kill)
5755 .addMemOperand(FIMMOSt));
5757 // Incoming value: jbuf
5760 // str r1, [$jbuf, #+4] ; &jbuf[1]
5761 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5762 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
5763 .addConstantPoolIndex(CPI)
5765 .addMemOperand(CPMMO));
5766 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5767 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5768 .addReg(NewVReg1, RegState::Kill)
5769 .addImm(PCLabelId));
5770 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5771 .addReg(NewVReg2, RegState::Kill)
5773 .addImm(36) // &jbuf[1] :: pc
5774 .addMemOperand(FIMMOSt));
5778 MachineBasicBlock *ARMTargetLowering::
5779 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5780 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5781 DebugLoc dl = MI->getDebugLoc();
5782 MachineFunction *MF = MBB->getParent();
5783 MachineRegisterInfo *MRI = &MF->getRegInfo();
5784 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5785 MachineFrameInfo *MFI = MF->getFrameInfo();
5786 int FI = MFI->getFunctionContextIndex();
5788 const TargetRegisterClass *TRC =
5789 Subtarget->isThumb() ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5791 // Get a mapping of the call site numbers to all of the landing pads they're
5793 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5794 unsigned MaxCSNum = 0;
5795 MachineModuleInfo &MMI = MF->getMMI();
5796 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; ++BB) {
5797 if (!BB->isLandingPad()) continue;
5799 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5801 for (MachineBasicBlock::iterator
5802 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5803 if (!II->isEHLabel()) continue;
5805 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5806 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5808 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5809 for (SmallVectorImpl<unsigned>::iterator
5810 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5811 CSI != CSE; ++CSI) {
5812 CallSiteNumToLPad[*CSI].push_back(BB);
5813 MaxCSNum = std::max(MaxCSNum, *CSI);
5819 // Get an ordered list of the machine basic blocks for the jump table.
5820 std::vector<MachineBasicBlock*> LPadList;
5821 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5822 LPadList.reserve(CallSiteNumToLPad.size());
5823 for (unsigned I = 1; I <= MaxCSNum; ++I) {
5824 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5825 for (SmallVectorImpl<MachineBasicBlock*>::iterator
5826 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5827 LPadList.push_back(*II);
5828 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5832 assert(!LPadList.empty() &&
5833 "No landing pad destinations for the dispatch jump table!");
5835 // Create the jump table and associated information.
5836 MachineJumpTableInfo *JTI =
5837 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5838 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5839 unsigned UId = AFI->createJumpTableUId();
5841 // Create the MBBs for the dispatch code.
5843 // Shove the dispatch's address into the return slot in the function context.
5844 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5845 DispatchBB->setIsLandingPad();
5847 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5848 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5849 DispatchBB->addSuccessor(TrapBB);
5851 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5852 DispatchBB->addSuccessor(DispContBB);
5855 MF->insert(MF->end(), DispatchBB);
5856 MF->insert(MF->end(), DispContBB);
5857 MF->insert(MF->end(), TrapBB);
5859 // Insert code into the entry block that creates and registers the function
5861 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5863 MachineMemOperand *FIMMOLd =
5864 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5865 MachineMemOperand::MOLoad |
5866 MachineMemOperand::MOVolatile, 4, 4);
5868 if (AFI->isThumb1OnlyFunction())
5869 BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5870 else if (!Subtarget->hasVFP2())
5871 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5873 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5875 unsigned NumLPads = LPadList.size();
5876 if (Subtarget->isThumb2()) {
5877 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5878 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5881 .addMemOperand(FIMMOLd));
5883 if (NumLPads < 256) {
5884 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5886 .addImm(LPadList.size()));
5888 unsigned VReg1 = MRI->createVirtualRegister(TRC);
5889 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5890 .addImm(NumLPads & 0xFFFF));
5892 unsigned VReg2 = VReg1;
5893 if ((NumLPads & 0xFFFF0000) != 0) {
5894 VReg2 = MRI->createVirtualRegister(TRC);
5895 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5897 .addImm(NumLPads >> 16));
5900 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5905 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5910 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5911 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5912 .addJumpTableIndex(MJTI)
5915 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5918 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5919 .addReg(NewVReg3, RegState::Kill)
5921 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5923 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5924 .addReg(NewVReg4, RegState::Kill)
5926 .addJumpTableIndex(MJTI)
5928 } else if (Subtarget->isThumb()) {
5929 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5930 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
5933 .addMemOperand(FIMMOLd));
5935 if (NumLPads < 256) {
5936 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
5940 MachineConstantPool *ConstantPool = MF->getConstantPool();
5941 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
5942 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
5944 // MachineConstantPool wants an explicit alignment.
5945 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
5947 Align = getTargetData()->getTypeAllocSize(C->getType());
5948 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
5950 unsigned VReg1 = MRI->createVirtualRegister(TRC);
5951 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
5952 .addReg(VReg1, RegState::Define)
5953 .addConstantPoolIndex(Idx));
5954 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
5959 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
5964 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5965 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
5966 .addReg(ARM::CPSR, RegState::Define)
5970 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5971 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
5972 .addJumpTableIndex(MJTI)
5975 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5976 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
5977 .addReg(ARM::CPSR, RegState::Define)
5978 .addReg(NewVReg2, RegState::Kill)
5981 MachineMemOperand *JTMMOLd =
5982 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
5983 MachineMemOperand::MOLoad, 4, 4);
5985 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5986 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
5987 .addReg(NewVReg4, RegState::Kill)
5989 .addMemOperand(JTMMOLd));
5991 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
5992 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
5993 .addReg(ARM::CPSR, RegState::Define)
5994 .addReg(NewVReg5, RegState::Kill)
5997 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
5998 .addReg(NewVReg6, RegState::Kill)
5999 .addJumpTableIndex(MJTI)
6002 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6003 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6006 .addMemOperand(FIMMOLd));
6008 if (NumLPads < 256) {
6009 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6012 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6013 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6014 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6015 .addImm(NumLPads & 0xFFFF));
6017 unsigned VReg2 = VReg1;
6018 if ((NumLPads & 0xFFFF0000) != 0) {
6019 VReg2 = MRI->createVirtualRegister(TRC);
6020 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6022 .addImm(NumLPads >> 16));
6025 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6029 MachineConstantPool *ConstantPool = MF->getConstantPool();
6030 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6031 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6033 // MachineConstantPool wants an explicit alignment.
6034 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6036 Align = getTargetData()->getTypeAllocSize(C->getType());
6037 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6039 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6040 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6041 .addReg(VReg1, RegState::Define)
6042 .addConstantPoolIndex(Idx)
6044 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6046 .addReg(VReg1, RegState::Kill));
6049 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6054 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6056 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6058 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6059 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6060 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6061 .addJumpTableIndex(MJTI)
6064 MachineMemOperand *JTMMOLd =
6065 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6066 MachineMemOperand::MOLoad, 4, 4);
6067 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6069 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6070 .addReg(NewVReg3, RegState::Kill)
6073 .addMemOperand(JTMMOLd));
6075 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6076 .addReg(NewVReg5, RegState::Kill)
6078 .addJumpTableIndex(MJTI)
6082 // Add the jump table entries as successors to the MBB.
6083 MachineBasicBlock *PrevMBB = 0;
6084 for (std::vector<MachineBasicBlock*>::iterator
6085 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6086 MachineBasicBlock *CurMBB = *I;
6087 if (PrevMBB != CurMBB)
6088 DispContBB->addSuccessor(CurMBB);
6092 // N.B. the order the invoke BBs are processed in doesn't matter here.
6093 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6094 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6095 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6096 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6097 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6098 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6099 MachineBasicBlock *BB = *I;
6101 // Remove the landing pad successor from the invoke block and replace it
6102 // with the new dispatch block.
6103 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6105 while (!Successors.empty()) {
6106 MachineBasicBlock *SMBB = Successors.pop_back_val();
6107 if (SMBB->isLandingPad()) {
6108 BB->removeSuccessor(SMBB);
6109 MBBLPads.push_back(SMBB);
6113 BB->addSuccessor(DispatchBB);
6115 // Find the invoke call and mark all of the callee-saved registers as
6116 // 'implicit defined' so that they're spilled. This prevents code from
6117 // moving instructions to before the EH block, where they will never be
6119 for (MachineBasicBlock::reverse_iterator
6120 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6121 if (!II->isCall()) continue;
6123 DenseMap<unsigned, bool> DefRegs;
6124 for (MachineInstr::mop_iterator
6125 OI = II->operands_begin(), OE = II->operands_end();
6127 if (!OI->isReg()) continue;
6128 DefRegs[OI->getReg()] = true;
6131 MachineInstrBuilder MIB(&*II);
6133 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6134 unsigned Reg = SavedRegs[i];
6135 if (Subtarget->isThumb2() &&
6136 !ARM::tGPRRegisterClass->contains(Reg) &&
6137 !ARM::hGPRRegisterClass->contains(Reg))
6139 else if (Subtarget->isThumb1Only() &&
6140 !ARM::tGPRRegisterClass->contains(Reg))
6142 else if (!Subtarget->isThumb() &&
6143 !ARM::GPRRegisterClass->contains(Reg))
6146 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6153 // Mark all former landing pads as non-landing pads. The dispatch is the only
6155 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6156 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6157 (*I)->setIsLandingPad(false);
6159 // The instruction is gone now.
6160 MI->eraseFromParent();
6166 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6167 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6168 E = MBB->succ_end(); I != E; ++I)
6171 llvm_unreachable("Expecting a BB with two successors!");
6175 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6176 MachineBasicBlock *BB) const {
6177 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6178 DebugLoc dl = MI->getDebugLoc();
6179 bool isThumb2 = Subtarget->isThumb2();
6180 switch (MI->getOpcode()) {
6183 llvm_unreachable("Unexpected instr type to insert");
6185 // The Thumb2 pre-indexed stores have the same MI operands, they just
6186 // define them differently in the .td files from the isel patterns, so
6187 // they need pseudos.
6188 case ARM::t2STR_preidx:
6189 MI->setDesc(TII->get(ARM::t2STR_PRE));
6191 case ARM::t2STRB_preidx:
6192 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6194 case ARM::t2STRH_preidx:
6195 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6198 case ARM::STRi_preidx:
6199 case ARM::STRBi_preidx: {
6200 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6201 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6202 // Decode the offset.
6203 unsigned Offset = MI->getOperand(4).getImm();
6204 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6205 Offset = ARM_AM::getAM2Offset(Offset);
6209 MachineMemOperand *MMO = *MI->memoperands_begin();
6210 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6211 .addOperand(MI->getOperand(0)) // Rn_wb
6212 .addOperand(MI->getOperand(1)) // Rt
6213 .addOperand(MI->getOperand(2)) // Rn
6214 .addImm(Offset) // offset (skip GPR==zero_reg)
6215 .addOperand(MI->getOperand(5)) // pred
6216 .addOperand(MI->getOperand(6))
6217 .addMemOperand(MMO);
6218 MI->eraseFromParent();
6221 case ARM::STRr_preidx:
6222 case ARM::STRBr_preidx:
6223 case ARM::STRH_preidx: {
6225 switch (MI->getOpcode()) {
6226 default: llvm_unreachable("unexpected opcode!");
6227 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6228 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6229 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6231 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6232 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6233 MIB.addOperand(MI->getOperand(i));
6234 MI->eraseFromParent();
6237 case ARM::ATOMIC_LOAD_ADD_I8:
6238 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6239 case ARM::ATOMIC_LOAD_ADD_I16:
6240 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6241 case ARM::ATOMIC_LOAD_ADD_I32:
6242 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6244 case ARM::ATOMIC_LOAD_AND_I8:
6245 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6246 case ARM::ATOMIC_LOAD_AND_I16:
6247 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6248 case ARM::ATOMIC_LOAD_AND_I32:
6249 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6251 case ARM::ATOMIC_LOAD_OR_I8:
6252 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6253 case ARM::ATOMIC_LOAD_OR_I16:
6254 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6255 case ARM::ATOMIC_LOAD_OR_I32:
6256 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6258 case ARM::ATOMIC_LOAD_XOR_I8:
6259 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6260 case ARM::ATOMIC_LOAD_XOR_I16:
6261 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6262 case ARM::ATOMIC_LOAD_XOR_I32:
6263 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6265 case ARM::ATOMIC_LOAD_NAND_I8:
6266 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6267 case ARM::ATOMIC_LOAD_NAND_I16:
6268 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6269 case ARM::ATOMIC_LOAD_NAND_I32:
6270 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6272 case ARM::ATOMIC_LOAD_SUB_I8:
6273 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6274 case ARM::ATOMIC_LOAD_SUB_I16:
6275 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6276 case ARM::ATOMIC_LOAD_SUB_I32:
6277 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6279 case ARM::ATOMIC_LOAD_MIN_I8:
6280 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6281 case ARM::ATOMIC_LOAD_MIN_I16:
6282 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6283 case ARM::ATOMIC_LOAD_MIN_I32:
6284 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6286 case ARM::ATOMIC_LOAD_MAX_I8:
6287 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6288 case ARM::ATOMIC_LOAD_MAX_I16:
6289 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6290 case ARM::ATOMIC_LOAD_MAX_I32:
6291 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6293 case ARM::ATOMIC_LOAD_UMIN_I8:
6294 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6295 case ARM::ATOMIC_LOAD_UMIN_I16:
6296 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6297 case ARM::ATOMIC_LOAD_UMIN_I32:
6298 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6300 case ARM::ATOMIC_LOAD_UMAX_I8:
6301 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6302 case ARM::ATOMIC_LOAD_UMAX_I16:
6303 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6304 case ARM::ATOMIC_LOAD_UMAX_I32:
6305 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6307 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
6308 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6309 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6311 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
6312 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6313 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6316 case ARM::ATOMADD6432:
6317 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6318 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6319 /*NeedsCarry*/ true);
6320 case ARM::ATOMSUB6432:
6321 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6322 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6323 /*NeedsCarry*/ true);
6324 case ARM::ATOMOR6432:
6325 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6326 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6327 case ARM::ATOMXOR6432:
6328 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6329 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6330 case ARM::ATOMAND6432:
6331 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6332 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6333 case ARM::ATOMSWAP6432:
6334 return EmitAtomicBinary64(MI, BB, 0, 0, false);
6335 case ARM::ATOMCMPXCHG6432:
6336 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6337 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6338 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6340 case ARM::tMOVCCr_pseudo: {
6341 // To "insert" a SELECT_CC instruction, we actually have to insert the
6342 // diamond control-flow pattern. The incoming instruction knows the
6343 // destination vreg to set, the condition code register to branch on, the
6344 // true/false values to select between, and a branch opcode to use.
6345 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6346 MachineFunction::iterator It = BB;
6352 // cmpTY ccX, r1, r2
6354 // fallthrough --> copy0MBB
6355 MachineBasicBlock *thisMBB = BB;
6356 MachineFunction *F = BB->getParent();
6357 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6358 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6359 F->insert(It, copy0MBB);
6360 F->insert(It, sinkMBB);
6362 // Transfer the remainder of BB and its successor edges to sinkMBB.
6363 sinkMBB->splice(sinkMBB->begin(), BB,
6364 llvm::next(MachineBasicBlock::iterator(MI)),
6366 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6368 BB->addSuccessor(copy0MBB);
6369 BB->addSuccessor(sinkMBB);
6371 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6372 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6375 // %FalseValue = ...
6376 // # fallthrough to sinkMBB
6379 // Update machine-CFG edges
6380 BB->addSuccessor(sinkMBB);
6383 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6386 BuildMI(*BB, BB->begin(), dl,
6387 TII->get(ARM::PHI), MI->getOperand(0).getReg())
6388 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6389 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6391 MI->eraseFromParent(); // The pseudo instruction is gone now.
6396 case ARM::BCCZi64: {
6397 // If there is an unconditional branch to the other successor, remove it.
6398 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6400 // Compare both parts that make up the double comparison separately for
6402 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6404 unsigned LHS1 = MI->getOperand(1).getReg();
6405 unsigned LHS2 = MI->getOperand(2).getReg();
6407 AddDefaultPred(BuildMI(BB, dl,
6408 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6409 .addReg(LHS1).addImm(0));
6410 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6411 .addReg(LHS2).addImm(0)
6412 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6414 unsigned RHS1 = MI->getOperand(3).getReg();
6415 unsigned RHS2 = MI->getOperand(4).getReg();
6416 AddDefaultPred(BuildMI(BB, dl,
6417 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6418 .addReg(LHS1).addReg(RHS1));
6419 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6420 .addReg(LHS2).addReg(RHS2)
6421 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6424 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6425 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6426 if (MI->getOperand(0).getImm() == ARMCC::NE)
6427 std::swap(destMBB, exitMBB);
6429 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6430 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6432 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6434 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6436 MI->eraseFromParent(); // The pseudo instruction is gone now.
6440 case ARM::Int_eh_sjlj_setjmp:
6441 case ARM::Int_eh_sjlj_setjmp_nofp:
6442 case ARM::tInt_eh_sjlj_setjmp:
6443 case ARM::t2Int_eh_sjlj_setjmp:
6444 case ARM::t2Int_eh_sjlj_setjmp_nofp:
6445 EmitSjLjDispatchBlock(MI, BB);
6450 // To insert an ABS instruction, we have to insert the
6451 // diamond control-flow pattern. The incoming instruction knows the
6452 // source vreg to test against 0, the destination vreg to set,
6453 // the condition code register to branch on, the
6454 // true/false values to select between, and a branch opcode to use.
6459 // BCC (branch to SinkBB if V0 >= 0)
6460 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
6461 // SinkBB: V1 = PHI(V2, V3)
6462 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6463 MachineFunction::iterator BBI = BB;
6465 MachineFunction *Fn = BB->getParent();
6466 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6467 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6468 Fn->insert(BBI, RSBBB);
6469 Fn->insert(BBI, SinkBB);
6471 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6472 unsigned int ABSDstReg = MI->getOperand(0).getReg();
6473 bool isThumb2 = Subtarget->isThumb2();
6474 MachineRegisterInfo &MRI = Fn->getRegInfo();
6475 // In Thumb mode S must not be specified if source register is the SP or
6476 // PC and if destination register is the SP, so restrict register class
6477 unsigned NewMovDstReg = MRI.createVirtualRegister(
6478 isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6479 unsigned NewRsbDstReg = MRI.createVirtualRegister(
6480 isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6482 // Transfer the remainder of BB and its successor edges to sinkMBB.
6483 SinkBB->splice(SinkBB->begin(), BB,
6484 llvm::next(MachineBasicBlock::iterator(MI)),
6486 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6488 BB->addSuccessor(RSBBB);
6489 BB->addSuccessor(SinkBB);
6491 // fall through to SinkMBB
6492 RSBBB->addSuccessor(SinkBB);
6494 // insert a movs at the end of BB
6495 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVr : ARM::MOVr),
6497 .addReg(ABSSrcReg, RegState::Kill)
6498 .addImm((unsigned)ARMCC::AL).addReg(0)
6499 .addReg(ARM::CPSR, RegState::Define);
6501 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6503 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6504 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6506 // insert rsbri in RSBBB
6507 // Note: BCC and rsbri will be converted into predicated rsbmi
6508 // by if-conversion pass
6509 BuildMI(*RSBBB, RSBBB->begin(), dl,
6510 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6511 .addReg(NewMovDstReg, RegState::Kill)
6512 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6514 // insert PHI in SinkBB,
6515 // reuse ABSDstReg to not change uses of ABS instruction
6516 BuildMI(*SinkBB, SinkBB->begin(), dl,
6517 TII->get(ARM::PHI), ABSDstReg)
6518 .addReg(NewRsbDstReg).addMBB(RSBBB)
6519 .addReg(NewMovDstReg).addMBB(BB);
6521 // remove ABS instruction
6522 MI->eraseFromParent();
6524 // return last added BB
6530 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6531 SDNode *Node) const {
6532 if (!MI->hasPostISelHook()) {
6533 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6534 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6538 const MCInstrDesc *MCID = &MI->getDesc();
6539 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6540 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6541 // operand is still set to noreg. If needed, set the optional operand's
6542 // register to CPSR, and remove the redundant implicit def.
6544 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6546 // Rename pseudo opcodes.
6547 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6549 const ARMBaseInstrInfo *TII =
6550 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6551 MCID = &TII->get(NewOpc);
6553 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6554 "converted opcode should be the same except for cc_out");
6558 // Add the optional cc_out operand
6559 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6561 unsigned ccOutIdx = MCID->getNumOperands() - 1;
6563 // Any ARM instruction that sets the 's' bit should specify an optional
6564 // "cc_out" operand in the last operand position.
6565 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6566 assert(!NewOpc && "Optional cc_out operand required");
6569 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6570 // since we already have an optional CPSR def.
6571 bool definesCPSR = false;
6572 bool deadCPSR = false;
6573 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6575 const MachineOperand &MO = MI->getOperand(i);
6576 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6580 MI->RemoveOperand(i);
6585 assert(!NewOpc && "Optional cc_out operand required");
6588 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6590 assert(!MI->getOperand(ccOutIdx).getReg() &&
6591 "expect uninitialized optional cc_out operand");
6595 // If this instruction was defined with an optional CPSR def and its dag node
6596 // had a live implicit CPSR def, then activate the optional CPSR def.
6597 MachineOperand &MO = MI->getOperand(ccOutIdx);
6598 MO.setReg(ARM::CPSR);
6602 //===----------------------------------------------------------------------===//
6603 // ARM Optimization Hooks
6604 //===----------------------------------------------------------------------===//
6607 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6608 TargetLowering::DAGCombinerInfo &DCI) {
6609 SelectionDAG &DAG = DCI.DAG;
6610 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6611 EVT VT = N->getValueType(0);
6612 unsigned Opc = N->getOpcode();
6613 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6614 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6615 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6616 ISD::CondCode CC = ISD::SETCC_INVALID;
6619 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6621 SDValue CCOp = Slct.getOperand(0);
6622 if (CCOp.getOpcode() == ISD::SETCC)
6623 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6626 bool DoXform = false;
6628 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6631 if (LHS.getOpcode() == ISD::Constant &&
6632 cast<ConstantSDNode>(LHS)->isNullValue()) {
6634 } else if (CC != ISD::SETCC_INVALID &&
6635 RHS.getOpcode() == ISD::Constant &&
6636 cast<ConstantSDNode>(RHS)->isNullValue()) {
6637 std::swap(LHS, RHS);
6638 SDValue Op0 = Slct.getOperand(0);
6639 EVT OpVT = isSlctCC ? Op0.getValueType() :
6640 Op0.getOperand(0).getValueType();
6641 bool isInt = OpVT.isInteger();
6642 CC = ISD::getSetCCInverse(CC, isInt);
6644 if (!TLI.isCondCodeLegal(CC, OpVT))
6645 return SDValue(); // Inverse operator isn't legal.
6652 SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
6654 return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
6655 Slct.getOperand(0), Slct.getOperand(1), CC);
6656 SDValue CCOp = Slct.getOperand(0);
6658 CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
6659 CCOp.getOperand(0), CCOp.getOperand(1), CC);
6660 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
6661 CCOp, OtherOp, Result);
6666 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
6667 // (only after legalization).
6668 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
6669 TargetLowering::DAGCombinerInfo &DCI,
6670 const ARMSubtarget *Subtarget) {
6672 // Only perform optimization if after legalize, and if NEON is available. We
6673 // also expected both operands to be BUILD_VECTORs.
6674 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
6675 || N0.getOpcode() != ISD::BUILD_VECTOR
6676 || N1.getOpcode() != ISD::BUILD_VECTOR)
6679 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
6680 EVT VT = N->getValueType(0);
6681 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
6684 // Check that the vector operands are of the right form.
6685 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
6686 // operands, where N is the size of the formed vector.
6687 // Each EXTRACT_VECTOR should have the same input vector and odd or even
6688 // index such that we have a pair wise add pattern.
6690 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
6691 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6693 SDValue Vec = N0->getOperand(0)->getOperand(0);
6694 SDNode *V = Vec.getNode();
6695 unsigned nextIndex = 0;
6697 // For each operands to the ADD which are BUILD_VECTORs,
6698 // check to see if each of their operands are an EXTRACT_VECTOR with
6699 // the same vector and appropriate index.
6700 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
6701 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
6702 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6704 SDValue ExtVec0 = N0->getOperand(i);
6705 SDValue ExtVec1 = N1->getOperand(i);
6707 // First operand is the vector, verify its the same.
6708 if (V != ExtVec0->getOperand(0).getNode() ||
6709 V != ExtVec1->getOperand(0).getNode())
6712 // Second is the constant, verify its correct.
6713 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
6714 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
6716 // For the constant, we want to see all the even or all the odd.
6717 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
6718 || C1->getZExtValue() != nextIndex+1)
6727 // Create VPADDL node.
6728 SelectionDAG &DAG = DCI.DAG;
6729 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6731 // Build operand list.
6732 SmallVector<SDValue, 8> Ops;
6733 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
6734 TLI.getPointerTy()));
6736 // Input is the vector.
6739 // Get widened type and narrowed type.
6741 unsigned numElem = VT.getVectorNumElements();
6742 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
6743 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
6744 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
6745 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
6747 llvm_unreachable("Invalid vector element type for padd optimization.");
6750 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6751 widenType, &Ops[0], Ops.size());
6752 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
6755 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
6756 /// operands N0 and N1. This is a helper for PerformADDCombine that is
6757 /// called with the default operands, and if that fails, with commuted
6759 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
6760 TargetLowering::DAGCombinerInfo &DCI,
6761 const ARMSubtarget *Subtarget){
6763 // Attempt to create vpaddl for this add.
6764 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
6765 if (Result.getNode())
6768 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
6769 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
6770 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
6771 if (Result.getNode()) return Result;
6776 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6778 static SDValue PerformADDCombine(SDNode *N,
6779 TargetLowering::DAGCombinerInfo &DCI,
6780 const ARMSubtarget *Subtarget) {
6781 SDValue N0 = N->getOperand(0);
6782 SDValue N1 = N->getOperand(1);
6784 // First try with the default operand order.
6785 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
6786 if (Result.getNode())
6789 // If that didn't work, try again with the operands commuted.
6790 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
6793 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
6795 static SDValue PerformSUBCombine(SDNode *N,
6796 TargetLowering::DAGCombinerInfo &DCI) {
6797 SDValue N0 = N->getOperand(0);
6798 SDValue N1 = N->getOperand(1);
6800 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6801 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
6802 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
6803 if (Result.getNode()) return Result;
6809 /// PerformVMULCombine
6810 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
6811 /// special multiplier accumulator forwarding.
6817 static SDValue PerformVMULCombine(SDNode *N,
6818 TargetLowering::DAGCombinerInfo &DCI,
6819 const ARMSubtarget *Subtarget) {
6820 if (!Subtarget->hasVMLxForwarding())
6823 SelectionDAG &DAG = DCI.DAG;
6824 SDValue N0 = N->getOperand(0);
6825 SDValue N1 = N->getOperand(1);
6826 unsigned Opcode = N0.getOpcode();
6827 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6828 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
6829 Opcode = N1.getOpcode();
6830 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6831 Opcode != ISD::FADD && Opcode != ISD::FSUB)
6836 EVT VT = N->getValueType(0);
6837 DebugLoc DL = N->getDebugLoc();
6838 SDValue N00 = N0->getOperand(0);
6839 SDValue N01 = N0->getOperand(1);
6840 return DAG.getNode(Opcode, DL, VT,
6841 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
6842 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
6845 static SDValue PerformMULCombine(SDNode *N,
6846 TargetLowering::DAGCombinerInfo &DCI,
6847 const ARMSubtarget *Subtarget) {
6848 SelectionDAG &DAG = DCI.DAG;
6850 if (Subtarget->isThumb1Only())
6853 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6856 EVT VT = N->getValueType(0);
6857 if (VT.is64BitVector() || VT.is128BitVector())
6858 return PerformVMULCombine(N, DCI, Subtarget);
6862 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6866 int64_t MulAmt = C->getSExtValue();
6867 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
6869 ShiftAmt = ShiftAmt & (32 - 1);
6870 SDValue V = N->getOperand(0);
6871 DebugLoc DL = N->getDebugLoc();
6874 MulAmt >>= ShiftAmt;
6877 if (isPowerOf2_32(MulAmt - 1)) {
6878 // (mul x, 2^N + 1) => (add (shl x, N), x)
6879 Res = DAG.getNode(ISD::ADD, DL, VT,
6881 DAG.getNode(ISD::SHL, DL, VT,
6883 DAG.getConstant(Log2_32(MulAmt - 1),
6885 } else if (isPowerOf2_32(MulAmt + 1)) {
6886 // (mul x, 2^N - 1) => (sub (shl x, N), x)
6887 Res = DAG.getNode(ISD::SUB, DL, VT,
6888 DAG.getNode(ISD::SHL, DL, VT,
6890 DAG.getConstant(Log2_32(MulAmt + 1),
6896 uint64_t MulAmtAbs = -MulAmt;
6897 if (isPowerOf2_32(MulAmtAbs + 1)) {
6898 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
6899 Res = DAG.getNode(ISD::SUB, DL, VT,
6901 DAG.getNode(ISD::SHL, DL, VT,
6903 DAG.getConstant(Log2_32(MulAmtAbs + 1),
6905 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
6906 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
6907 Res = DAG.getNode(ISD::ADD, DL, VT,
6909 DAG.getNode(ISD::SHL, DL, VT,
6911 DAG.getConstant(Log2_32(MulAmtAbs-1),
6913 Res = DAG.getNode(ISD::SUB, DL, VT,
6914 DAG.getConstant(0, MVT::i32),Res);
6921 Res = DAG.getNode(ISD::SHL, DL, VT,
6922 Res, DAG.getConstant(ShiftAmt, MVT::i32));
6924 // Do not add new nodes to DAG combiner worklist.
6925 DCI.CombineTo(N, Res, false);
6929 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
6930 if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
6933 SDValue FalseVal = N.getOperand(0);
6934 ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
6938 return C->isAllOnesValue();
6939 return C->isNullValue();
6942 /// formConditionalOp - Combine an operation with a conditional move operand
6943 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
6944 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
6945 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
6947 SDValue N0 = N->getOperand(0);
6948 SDValue N1 = N->getOperand(1);
6950 bool isAND = N->getOpcode() == ISD::AND;
6951 bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
6952 if (!isCand && Commutable) {
6953 isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
6961 switch (N->getOpcode()) {
6962 default: llvm_unreachable("Unexpected node");
6963 case ISD::AND: Opc = ARMISD::CAND; break;
6964 case ISD::OR: Opc = ARMISD::COR; break;
6965 case ISD::XOR: Opc = ARMISD::CXOR; break;
6967 return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
6968 N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
6972 static SDValue PerformANDCombine(SDNode *N,
6973 TargetLowering::DAGCombinerInfo &DCI,
6974 const ARMSubtarget *Subtarget) {
6976 // Attempt to use immediate-form VBIC
6977 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6978 DebugLoc dl = N->getDebugLoc();
6979 EVT VT = N->getValueType(0);
6980 SelectionDAG &DAG = DCI.DAG;
6982 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6985 APInt SplatBits, SplatUndef;
6986 unsigned SplatBitSize;
6989 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6990 if (SplatBitSize <= 64) {
6992 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
6993 SplatUndef.getZExtValue(), SplatBitSize,
6994 DAG, VbicVT, VT.is128BitVector(),
6996 if (Val.getNode()) {
6998 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
6999 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7000 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7005 if (!Subtarget->isThumb1Only()) {
7006 // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7007 SDValue CAND = formConditionalOp(N, DAG, true);
7015 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7016 static SDValue PerformORCombine(SDNode *N,
7017 TargetLowering::DAGCombinerInfo &DCI,
7018 const ARMSubtarget *Subtarget) {
7019 // Attempt to use immediate-form VORR
7020 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7021 DebugLoc dl = N->getDebugLoc();
7022 EVT VT = N->getValueType(0);
7023 SelectionDAG &DAG = DCI.DAG;
7025 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7028 APInt SplatBits, SplatUndef;
7029 unsigned SplatBitSize;
7031 if (BVN && Subtarget->hasNEON() &&
7032 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7033 if (SplatBitSize <= 64) {
7035 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7036 SplatUndef.getZExtValue(), SplatBitSize,
7037 DAG, VorrVT, VT.is128BitVector(),
7039 if (Val.getNode()) {
7041 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7042 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7043 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7048 if (!Subtarget->isThumb1Only()) {
7049 // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7050 SDValue COR = formConditionalOp(N, DAG, true);
7055 SDValue N0 = N->getOperand(0);
7056 if (N0.getOpcode() != ISD::AND)
7058 SDValue N1 = N->getOperand(1);
7060 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7061 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7062 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7064 unsigned SplatBitSize;
7067 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7069 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7070 HasAnyUndefs) && !HasAnyUndefs) {
7071 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7073 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7074 HasAnyUndefs) && !HasAnyUndefs &&
7075 SplatBits0 == ~SplatBits1) {
7076 // Canonicalize the vector type to make instruction selection simpler.
7077 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7078 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7079 N0->getOperand(1), N0->getOperand(0),
7081 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7086 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7089 // BFI is only available on V6T2+
7090 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7093 DebugLoc DL = N->getDebugLoc();
7094 // 1) or (and A, mask), val => ARMbfi A, val, mask
7095 // iff (val & mask) == val
7097 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7098 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7099 // && mask == ~mask2
7100 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7101 // && ~mask == mask2
7102 // (i.e., copy a bitfield value into another bitfield of the same width)
7107 SDValue N00 = N0.getOperand(0);
7109 // The value and the mask need to be constants so we can verify this is
7110 // actually a bitfield set. If the mask is 0xffff, we can do better
7111 // via a movt instruction, so don't use BFI in that case.
7112 SDValue MaskOp = N0.getOperand(1);
7113 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7116 unsigned Mask = MaskC->getZExtValue();
7120 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7121 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7123 unsigned Val = N1C->getZExtValue();
7124 if ((Val & ~Mask) != Val)
7127 if (ARM::isBitFieldInvertedMask(Mask)) {
7128 Val >>= CountTrailingZeros_32(~Mask);
7130 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7131 DAG.getConstant(Val, MVT::i32),
7132 DAG.getConstant(Mask, MVT::i32));
7134 // Do not add new nodes to DAG combiner worklist.
7135 DCI.CombineTo(N, Res, false);
7138 } else if (N1.getOpcode() == ISD::AND) {
7139 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7140 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7143 unsigned Mask2 = N11C->getZExtValue();
7145 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7147 if (ARM::isBitFieldInvertedMask(Mask) &&
7149 // The pack halfword instruction works better for masks that fit it,
7150 // so use that when it's available.
7151 if (Subtarget->hasT2ExtractPack() &&
7152 (Mask == 0xffff || Mask == 0xffff0000))
7155 unsigned amt = CountTrailingZeros_32(Mask2);
7156 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7157 DAG.getConstant(amt, MVT::i32));
7158 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7159 DAG.getConstant(Mask, MVT::i32));
7160 // Do not add new nodes to DAG combiner worklist.
7161 DCI.CombineTo(N, Res, false);
7163 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7165 // The pack halfword instruction works better for masks that fit it,
7166 // so use that when it's available.
7167 if (Subtarget->hasT2ExtractPack() &&
7168 (Mask2 == 0xffff || Mask2 == 0xffff0000))
7171 unsigned lsb = CountTrailingZeros_32(Mask);
7172 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7173 DAG.getConstant(lsb, MVT::i32));
7174 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7175 DAG.getConstant(Mask2, MVT::i32));
7176 // Do not add new nodes to DAG combiner worklist.
7177 DCI.CombineTo(N, Res, false);
7182 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7183 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7184 ARM::isBitFieldInvertedMask(~Mask)) {
7185 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7186 // where lsb(mask) == #shamt and masked bits of B are known zero.
7187 SDValue ShAmt = N00.getOperand(1);
7188 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7189 unsigned LSB = CountTrailingZeros_32(Mask);
7193 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7194 DAG.getConstant(~Mask, MVT::i32));
7196 // Do not add new nodes to DAG combiner worklist.
7197 DCI.CombineTo(N, Res, false);
7203 static SDValue PerformXORCombine(SDNode *N,
7204 TargetLowering::DAGCombinerInfo &DCI,
7205 const ARMSubtarget *Subtarget) {
7206 EVT VT = N->getValueType(0);
7207 SelectionDAG &DAG = DCI.DAG;
7209 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7212 if (!Subtarget->isThumb1Only()) {
7213 // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7214 SDValue CXOR = formConditionalOp(N, DAG, true);
7222 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7223 /// the bits being cleared by the AND are not demanded by the BFI.
7224 static SDValue PerformBFICombine(SDNode *N,
7225 TargetLowering::DAGCombinerInfo &DCI) {
7226 SDValue N1 = N->getOperand(1);
7227 if (N1.getOpcode() == ISD::AND) {
7228 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7231 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7232 unsigned LSB = CountTrailingZeros_32(~InvMask);
7233 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7234 unsigned Mask = (1 << Width)-1;
7235 unsigned Mask2 = N11C->getZExtValue();
7236 if ((Mask & (~Mask2)) == 0)
7237 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7238 N->getOperand(0), N1.getOperand(0),
7244 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7245 /// ARMISD::VMOVRRD.
7246 static SDValue PerformVMOVRRDCombine(SDNode *N,
7247 TargetLowering::DAGCombinerInfo &DCI) {
7248 // vmovrrd(vmovdrr x, y) -> x,y
7249 SDValue InDouble = N->getOperand(0);
7250 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7251 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7253 // vmovrrd(load f64) -> (load i32), (load i32)
7254 SDNode *InNode = InDouble.getNode();
7255 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7256 InNode->getValueType(0) == MVT::f64 &&
7257 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7258 !cast<LoadSDNode>(InNode)->isVolatile()) {
7259 // TODO: Should this be done for non-FrameIndex operands?
7260 LoadSDNode *LD = cast<LoadSDNode>(InNode);
7262 SelectionDAG &DAG = DCI.DAG;
7263 DebugLoc DL = LD->getDebugLoc();
7264 SDValue BasePtr = LD->getBasePtr();
7265 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7266 LD->getPointerInfo(), LD->isVolatile(),
7267 LD->isNonTemporal(), LD->isInvariant(),
7268 LD->getAlignment());
7270 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7271 DAG.getConstant(4, MVT::i32));
7272 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7273 LD->getPointerInfo(), LD->isVolatile(),
7274 LD->isNonTemporal(), LD->isInvariant(),
7275 std::min(4U, LD->getAlignment() / 2));
7277 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7278 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7279 DCI.RemoveFromWorklist(LD);
7287 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7288 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
7289 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7290 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7291 SDValue Op0 = N->getOperand(0);
7292 SDValue Op1 = N->getOperand(1);
7293 if (Op0.getOpcode() == ISD::BITCAST)
7294 Op0 = Op0.getOperand(0);
7295 if (Op1.getOpcode() == ISD::BITCAST)
7296 Op1 = Op1.getOperand(0);
7297 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7298 Op0.getNode() == Op1.getNode() &&
7299 Op0.getResNo() == 0 && Op1.getResNo() == 1)
7300 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7301 N->getValueType(0), Op0.getOperand(0));
7305 /// PerformSTORECombine - Target-specific dag combine xforms for
7307 static SDValue PerformSTORECombine(SDNode *N,
7308 TargetLowering::DAGCombinerInfo &DCI) {
7309 // Bitcast an i64 store extracted from a vector to f64.
7310 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7311 StoreSDNode *St = cast<StoreSDNode>(N);
7312 SDValue StVal = St->getValue();
7313 if (!ISD::isNormalStore(St) || St->isVolatile())
7316 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7317 StVal.getNode()->hasOneUse() && !St->isVolatile()) {
7318 SelectionDAG &DAG = DCI.DAG;
7319 DebugLoc DL = St->getDebugLoc();
7320 SDValue BasePtr = St->getBasePtr();
7321 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7322 StVal.getNode()->getOperand(0), BasePtr,
7323 St->getPointerInfo(), St->isVolatile(),
7324 St->isNonTemporal(), St->getAlignment());
7326 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7327 DAG.getConstant(4, MVT::i32));
7328 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7329 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7330 St->isNonTemporal(),
7331 std::min(4U, St->getAlignment() / 2));
7334 if (StVal.getValueType() != MVT::i64 ||
7335 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7338 SelectionDAG &DAG = DCI.DAG;
7339 DebugLoc dl = StVal.getDebugLoc();
7340 SDValue IntVec = StVal.getOperand(0);
7341 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7342 IntVec.getValueType().getVectorNumElements());
7343 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7344 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7345 Vec, StVal.getOperand(1));
7346 dl = N->getDebugLoc();
7347 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7348 // Make the DAGCombiner fold the bitcasts.
7349 DCI.AddToWorklist(Vec.getNode());
7350 DCI.AddToWorklist(ExtElt.getNode());
7351 DCI.AddToWorklist(V.getNode());
7352 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7353 St->getPointerInfo(), St->isVolatile(),
7354 St->isNonTemporal(), St->getAlignment(),
7358 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7359 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
7360 /// i64 vector to have f64 elements, since the value can then be loaded
7361 /// directly into a VFP register.
7362 static bool hasNormalLoadOperand(SDNode *N) {
7363 unsigned NumElts = N->getValueType(0).getVectorNumElements();
7364 for (unsigned i = 0; i < NumElts; ++i) {
7365 SDNode *Elt = N->getOperand(i).getNode();
7366 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7372 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7373 /// ISD::BUILD_VECTOR.
7374 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7375 TargetLowering::DAGCombinerInfo &DCI){
7376 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7377 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
7378 // into a pair of GPRs, which is fine when the value is used as a scalar,
7379 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7380 SelectionDAG &DAG = DCI.DAG;
7381 if (N->getNumOperands() == 2) {
7382 SDValue RV = PerformVMOVDRRCombine(N, DAG);
7387 // Load i64 elements as f64 values so that type legalization does not split
7388 // them up into i32 values.
7389 EVT VT = N->getValueType(0);
7390 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7392 DebugLoc dl = N->getDebugLoc();
7393 SmallVector<SDValue, 8> Ops;
7394 unsigned NumElts = VT.getVectorNumElements();
7395 for (unsigned i = 0; i < NumElts; ++i) {
7396 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7398 // Make the DAGCombiner fold the bitcast.
7399 DCI.AddToWorklist(V.getNode());
7401 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7402 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7403 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7406 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7407 /// ISD::INSERT_VECTOR_ELT.
7408 static SDValue PerformInsertEltCombine(SDNode *N,
7409 TargetLowering::DAGCombinerInfo &DCI) {
7410 // Bitcast an i64 load inserted into a vector to f64.
7411 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7412 EVT VT = N->getValueType(0);
7413 SDNode *Elt = N->getOperand(1).getNode();
7414 if (VT.getVectorElementType() != MVT::i64 ||
7415 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7418 SelectionDAG &DAG = DCI.DAG;
7419 DebugLoc dl = N->getDebugLoc();
7420 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7421 VT.getVectorNumElements());
7422 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7423 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7424 // Make the DAGCombiner fold the bitcasts.
7425 DCI.AddToWorklist(Vec.getNode());
7426 DCI.AddToWorklist(V.getNode());
7427 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7428 Vec, V, N->getOperand(2));
7429 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7432 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7433 /// ISD::VECTOR_SHUFFLE.
7434 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7435 // The LLVM shufflevector instruction does not require the shuffle mask
7436 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7437 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
7438 // operands do not match the mask length, they are extended by concatenating
7439 // them with undef vectors. That is probably the right thing for other
7440 // targets, but for NEON it is better to concatenate two double-register
7441 // size vector operands into a single quad-register size vector. Do that
7442 // transformation here:
7443 // shuffle(concat(v1, undef), concat(v2, undef)) ->
7444 // shuffle(concat(v1, v2), undef)
7445 SDValue Op0 = N->getOperand(0);
7446 SDValue Op1 = N->getOperand(1);
7447 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7448 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7449 Op0.getNumOperands() != 2 ||
7450 Op1.getNumOperands() != 2)
7452 SDValue Concat0Op1 = Op0.getOperand(1);
7453 SDValue Concat1Op1 = Op1.getOperand(1);
7454 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7455 Concat1Op1.getOpcode() != ISD::UNDEF)
7457 // Skip the transformation if any of the types are illegal.
7458 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7459 EVT VT = N->getValueType(0);
7460 if (!TLI.isTypeLegal(VT) ||
7461 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7462 !TLI.isTypeLegal(Concat1Op1.getValueType()))
7465 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7466 Op0.getOperand(0), Op1.getOperand(0));
7467 // Translate the shuffle mask.
7468 SmallVector<int, 16> NewMask;
7469 unsigned NumElts = VT.getVectorNumElements();
7470 unsigned HalfElts = NumElts/2;
7471 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7472 for (unsigned n = 0; n < NumElts; ++n) {
7473 int MaskElt = SVN->getMaskElt(n);
7475 if (MaskElt < (int)HalfElts)
7477 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7478 NewElt = HalfElts + MaskElt - NumElts;
7479 NewMask.push_back(NewElt);
7481 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7482 DAG.getUNDEF(VT), NewMask.data());
7485 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7486 /// NEON load/store intrinsics to merge base address updates.
7487 static SDValue CombineBaseUpdate(SDNode *N,
7488 TargetLowering::DAGCombinerInfo &DCI) {
7489 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7492 SelectionDAG &DAG = DCI.DAG;
7493 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7494 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7495 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7496 SDValue Addr = N->getOperand(AddrOpIdx);
7498 // Search for a use of the address operand that is an increment.
7499 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7500 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7502 if (User->getOpcode() != ISD::ADD ||
7503 UI.getUse().getResNo() != Addr.getResNo())
7506 // Check that the add is independent of the load/store. Otherwise, folding
7507 // it would create a cycle.
7508 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7511 // Find the new opcode for the updating load/store.
7513 bool isLaneOp = false;
7514 unsigned NewOpc = 0;
7515 unsigned NumVecs = 0;
7517 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7519 default: llvm_unreachable("unexpected intrinsic for Neon base update");
7520 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
7522 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
7524 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
7526 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
7528 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7529 NumVecs = 2; isLaneOp = true; break;
7530 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7531 NumVecs = 3; isLaneOp = true; break;
7532 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7533 NumVecs = 4; isLaneOp = true; break;
7534 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
7535 NumVecs = 1; isLoad = false; break;
7536 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
7537 NumVecs = 2; isLoad = false; break;
7538 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
7539 NumVecs = 3; isLoad = false; break;
7540 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
7541 NumVecs = 4; isLoad = false; break;
7542 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7543 NumVecs = 2; isLoad = false; isLaneOp = true; break;
7544 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7545 NumVecs = 3; isLoad = false; isLaneOp = true; break;
7546 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
7547 NumVecs = 4; isLoad = false; isLaneOp = true; break;
7551 switch (N->getOpcode()) {
7552 default: llvm_unreachable("unexpected opcode for Neon base update");
7553 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
7554 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
7555 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
7559 // Find the size of memory referenced by the load/store.
7562 VecTy = N->getValueType(0);
7564 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
7565 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7567 NumBytes /= VecTy.getVectorNumElements();
7569 // If the increment is a constant, it must match the memory ref size.
7570 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7571 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7572 uint64_t IncVal = CInc->getZExtValue();
7573 if (IncVal != NumBytes)
7575 } else if (NumBytes >= 3 * 16) {
7576 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
7577 // separate instructions that make it harder to use a non-constant update.
7581 // Create the new updating load/store node.
7583 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
7585 for (n = 0; n < NumResultVecs; ++n)
7587 Tys[n++] = MVT::i32;
7588 Tys[n] = MVT::Other;
7589 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
7590 SmallVector<SDValue, 8> Ops;
7591 Ops.push_back(N->getOperand(0)); // incoming chain
7592 Ops.push_back(N->getOperand(AddrOpIdx));
7594 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
7595 Ops.push_back(N->getOperand(i));
7597 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7598 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
7599 Ops.data(), Ops.size(),
7600 MemInt->getMemoryVT(),
7601 MemInt->getMemOperand());
7604 std::vector<SDValue> NewResults;
7605 for (unsigned i = 0; i < NumResultVecs; ++i) {
7606 NewResults.push_back(SDValue(UpdN.getNode(), i));
7608 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
7609 DCI.CombineTo(N, NewResults);
7610 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7617 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
7618 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
7619 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
7621 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
7622 SelectionDAG &DAG = DCI.DAG;
7623 EVT VT = N->getValueType(0);
7624 // vldN-dup instructions only support 64-bit vectors for N > 1.
7625 if (!VT.is64BitVector())
7628 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
7629 SDNode *VLD = N->getOperand(0).getNode();
7630 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
7632 unsigned NumVecs = 0;
7633 unsigned NewOpc = 0;
7634 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
7635 if (IntNo == Intrinsic::arm_neon_vld2lane) {
7637 NewOpc = ARMISD::VLD2DUP;
7638 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
7640 NewOpc = ARMISD::VLD3DUP;
7641 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
7643 NewOpc = ARMISD::VLD4DUP;
7648 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
7649 // numbers match the load.
7650 unsigned VLDLaneNo =
7651 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
7652 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7654 // Ignore uses of the chain result.
7655 if (UI.getUse().getResNo() == NumVecs)
7658 if (User->getOpcode() != ARMISD::VDUPLANE ||
7659 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
7663 // Create the vldN-dup node.
7666 for (n = 0; n < NumVecs; ++n)
7668 Tys[n] = MVT::Other;
7669 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
7670 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
7671 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
7672 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
7673 Ops, 2, VLDMemInt->getMemoryVT(),
7674 VLDMemInt->getMemOperand());
7677 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7679 unsigned ResNo = UI.getUse().getResNo();
7680 // Ignore uses of the chain result.
7681 if (ResNo == NumVecs)
7684 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
7687 // Now the vldN-lane intrinsic is dead except for its chain result.
7688 // Update uses of the chain.
7689 std::vector<SDValue> VLDDupResults;
7690 for (unsigned n = 0; n < NumVecs; ++n)
7691 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
7692 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
7693 DCI.CombineTo(VLD, VLDDupResults);
7698 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
7699 /// ARMISD::VDUPLANE.
7700 static SDValue PerformVDUPLANECombine(SDNode *N,
7701 TargetLowering::DAGCombinerInfo &DCI) {
7702 SDValue Op = N->getOperand(0);
7704 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
7705 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
7706 if (CombineVLDDUP(N, DCI))
7707 return SDValue(N, 0);
7709 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
7710 // redundant. Ignore bit_converts for now; element sizes are checked below.
7711 while (Op.getOpcode() == ISD::BITCAST)
7712 Op = Op.getOperand(0);
7713 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
7716 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
7717 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
7718 // The canonical VMOV for a zero vector uses a 32-bit element size.
7719 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7721 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
7723 EVT VT = N->getValueType(0);
7724 if (EltSize > VT.getVectorElementType().getSizeInBits())
7727 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
7730 // isConstVecPow2 - Return true if each vector element is a power of 2, all
7731 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
7732 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
7736 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
7738 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
7743 APFloat APF = C->getValueAPF();
7744 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
7745 != APFloat::opOK || !isExact)
7748 c0 = (I == 0) ? cN : c0;
7749 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
7756 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
7757 /// can replace combinations of VMUL and VCVT (floating-point to integer)
7758 /// when the VMUL has a constant operand that is a power of 2.
7760 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7761 /// vmul.f32 d16, d17, d16
7762 /// vcvt.s32.f32 d16, d16
7764 /// vcvt.s32.f32 d16, d16, #3
7765 static SDValue PerformVCVTCombine(SDNode *N,
7766 TargetLowering::DAGCombinerInfo &DCI,
7767 const ARMSubtarget *Subtarget) {
7768 SelectionDAG &DAG = DCI.DAG;
7769 SDValue Op = N->getOperand(0);
7771 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
7772 Op.getOpcode() != ISD::FMUL)
7776 SDValue N0 = Op->getOperand(0);
7777 SDValue ConstVec = Op->getOperand(1);
7778 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
7780 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7781 !isConstVecPow2(ConstVec, isSigned, C))
7784 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
7785 Intrinsic::arm_neon_vcvtfp2fxu;
7786 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7788 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
7789 DAG.getConstant(Log2_64(C), MVT::i32));
7792 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
7793 /// can replace combinations of VCVT (integer to floating-point) and VDIV
7794 /// when the VDIV has a constant operand that is a power of 2.
7796 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7797 /// vcvt.f32.s32 d16, d16
7798 /// vdiv.f32 d16, d17, d16
7800 /// vcvt.f32.s32 d16, d16, #3
7801 static SDValue PerformVDIVCombine(SDNode *N,
7802 TargetLowering::DAGCombinerInfo &DCI,
7803 const ARMSubtarget *Subtarget) {
7804 SelectionDAG &DAG = DCI.DAG;
7805 SDValue Op = N->getOperand(0);
7806 unsigned OpOpcode = Op.getNode()->getOpcode();
7808 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
7809 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
7813 SDValue ConstVec = N->getOperand(1);
7814 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
7816 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7817 !isConstVecPow2(ConstVec, isSigned, C))
7820 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
7821 Intrinsic::arm_neon_vcvtfxu2fp;
7822 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7824 DAG.getConstant(IntrinsicOpcode, MVT::i32),
7825 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
7828 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
7829 /// operand of a vector shift operation, where all the elements of the
7830 /// build_vector must have the same constant integer value.
7831 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7832 // Ignore bit_converts.
7833 while (Op.getOpcode() == ISD::BITCAST)
7834 Op = Op.getOperand(0);
7835 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7836 APInt SplatBits, SplatUndef;
7837 unsigned SplatBitSize;
7839 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7840 HasAnyUndefs, ElementBits) ||
7841 SplatBitSize > ElementBits)
7843 Cnt = SplatBits.getSExtValue();
7847 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7848 /// operand of a vector shift left operation. That value must be in the range:
7849 /// 0 <= Value < ElementBits for a left shift; or
7850 /// 0 <= Value <= ElementBits for a long left shift.
7851 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7852 assert(VT.isVector() && "vector shift count is not a vector type");
7853 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7854 if (! getVShiftImm(Op, ElementBits, Cnt))
7856 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
7859 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7860 /// operand of a vector shift right operation. For a shift opcode, the value
7861 /// is positive, but for an intrinsic the value count must be negative. The
7862 /// absolute value must be in the range:
7863 /// 1 <= |Value| <= ElementBits for a right shift; or
7864 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
7865 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
7867 assert(VT.isVector() && "vector shift count is not a vector type");
7868 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7869 if (! getVShiftImm(Op, ElementBits, Cnt))
7873 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
7876 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
7877 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
7878 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7881 // Don't do anything for most intrinsics.
7884 // Vector shifts: check for immediate versions and lower them.
7885 // Note: This is done during DAG combining instead of DAG legalizing because
7886 // the build_vectors for 64-bit vector element shift counts are generally
7887 // not legal, and it is hard to see their values after they get legalized to
7888 // loads from a constant pool.
7889 case Intrinsic::arm_neon_vshifts:
7890 case Intrinsic::arm_neon_vshiftu:
7891 case Intrinsic::arm_neon_vshiftls:
7892 case Intrinsic::arm_neon_vshiftlu:
7893 case Intrinsic::arm_neon_vshiftn:
7894 case Intrinsic::arm_neon_vrshifts:
7895 case Intrinsic::arm_neon_vrshiftu:
7896 case Intrinsic::arm_neon_vrshiftn:
7897 case Intrinsic::arm_neon_vqshifts:
7898 case Intrinsic::arm_neon_vqshiftu:
7899 case Intrinsic::arm_neon_vqshiftsu:
7900 case Intrinsic::arm_neon_vqshiftns:
7901 case Intrinsic::arm_neon_vqshiftnu:
7902 case Intrinsic::arm_neon_vqshiftnsu:
7903 case Intrinsic::arm_neon_vqrshiftns:
7904 case Intrinsic::arm_neon_vqrshiftnu:
7905 case Intrinsic::arm_neon_vqrshiftnsu: {
7906 EVT VT = N->getOperand(1).getValueType();
7908 unsigned VShiftOpc = 0;
7911 case Intrinsic::arm_neon_vshifts:
7912 case Intrinsic::arm_neon_vshiftu:
7913 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
7914 VShiftOpc = ARMISD::VSHL;
7917 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
7918 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
7919 ARMISD::VSHRs : ARMISD::VSHRu);
7924 case Intrinsic::arm_neon_vshiftls:
7925 case Intrinsic::arm_neon_vshiftlu:
7926 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
7928 llvm_unreachable("invalid shift count for vshll intrinsic");
7930 case Intrinsic::arm_neon_vrshifts:
7931 case Intrinsic::arm_neon_vrshiftu:
7932 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
7936 case Intrinsic::arm_neon_vqshifts:
7937 case Intrinsic::arm_neon_vqshiftu:
7938 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7942 case Intrinsic::arm_neon_vqshiftsu:
7943 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7945 llvm_unreachable("invalid shift count for vqshlu intrinsic");
7947 case Intrinsic::arm_neon_vshiftn:
7948 case Intrinsic::arm_neon_vrshiftn:
7949 case Intrinsic::arm_neon_vqshiftns:
7950 case Intrinsic::arm_neon_vqshiftnu:
7951 case Intrinsic::arm_neon_vqshiftnsu:
7952 case Intrinsic::arm_neon_vqrshiftns:
7953 case Intrinsic::arm_neon_vqrshiftnu:
7954 case Intrinsic::arm_neon_vqrshiftnsu:
7955 // Narrowing shifts require an immediate right shift.
7956 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
7958 llvm_unreachable("invalid shift count for narrowing vector shift "
7962 llvm_unreachable("unhandled vector shift");
7966 case Intrinsic::arm_neon_vshifts:
7967 case Intrinsic::arm_neon_vshiftu:
7968 // Opcode already set above.
7970 case Intrinsic::arm_neon_vshiftls:
7971 case Intrinsic::arm_neon_vshiftlu:
7972 if (Cnt == VT.getVectorElementType().getSizeInBits())
7973 VShiftOpc = ARMISD::VSHLLi;
7975 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
7976 ARMISD::VSHLLs : ARMISD::VSHLLu);
7978 case Intrinsic::arm_neon_vshiftn:
7979 VShiftOpc = ARMISD::VSHRN; break;
7980 case Intrinsic::arm_neon_vrshifts:
7981 VShiftOpc = ARMISD::VRSHRs; break;
7982 case Intrinsic::arm_neon_vrshiftu:
7983 VShiftOpc = ARMISD::VRSHRu; break;
7984 case Intrinsic::arm_neon_vrshiftn:
7985 VShiftOpc = ARMISD::VRSHRN; break;
7986 case Intrinsic::arm_neon_vqshifts:
7987 VShiftOpc = ARMISD::VQSHLs; break;
7988 case Intrinsic::arm_neon_vqshiftu:
7989 VShiftOpc = ARMISD::VQSHLu; break;
7990 case Intrinsic::arm_neon_vqshiftsu:
7991 VShiftOpc = ARMISD::VQSHLsu; break;
7992 case Intrinsic::arm_neon_vqshiftns:
7993 VShiftOpc = ARMISD::VQSHRNs; break;
7994 case Intrinsic::arm_neon_vqshiftnu:
7995 VShiftOpc = ARMISD::VQSHRNu; break;
7996 case Intrinsic::arm_neon_vqshiftnsu:
7997 VShiftOpc = ARMISD::VQSHRNsu; break;
7998 case Intrinsic::arm_neon_vqrshiftns:
7999 VShiftOpc = ARMISD::VQRSHRNs; break;
8000 case Intrinsic::arm_neon_vqrshiftnu:
8001 VShiftOpc = ARMISD::VQRSHRNu; break;
8002 case Intrinsic::arm_neon_vqrshiftnsu:
8003 VShiftOpc = ARMISD::VQRSHRNsu; break;
8006 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8007 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8010 case Intrinsic::arm_neon_vshiftins: {
8011 EVT VT = N->getOperand(1).getValueType();
8013 unsigned VShiftOpc = 0;
8015 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8016 VShiftOpc = ARMISD::VSLI;
8017 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8018 VShiftOpc = ARMISD::VSRI;
8020 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8023 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8024 N->getOperand(1), N->getOperand(2),
8025 DAG.getConstant(Cnt, MVT::i32));
8028 case Intrinsic::arm_neon_vqrshifts:
8029 case Intrinsic::arm_neon_vqrshiftu:
8030 // No immediate versions of these to check for.
8037 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8038 /// lowers them. As with the vector shift intrinsics, this is done during DAG
8039 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8040 /// vector element shift counts are generally not legal, and it is hard to see
8041 /// their values after they get legalized to loads from a constant pool.
8042 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8043 const ARMSubtarget *ST) {
8044 EVT VT = N->getValueType(0);
8045 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8046 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8047 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8048 SDValue N1 = N->getOperand(1);
8049 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8050 SDValue N0 = N->getOperand(0);
8051 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8052 DAG.MaskedValueIsZero(N0.getOperand(0),
8053 APInt::getHighBitsSet(32, 16)))
8054 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8058 // Nothing to be done for scalar shifts.
8059 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8060 if (!VT.isVector() || !TLI.isTypeLegal(VT))
8063 assert(ST->hasNEON() && "unexpected vector shift");
8066 switch (N->getOpcode()) {
8067 default: llvm_unreachable("unexpected shift opcode");
8070 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8071 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8072 DAG.getConstant(Cnt, MVT::i32));
8077 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8078 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8079 ARMISD::VSHRs : ARMISD::VSHRu);
8080 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8081 DAG.getConstant(Cnt, MVT::i32));
8087 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8088 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8089 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8090 const ARMSubtarget *ST) {
8091 SDValue N0 = N->getOperand(0);
8093 // Check for sign- and zero-extensions of vector extract operations of 8-
8094 // and 16-bit vector elements. NEON supports these directly. They are
8095 // handled during DAG combining because type legalization will promote them
8096 // to 32-bit types and it is messy to recognize the operations after that.
8097 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8098 SDValue Vec = N0.getOperand(0);
8099 SDValue Lane = N0.getOperand(1);
8100 EVT VT = N->getValueType(0);
8101 EVT EltVT = N0.getValueType();
8102 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8104 if (VT == MVT::i32 &&
8105 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8106 TLI.isTypeLegal(Vec.getValueType()) &&
8107 isa<ConstantSDNode>(Lane)) {
8110 switch (N->getOpcode()) {
8111 default: llvm_unreachable("unexpected opcode");
8112 case ISD::SIGN_EXTEND:
8113 Opc = ARMISD::VGETLANEs;
8115 case ISD::ZERO_EXTEND:
8116 case ISD::ANY_EXTEND:
8117 Opc = ARMISD::VGETLANEu;
8120 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8127 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8128 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8129 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8130 const ARMSubtarget *ST) {
8131 // If the target supports NEON, try to use vmax/vmin instructions for f32
8132 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
8133 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
8134 // a NaN; only do the transformation when it matches that behavior.
8136 // For now only do this when using NEON for FP operations; if using VFP, it
8137 // is not obvious that the benefit outweighs the cost of switching to the
8139 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8140 N->getValueType(0) != MVT::f32)
8143 SDValue CondLHS = N->getOperand(0);
8144 SDValue CondRHS = N->getOperand(1);
8145 SDValue LHS = N->getOperand(2);
8146 SDValue RHS = N->getOperand(3);
8147 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8149 unsigned Opcode = 0;
8151 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8152 IsReversed = false; // x CC y ? x : y
8153 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8154 IsReversed = true ; // x CC y ? y : x
8168 // If LHS is NaN, an ordered comparison will be false and the result will
8169 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
8170 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8171 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8172 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8174 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8175 // will return -0, so vmin can only be used for unsafe math or if one of
8176 // the operands is known to be nonzero.
8177 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8178 !DAG.getTarget().Options.UnsafeFPMath &&
8179 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8181 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8190 // If LHS is NaN, an ordered comparison will be false and the result will
8191 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
8192 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8193 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8194 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8196 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8197 // will return +0, so vmax can only be used for unsafe math or if one of
8198 // the operands is known to be nonzero.
8199 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8200 !DAG.getTarget().Options.UnsafeFPMath &&
8201 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8203 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8209 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8212 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8214 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8215 SDValue Cmp = N->getOperand(4);
8216 if (Cmp.getOpcode() != ARMISD::CMPZ)
8217 // Only looking at EQ and NE cases.
8220 EVT VT = N->getValueType(0);
8221 DebugLoc dl = N->getDebugLoc();
8222 SDValue LHS = Cmp.getOperand(0);
8223 SDValue RHS = Cmp.getOperand(1);
8224 SDValue FalseVal = N->getOperand(0);
8225 SDValue TrueVal = N->getOperand(1);
8226 SDValue ARMcc = N->getOperand(2);
8227 ARMCC::CondCodes CC =
8228 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8246 /// FIXME: Turn this into a target neutral optimization?
8248 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8249 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8250 N->getOperand(3), Cmp);
8251 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8253 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8254 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8255 N->getOperand(3), NewCmp);
8258 if (Res.getNode()) {
8259 APInt KnownZero, KnownOne;
8260 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
8261 DAG.ComputeMaskedBits(SDValue(N,0), Mask, KnownZero, KnownOne);
8262 // Capture demanded bits information that would be otherwise lost.
8263 if (KnownZero == 0xfffffffe)
8264 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8265 DAG.getValueType(MVT::i1));
8266 else if (KnownZero == 0xffffff00)
8267 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8268 DAG.getValueType(MVT::i8));
8269 else if (KnownZero == 0xffff0000)
8270 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8271 DAG.getValueType(MVT::i16));
8277 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8278 DAGCombinerInfo &DCI) const {
8279 switch (N->getOpcode()) {
8281 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
8282 case ISD::SUB: return PerformSUBCombine(N, DCI);
8283 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
8284 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
8285 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
8286 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
8287 case ARMISD::BFI: return PerformBFICombine(N, DCI);
8288 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8289 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8290 case ISD::STORE: return PerformSTORECombine(N, DCI);
8291 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8292 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8293 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8294 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8295 case ISD::FP_TO_SINT:
8296 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8297 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
8298 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8301 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
8302 case ISD::SIGN_EXTEND:
8303 case ISD::ZERO_EXTEND:
8304 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8305 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8306 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8307 case ARMISD::VLD2DUP:
8308 case ARMISD::VLD3DUP:
8309 case ARMISD::VLD4DUP:
8310 return CombineBaseUpdate(N, DCI);
8311 case ISD::INTRINSIC_VOID:
8312 case ISD::INTRINSIC_W_CHAIN:
8313 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8314 case Intrinsic::arm_neon_vld1:
8315 case Intrinsic::arm_neon_vld2:
8316 case Intrinsic::arm_neon_vld3:
8317 case Intrinsic::arm_neon_vld4:
8318 case Intrinsic::arm_neon_vld2lane:
8319 case Intrinsic::arm_neon_vld3lane:
8320 case Intrinsic::arm_neon_vld4lane:
8321 case Intrinsic::arm_neon_vst1:
8322 case Intrinsic::arm_neon_vst2:
8323 case Intrinsic::arm_neon_vst3:
8324 case Intrinsic::arm_neon_vst4:
8325 case Intrinsic::arm_neon_vst2lane:
8326 case Intrinsic::arm_neon_vst3lane:
8327 case Intrinsic::arm_neon_vst4lane:
8328 return CombineBaseUpdate(N, DCI);
8336 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8338 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8341 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8342 if (!Subtarget->allowsUnalignedMem())
8345 switch (VT.getSimpleVT().SimpleTy) {
8352 // FIXME: VLD1 etc with standard alignment is legal.
8356 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8357 unsigned AlignCheck) {
8358 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8359 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8362 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8363 unsigned DstAlign, unsigned SrcAlign,
8366 MachineFunction &MF) const {
8367 const Function *F = MF.getFunction();
8369 // See if we can use NEON instructions for this...
8371 !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8372 Subtarget->hasNEON()) {
8373 if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8375 } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8380 // Lowering to i32/i16 if the size permits.
8383 } else if (Size >= 2) {
8387 // Let the target-independent logic figure it out.
8391 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8396 switch (VT.getSimpleVT().SimpleTy) {
8397 default: return false;
8412 if ((V & (Scale - 1)) != 0)
8415 return V == (V & ((1LL << 5) - 1));
8418 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8419 const ARMSubtarget *Subtarget) {
8426 switch (VT.getSimpleVT().SimpleTy) {
8427 default: return false;
8432 // + imm12 or - imm8
8434 return V == (V & ((1LL << 8) - 1));
8435 return V == (V & ((1LL << 12) - 1));
8438 // Same as ARM mode. FIXME: NEON?
8439 if (!Subtarget->hasVFP2())
8444 return V == (V & ((1LL << 8) - 1));
8448 /// isLegalAddressImmediate - Return true if the integer value can be used
8449 /// as the offset of the target addressing mode for load / store of the
8451 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8452 const ARMSubtarget *Subtarget) {
8459 if (Subtarget->isThumb1Only())
8460 return isLegalT1AddressImmediate(V, VT);
8461 else if (Subtarget->isThumb2())
8462 return isLegalT2AddressImmediate(V, VT, Subtarget);
8467 switch (VT.getSimpleVT().SimpleTy) {
8468 default: return false;
8473 return V == (V & ((1LL << 12) - 1));
8476 return V == (V & ((1LL << 8) - 1));
8479 if (!Subtarget->hasVFP2()) // FIXME: NEON?
8484 return V == (V & ((1LL << 8) - 1));
8488 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8490 int Scale = AM.Scale;
8494 switch (VT.getSimpleVT().SimpleTy) {
8495 default: return false;
8504 return Scale == 2 || Scale == 4 || Scale == 8;
8507 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8511 // Note, we allow "void" uses (basically, uses that aren't loads or
8512 // stores), because arm allows folding a scale into many arithmetic
8513 // operations. This should be made more precise and revisited later.
8515 // Allow r << imm, but the imm has to be a multiple of two.
8516 if (Scale & 1) return false;
8517 return isPowerOf2_32(Scale);
8521 /// isLegalAddressingMode - Return true if the addressing mode represented
8522 /// by AM is legal for this target, for a load/store of the specified type.
8523 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8525 EVT VT = getValueType(Ty, true);
8526 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8529 // Can never fold addr of global into load/store.
8534 case 0: // no scale reg, must be "r+i" or "r", or "i".
8537 if (Subtarget->isThumb1Only())
8541 // ARM doesn't support any R+R*scale+imm addr modes.
8548 if (Subtarget->isThumb2())
8549 return isLegalT2ScaledAddressingMode(AM, VT);
8551 int Scale = AM.Scale;
8552 switch (VT.getSimpleVT().SimpleTy) {
8553 default: return false;
8557 if (Scale < 0) Scale = -Scale;
8561 return isPowerOf2_32(Scale & ~1);
8565 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8570 // Note, we allow "void" uses (basically, uses that aren't loads or
8571 // stores), because arm allows folding a scale into many arithmetic
8572 // operations. This should be made more precise and revisited later.
8574 // Allow r << imm, but the imm has to be a multiple of two.
8575 if (Scale & 1) return false;
8576 return isPowerOf2_32(Scale);
8582 /// isLegalICmpImmediate - Return true if the specified immediate is legal
8583 /// icmp immediate, that is the target has icmp instructions which can compare
8584 /// a register against the immediate without having to materialize the
8585 /// immediate into a register.
8586 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8587 if (!Subtarget->isThumb())
8588 return ARM_AM::getSOImmVal(Imm) != -1;
8589 if (Subtarget->isThumb2())
8590 return ARM_AM::getT2SOImmVal(Imm) != -1;
8591 return Imm >= 0 && Imm <= 255;
8594 /// isLegalAddImmediate - Return true if the specified immediate is legal
8595 /// add immediate, that is the target has add instructions which can add
8596 /// a register with the immediate without having to materialize the
8597 /// immediate into a register.
8598 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8599 return ARM_AM::getSOImmVal(Imm) != -1;
8602 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
8603 bool isSEXTLoad, SDValue &Base,
8604 SDValue &Offset, bool &isInc,
8605 SelectionDAG &DAG) {
8606 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8609 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
8611 Base = Ptr->getOperand(0);
8612 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8613 int RHSC = (int)RHS->getZExtValue();
8614 if (RHSC < 0 && RHSC > -256) {
8615 assert(Ptr->getOpcode() == ISD::ADD);
8617 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8621 isInc = (Ptr->getOpcode() == ISD::ADD);
8622 Offset = Ptr->getOperand(1);
8624 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
8626 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8627 int RHSC = (int)RHS->getZExtValue();
8628 if (RHSC < 0 && RHSC > -0x1000) {
8629 assert(Ptr->getOpcode() == ISD::ADD);
8631 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8632 Base = Ptr->getOperand(0);
8637 if (Ptr->getOpcode() == ISD::ADD) {
8639 ARM_AM::ShiftOpc ShOpcVal=
8640 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
8641 if (ShOpcVal != ARM_AM::no_shift) {
8642 Base = Ptr->getOperand(1);
8643 Offset = Ptr->getOperand(0);
8645 Base = Ptr->getOperand(0);
8646 Offset = Ptr->getOperand(1);
8651 isInc = (Ptr->getOpcode() == ISD::ADD);
8652 Base = Ptr->getOperand(0);
8653 Offset = Ptr->getOperand(1);
8657 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
8661 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
8662 bool isSEXTLoad, SDValue &Base,
8663 SDValue &Offset, bool &isInc,
8664 SelectionDAG &DAG) {
8665 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8668 Base = Ptr->getOperand(0);
8669 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8670 int RHSC = (int)RHS->getZExtValue();
8671 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
8672 assert(Ptr->getOpcode() == ISD::ADD);
8674 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8676 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
8677 isInc = Ptr->getOpcode() == ISD::ADD;
8678 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
8686 /// getPreIndexedAddressParts - returns true by value, base pointer and
8687 /// offset pointer and addressing mode by reference if the node's address
8688 /// can be legally represented as pre-indexed load / store address.
8690 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8692 ISD::MemIndexedMode &AM,
8693 SelectionDAG &DAG) const {
8694 if (Subtarget->isThumb1Only())
8699 bool isSEXTLoad = false;
8700 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8701 Ptr = LD->getBasePtr();
8702 VT = LD->getMemoryVT();
8703 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8704 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8705 Ptr = ST->getBasePtr();
8706 VT = ST->getMemoryVT();
8711 bool isLegal = false;
8712 if (Subtarget->isThumb2())
8713 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8714 Offset, isInc, DAG);
8716 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8717 Offset, isInc, DAG);
8721 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
8725 /// getPostIndexedAddressParts - returns true by value, base pointer and
8726 /// offset pointer and addressing mode by reference if this node can be
8727 /// combined with a load / store to form a post-indexed load / store.
8728 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
8731 ISD::MemIndexedMode &AM,
8732 SelectionDAG &DAG) const {
8733 if (Subtarget->isThumb1Only())
8738 bool isSEXTLoad = false;
8739 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8740 VT = LD->getMemoryVT();
8741 Ptr = LD->getBasePtr();
8742 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8743 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8744 VT = ST->getMemoryVT();
8745 Ptr = ST->getBasePtr();
8750 bool isLegal = false;
8751 if (Subtarget->isThumb2())
8752 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8755 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8761 // Swap base ptr and offset to catch more post-index load / store when
8762 // it's legal. In Thumb2 mode, offset must be an immediate.
8763 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
8764 !Subtarget->isThumb2())
8765 std::swap(Base, Offset);
8767 // Post-indexed load / store update the base pointer.
8772 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
8776 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8780 const SelectionDAG &DAG,
8781 unsigned Depth) const {
8782 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
8783 switch (Op.getOpcode()) {
8785 case ARMISD::CMOV: {
8786 // Bits are known zero/one if known on the LHS and RHS.
8787 DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
8788 if (KnownZero == 0 && KnownOne == 0) return;
8790 APInt KnownZeroRHS, KnownOneRHS;
8791 DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
8792 KnownZeroRHS, KnownOneRHS, Depth+1);
8793 KnownZero &= KnownZeroRHS;
8794 KnownOne &= KnownOneRHS;
8800 //===----------------------------------------------------------------------===//
8801 // ARM Inline Assembly Support
8802 //===----------------------------------------------------------------------===//
8804 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
8805 // Looking for "rev" which is V6+.
8806 if (!Subtarget->hasV6Ops())
8809 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8810 std::string AsmStr = IA->getAsmString();
8811 SmallVector<StringRef, 4> AsmPieces;
8812 SplitString(AsmStr, AsmPieces, ";\n");
8814 switch (AsmPieces.size()) {
8815 default: return false;
8817 AsmStr = AsmPieces[0];
8819 SplitString(AsmStr, AsmPieces, " \t,");
8822 if (AsmPieces.size() == 3 &&
8823 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
8824 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
8825 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8826 if (Ty && Ty->getBitWidth() == 32)
8827 return IntrinsicLowering::LowerToByteSwap(CI);
8835 /// getConstraintType - Given a constraint letter, return the type of
8836 /// constraint it is for this target.
8837 ARMTargetLowering::ConstraintType
8838 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
8839 if (Constraint.size() == 1) {
8840 switch (Constraint[0]) {
8842 case 'l': return C_RegisterClass;
8843 case 'w': return C_RegisterClass;
8844 case 'h': return C_RegisterClass;
8845 case 'x': return C_RegisterClass;
8846 case 't': return C_RegisterClass;
8847 case 'j': return C_Other; // Constant for movw.
8848 // An address with a single base register. Due to the way we
8849 // currently handle addresses it is the same as an 'r' memory constraint.
8850 case 'Q': return C_Memory;
8852 } else if (Constraint.size() == 2) {
8853 switch (Constraint[0]) {
8855 // All 'U+' constraints are addresses.
8856 case 'U': return C_Memory;
8859 return TargetLowering::getConstraintType(Constraint);
8862 /// Examine constraint type and operand type and determine a weight value.
8863 /// This object must already have been set up with the operand type
8864 /// and the current alternative constraint selected.
8865 TargetLowering::ConstraintWeight
8866 ARMTargetLowering::getSingleConstraintMatchWeight(
8867 AsmOperandInfo &info, const char *constraint) const {
8868 ConstraintWeight weight = CW_Invalid;
8869 Value *CallOperandVal = info.CallOperandVal;
8870 // If we don't have a value, we can't do a match,
8871 // but allow it at the lowest weight.
8872 if (CallOperandVal == NULL)
8874 Type *type = CallOperandVal->getType();
8875 // Look at the constraint type.
8876 switch (*constraint) {
8878 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8881 if (type->isIntegerTy()) {
8882 if (Subtarget->isThumb())
8883 weight = CW_SpecificReg;
8885 weight = CW_Register;
8889 if (type->isFloatingPointTy())
8890 weight = CW_Register;
8896 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
8898 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8900 if (Constraint.size() == 1) {
8901 // GCC ARM Constraint Letters
8902 switch (Constraint[0]) {
8903 case 'l': // Low regs or general regs.
8904 if (Subtarget->isThumb())
8905 return RCPair(0U, ARM::tGPRRegisterClass);
8907 return RCPair(0U, ARM::GPRRegisterClass);
8908 case 'h': // High regs or no regs.
8909 if (Subtarget->isThumb())
8910 return RCPair(0U, ARM::hGPRRegisterClass);
8913 return RCPair(0U, ARM::GPRRegisterClass);
8916 return RCPair(0U, ARM::SPRRegisterClass);
8917 if (VT.getSizeInBits() == 64)
8918 return RCPair(0U, ARM::DPRRegisterClass);
8919 if (VT.getSizeInBits() == 128)
8920 return RCPair(0U, ARM::QPRRegisterClass);
8924 return RCPair(0U, ARM::SPR_8RegisterClass);
8925 if (VT.getSizeInBits() == 64)
8926 return RCPair(0U, ARM::DPR_8RegisterClass);
8927 if (VT.getSizeInBits() == 128)
8928 return RCPair(0U, ARM::QPR_8RegisterClass);
8932 return RCPair(0U, ARM::SPRRegisterClass);
8936 if (StringRef("{cc}").equals_lower(Constraint))
8937 return std::make_pair(unsigned(ARM::CPSR), ARM::CCRRegisterClass);
8939 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8942 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8943 /// vector. If it is invalid, don't add anything to Ops.
8944 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8945 std::string &Constraint,
8946 std::vector<SDValue>&Ops,
8947 SelectionDAG &DAG) const {
8948 SDValue Result(0, 0);
8950 // Currently only support length 1 constraints.
8951 if (Constraint.length() != 1) return;
8953 char ConstraintLetter = Constraint[0];
8954 switch (ConstraintLetter) {
8957 case 'I': case 'J': case 'K': case 'L':
8958 case 'M': case 'N': case 'O':
8959 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
8963 int64_t CVal64 = C->getSExtValue();
8964 int CVal = (int) CVal64;
8965 // None of these constraints allow values larger than 32 bits. Check
8966 // that the value fits in an int.
8970 switch (ConstraintLetter) {
8972 // Constant suitable for movw, must be between 0 and
8974 if (Subtarget->hasV6T2Ops())
8975 if (CVal >= 0 && CVal <= 65535)
8979 if (Subtarget->isThumb1Only()) {
8980 // This must be a constant between 0 and 255, for ADD
8982 if (CVal >= 0 && CVal <= 255)
8984 } else if (Subtarget->isThumb2()) {
8985 // A constant that can be used as an immediate value in a
8986 // data-processing instruction.
8987 if (ARM_AM::getT2SOImmVal(CVal) != -1)
8990 // A constant that can be used as an immediate value in a
8991 // data-processing instruction.
8992 if (ARM_AM::getSOImmVal(CVal) != -1)
8998 if (Subtarget->isThumb()) { // FIXME thumb2
8999 // This must be a constant between -255 and -1, for negated ADD
9000 // immediates. This can be used in GCC with an "n" modifier that
9001 // prints the negated value, for use with SUB instructions. It is
9002 // not useful otherwise but is implemented for compatibility.
9003 if (CVal >= -255 && CVal <= -1)
9006 // This must be a constant between -4095 and 4095. It is not clear
9007 // what this constraint is intended for. Implemented for
9008 // compatibility with GCC.
9009 if (CVal >= -4095 && CVal <= 4095)
9015 if (Subtarget->isThumb1Only()) {
9016 // A 32-bit value where only one byte has a nonzero value. Exclude
9017 // zero to match GCC. This constraint is used by GCC internally for
9018 // constants that can be loaded with a move/shift combination.
9019 // It is not useful otherwise but is implemented for compatibility.
9020 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9022 } else if (Subtarget->isThumb2()) {
9023 // A constant whose bitwise inverse can be used as an immediate
9024 // value in a data-processing instruction. This can be used in GCC
9025 // with a "B" modifier that prints the inverted value, for use with
9026 // BIC and MVN instructions. It is not useful otherwise but is
9027 // implemented for compatibility.
9028 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9031 // A constant whose bitwise inverse can be used as an immediate
9032 // value in a data-processing instruction. This can be used in GCC
9033 // with a "B" modifier that prints the inverted value, for use with
9034 // BIC and MVN instructions. It is not useful otherwise but is
9035 // implemented for compatibility.
9036 if (ARM_AM::getSOImmVal(~CVal) != -1)
9042 if (Subtarget->isThumb1Only()) {
9043 // This must be a constant between -7 and 7,
9044 // for 3-operand ADD/SUB immediate instructions.
9045 if (CVal >= -7 && CVal < 7)
9047 } else if (Subtarget->isThumb2()) {
9048 // A constant whose negation can be used as an immediate value in a
9049 // data-processing instruction. This can be used in GCC with an "n"
9050 // modifier that prints the negated value, for use with SUB
9051 // instructions. It is not useful otherwise but is implemented for
9053 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9056 // A constant whose negation can be used as an immediate value in a
9057 // data-processing instruction. This can be used in GCC with an "n"
9058 // modifier that prints the negated value, for use with SUB
9059 // instructions. It is not useful otherwise but is implemented for
9061 if (ARM_AM::getSOImmVal(-CVal) != -1)
9067 if (Subtarget->isThumb()) { // FIXME thumb2
9068 // This must be a multiple of 4 between 0 and 1020, for
9069 // ADD sp + immediate.
9070 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9073 // A power of two or a constant between 0 and 32. This is used in
9074 // GCC for the shift amount on shifted register operands, but it is
9075 // useful in general for any shift amounts.
9076 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9082 if (Subtarget->isThumb()) { // FIXME thumb2
9083 // This must be a constant between 0 and 31, for shift amounts.
9084 if (CVal >= 0 && CVal <= 31)
9090 if (Subtarget->isThumb()) { // FIXME thumb2
9091 // This must be a multiple of 4 between -508 and 508, for
9092 // ADD/SUB sp = sp + immediate.
9093 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9098 Result = DAG.getTargetConstant(CVal, Op.getValueType());
9102 if (Result.getNode()) {
9103 Ops.push_back(Result);
9106 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9110 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9111 // The ARM target isn't yet aware of offsets.
9115 bool ARM::isBitFieldInvertedMask(unsigned v) {
9116 if (v == 0xffffffff)
9118 // there can be 1's on either or both "outsides", all the "inside"
9120 unsigned int lsb = 0, msb = 31;
9121 while (v & (1 << msb)) --msb;
9122 while (v & (1 << lsb)) ++lsb;
9123 for (unsigned int i = lsb; i <= msb; ++i) {
9130 /// isFPImmLegal - Returns true if the target can instruction select the
9131 /// specified FP immediate natively. If false, the legalizer will
9132 /// materialize the FP immediate as a load from a constant pool.
9133 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9134 if (!Subtarget->hasVFP3())
9137 return ARM_AM::getFP32Imm(Imm) != -1;
9139 return ARM_AM::getFP64Imm(Imm) != -1;
9143 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9144 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9145 /// specified in the intrinsic calls.
9146 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9148 unsigned Intrinsic) const {
9149 switch (Intrinsic) {
9150 case Intrinsic::arm_neon_vld1:
9151 case Intrinsic::arm_neon_vld2:
9152 case Intrinsic::arm_neon_vld3:
9153 case Intrinsic::arm_neon_vld4:
9154 case Intrinsic::arm_neon_vld2lane:
9155 case Intrinsic::arm_neon_vld3lane:
9156 case Intrinsic::arm_neon_vld4lane: {
9157 Info.opc = ISD::INTRINSIC_W_CHAIN;
9158 // Conservatively set memVT to the entire set of vectors loaded.
9159 uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9160 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9161 Info.ptrVal = I.getArgOperand(0);
9163 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9164 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9165 Info.vol = false; // volatile loads with NEON intrinsics not supported
9166 Info.readMem = true;
9167 Info.writeMem = false;
9170 case Intrinsic::arm_neon_vst1:
9171 case Intrinsic::arm_neon_vst2:
9172 case Intrinsic::arm_neon_vst3:
9173 case Intrinsic::arm_neon_vst4:
9174 case Intrinsic::arm_neon_vst2lane:
9175 case Intrinsic::arm_neon_vst3lane:
9176 case Intrinsic::arm_neon_vst4lane: {
9177 Info.opc = ISD::INTRINSIC_VOID;
9178 // Conservatively set memVT to the entire set of vectors stored.
9179 unsigned NumElts = 0;
9180 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9181 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9182 if (!ArgTy->isVectorTy())
9184 NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9186 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9187 Info.ptrVal = I.getArgOperand(0);
9189 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9190 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9191 Info.vol = false; // volatile stores with NEON intrinsics not supported
9192 Info.readMem = false;
9193 Info.writeMem = true;
9196 case Intrinsic::arm_strexd: {
9197 Info.opc = ISD::INTRINSIC_W_CHAIN;
9198 Info.memVT = MVT::i64;
9199 Info.ptrVal = I.getArgOperand(2);
9203 Info.readMem = false;
9204 Info.writeMem = true;
9207 case Intrinsic::arm_ldrexd: {
9208 Info.opc = ISD::INTRINSIC_W_CHAIN;
9209 Info.memVT = MVT::i64;
9210 Info.ptrVal = I.getArgOperand(0);
9214 Info.readMem = true;
9215 Info.writeMem = false;