1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57 // This option should go away when tail calls fully work.
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65 cl::desc("Generate calls via indirect call instructions"),
69 ARMInterworking("arm-interworking", cl::Hidden,
70 cl::desc("Enable / disable ARM interworking (for debugging only)"),
74 class ARMCCState : public CCState {
76 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77 const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78 LLVMContext &C, ParmContext PC)
79 : CCState(CC, isVarArg, MF, TM, locs, C) {
80 assert(((PC == Call) || (PC == Prologue)) &&
81 "ARMCCState users must specify whether their context is call"
82 "or prologue generation.");
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90 ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94 MVT PromotedBitwiseVT) {
95 if (VT != PromotedLdStVT) {
96 setOperationAction(ISD::LOAD, VT, Promote);
97 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99 setOperationAction(ISD::STORE, VT, Promote);
100 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103 MVT ElemTy = VT.getVectorElementType();
104 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105 setOperationAction(ISD::SETCC, VT, Custom);
106 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108 if (ElemTy == MVT::i32) {
109 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
120 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
121 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
122 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123 setOperationAction(ISD::SELECT, VT, Expand);
124 setOperationAction(ISD::SELECT_CC, VT, Expand);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
126 if (VT.isInteger()) {
127 setOperationAction(ISD::SHL, VT, Custom);
128 setOperationAction(ISD::SRA, VT, Custom);
129 setOperationAction(ISD::SRL, VT, Custom);
132 // Promote all bit-wise operations.
133 if (VT.isInteger() && VT != PromotedBitwiseVT) {
134 setOperationAction(ISD::AND, VT, Promote);
135 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
136 setOperationAction(ISD::OR, VT, Promote);
137 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
138 setOperationAction(ISD::XOR, VT, Promote);
139 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
142 // Neon does not support vector divide/remainder operations.
143 setOperationAction(ISD::SDIV, VT, Expand);
144 setOperationAction(ISD::UDIV, VT, Expand);
145 setOperationAction(ISD::FDIV, VT, Expand);
146 setOperationAction(ISD::SREM, VT, Expand);
147 setOperationAction(ISD::UREM, VT, Expand);
148 setOperationAction(ISD::FREM, VT, Expand);
151 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
152 addRegisterClass(VT, &ARM::DPRRegClass);
153 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
156 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
157 addRegisterClass(VT, &ARM::QPRRegClass);
158 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
161 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
162 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
163 return new TargetLoweringObjectFileMachO();
165 return new ARMElfTargetObjectFile();
168 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
169 : TargetLowering(TM, createTLOF(TM)) {
170 Subtarget = &TM.getSubtarget<ARMSubtarget>();
171 RegInfo = TM.getRegisterInfo();
172 Itins = TM.getInstrItineraryData();
174 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176 if (Subtarget->isTargetDarwin()) {
177 // Uses VFP for Thumb libfuncs if available.
178 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
179 // Single-precision floating-point arithmetic.
180 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185 // Double-precision floating-point arithmetic.
186 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191 // Single-precision comparisons.
192 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
199 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
201 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
210 // Double-precision comparisons.
211 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
218 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
220 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
229 // Floating-point to integer conversions.
230 // i64 conversions are done via library routines even when generating VFP
231 // instructions, so use the same ones.
232 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237 // Conversions between floating types.
238 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
241 // Integer to floating-point conversions.
242 // i64 conversions are done via library routines even when generating VFP
243 // instructions, so use the same ones.
244 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245 // e.g., __floatunsidf vs. __floatunssidfvfp.
246 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
253 // These libcalls are not available in 32-bit.
254 setLibcallName(RTLIB::SHL_I128, 0);
255 setLibcallName(RTLIB::SRL_I128, 0);
256 setLibcallName(RTLIB::SRA_I128, 0);
258 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
259 // Double-precision floating-point arithmetic helper functions
260 // RTABI chapter 4.1.2, Table 2
261 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
262 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
263 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
264 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
265 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
266 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
267 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
268 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270 // Double-precision floating-point comparison helper functions
271 // RTABI chapter 4.1.2, Table 3
272 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
273 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
274 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
275 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
276 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
277 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
278 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
279 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
280 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
281 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
282 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
283 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
284 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
285 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
286 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
287 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
288 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
289 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297 // Single-precision floating-point arithmetic helper functions
298 // RTABI chapter 4.1.2, Table 4
299 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
300 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
301 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
302 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
303 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
304 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
305 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
306 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308 // Single-precision floating-point comparison helper functions
309 // RTABI chapter 4.1.2, Table 5
310 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
311 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
312 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
313 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
314 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
315 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
316 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
317 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
318 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
319 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
320 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
321 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
322 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
323 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
324 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
325 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
326 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
327 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335 // Floating-point to integer conversions.
336 // RTABI chapter 4.1.2, Table 6
337 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
338 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
339 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
340 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
341 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
342 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
343 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
344 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
345 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
346 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354 // Conversions between floating types.
355 // RTABI chapter 4.1.2, Table 7
356 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
357 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
358 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
359 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361 // Integer to floating-point conversions.
362 // RTABI chapter 4.1.2, Table 8
363 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
364 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
365 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
366 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
367 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
368 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
369 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
370 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
371 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380 // Long long helper functions
381 // RTABI chapter 4.2, Table 9
382 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
383 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
384 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
385 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
386 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
387 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393 // Integer division functions
394 // RTABI chapter 4.3.1
395 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
396 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
397 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
398 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
399 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
400 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
401 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
402 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
403 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
404 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
413 // RTABI chapter 4.3.4
414 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
415 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
416 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
417 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
418 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
419 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
422 // Use divmod compiler-rt calls for iOS 5.0 and later.
423 if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
424 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
425 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
426 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
429 if (Subtarget->isThumb1Only())
430 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
433 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
434 !Subtarget->isThumb1Only()) {
435 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
436 if (!Subtarget->isFPOnlySP())
437 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
442 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
444 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
445 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
446 setTruncStoreAction((MVT::SimpleValueType)VT,
447 (MVT::SimpleValueType)InnerVT, Expand);
448 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
449 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
453 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455 if (Subtarget->hasNEON()) {
456 addDRTypeForNEON(MVT::v2f32);
457 addDRTypeForNEON(MVT::v8i8);
458 addDRTypeForNEON(MVT::v4i16);
459 addDRTypeForNEON(MVT::v2i32);
460 addDRTypeForNEON(MVT::v1i64);
462 addQRTypeForNEON(MVT::v4f32);
463 addQRTypeForNEON(MVT::v2f64);
464 addQRTypeForNEON(MVT::v16i8);
465 addQRTypeForNEON(MVT::v8i16);
466 addQRTypeForNEON(MVT::v4i32);
467 addQRTypeForNEON(MVT::v2i64);
469 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
470 // neither Neon nor VFP support any arithmetic operations on it.
471 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
472 // supported for v4f32.
473 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
474 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
475 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
476 // FIXME: Code duplication: FDIV and FREM are expanded always, see
477 // ARMTargetLowering::addTypeForNEON method for details.
478 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
479 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
480 // FIXME: Create unittest.
481 // In another words, find a way when "copysign" appears in DAG with vector
483 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
484 // FIXME: Code duplication: SETCC has custom operation action, see
485 // ARMTargetLowering::addTypeForNEON method for details.
486 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
487 // FIXME: Create unittest for FNEG and for FABS.
488 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
489 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
490 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
491 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
492 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
493 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
494 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
495 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
496 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
497 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
498 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
499 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
500 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
501 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
502 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
503 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
504 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
505 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
508 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
509 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
510 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
511 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
512 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
513 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
514 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
515 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
516 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
518 // Neon does not support some operations on v1i64 and v2i64 types.
519 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
520 // Custom handling for some quad-vector types to detect VMULL.
521 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
523 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
524 // Custom handling for some vector types to avoid expensive expansions
525 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
526 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
527 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
528 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
529 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
530 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
531 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
532 // a destination type that is wider than the source, and nor does
533 // it have a FP_TO_[SU]INT instruction with a narrower destination than
535 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
538 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
540 setTargetDAGCombine(ISD::INTRINSIC_VOID);
541 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
542 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
543 setTargetDAGCombine(ISD::SHL);
544 setTargetDAGCombine(ISD::SRL);
545 setTargetDAGCombine(ISD::SRA);
546 setTargetDAGCombine(ISD::SIGN_EXTEND);
547 setTargetDAGCombine(ISD::ZERO_EXTEND);
548 setTargetDAGCombine(ISD::ANY_EXTEND);
549 setTargetDAGCombine(ISD::SELECT_CC);
550 setTargetDAGCombine(ISD::BUILD_VECTOR);
551 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
552 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
553 setTargetDAGCombine(ISD::STORE);
554 setTargetDAGCombine(ISD::FP_TO_SINT);
555 setTargetDAGCombine(ISD::FP_TO_UINT);
556 setTargetDAGCombine(ISD::FDIV);
558 // It is legal to extload from v4i8 to v4i16 or v4i32.
559 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
560 MVT::v4i16, MVT::v2i16,
562 for (unsigned i = 0; i < 6; ++i) {
563 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
564 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
565 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
569 computeRegisterProperties();
571 // ARM does not have f32 extending load.
572 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
574 // ARM does not have i1 sign extending load.
575 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
577 // ARM supports all 4 flavors of integer indexed load / store.
578 if (!Subtarget->isThumb1Only()) {
579 for (unsigned im = (unsigned)ISD::PRE_INC;
580 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
581 setIndexedLoadAction(im, MVT::i1, Legal);
582 setIndexedLoadAction(im, MVT::i8, Legal);
583 setIndexedLoadAction(im, MVT::i16, Legal);
584 setIndexedLoadAction(im, MVT::i32, Legal);
585 setIndexedStoreAction(im, MVT::i1, Legal);
586 setIndexedStoreAction(im, MVT::i8, Legal);
587 setIndexedStoreAction(im, MVT::i16, Legal);
588 setIndexedStoreAction(im, MVT::i32, Legal);
592 // i64 operation support.
593 setOperationAction(ISD::MUL, MVT::i64, Expand);
594 setOperationAction(ISD::MULHU, MVT::i32, Expand);
595 if (Subtarget->isThumb1Only()) {
596 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
597 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
599 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
600 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
601 setOperationAction(ISD::MULHS, MVT::i32, Expand);
603 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
604 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
605 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
606 setOperationAction(ISD::SRL, MVT::i64, Custom);
607 setOperationAction(ISD::SRA, MVT::i64, Custom);
609 if (!Subtarget->isThumb1Only()) {
610 // FIXME: We should do this for Thumb1 as well.
611 setOperationAction(ISD::ADDC, MVT::i32, Custom);
612 setOperationAction(ISD::ADDE, MVT::i32, Custom);
613 setOperationAction(ISD::SUBC, MVT::i32, Custom);
614 setOperationAction(ISD::SUBE, MVT::i32, Custom);
617 // ARM does not have ROTL.
618 setOperationAction(ISD::ROTL, MVT::i32, Expand);
619 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
620 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
621 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
622 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
624 // These just redirect to CTTZ and CTLZ on ARM.
625 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
626 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
628 // Only ARMv6 has BSWAP.
629 if (!Subtarget->hasV6Ops())
630 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
632 // These are expanded into libcalls.
633 if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
634 // v7M has a hardware divider
635 setOperationAction(ISD::SDIV, MVT::i32, Expand);
636 setOperationAction(ISD::UDIV, MVT::i32, Expand);
638 setOperationAction(ISD::SREM, MVT::i32, Expand);
639 setOperationAction(ISD::UREM, MVT::i32, Expand);
640 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
641 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
643 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
644 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
645 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
646 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
647 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
649 setOperationAction(ISD::TRAP, MVT::Other, Legal);
651 // Use the default implementation.
652 setOperationAction(ISD::VASTART, MVT::Other, Custom);
653 setOperationAction(ISD::VAARG, MVT::Other, Expand);
654 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
655 setOperationAction(ISD::VAEND, MVT::Other, Expand);
656 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
657 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
659 if (!Subtarget->isTargetDarwin()) {
660 // Non-Darwin platforms may return values in these registers via the
661 // personality function.
662 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
663 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
664 setExceptionPointerRegister(ARM::R0);
665 setExceptionSelectorRegister(ARM::R1);
668 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
669 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
670 // the default expansion.
671 // FIXME: This should be checking for v6k, not just v6.
672 if (Subtarget->hasDataBarrier() ||
673 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
674 // membarrier needs custom lowering; the rest are legal and handled
676 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
677 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
678 // Custom lowering for 64-bit ops
679 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
680 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
681 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
682 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
683 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
684 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
685 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
686 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
687 setInsertFencesForAtomic(true);
689 // Set them all for expansion, which will force libcalls.
690 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
691 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
692 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
693 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
694 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
695 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
696 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
697 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
698 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
699 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
700 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
701 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
702 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
703 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
704 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
705 // Unordered/Monotonic case.
706 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
707 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
708 // Since the libcalls include locking, fold in the fences
709 setShouldFoldAtomicFences(true);
712 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
714 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
715 if (!Subtarget->hasV6Ops()) {
716 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
717 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
719 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
721 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
722 !Subtarget->isThumb1Only()) {
723 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
724 // iff target supports vfp2.
725 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
726 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
729 // We want to custom lower some of our intrinsics.
730 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
731 if (Subtarget->isTargetDarwin()) {
732 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
733 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
734 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
737 setOperationAction(ISD::SETCC, MVT::i32, Expand);
738 setOperationAction(ISD::SETCC, MVT::f32, Expand);
739 setOperationAction(ISD::SETCC, MVT::f64, Expand);
740 setOperationAction(ISD::SELECT, MVT::i32, Custom);
741 setOperationAction(ISD::SELECT, MVT::f32, Custom);
742 setOperationAction(ISD::SELECT, MVT::f64, Custom);
743 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
744 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
745 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
747 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
748 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
749 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
750 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
751 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
753 // We don't support sin/cos/fmod/copysign/pow
754 setOperationAction(ISD::FSIN, MVT::f64, Expand);
755 setOperationAction(ISD::FSIN, MVT::f32, Expand);
756 setOperationAction(ISD::FCOS, MVT::f32, Expand);
757 setOperationAction(ISD::FCOS, MVT::f64, Expand);
758 setOperationAction(ISD::FREM, MVT::f64, Expand);
759 setOperationAction(ISD::FREM, MVT::f32, Expand);
760 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
761 !Subtarget->isThumb1Only()) {
762 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
763 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
765 setOperationAction(ISD::FPOW, MVT::f64, Expand);
766 setOperationAction(ISD::FPOW, MVT::f32, Expand);
768 if (!Subtarget->hasVFP4()) {
769 setOperationAction(ISD::FMA, MVT::f64, Expand);
770 setOperationAction(ISD::FMA, MVT::f32, Expand);
773 // Various VFP goodness
774 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
775 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
776 if (Subtarget->hasVFP2()) {
777 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
778 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
779 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
780 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
782 // Special handling for half-precision FP.
783 if (!Subtarget->hasFP16()) {
784 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
785 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
789 // We have target-specific dag combine patterns for the following nodes:
790 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
791 setTargetDAGCombine(ISD::ADD);
792 setTargetDAGCombine(ISD::SUB);
793 setTargetDAGCombine(ISD::MUL);
795 if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
796 setTargetDAGCombine(ISD::AND);
797 setTargetDAGCombine(ISD::OR);
798 setTargetDAGCombine(ISD::XOR);
801 if (Subtarget->hasV6Ops())
802 setTargetDAGCombine(ISD::SRL);
804 setStackPointerRegisterToSaveRestore(ARM::SP);
806 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
807 !Subtarget->hasVFP2())
808 setSchedulingPreference(Sched::RegPressure);
810 setSchedulingPreference(Sched::Hybrid);
812 //// temporary - rewrite interface to use type
813 maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
814 maxStoresPerMemset = 16;
815 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
817 // On ARM arguments smaller than 4 bytes are extended, so all arguments
818 // are at least 4 bytes aligned.
819 setMinStackArgumentAlignment(4);
821 benefitFromCodePlacementOpt = true;
823 // Prefer likely predicted branches to selects on out-of-order cores.
824 predictableSelectIsExpensive = Subtarget->isCortexA9();
826 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
829 // FIXME: It might make sense to define the representative register class as the
830 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
831 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
832 // SPR's representative would be DPR_VFP2. This should work well if register
833 // pressure tracking were modified such that a register use would increment the
834 // pressure of the register class's representative and all of it's super
835 // classes' representatives transitively. We have not implemented this because
836 // of the difficulty prior to coalescing of modeling operand register classes
837 // due to the common occurrence of cross class copies and subregister insertions
839 std::pair<const TargetRegisterClass*, uint8_t>
840 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
841 const TargetRegisterClass *RRC = 0;
843 switch (VT.getSimpleVT().SimpleTy) {
845 return TargetLowering::findRepresentativeClass(VT);
846 // Use DPR as representative register class for all floating point
847 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
848 // the cost is 1 for both f32 and f64.
849 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
850 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
851 RRC = &ARM::DPRRegClass;
852 // When NEON is used for SP, only half of the register file is available
853 // because operations that define both SP and DP results will be constrained
854 // to the VFP2 class (D0-D15). We currently model this constraint prior to
855 // coalescing by double-counting the SP regs. See the FIXME above.
856 if (Subtarget->useNEONForSinglePrecisionFP())
859 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
860 case MVT::v4f32: case MVT::v2f64:
861 RRC = &ARM::DPRRegClass;
865 RRC = &ARM::DPRRegClass;
869 RRC = &ARM::DPRRegClass;
873 return std::make_pair(RRC, Cost);
876 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
879 case ARMISD::Wrapper: return "ARMISD::Wrapper";
880 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
881 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
882 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
883 case ARMISD::CALL: return "ARMISD::CALL";
884 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
885 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
886 case ARMISD::tCALL: return "ARMISD::tCALL";
887 case ARMISD::BRCOND: return "ARMISD::BRCOND";
888 case ARMISD::BR_JT: return "ARMISD::BR_JT";
889 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
890 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
891 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
892 case ARMISD::CMP: return "ARMISD::CMP";
893 case ARMISD::CMN: return "ARMISD::CMN";
894 case ARMISD::CMPZ: return "ARMISD::CMPZ";
895 case ARMISD::CMPFP: return "ARMISD::CMPFP";
896 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
897 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
898 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
900 case ARMISD::CMOV: return "ARMISD::CMOV";
901 case ARMISD::CAND: return "ARMISD::CAND";
902 case ARMISD::COR: return "ARMISD::COR";
903 case ARMISD::CXOR: return "ARMISD::CXOR";
905 case ARMISD::RBIT: return "ARMISD::RBIT";
907 case ARMISD::FTOSI: return "ARMISD::FTOSI";
908 case ARMISD::FTOUI: return "ARMISD::FTOUI";
909 case ARMISD::SITOF: return "ARMISD::SITOF";
910 case ARMISD::UITOF: return "ARMISD::UITOF";
912 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
913 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
914 case ARMISD::RRX: return "ARMISD::RRX";
916 case ARMISD::ADDC: return "ARMISD::ADDC";
917 case ARMISD::ADDE: return "ARMISD::ADDE";
918 case ARMISD::SUBC: return "ARMISD::SUBC";
919 case ARMISD::SUBE: return "ARMISD::SUBE";
921 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
922 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
924 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
925 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
927 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
929 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
931 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
933 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
934 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
936 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
938 case ARMISD::VCEQ: return "ARMISD::VCEQ";
939 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
940 case ARMISD::VCGE: return "ARMISD::VCGE";
941 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
942 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
943 case ARMISD::VCGEU: return "ARMISD::VCGEU";
944 case ARMISD::VCGT: return "ARMISD::VCGT";
945 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
946 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
947 case ARMISD::VCGTU: return "ARMISD::VCGTU";
948 case ARMISD::VTST: return "ARMISD::VTST";
950 case ARMISD::VSHL: return "ARMISD::VSHL";
951 case ARMISD::VSHRs: return "ARMISD::VSHRs";
952 case ARMISD::VSHRu: return "ARMISD::VSHRu";
953 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
954 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
955 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
956 case ARMISD::VSHRN: return "ARMISD::VSHRN";
957 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
958 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
959 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
960 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
961 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
962 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
963 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
964 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
965 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
966 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
967 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
968 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
969 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
970 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
971 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
972 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
973 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
974 case ARMISD::VDUP: return "ARMISD::VDUP";
975 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
976 case ARMISD::VEXT: return "ARMISD::VEXT";
977 case ARMISD::VREV64: return "ARMISD::VREV64";
978 case ARMISD::VREV32: return "ARMISD::VREV32";
979 case ARMISD::VREV16: return "ARMISD::VREV16";
980 case ARMISD::VZIP: return "ARMISD::VZIP";
981 case ARMISD::VUZP: return "ARMISD::VUZP";
982 case ARMISD::VTRN: return "ARMISD::VTRN";
983 case ARMISD::VTBL1: return "ARMISD::VTBL1";
984 case ARMISD::VTBL2: return "ARMISD::VTBL2";
985 case ARMISD::VMULLs: return "ARMISD::VMULLs";
986 case ARMISD::VMULLu: return "ARMISD::VMULLu";
987 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
988 case ARMISD::FMAX: return "ARMISD::FMAX";
989 case ARMISD::FMIN: return "ARMISD::FMIN";
990 case ARMISD::BFI: return "ARMISD::BFI";
991 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
992 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
993 case ARMISD::VBSL: return "ARMISD::VBSL";
994 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
995 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
996 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
997 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
998 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
999 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1000 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1001 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1002 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1003 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1004 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1005 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1006 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1007 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1008 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1009 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1010 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1011 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1012 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1013 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1017 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1018 if (!VT.isVector()) return getPointerTy();
1019 return VT.changeVectorElementTypeToInteger();
1022 /// getRegClassFor - Return the register class that should be used for the
1023 /// specified value type.
1024 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1025 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1026 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1027 // load / store 4 to 8 consecutive D registers.
1028 if (Subtarget->hasNEON()) {
1029 if (VT == MVT::v4i64)
1030 return &ARM::QQPRRegClass;
1031 if (VT == MVT::v8i64)
1032 return &ARM::QQQQPRRegClass;
1034 return TargetLowering::getRegClassFor(VT);
1037 // Create a fast isel object.
1039 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1040 const TargetLibraryInfo *libInfo) const {
1041 return ARM::createFastISel(funcInfo, libInfo);
1044 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1045 /// be used for loads / stores from the global.
1046 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1047 return (Subtarget->isThumb1Only() ? 127 : 4095);
1050 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1051 unsigned NumVals = N->getNumValues();
1053 return Sched::RegPressure;
1055 for (unsigned i = 0; i != NumVals; ++i) {
1056 EVT VT = N->getValueType(i);
1057 if (VT == MVT::Glue || VT == MVT::Other)
1059 if (VT.isFloatingPoint() || VT.isVector())
1063 if (!N->isMachineOpcode())
1064 return Sched::RegPressure;
1066 // Load are scheduled for latency even if there instruction itinerary
1067 // is not available.
1068 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1069 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1071 if (MCID.getNumDefs() == 0)
1072 return Sched::RegPressure;
1073 if (!Itins->isEmpty() &&
1074 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1077 return Sched::RegPressure;
1080 //===----------------------------------------------------------------------===//
1082 //===----------------------------------------------------------------------===//
1084 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1085 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1087 default: llvm_unreachable("Unknown condition code!");
1088 case ISD::SETNE: return ARMCC::NE;
1089 case ISD::SETEQ: return ARMCC::EQ;
1090 case ISD::SETGT: return ARMCC::GT;
1091 case ISD::SETGE: return ARMCC::GE;
1092 case ISD::SETLT: return ARMCC::LT;
1093 case ISD::SETLE: return ARMCC::LE;
1094 case ISD::SETUGT: return ARMCC::HI;
1095 case ISD::SETUGE: return ARMCC::HS;
1096 case ISD::SETULT: return ARMCC::LO;
1097 case ISD::SETULE: return ARMCC::LS;
1101 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1102 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1103 ARMCC::CondCodes &CondCode2) {
1104 CondCode2 = ARMCC::AL;
1106 default: llvm_unreachable("Unknown FP condition!");
1108 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1110 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1112 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1113 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1114 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1115 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1116 case ISD::SETO: CondCode = ARMCC::VC; break;
1117 case ISD::SETUO: CondCode = ARMCC::VS; break;
1118 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1119 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1120 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1122 case ISD::SETULT: CondCode = ARMCC::LT; break;
1124 case ISD::SETULE: CondCode = ARMCC::LE; break;
1126 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1130 //===----------------------------------------------------------------------===//
1131 // Calling Convention Implementation
1132 //===----------------------------------------------------------------------===//
1134 #include "ARMGenCallingConv.inc"
1136 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1137 /// given CallingConvention value.
1138 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1140 bool isVarArg) const {
1143 llvm_unreachable("Unsupported calling convention");
1144 case CallingConv::Fast:
1145 if (Subtarget->hasVFP2() && !isVarArg) {
1146 if (!Subtarget->isAAPCS_ABI())
1147 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1148 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1149 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1152 case CallingConv::C: {
1153 // Use target triple & subtarget features to do actual dispatch.
1154 if (!Subtarget->isAAPCS_ABI())
1155 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1156 else if (Subtarget->hasVFP2() &&
1157 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1159 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1160 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1162 case CallingConv::ARM_AAPCS_VFP:
1164 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1166 case CallingConv::ARM_AAPCS:
1167 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1168 case CallingConv::ARM_APCS:
1169 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1170 case CallingConv::GHC:
1171 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1175 /// LowerCallResult - Lower the result values of a call into the
1176 /// appropriate copies out of appropriate physical registers.
1178 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1179 CallingConv::ID CallConv, bool isVarArg,
1180 const SmallVectorImpl<ISD::InputArg> &Ins,
1181 DebugLoc dl, SelectionDAG &DAG,
1182 SmallVectorImpl<SDValue> &InVals) const {
1184 // Assign locations to each value returned by this call.
1185 SmallVector<CCValAssign, 16> RVLocs;
1186 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1187 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1188 CCInfo.AnalyzeCallResult(Ins,
1189 CCAssignFnForNode(CallConv, /* Return*/ true,
1192 // Copy all of the result registers out of their specified physreg.
1193 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1194 CCValAssign VA = RVLocs[i];
1197 if (VA.needsCustom()) {
1198 // Handle f64 or half of a v2f64.
1199 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1201 Chain = Lo.getValue(1);
1202 InFlag = Lo.getValue(2);
1203 VA = RVLocs[++i]; // skip ahead to next loc
1204 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1206 Chain = Hi.getValue(1);
1207 InFlag = Hi.getValue(2);
1208 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1210 if (VA.getLocVT() == MVT::v2f64) {
1211 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1212 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1213 DAG.getConstant(0, MVT::i32));
1215 VA = RVLocs[++i]; // skip ahead to next loc
1216 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1217 Chain = Lo.getValue(1);
1218 InFlag = Lo.getValue(2);
1219 VA = RVLocs[++i]; // skip ahead to next loc
1220 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1221 Chain = Hi.getValue(1);
1222 InFlag = Hi.getValue(2);
1223 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1224 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1225 DAG.getConstant(1, MVT::i32));
1228 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1230 Chain = Val.getValue(1);
1231 InFlag = Val.getValue(2);
1234 switch (VA.getLocInfo()) {
1235 default: llvm_unreachable("Unknown loc info!");
1236 case CCValAssign::Full: break;
1237 case CCValAssign::BCvt:
1238 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1242 InVals.push_back(Val);
1248 /// LowerMemOpCallTo - Store the argument to the stack.
1250 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1251 SDValue StackPtr, SDValue Arg,
1252 DebugLoc dl, SelectionDAG &DAG,
1253 const CCValAssign &VA,
1254 ISD::ArgFlagsTy Flags) const {
1255 unsigned LocMemOffset = VA.getLocMemOffset();
1256 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1257 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1258 return DAG.getStore(Chain, dl, Arg, PtrOff,
1259 MachinePointerInfo::getStack(LocMemOffset),
1263 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1264 SDValue Chain, SDValue &Arg,
1265 RegsToPassVector &RegsToPass,
1266 CCValAssign &VA, CCValAssign &NextVA,
1268 SmallVector<SDValue, 8> &MemOpChains,
1269 ISD::ArgFlagsTy Flags) const {
1271 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1272 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1273 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1275 if (NextVA.isRegLoc())
1276 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1278 assert(NextVA.isMemLoc());
1279 if (StackPtr.getNode() == 0)
1280 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1282 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1288 /// LowerCall - Lowering a call into a callseq_start <-
1289 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1292 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1293 SmallVectorImpl<SDValue> &InVals) const {
1294 SelectionDAG &DAG = CLI.DAG;
1295 DebugLoc &dl = CLI.DL;
1296 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1297 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1298 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1299 SDValue Chain = CLI.Chain;
1300 SDValue Callee = CLI.Callee;
1301 bool &isTailCall = CLI.IsTailCall;
1302 CallingConv::ID CallConv = CLI.CallConv;
1303 bool doesNotRet = CLI.DoesNotReturn;
1304 bool isVarArg = CLI.IsVarArg;
1306 MachineFunction &MF = DAG.getMachineFunction();
1307 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1308 bool IsSibCall = false;
1309 // Disable tail calls if they're not supported.
1310 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1313 // Check if it's really possible to do a tail call.
1314 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1315 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1316 Outs, OutVals, Ins, DAG);
1317 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1318 // detected sibcalls.
1325 // Analyze operands of the call, assigning locations to each operand.
1326 SmallVector<CCValAssign, 16> ArgLocs;
1327 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1328 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1329 CCInfo.AnalyzeCallOperands(Outs,
1330 CCAssignFnForNode(CallConv, /* Return*/ false,
1333 // Get a count of how many bytes are to be pushed on the stack.
1334 unsigned NumBytes = CCInfo.getNextStackOffset();
1336 // For tail calls, memory operands are available in our caller's stack.
1340 // Adjust the stack pointer for the new arguments...
1341 // These operations are automatically eliminated by the prolog/epilog pass
1343 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1345 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1347 RegsToPassVector RegsToPass;
1348 SmallVector<SDValue, 8> MemOpChains;
1350 // Walk the register/memloc assignments, inserting copies/loads. In the case
1351 // of tail call optimization, arguments are handled later.
1352 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1354 ++i, ++realArgIdx) {
1355 CCValAssign &VA = ArgLocs[i];
1356 SDValue Arg = OutVals[realArgIdx];
1357 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1358 bool isByVal = Flags.isByVal();
1360 // Promote the value if needed.
1361 switch (VA.getLocInfo()) {
1362 default: llvm_unreachable("Unknown loc info!");
1363 case CCValAssign::Full: break;
1364 case CCValAssign::SExt:
1365 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1367 case CCValAssign::ZExt:
1368 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1370 case CCValAssign::AExt:
1371 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1373 case CCValAssign::BCvt:
1374 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1378 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1379 if (VA.needsCustom()) {
1380 if (VA.getLocVT() == MVT::v2f64) {
1381 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1382 DAG.getConstant(0, MVT::i32));
1383 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1384 DAG.getConstant(1, MVT::i32));
1386 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1387 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1389 VA = ArgLocs[++i]; // skip ahead to next loc
1390 if (VA.isRegLoc()) {
1391 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1392 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1394 assert(VA.isMemLoc());
1396 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1397 dl, DAG, VA, Flags));
1400 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1401 StackPtr, MemOpChains, Flags);
1403 } else if (VA.isRegLoc()) {
1404 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1405 } else if (isByVal) {
1406 assert(VA.isMemLoc());
1407 unsigned offset = 0;
1409 // True if this byval aggregate will be split between registers
1411 if (CCInfo.isFirstByValRegValid()) {
1412 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1414 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1415 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1416 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1417 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1418 MachinePointerInfo(),
1419 false, false, false, 0);
1420 MemOpChains.push_back(Load.getValue(1));
1421 RegsToPass.push_back(std::make_pair(j, Load));
1423 offset = ARM::R4 - CCInfo.getFirstByValReg();
1424 CCInfo.clearFirstByValReg();
1427 if (Flags.getByValSize() - 4*offset > 0) {
1428 unsigned LocMemOffset = VA.getLocMemOffset();
1429 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1430 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1432 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1433 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1434 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1436 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1438 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1439 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1440 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1441 Ops, array_lengthof(Ops)));
1443 } else if (!IsSibCall) {
1444 assert(VA.isMemLoc());
1446 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1447 dl, DAG, VA, Flags));
1451 if (!MemOpChains.empty())
1452 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1453 &MemOpChains[0], MemOpChains.size());
1455 // Build a sequence of copy-to-reg nodes chained together with token chain
1456 // and flag operands which copy the outgoing args into the appropriate regs.
1458 // Tail call byval lowering might overwrite argument registers so in case of
1459 // tail call optimization the copies to registers are lowered later.
1461 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1462 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1463 RegsToPass[i].second, InFlag);
1464 InFlag = Chain.getValue(1);
1467 // For tail calls lower the arguments to the 'real' stack slot.
1469 // Force all the incoming stack arguments to be loaded from the stack
1470 // before any new outgoing arguments are stored to the stack, because the
1471 // outgoing stack slots may alias the incoming argument stack slots, and
1472 // the alias isn't otherwise explicit. This is slightly more conservative
1473 // than necessary, because it means that each store effectively depends
1474 // on every argument instead of just those arguments it would clobber.
1476 // Do not flag preceding copytoreg stuff together with the following stuff.
1478 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1479 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1480 RegsToPass[i].second, InFlag);
1481 InFlag = Chain.getValue(1);
1486 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1487 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1488 // node so that legalize doesn't hack it.
1489 bool isDirect = false;
1490 bool isARMFunc = false;
1491 bool isLocalARMFunc = false;
1492 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1494 if (EnableARMLongCalls) {
1495 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1496 && "long-calls with non-static relocation model!");
1497 // Handle a global address or an external symbol. If it's not one of
1498 // those, the target's already in a register, so we don't need to do
1500 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1501 const GlobalValue *GV = G->getGlobal();
1502 // Create a constant pool entry for the callee address
1503 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1504 ARMConstantPoolValue *CPV =
1505 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1507 // Get the address of the callee into a register
1508 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1509 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1510 Callee = DAG.getLoad(getPointerTy(), dl,
1511 DAG.getEntryNode(), CPAddr,
1512 MachinePointerInfo::getConstantPool(),
1513 false, false, false, 0);
1514 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1515 const char *Sym = S->getSymbol();
1517 // Create a constant pool entry for the callee address
1518 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1519 ARMConstantPoolValue *CPV =
1520 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1521 ARMPCLabelIndex, 0);
1522 // Get the address of the callee into a register
1523 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1524 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1525 Callee = DAG.getLoad(getPointerTy(), dl,
1526 DAG.getEntryNode(), CPAddr,
1527 MachinePointerInfo::getConstantPool(),
1528 false, false, false, 0);
1530 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1531 const GlobalValue *GV = G->getGlobal();
1533 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1534 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1535 getTargetMachine().getRelocationModel() != Reloc::Static;
1536 isARMFunc = !Subtarget->isThumb() || isStub;
1537 // ARM call to a local ARM function is predicable.
1538 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1539 // tBX takes a register source operand.
1540 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1541 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1542 ARMConstantPoolValue *CPV =
1543 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1544 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1545 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1546 Callee = DAG.getLoad(getPointerTy(), dl,
1547 DAG.getEntryNode(), CPAddr,
1548 MachinePointerInfo::getConstantPool(),
1549 false, false, false, 0);
1550 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1551 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1552 getPointerTy(), Callee, PICLabel);
1554 // On ELF targets for PIC code, direct calls should go through the PLT
1555 unsigned OpFlags = 0;
1556 if (Subtarget->isTargetELF() &&
1557 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1558 OpFlags = ARMII::MO_PLT;
1559 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1561 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1563 bool isStub = Subtarget->isTargetDarwin() &&
1564 getTargetMachine().getRelocationModel() != Reloc::Static;
1565 isARMFunc = !Subtarget->isThumb() || isStub;
1566 // tBX takes a register source operand.
1567 const char *Sym = S->getSymbol();
1568 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1569 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1570 ARMConstantPoolValue *CPV =
1571 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1572 ARMPCLabelIndex, 4);
1573 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1574 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1575 Callee = DAG.getLoad(getPointerTy(), dl,
1576 DAG.getEntryNode(), CPAddr,
1577 MachinePointerInfo::getConstantPool(),
1578 false, false, false, 0);
1579 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1580 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1581 getPointerTy(), Callee, PICLabel);
1583 unsigned OpFlags = 0;
1584 // On ELF targets for PIC code, direct calls should go through the PLT
1585 if (Subtarget->isTargetELF() &&
1586 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1587 OpFlags = ARMII::MO_PLT;
1588 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1592 // FIXME: handle tail calls differently.
1594 if (Subtarget->isThumb()) {
1595 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1596 CallOpc = ARMISD::CALL_NOLINK;
1597 else if (doesNotRet && isDirect && !isARMFunc &&
1598 Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1599 // "mov lr, pc; b _foo" to avoid confusing the RSP
1600 CallOpc = ARMISD::CALL_NOLINK;
1602 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1604 if (!isDirect && !Subtarget->hasV5TOps()) {
1605 CallOpc = ARMISD::CALL_NOLINK;
1606 } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1607 // "mov lr, pc; b _foo" to avoid confusing the RSP
1608 CallOpc = ARMISD::CALL_NOLINK;
1610 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1613 std::vector<SDValue> Ops;
1614 Ops.push_back(Chain);
1615 Ops.push_back(Callee);
1617 // Add argument registers to the end of the list so that they are known live
1619 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1620 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1621 RegsToPass[i].second.getValueType()));
1623 // Add a register mask operand representing the call-preserved registers.
1624 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1625 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1626 assert(Mask && "Missing call preserved mask for calling convention");
1627 Ops.push_back(DAG.getRegisterMask(Mask));
1629 if (InFlag.getNode())
1630 Ops.push_back(InFlag);
1632 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1634 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1636 // Returns a chain and a flag for retval copy to use.
1637 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1638 InFlag = Chain.getValue(1);
1640 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1641 DAG.getIntPtrConstant(0, true), InFlag);
1643 InFlag = Chain.getValue(1);
1645 // Handle result values, copying them out of physregs into vregs that we
1647 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1651 /// HandleByVal - Every parameter *after* a byval parameter is passed
1652 /// on the stack. Remember the next parameter register to allocate,
1653 /// and then confiscate the rest of the parameter registers to insure
1656 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1657 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1658 assert((State->getCallOrPrologue() == Prologue ||
1659 State->getCallOrPrologue() == Call) &&
1660 "unhandled ParmContext");
1661 if ((!State->isFirstByValRegValid()) &&
1662 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1663 State->setFirstByValReg(reg);
1664 // At a call site, a byval parameter that is split between
1665 // registers and memory needs its size truncated here. In a
1666 // function prologue, such byval parameters are reassembled in
1667 // memory, and are not truncated.
1668 if (State->getCallOrPrologue() == Call) {
1669 unsigned excess = 4 * (ARM::R4 - reg);
1670 assert(size >= excess && "expected larger existing stack allocation");
1674 // Confiscate any remaining parameter registers to preclude their
1675 // assignment to subsequent parameters.
1676 while (State->AllocateReg(GPRArgRegs, 4))
1680 /// MatchingStackOffset - Return true if the given stack call argument is
1681 /// already available in the same position (relatively) of the caller's
1682 /// incoming argument stack.
1684 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1685 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1686 const TargetInstrInfo *TII) {
1687 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1689 if (Arg.getOpcode() == ISD::CopyFromReg) {
1690 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1691 if (!TargetRegisterInfo::isVirtualRegister(VR))
1693 MachineInstr *Def = MRI->getVRegDef(VR);
1696 if (!Flags.isByVal()) {
1697 if (!TII->isLoadFromStackSlot(Def, FI))
1702 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1703 if (Flags.isByVal())
1704 // ByVal argument is passed in as a pointer but it's now being
1705 // dereferenced. e.g.
1706 // define @foo(%struct.X* %A) {
1707 // tail call @bar(%struct.X* byval %A)
1710 SDValue Ptr = Ld->getBasePtr();
1711 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1714 FI = FINode->getIndex();
1718 assert(FI != INT_MAX);
1719 if (!MFI->isFixedObjectIndex(FI))
1721 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1724 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1725 /// for tail call optimization. Targets which want to do tail call
1726 /// optimization should implement this function.
1728 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1729 CallingConv::ID CalleeCC,
1731 bool isCalleeStructRet,
1732 bool isCallerStructRet,
1733 const SmallVectorImpl<ISD::OutputArg> &Outs,
1734 const SmallVectorImpl<SDValue> &OutVals,
1735 const SmallVectorImpl<ISD::InputArg> &Ins,
1736 SelectionDAG& DAG) const {
1737 const Function *CallerF = DAG.getMachineFunction().getFunction();
1738 CallingConv::ID CallerCC = CallerF->getCallingConv();
1739 bool CCMatch = CallerCC == CalleeCC;
1741 // Look for obvious safe cases to perform tail call optimization that do not
1742 // require ABI changes. This is what gcc calls sibcall.
1744 // Do not sibcall optimize vararg calls unless the call site is not passing
1746 if (isVarArg && !Outs.empty())
1749 // Also avoid sibcall optimization if either caller or callee uses struct
1750 // return semantics.
1751 if (isCalleeStructRet || isCallerStructRet)
1754 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1755 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1756 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1757 // support in the assembler and linker to be used. This would need to be
1758 // fixed to fully support tail calls in Thumb1.
1760 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1761 // LR. This means if we need to reload LR, it takes an extra instructions,
1762 // which outweighs the value of the tail call; but here we don't know yet
1763 // whether LR is going to be used. Probably the right approach is to
1764 // generate the tail call here and turn it back into CALL/RET in
1765 // emitEpilogue if LR is used.
1767 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1768 // but we need to make sure there are enough registers; the only valid
1769 // registers are the 4 used for parameters. We don't currently do this
1771 if (Subtarget->isThumb1Only())
1774 // If the calling conventions do not match, then we'd better make sure the
1775 // results are returned in the same way as what the caller expects.
1777 SmallVector<CCValAssign, 16> RVLocs1;
1778 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1779 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1780 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1782 SmallVector<CCValAssign, 16> RVLocs2;
1783 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1784 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1785 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1787 if (RVLocs1.size() != RVLocs2.size())
1789 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1790 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1792 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1794 if (RVLocs1[i].isRegLoc()) {
1795 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1798 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1804 // If the callee takes no arguments then go on to check the results of the
1806 if (!Outs.empty()) {
1807 // Check if stack adjustment is needed. For now, do not do this if any
1808 // argument is passed on the stack.
1809 SmallVector<CCValAssign, 16> ArgLocs;
1810 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1811 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1812 CCInfo.AnalyzeCallOperands(Outs,
1813 CCAssignFnForNode(CalleeCC, false, isVarArg));
1814 if (CCInfo.getNextStackOffset()) {
1815 MachineFunction &MF = DAG.getMachineFunction();
1817 // Check if the arguments are already laid out in the right way as
1818 // the caller's fixed stack objects.
1819 MachineFrameInfo *MFI = MF.getFrameInfo();
1820 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1821 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1822 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1824 ++i, ++realArgIdx) {
1825 CCValAssign &VA = ArgLocs[i];
1826 EVT RegVT = VA.getLocVT();
1827 SDValue Arg = OutVals[realArgIdx];
1828 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1829 if (VA.getLocInfo() == CCValAssign::Indirect)
1831 if (VA.needsCustom()) {
1832 // f64 and vector types are split into multiple registers or
1833 // register/stack-slot combinations. The types will not match
1834 // the registers; give up on memory f64 refs until we figure
1835 // out what to do about this.
1838 if (!ArgLocs[++i].isRegLoc())
1840 if (RegVT == MVT::v2f64) {
1841 if (!ArgLocs[++i].isRegLoc())
1843 if (!ArgLocs[++i].isRegLoc())
1846 } else if (!VA.isRegLoc()) {
1847 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1859 ARMTargetLowering::LowerReturn(SDValue Chain,
1860 CallingConv::ID CallConv, bool isVarArg,
1861 const SmallVectorImpl<ISD::OutputArg> &Outs,
1862 const SmallVectorImpl<SDValue> &OutVals,
1863 DebugLoc dl, SelectionDAG &DAG) const {
1865 // CCValAssign - represent the assignment of the return value to a location.
1866 SmallVector<CCValAssign, 16> RVLocs;
1868 // CCState - Info about the registers and stack slots.
1869 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1870 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1872 // Analyze outgoing return values.
1873 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1876 // If this is the first return lowered for this function, add
1877 // the regs to the liveout set for the function.
1878 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1879 for (unsigned i = 0; i != RVLocs.size(); ++i)
1880 if (RVLocs[i].isRegLoc())
1881 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1886 // Copy the result values into the output registers.
1887 for (unsigned i = 0, realRVLocIdx = 0;
1889 ++i, ++realRVLocIdx) {
1890 CCValAssign &VA = RVLocs[i];
1891 assert(VA.isRegLoc() && "Can only return in registers!");
1893 SDValue Arg = OutVals[realRVLocIdx];
1895 switch (VA.getLocInfo()) {
1896 default: llvm_unreachable("Unknown loc info!");
1897 case CCValAssign::Full: break;
1898 case CCValAssign::BCvt:
1899 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1903 if (VA.needsCustom()) {
1904 if (VA.getLocVT() == MVT::v2f64) {
1905 // Extract the first half and return it in two registers.
1906 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1907 DAG.getConstant(0, MVT::i32));
1908 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1909 DAG.getVTList(MVT::i32, MVT::i32), Half);
1911 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1912 Flag = Chain.getValue(1);
1913 VA = RVLocs[++i]; // skip ahead to next loc
1914 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1915 HalfGPRs.getValue(1), Flag);
1916 Flag = Chain.getValue(1);
1917 VA = RVLocs[++i]; // skip ahead to next loc
1919 // Extract the 2nd half and fall through to handle it as an f64 value.
1920 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1921 DAG.getConstant(1, MVT::i32));
1923 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1925 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1926 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1927 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1928 Flag = Chain.getValue(1);
1929 VA = RVLocs[++i]; // skip ahead to next loc
1930 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1933 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1935 // Guarantee that all emitted copies are
1936 // stuck together, avoiding something bad.
1937 Flag = Chain.getValue(1);
1942 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1944 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1949 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1950 if (N->getNumValues() != 1)
1952 if (!N->hasNUsesOfValue(1, 0))
1955 SDValue TCChain = Chain;
1956 SDNode *Copy = *N->use_begin();
1957 if (Copy->getOpcode() == ISD::CopyToReg) {
1958 // If the copy has a glue operand, we conservatively assume it isn't safe to
1959 // perform a tail call.
1960 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1962 TCChain = Copy->getOperand(0);
1963 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1964 SDNode *VMov = Copy;
1965 // f64 returned in a pair of GPRs.
1966 SmallPtrSet<SDNode*, 2> Copies;
1967 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1969 if (UI->getOpcode() != ISD::CopyToReg)
1973 if (Copies.size() > 2)
1976 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1978 SDValue UseChain = UI->getOperand(0);
1979 if (Copies.count(UseChain.getNode()))
1986 } else if (Copy->getOpcode() == ISD::BITCAST) {
1987 // f32 returned in a single GPR.
1988 if (!Copy->hasOneUse())
1990 Copy = *Copy->use_begin();
1991 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1993 Chain = Copy->getOperand(0);
1998 bool HasRet = false;
1999 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2001 if (UI->getOpcode() != ARMISD::RET_FLAG)
2013 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2014 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2017 if (!CI->isTailCall())
2020 return !Subtarget->isThumb1Only();
2023 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2024 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2025 // one of the above mentioned nodes. It has to be wrapped because otherwise
2026 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2027 // be used to form addressing mode. These wrapped nodes will be selected
2029 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2030 EVT PtrVT = Op.getValueType();
2031 // FIXME there is no actual debug info here
2032 DebugLoc dl = Op.getDebugLoc();
2033 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2035 if (CP->isMachineConstantPoolEntry())
2036 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2037 CP->getAlignment());
2039 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2040 CP->getAlignment());
2041 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2044 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2045 return MachineJumpTableInfo::EK_Inline;
2048 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2049 SelectionDAG &DAG) const {
2050 MachineFunction &MF = DAG.getMachineFunction();
2051 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2052 unsigned ARMPCLabelIndex = 0;
2053 DebugLoc DL = Op.getDebugLoc();
2054 EVT PtrVT = getPointerTy();
2055 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2056 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2058 if (RelocM == Reloc::Static) {
2059 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2061 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2062 ARMPCLabelIndex = AFI->createPICLabelUId();
2063 ARMConstantPoolValue *CPV =
2064 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2065 ARMCP::CPBlockAddress, PCAdj);
2066 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2068 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2069 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2070 MachinePointerInfo::getConstantPool(),
2071 false, false, false, 0);
2072 if (RelocM == Reloc::Static)
2074 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2075 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2078 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2080 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2081 SelectionDAG &DAG) const {
2082 DebugLoc dl = GA->getDebugLoc();
2083 EVT PtrVT = getPointerTy();
2084 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2085 MachineFunction &MF = DAG.getMachineFunction();
2086 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2087 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2088 ARMConstantPoolValue *CPV =
2089 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2090 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2091 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2092 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2093 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2094 MachinePointerInfo::getConstantPool(),
2095 false, false, false, 0);
2096 SDValue Chain = Argument.getValue(1);
2098 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2099 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2101 // call __tls_get_addr.
2104 Entry.Node = Argument;
2105 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2106 Args.push_back(Entry);
2107 // FIXME: is there useful debug info available here?
2108 TargetLowering::CallLoweringInfo CLI(Chain,
2109 (Type *) Type::getInt32Ty(*DAG.getContext()),
2110 false, false, false, false,
2111 0, CallingConv::C, /*isTailCall=*/false,
2112 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2113 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2114 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2115 return CallResult.first;
2118 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2119 // "local exec" model.
2121 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2123 TLSModel::Model model) const {
2124 const GlobalValue *GV = GA->getGlobal();
2125 DebugLoc dl = GA->getDebugLoc();
2127 SDValue Chain = DAG.getEntryNode();
2128 EVT PtrVT = getPointerTy();
2129 // Get the Thread Pointer
2130 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2132 if (model == TLSModel::InitialExec) {
2133 MachineFunction &MF = DAG.getMachineFunction();
2134 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2135 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2136 // Initial exec model.
2137 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2138 ARMConstantPoolValue *CPV =
2139 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2140 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2142 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2143 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2144 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2145 MachinePointerInfo::getConstantPool(),
2146 false, false, false, 0);
2147 Chain = Offset.getValue(1);
2149 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2150 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2152 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2153 MachinePointerInfo::getConstantPool(),
2154 false, false, false, 0);
2157 assert(model == TLSModel::LocalExec);
2158 ARMConstantPoolValue *CPV =
2159 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2160 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2161 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2162 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2163 MachinePointerInfo::getConstantPool(),
2164 false, false, false, 0);
2167 // The address of the thread local variable is the add of the thread
2168 // pointer with the offset of the variable.
2169 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2173 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2174 // TODO: implement the "local dynamic" model
2175 assert(Subtarget->isTargetELF() &&
2176 "TLS not implemented for non-ELF targets");
2177 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2179 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2182 case TLSModel::GeneralDynamic:
2183 case TLSModel::LocalDynamic:
2184 return LowerToTLSGeneralDynamicModel(GA, DAG);
2185 case TLSModel::InitialExec:
2186 case TLSModel::LocalExec:
2187 return LowerToTLSExecModels(GA, DAG, model);
2189 llvm_unreachable("bogus TLS model");
2192 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2193 SelectionDAG &DAG) const {
2194 EVT PtrVT = getPointerTy();
2195 DebugLoc dl = Op.getDebugLoc();
2196 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2197 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2198 if (RelocM == Reloc::PIC_) {
2199 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2200 ARMConstantPoolValue *CPV =
2201 ARMConstantPoolConstant::Create(GV,
2202 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2203 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2204 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2205 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2207 MachinePointerInfo::getConstantPool(),
2208 false, false, false, 0);
2209 SDValue Chain = Result.getValue(1);
2210 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2211 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2213 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2214 MachinePointerInfo::getGOT(),
2215 false, false, false, 0);
2219 // If we have T2 ops, we can materialize the address directly via movt/movw
2220 // pair. This is always cheaper.
2221 if (Subtarget->useMovt()) {
2223 // FIXME: Once remat is capable of dealing with instructions with register
2224 // operands, expand this into two nodes.
2225 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2226 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2228 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2229 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2230 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2231 MachinePointerInfo::getConstantPool(),
2232 false, false, false, 0);
2236 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2237 SelectionDAG &DAG) const {
2238 EVT PtrVT = getPointerTy();
2239 DebugLoc dl = Op.getDebugLoc();
2240 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2241 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2242 MachineFunction &MF = DAG.getMachineFunction();
2243 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2245 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2246 // update ARMFastISel::ARMMaterializeGV.
2247 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2249 // FIXME: Once remat is capable of dealing with instructions with register
2250 // operands, expand this into two nodes.
2251 if (RelocM == Reloc::Static)
2252 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2253 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2255 unsigned Wrapper = (RelocM == Reloc::PIC_)
2256 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2257 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2258 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2259 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2260 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2261 MachinePointerInfo::getGOT(),
2262 false, false, false, 0);
2266 unsigned ARMPCLabelIndex = 0;
2268 if (RelocM == Reloc::Static) {
2269 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2271 ARMPCLabelIndex = AFI->createPICLabelUId();
2272 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2273 ARMConstantPoolValue *CPV =
2274 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2276 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2278 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2280 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2281 MachinePointerInfo::getConstantPool(),
2282 false, false, false, 0);
2283 SDValue Chain = Result.getValue(1);
2285 if (RelocM == Reloc::PIC_) {
2286 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2287 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2290 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2291 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2292 false, false, false, 0);
2297 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2298 SelectionDAG &DAG) const {
2299 assert(Subtarget->isTargetELF() &&
2300 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2301 MachineFunction &MF = DAG.getMachineFunction();
2302 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2303 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2304 EVT PtrVT = getPointerTy();
2305 DebugLoc dl = Op.getDebugLoc();
2306 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2307 ARMConstantPoolValue *CPV =
2308 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2309 ARMPCLabelIndex, PCAdj);
2310 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2311 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2312 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2313 MachinePointerInfo::getConstantPool(),
2314 false, false, false, 0);
2315 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2316 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2320 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2321 DebugLoc dl = Op.getDebugLoc();
2322 SDValue Val = DAG.getConstant(0, MVT::i32);
2323 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2324 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2325 Op.getOperand(1), Val);
2329 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2330 DebugLoc dl = Op.getDebugLoc();
2331 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2332 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2336 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2337 const ARMSubtarget *Subtarget) const {
2338 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2339 DebugLoc dl = Op.getDebugLoc();
2341 default: return SDValue(); // Don't custom lower most intrinsics.
2342 case Intrinsic::arm_thread_pointer: {
2343 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2344 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2346 case Intrinsic::eh_sjlj_lsda: {
2347 MachineFunction &MF = DAG.getMachineFunction();
2348 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2349 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2350 EVT PtrVT = getPointerTy();
2351 DebugLoc dl = Op.getDebugLoc();
2352 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2354 unsigned PCAdj = (RelocM != Reloc::PIC_)
2355 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2356 ARMConstantPoolValue *CPV =
2357 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2358 ARMCP::CPLSDA, PCAdj);
2359 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2360 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2362 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2363 MachinePointerInfo::getConstantPool(),
2364 false, false, false, 0);
2366 if (RelocM == Reloc::PIC_) {
2367 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2368 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2372 case Intrinsic::arm_neon_vmulls:
2373 case Intrinsic::arm_neon_vmullu: {
2374 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2375 ? ARMISD::VMULLs : ARMISD::VMULLu;
2376 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2377 Op.getOperand(1), Op.getOperand(2));
2382 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2383 const ARMSubtarget *Subtarget) {
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 SDValue Op5 = Op.getOperand(5);
2396 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2397 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2398 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2399 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2401 ARM_MB::MemBOpt DMBOpt;
2402 if (isDeviceBarrier)
2403 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2405 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2406 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2407 DAG.getConstant(DMBOpt, MVT::i32));
2411 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2412 const ARMSubtarget *Subtarget) {
2413 // FIXME: handle "fence singlethread" more efficiently.
2414 DebugLoc dl = Op.getDebugLoc();
2415 if (!Subtarget->hasDataBarrier()) {
2416 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2417 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2419 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2420 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2421 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2422 DAG.getConstant(0, MVT::i32));
2425 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2426 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2429 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2430 const ARMSubtarget *Subtarget) {
2431 // ARM pre v5TE and Thumb1 does not have preload instructions.
2432 if (!(Subtarget->isThumb2() ||
2433 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2434 // Just preserve the chain.
2435 return Op.getOperand(0);
2437 DebugLoc dl = Op.getDebugLoc();
2438 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2440 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2441 // ARMv7 with MP extension has PLDW.
2442 return Op.getOperand(0);
2444 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2445 if (Subtarget->isThumb()) {
2447 isRead = ~isRead & 1;
2448 isData = ~isData & 1;
2451 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2452 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2453 DAG.getConstant(isData, MVT::i32));
2456 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2457 MachineFunction &MF = DAG.getMachineFunction();
2458 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2460 // vastart just stores the address of the VarArgsFrameIndex slot into the
2461 // memory location argument.
2462 DebugLoc dl = Op.getDebugLoc();
2463 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2464 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2465 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2466 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2467 MachinePointerInfo(SV), false, false, 0);
2471 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2472 SDValue &Root, SelectionDAG &DAG,
2473 DebugLoc dl) const {
2474 MachineFunction &MF = DAG.getMachineFunction();
2475 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2477 const TargetRegisterClass *RC;
2478 if (AFI->isThumb1OnlyFunction())
2479 RC = &ARM::tGPRRegClass;
2481 RC = &ARM::GPRRegClass;
2483 // Transform the arguments stored in physical registers into virtual ones.
2484 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2485 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2488 if (NextVA.isMemLoc()) {
2489 MachineFrameInfo *MFI = MF.getFrameInfo();
2490 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2492 // Create load node to retrieve arguments from the stack.
2493 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2494 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2495 MachinePointerInfo::getFixedStack(FI),
2496 false, false, false, 0);
2498 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2499 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2502 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2506 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2507 unsigned &VARegSize, unsigned &VARegSaveSize)
2510 if (CCInfo.isFirstByValRegValid())
2511 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2513 unsigned int firstUnalloced;
2514 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2515 sizeof(GPRArgRegs) /
2516 sizeof(GPRArgRegs[0]));
2517 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2520 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2521 VARegSize = NumGPRs * 4;
2522 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2525 // The remaining GPRs hold either the beginning of variable-argument
2526 // data, or the beginning of an aggregate passed by value (usuall
2527 // byval). Either way, we allocate stack slots adjacent to the data
2528 // provided by our caller, and store the unallocated registers there.
2529 // If this is a variadic function, the va_list pointer will begin with
2530 // these values; otherwise, this reassembles a (byval) structure that
2531 // was split between registers and memory.
2533 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2534 DebugLoc dl, SDValue &Chain,
2535 unsigned ArgOffset) const {
2536 MachineFunction &MF = DAG.getMachineFunction();
2537 MachineFrameInfo *MFI = MF.getFrameInfo();
2538 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2539 unsigned firstRegToSaveIndex;
2540 if (CCInfo.isFirstByValRegValid())
2541 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2543 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2544 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2547 unsigned VARegSize, VARegSaveSize;
2548 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2549 if (VARegSaveSize) {
2550 // If this function is vararg, store any remaining integer argument regs
2551 // to their spots on the stack so that they may be loaded by deferencing
2552 // the result of va_next.
2553 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2554 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2555 ArgOffset + VARegSaveSize
2558 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2561 SmallVector<SDValue, 4> MemOps;
2562 for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2563 const TargetRegisterClass *RC;
2564 if (AFI->isThumb1OnlyFunction())
2565 RC = &ARM::tGPRRegClass;
2567 RC = &ARM::GPRRegClass;
2569 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2570 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2572 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2573 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2575 MemOps.push_back(Store);
2576 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2577 DAG.getConstant(4, getPointerTy()));
2579 if (!MemOps.empty())
2580 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2581 &MemOps[0], MemOps.size());
2583 // This will point to the next argument passed via stack.
2584 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2588 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2589 CallingConv::ID CallConv, bool isVarArg,
2590 const SmallVectorImpl<ISD::InputArg>
2592 DebugLoc dl, SelectionDAG &DAG,
2593 SmallVectorImpl<SDValue> &InVals)
2595 MachineFunction &MF = DAG.getMachineFunction();
2596 MachineFrameInfo *MFI = MF.getFrameInfo();
2598 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2600 // Assign locations to all of the incoming arguments.
2601 SmallVector<CCValAssign, 16> ArgLocs;
2602 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2603 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2604 CCInfo.AnalyzeFormalArguments(Ins,
2605 CCAssignFnForNode(CallConv, /* Return*/ false,
2608 SmallVector<SDValue, 16> ArgValues;
2609 int lastInsIndex = -1;
2612 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2613 CCValAssign &VA = ArgLocs[i];
2615 // Arguments stored in registers.
2616 if (VA.isRegLoc()) {
2617 EVT RegVT = VA.getLocVT();
2619 if (VA.needsCustom()) {
2620 // f64 and vector types are split up into multiple registers or
2621 // combinations of registers and stack slots.
2622 if (VA.getLocVT() == MVT::v2f64) {
2623 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2625 VA = ArgLocs[++i]; // skip ahead to next loc
2627 if (VA.isMemLoc()) {
2628 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2629 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2630 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2631 MachinePointerInfo::getFixedStack(FI),
2632 false, false, false, 0);
2634 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2637 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2638 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2639 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2640 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2641 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2643 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2646 const TargetRegisterClass *RC;
2648 if (RegVT == MVT::f32)
2649 RC = &ARM::SPRRegClass;
2650 else if (RegVT == MVT::f64)
2651 RC = &ARM::DPRRegClass;
2652 else if (RegVT == MVT::v2f64)
2653 RC = &ARM::QPRRegClass;
2654 else if (RegVT == MVT::i32)
2655 RC = AFI->isThumb1OnlyFunction() ?
2656 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2657 (const TargetRegisterClass*)&ARM::GPRRegClass;
2659 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2661 // Transform the arguments in physical registers into virtual ones.
2662 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2663 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2666 // If this is an 8 or 16-bit value, it is really passed promoted
2667 // to 32 bits. Insert an assert[sz]ext to capture this, then
2668 // truncate to the right size.
2669 switch (VA.getLocInfo()) {
2670 default: llvm_unreachable("Unknown loc info!");
2671 case CCValAssign::Full: break;
2672 case CCValAssign::BCvt:
2673 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2675 case CCValAssign::SExt:
2676 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2677 DAG.getValueType(VA.getValVT()));
2678 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2680 case CCValAssign::ZExt:
2681 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2682 DAG.getValueType(VA.getValVT()));
2683 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2687 InVals.push_back(ArgValue);
2689 } else { // VA.isRegLoc()
2692 assert(VA.isMemLoc());
2693 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2695 int index = ArgLocs[i].getValNo();
2697 // Some Ins[] entries become multiple ArgLoc[] entries.
2698 // Process them only once.
2699 if (index != lastInsIndex)
2701 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2702 // FIXME: For now, all byval parameter objects are marked mutable.
2703 // This can be changed with more analysis.
2704 // In case of tail call optimization mark all arguments mutable.
2705 // Since they could be overwritten by lowering of arguments in case of
2707 if (Flags.isByVal()) {
2708 unsigned VARegSize, VARegSaveSize;
2709 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2710 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2711 unsigned Bytes = Flags.getByValSize() - VARegSize;
2712 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2713 int FI = MFI->CreateFixedObject(Bytes,
2714 VA.getLocMemOffset(), false);
2715 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2717 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2718 VA.getLocMemOffset(), true);
2720 // Create load nodes to retrieve arguments from the stack.
2721 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2722 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2723 MachinePointerInfo::getFixedStack(FI),
2724 false, false, false, 0));
2726 lastInsIndex = index;
2733 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2738 /// isFloatingPointZero - Return true if this is +0.0.
2739 static bool isFloatingPointZero(SDValue Op) {
2740 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2741 return CFP->getValueAPF().isPosZero();
2742 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2743 // Maybe this has already been legalized into the constant pool?
2744 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2745 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2746 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2747 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2748 return CFP->getValueAPF().isPosZero();
2754 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2755 /// the given operands.
2757 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2758 SDValue &ARMcc, SelectionDAG &DAG,
2759 DebugLoc dl) const {
2760 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2761 unsigned C = RHSC->getZExtValue();
2762 if (!isLegalICmpImmediate(C)) {
2763 // Constant does not fit, try adjusting it by one?
2768 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2769 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2770 RHS = DAG.getConstant(C-1, MVT::i32);
2775 if (C != 0 && isLegalICmpImmediate(C-1)) {
2776 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2777 RHS = DAG.getConstant(C-1, MVT::i32);
2782 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2783 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2784 RHS = DAG.getConstant(C+1, MVT::i32);
2789 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2790 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2791 RHS = DAG.getConstant(C+1, MVT::i32);
2798 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2799 ARMISD::NodeType CompareType;
2802 CompareType = ARMISD::CMP;
2807 CompareType = ARMISD::CMPZ;
2810 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2811 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2814 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2816 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2817 DebugLoc dl) const {
2819 if (!isFloatingPointZero(RHS))
2820 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2822 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2823 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2826 /// duplicateCmp - Glue values can have only one use, so this function
2827 /// duplicates a comparison node.
2829 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2830 unsigned Opc = Cmp.getOpcode();
2831 DebugLoc DL = Cmp.getDebugLoc();
2832 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2833 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2835 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2836 Cmp = Cmp.getOperand(0);
2837 Opc = Cmp.getOpcode();
2838 if (Opc == ARMISD::CMPFP)
2839 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2841 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2842 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2844 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2847 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2848 SDValue Cond = Op.getOperand(0);
2849 SDValue SelectTrue = Op.getOperand(1);
2850 SDValue SelectFalse = Op.getOperand(2);
2851 DebugLoc dl = Op.getDebugLoc();
2855 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2856 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2858 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2859 const ConstantSDNode *CMOVTrue =
2860 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2861 const ConstantSDNode *CMOVFalse =
2862 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2864 if (CMOVTrue && CMOVFalse) {
2865 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2866 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2870 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2872 False = SelectFalse;
2873 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2878 if (True.getNode() && False.getNode()) {
2879 EVT VT = Op.getValueType();
2880 SDValue ARMcc = Cond.getOperand(2);
2881 SDValue CCR = Cond.getOperand(3);
2882 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2883 assert(True.getValueType() == VT);
2884 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2889 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2890 // undefined bits before doing a full-word comparison with zero.
2891 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2892 DAG.getConstant(1, Cond.getValueType()));
2894 return DAG.getSelectCC(dl, Cond,
2895 DAG.getConstant(0, Cond.getValueType()),
2896 SelectTrue, SelectFalse, ISD::SETNE);
2899 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2900 EVT VT = Op.getValueType();
2901 SDValue LHS = Op.getOperand(0);
2902 SDValue RHS = Op.getOperand(1);
2903 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2904 SDValue TrueVal = Op.getOperand(2);
2905 SDValue FalseVal = Op.getOperand(3);
2906 DebugLoc dl = Op.getDebugLoc();
2908 if (LHS.getValueType() == MVT::i32) {
2910 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2911 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2912 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2915 ARMCC::CondCodes CondCode, CondCode2;
2916 FPCCToARMCC(CC, CondCode, CondCode2);
2918 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2919 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2920 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2921 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2923 if (CondCode2 != ARMCC::AL) {
2924 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2925 // FIXME: Needs another CMP because flag can have but one use.
2926 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2927 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2928 Result, TrueVal, ARMcc2, CCR, Cmp2);
2933 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2934 /// to morph to an integer compare sequence.
2935 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2936 const ARMSubtarget *Subtarget) {
2937 SDNode *N = Op.getNode();
2938 if (!N->hasOneUse())
2939 // Otherwise it requires moving the value from fp to integer registers.
2941 if (!N->getNumValues())
2943 EVT VT = Op.getValueType();
2944 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2945 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2946 // vmrs are very slow, e.g. cortex-a8.
2949 if (isFloatingPointZero(Op)) {
2953 return ISD::isNormalLoad(N);
2956 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2957 if (isFloatingPointZero(Op))
2958 return DAG.getConstant(0, MVT::i32);
2960 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2961 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2962 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2963 Ld->isVolatile(), Ld->isNonTemporal(),
2964 Ld->isInvariant(), Ld->getAlignment());
2966 llvm_unreachable("Unknown VFP cmp argument!");
2969 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2970 SDValue &RetVal1, SDValue &RetVal2) {
2971 if (isFloatingPointZero(Op)) {
2972 RetVal1 = DAG.getConstant(0, MVT::i32);
2973 RetVal2 = DAG.getConstant(0, MVT::i32);
2977 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2978 SDValue Ptr = Ld->getBasePtr();
2979 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2980 Ld->getChain(), Ptr,
2981 Ld->getPointerInfo(),
2982 Ld->isVolatile(), Ld->isNonTemporal(),
2983 Ld->isInvariant(), Ld->getAlignment());
2985 EVT PtrType = Ptr.getValueType();
2986 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2987 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2988 PtrType, Ptr, DAG.getConstant(4, PtrType));
2989 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2990 Ld->getChain(), NewPtr,
2991 Ld->getPointerInfo().getWithOffset(4),
2992 Ld->isVolatile(), Ld->isNonTemporal(),
2993 Ld->isInvariant(), NewAlign);
2997 llvm_unreachable("Unknown VFP cmp argument!");
3000 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3001 /// f32 and even f64 comparisons to integer ones.
3003 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3004 SDValue Chain = Op.getOperand(0);
3005 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3006 SDValue LHS = Op.getOperand(2);
3007 SDValue RHS = Op.getOperand(3);
3008 SDValue Dest = Op.getOperand(4);
3009 DebugLoc dl = Op.getDebugLoc();
3011 bool LHSSeenZero = false;
3012 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3013 bool RHSSeenZero = false;
3014 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3015 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3016 // If unsafe fp math optimization is enabled and there are no other uses of
3017 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3018 // to an integer comparison.
3019 if (CC == ISD::SETOEQ)
3021 else if (CC == ISD::SETUNE)
3024 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3026 if (LHS.getValueType() == MVT::f32) {
3027 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3028 bitcastf32Toi32(LHS, DAG), Mask);
3029 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3030 bitcastf32Toi32(RHS, DAG), Mask);
3031 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3032 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3033 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3034 Chain, Dest, ARMcc, CCR, Cmp);
3039 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3040 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3041 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3042 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3043 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3044 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3045 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3046 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3047 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3053 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3054 SDValue Chain = Op.getOperand(0);
3055 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3056 SDValue LHS = Op.getOperand(2);
3057 SDValue RHS = Op.getOperand(3);
3058 SDValue Dest = Op.getOperand(4);
3059 DebugLoc dl = Op.getDebugLoc();
3061 if (LHS.getValueType() == MVT::i32) {
3063 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3064 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3065 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3066 Chain, Dest, ARMcc, CCR, Cmp);
3069 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3071 if (getTargetMachine().Options.UnsafeFPMath &&
3072 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3073 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3074 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3075 if (Result.getNode())
3079 ARMCC::CondCodes CondCode, CondCode2;
3080 FPCCToARMCC(CC, CondCode, CondCode2);
3082 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3083 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3084 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3085 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3086 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3087 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3088 if (CondCode2 != ARMCC::AL) {
3089 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3090 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3091 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3096 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3097 SDValue Chain = Op.getOperand(0);
3098 SDValue Table = Op.getOperand(1);
3099 SDValue Index = Op.getOperand(2);
3100 DebugLoc dl = Op.getDebugLoc();
3102 EVT PTy = getPointerTy();
3103 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3104 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3105 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3106 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3107 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3108 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3109 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3110 if (Subtarget->isThumb2()) {
3111 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3112 // which does another jump to the destination. This also makes it easier
3113 // to translate it to TBB / TBH later.
3114 // FIXME: This might not work if the function is extremely large.
3115 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3116 Addr, Op.getOperand(2), JTI, UId);
3118 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3119 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3120 MachinePointerInfo::getJumpTable(),
3121 false, false, false, 0);
3122 Chain = Addr.getValue(1);
3123 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3124 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3126 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3127 MachinePointerInfo::getJumpTable(),
3128 false, false, false, 0);
3129 Chain = Addr.getValue(1);
3130 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3134 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3135 EVT VT = Op.getValueType();
3136 DebugLoc dl = Op.getDebugLoc();
3138 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3139 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3141 return DAG.UnrollVectorOp(Op.getNode());
3144 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3145 "Invalid type for custom lowering!");
3146 if (VT != MVT::v4i16)
3147 return DAG.UnrollVectorOp(Op.getNode());
3149 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3150 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3153 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3154 EVT VT = Op.getValueType();
3156 return LowerVectorFP_TO_INT(Op, DAG);
3158 DebugLoc dl = Op.getDebugLoc();
3161 switch (Op.getOpcode()) {
3162 default: llvm_unreachable("Invalid opcode!");
3163 case ISD::FP_TO_SINT:
3164 Opc = ARMISD::FTOSI;
3166 case ISD::FP_TO_UINT:
3167 Opc = ARMISD::FTOUI;
3170 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3171 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3174 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3175 EVT VT = Op.getValueType();
3176 DebugLoc dl = Op.getDebugLoc();
3178 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3179 if (VT.getVectorElementType() == MVT::f32)
3181 return DAG.UnrollVectorOp(Op.getNode());
3184 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3185 "Invalid type for custom lowering!");
3186 if (VT != MVT::v4f32)
3187 return DAG.UnrollVectorOp(Op.getNode());
3191 switch (Op.getOpcode()) {
3192 default: llvm_unreachable("Invalid opcode!");
3193 case ISD::SINT_TO_FP:
3194 CastOpc = ISD::SIGN_EXTEND;
3195 Opc = ISD::SINT_TO_FP;
3197 case ISD::UINT_TO_FP:
3198 CastOpc = ISD::ZERO_EXTEND;
3199 Opc = ISD::UINT_TO_FP;
3203 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3204 return DAG.getNode(Opc, dl, VT, Op);
3207 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3208 EVT VT = Op.getValueType();
3210 return LowerVectorINT_TO_FP(Op, DAG);
3212 DebugLoc dl = Op.getDebugLoc();
3215 switch (Op.getOpcode()) {
3216 default: llvm_unreachable("Invalid opcode!");
3217 case ISD::SINT_TO_FP:
3218 Opc = ARMISD::SITOF;
3220 case ISD::UINT_TO_FP:
3221 Opc = ARMISD::UITOF;
3225 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3226 return DAG.getNode(Opc, dl, VT, Op);
3229 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3230 // Implement fcopysign with a fabs and a conditional fneg.
3231 SDValue Tmp0 = Op.getOperand(0);
3232 SDValue Tmp1 = Op.getOperand(1);
3233 DebugLoc dl = Op.getDebugLoc();
3234 EVT VT = Op.getValueType();
3235 EVT SrcVT = Tmp1.getValueType();
3236 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3237 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3238 bool UseNEON = !InGPR && Subtarget->hasNEON();
3241 // Use VBSL to copy the sign bit.
3242 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3243 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3244 DAG.getTargetConstant(EncodedVal, MVT::i32));
3245 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3247 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3248 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3249 DAG.getConstant(32, MVT::i32));
3250 else /*if (VT == MVT::f32)*/
3251 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3252 if (SrcVT == MVT::f32) {
3253 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3255 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3256 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3257 DAG.getConstant(32, MVT::i32));
3258 } else if (VT == MVT::f32)
3259 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3260 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3261 DAG.getConstant(32, MVT::i32));
3262 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3263 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3265 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3267 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3268 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3269 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3271 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3272 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3273 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3274 if (VT == MVT::f32) {
3275 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3276 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3277 DAG.getConstant(0, MVT::i32));
3279 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3285 // Bitcast operand 1 to i32.
3286 if (SrcVT == MVT::f64)
3287 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3288 &Tmp1, 1).getValue(1);
3289 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3291 // Or in the signbit with integer operations.
3292 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3293 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3294 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3295 if (VT == MVT::f32) {
3296 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3297 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3298 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3299 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3302 // f64: Or the high part with signbit and then combine two parts.
3303 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3305 SDValue Lo = Tmp0.getValue(0);
3306 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3307 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3308 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3311 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3312 MachineFunction &MF = DAG.getMachineFunction();
3313 MachineFrameInfo *MFI = MF.getFrameInfo();
3314 MFI->setReturnAddressIsTaken(true);
3316 EVT VT = Op.getValueType();
3317 DebugLoc dl = Op.getDebugLoc();
3318 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3320 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3321 SDValue Offset = DAG.getConstant(4, MVT::i32);
3322 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3323 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3324 MachinePointerInfo(), false, false, false, 0);
3327 // Return LR, which contains the return address. Mark it an implicit live-in.
3328 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3329 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3332 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3333 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3334 MFI->setFrameAddressIsTaken(true);
3336 EVT VT = Op.getValueType();
3337 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3338 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3339 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3340 ? ARM::R7 : ARM::R11;
3341 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3343 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3344 MachinePointerInfo(),
3345 false, false, false, 0);
3349 /// ExpandBITCAST - If the target supports VFP, this function is called to
3350 /// expand a bit convert where either the source or destination type is i64 to
3351 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3352 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3353 /// vectors), since the legalizer won't know what to do with that.
3354 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3355 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3356 DebugLoc dl = N->getDebugLoc();
3357 SDValue Op = N->getOperand(0);
3359 // This function is only supposed to be called for i64 types, either as the
3360 // source or destination of the bit convert.
3361 EVT SrcVT = Op.getValueType();
3362 EVT DstVT = N->getValueType(0);
3363 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3364 "ExpandBITCAST called for non-i64 type");
3366 // Turn i64->f64 into VMOVDRR.
3367 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3368 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3369 DAG.getConstant(0, MVT::i32));
3370 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3371 DAG.getConstant(1, MVT::i32));
3372 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3373 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3376 // Turn f64->i64 into VMOVRRD.
3377 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3378 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3379 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3380 // Merge the pieces into a single i64 value.
3381 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3387 /// getZeroVector - Returns a vector of specified type with all zero elements.
3388 /// Zero vectors are used to represent vector negation and in those cases
3389 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3390 /// not support i64 elements, so sometimes the zero vectors will need to be
3391 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3393 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3394 assert(VT.isVector() && "Expected a vector type");
3395 // The canonical modified immediate encoding of a zero vector is....0!
3396 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3397 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3398 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3399 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3402 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3403 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3404 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3405 SelectionDAG &DAG) const {
3406 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3407 EVT VT = Op.getValueType();
3408 unsigned VTBits = VT.getSizeInBits();
3409 DebugLoc dl = Op.getDebugLoc();
3410 SDValue ShOpLo = Op.getOperand(0);
3411 SDValue ShOpHi = Op.getOperand(1);
3412 SDValue ShAmt = Op.getOperand(2);
3414 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3416 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3418 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3419 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3420 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3421 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3422 DAG.getConstant(VTBits, MVT::i32));
3423 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3424 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3425 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3427 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3428 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3430 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3431 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3434 SDValue Ops[2] = { Lo, Hi };
3435 return DAG.getMergeValues(Ops, 2, dl);
3438 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3439 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3440 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3441 SelectionDAG &DAG) const {
3442 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3443 EVT VT = Op.getValueType();
3444 unsigned VTBits = VT.getSizeInBits();
3445 DebugLoc dl = Op.getDebugLoc();
3446 SDValue ShOpLo = Op.getOperand(0);
3447 SDValue ShOpHi = Op.getOperand(1);
3448 SDValue ShAmt = Op.getOperand(2);
3451 assert(Op.getOpcode() == ISD::SHL_PARTS);
3452 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3453 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3454 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3455 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3456 DAG.getConstant(VTBits, MVT::i32));
3457 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3458 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3460 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3461 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3462 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3464 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3465 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3468 SDValue Ops[2] = { Lo, Hi };
3469 return DAG.getMergeValues(Ops, 2, dl);
3472 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3473 SelectionDAG &DAG) const {
3474 // The rounding mode is in bits 23:22 of the FPSCR.
3475 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3476 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3477 // so that the shift + and get folded into a bitfield extract.
3478 DebugLoc dl = Op.getDebugLoc();
3479 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3480 DAG.getConstant(Intrinsic::arm_get_fpscr,
3482 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3483 DAG.getConstant(1U << 22, MVT::i32));
3484 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3485 DAG.getConstant(22, MVT::i32));
3486 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3487 DAG.getConstant(3, MVT::i32));
3490 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3491 const ARMSubtarget *ST) {
3492 EVT VT = N->getValueType(0);
3493 DebugLoc dl = N->getDebugLoc();
3495 if (!ST->hasV6T2Ops())
3498 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3499 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3502 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3503 const ARMSubtarget *ST) {
3504 EVT VT = N->getValueType(0);
3505 DebugLoc dl = N->getDebugLoc();
3510 // Lower vector shifts on NEON to use VSHL.
3511 assert(ST->hasNEON() && "unexpected vector shift");
3513 // Left shifts translate directly to the vshiftu intrinsic.
3514 if (N->getOpcode() == ISD::SHL)
3515 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3516 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3517 N->getOperand(0), N->getOperand(1));
3519 assert((N->getOpcode() == ISD::SRA ||
3520 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3522 // NEON uses the same intrinsics for both left and right shifts. For
3523 // right shifts, the shift amounts are negative, so negate the vector of
3525 EVT ShiftVT = N->getOperand(1).getValueType();
3526 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3527 getZeroVector(ShiftVT, DAG, dl),
3529 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3530 Intrinsic::arm_neon_vshifts :
3531 Intrinsic::arm_neon_vshiftu);
3532 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3533 DAG.getConstant(vshiftInt, MVT::i32),
3534 N->getOperand(0), NegatedCount);
3537 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3538 const ARMSubtarget *ST) {
3539 EVT VT = N->getValueType(0);
3540 DebugLoc dl = N->getDebugLoc();
3542 // We can get here for a node like i32 = ISD::SHL i32, i64
3546 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3547 "Unknown shift to lower!");
3549 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3550 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3551 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3554 // If we are in thumb mode, we don't have RRX.
3555 if (ST->isThumb1Only()) return SDValue();
3557 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3558 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3559 DAG.getConstant(0, MVT::i32));
3560 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3561 DAG.getConstant(1, MVT::i32));
3563 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3564 // captures the result into a carry flag.
3565 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3566 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3568 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3569 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3571 // Merge the pieces into a single i64 value.
3572 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3575 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3576 SDValue TmpOp0, TmpOp1;
3577 bool Invert = false;
3581 SDValue Op0 = Op.getOperand(0);
3582 SDValue Op1 = Op.getOperand(1);
3583 SDValue CC = Op.getOperand(2);
3584 EVT VT = Op.getValueType();
3585 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3586 DebugLoc dl = Op.getDebugLoc();
3588 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3589 switch (SetCCOpcode) {
3590 default: llvm_unreachable("Illegal FP comparison");
3592 case ISD::SETNE: Invert = true; // Fallthrough
3594 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3596 case ISD::SETLT: Swap = true; // Fallthrough
3598 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3600 case ISD::SETLE: Swap = true; // Fallthrough
3602 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3603 case ISD::SETUGE: Swap = true; // Fallthrough
3604 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3605 case ISD::SETUGT: Swap = true; // Fallthrough
3606 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3607 case ISD::SETUEQ: Invert = true; // Fallthrough
3609 // Expand this to (OLT | OGT).
3613 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3614 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3616 case ISD::SETUO: Invert = true; // Fallthrough
3618 // Expand this to (OLT | OGE).
3622 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3623 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3627 // Integer comparisons.
3628 switch (SetCCOpcode) {
3629 default: llvm_unreachable("Illegal integer comparison");
3630 case ISD::SETNE: Invert = true;
3631 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3632 case ISD::SETLT: Swap = true;
3633 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3634 case ISD::SETLE: Swap = true;
3635 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3636 case ISD::SETULT: Swap = true;
3637 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3638 case ISD::SETULE: Swap = true;
3639 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3642 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3643 if (Opc == ARMISD::VCEQ) {
3646 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3648 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3651 // Ignore bitconvert.
3652 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3653 AndOp = AndOp.getOperand(0);
3655 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3657 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3658 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3665 std::swap(Op0, Op1);
3667 // If one of the operands is a constant vector zero, attempt to fold the
3668 // comparison to a specialized compare-against-zero form.
3670 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3672 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3673 if (Opc == ARMISD::VCGE)
3674 Opc = ARMISD::VCLEZ;
3675 else if (Opc == ARMISD::VCGT)
3676 Opc = ARMISD::VCLTZ;
3681 if (SingleOp.getNode()) {
3684 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3686 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3688 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3690 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3692 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3694 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3697 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3701 Result = DAG.getNOT(dl, Result, VT);
3706 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3707 /// valid vector constant for a NEON instruction with a "modified immediate"
3708 /// operand (e.g., VMOV). If so, return the encoded value.
3709 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3710 unsigned SplatBitSize, SelectionDAG &DAG,
3711 EVT &VT, bool is128Bits, NEONModImmType type) {
3712 unsigned OpCmode, Imm;
3714 // SplatBitSize is set to the smallest size that splats the vector, so a
3715 // zero vector will always have SplatBitSize == 8. However, NEON modified
3716 // immediate instructions others than VMOV do not support the 8-bit encoding
3717 // of a zero vector, and the default encoding of zero is supposed to be the
3722 switch (SplatBitSize) {
3724 if (type != VMOVModImm)
3726 // Any 1-byte value is OK. Op=0, Cmode=1110.
3727 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3730 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3734 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3735 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3736 if ((SplatBits & ~0xff) == 0) {
3737 // Value = 0x00nn: Op=x, Cmode=100x.
3742 if ((SplatBits & ~0xff00) == 0) {
3743 // Value = 0xnn00: Op=x, Cmode=101x.
3745 Imm = SplatBits >> 8;
3751 // NEON's 32-bit VMOV supports splat values where:
3752 // * only one byte is nonzero, or
3753 // * the least significant byte is 0xff and the second byte is nonzero, or
3754 // * the least significant 2 bytes are 0xff and the third is nonzero.
3755 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3756 if ((SplatBits & ~0xff) == 0) {
3757 // Value = 0x000000nn: Op=x, Cmode=000x.
3762 if ((SplatBits & ~0xff00) == 0) {
3763 // Value = 0x0000nn00: Op=x, Cmode=001x.
3765 Imm = SplatBits >> 8;
3768 if ((SplatBits & ~0xff0000) == 0) {
3769 // Value = 0x00nn0000: Op=x, Cmode=010x.
3771 Imm = SplatBits >> 16;
3774 if ((SplatBits & ~0xff000000) == 0) {
3775 // Value = 0xnn000000: Op=x, Cmode=011x.
3777 Imm = SplatBits >> 24;
3781 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3782 if (type == OtherModImm) return SDValue();
3784 if ((SplatBits & ~0xffff) == 0 &&
3785 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3786 // Value = 0x0000nnff: Op=x, Cmode=1100.
3788 Imm = SplatBits >> 8;
3793 if ((SplatBits & ~0xffffff) == 0 &&
3794 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3795 // Value = 0x00nnffff: Op=x, Cmode=1101.
3797 Imm = SplatBits >> 16;
3798 SplatBits |= 0xffff;
3802 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3803 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3804 // VMOV.I32. A (very) minor optimization would be to replicate the value
3805 // and fall through here to test for a valid 64-bit splat. But, then the
3806 // caller would also need to check and handle the change in size.
3810 if (type != VMOVModImm)
3812 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3813 uint64_t BitMask = 0xff;
3815 unsigned ImmMask = 1;
3817 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3818 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3821 } else if ((SplatBits & BitMask) != 0) {
3827 // Op=1, Cmode=1110.
3830 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3835 llvm_unreachable("unexpected size for isNEONModifiedImm");
3838 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3839 return DAG.getTargetConstant(EncodedVal, MVT::i32);
3842 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3843 const ARMSubtarget *ST) const {
3844 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3847 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3848 assert(Op.getValueType() == MVT::f32 &&
3849 "ConstantFP custom lowering should only occur for f32.");
3851 // Try splatting with a VMOV.f32...
3852 APFloat FPVal = CFP->getValueAPF();
3853 int ImmVal = ARM_AM::getFP32Imm(FPVal);
3855 DebugLoc DL = Op.getDebugLoc();
3856 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3857 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3859 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3860 DAG.getConstant(0, MVT::i32));
3863 // If that fails, try a VMOV.i32
3865 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3866 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3868 if (NewVal != SDValue()) {
3869 DebugLoc DL = Op.getDebugLoc();
3870 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3872 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3874 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3875 DAG.getConstant(0, MVT::i32));
3878 // Finally, try a VMVN.i32
3879 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3881 if (NewVal != SDValue()) {
3882 DebugLoc DL = Op.getDebugLoc();
3883 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3884 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3886 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3887 DAG.getConstant(0, MVT::i32));
3894 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3895 bool &ReverseVEXT, unsigned &Imm) {
3896 unsigned NumElts = VT.getVectorNumElements();
3897 ReverseVEXT = false;
3899 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3905 // If this is a VEXT shuffle, the immediate value is the index of the first
3906 // element. The other shuffle indices must be the successive elements after
3908 unsigned ExpectedElt = Imm;
3909 for (unsigned i = 1; i < NumElts; ++i) {
3910 // Increment the expected index. If it wraps around, it may still be
3911 // a VEXT but the source vectors must be swapped.
3913 if (ExpectedElt == NumElts * 2) {
3918 if (M[i] < 0) continue; // ignore UNDEF indices
3919 if (ExpectedElt != static_cast<unsigned>(M[i]))
3923 // Adjust the index value if the source operands will be swapped.
3930 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3931 /// instruction with the specified blocksize. (The order of the elements
3932 /// within each block of the vector is reversed.)
3933 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3934 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3935 "Only possible block sizes for VREV are: 16, 32, 64");
3937 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3941 unsigned NumElts = VT.getVectorNumElements();
3942 unsigned BlockElts = M[0] + 1;
3943 // If the first shuffle index is UNDEF, be optimistic.
3945 BlockElts = BlockSize / EltSz;
3947 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3950 for (unsigned i = 0; i < NumElts; ++i) {
3951 if (M[i] < 0) continue; // ignore UNDEF indices
3952 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3959 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3960 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3961 // range, then 0 is placed into the resulting vector. So pretty much any mask
3962 // of 8 elements can work here.
3963 return VT == MVT::v8i8 && M.size() == 8;
3966 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3967 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3971 unsigned NumElts = VT.getVectorNumElements();
3972 WhichResult = (M[0] == 0 ? 0 : 1);
3973 for (unsigned i = 0; i < NumElts; i += 2) {
3974 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3975 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3981 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3982 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3983 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3984 static bool isVTRN_v_undef_Mask(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 for (unsigned i = 0; i < NumElts; i += 2) {
3992 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3993 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3999 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4000 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4004 unsigned NumElts = VT.getVectorNumElements();
4005 WhichResult = (M[0] == 0 ? 0 : 1);
4006 for (unsigned i = 0; i != NumElts; ++i) {
4007 if (M[i] < 0) continue; // ignore UNDEF indices
4008 if ((unsigned) M[i] != 2 * i + WhichResult)
4012 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4013 if (VT.is64BitVector() && EltSz == 32)
4019 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4020 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4021 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4022 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4023 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4027 unsigned Half = VT.getVectorNumElements() / 2;
4028 WhichResult = (M[0] == 0 ? 0 : 1);
4029 for (unsigned j = 0; j != 2; ++j) {
4030 unsigned Idx = WhichResult;
4031 for (unsigned i = 0; i != Half; ++i) {
4032 int MIdx = M[i + j * Half];
4033 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4039 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4040 if (VT.is64BitVector() && EltSz == 32)
4046 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4047 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4051 unsigned NumElts = VT.getVectorNumElements();
4052 WhichResult = (M[0] == 0 ? 0 : 1);
4053 unsigned Idx = WhichResult * NumElts / 2;
4054 for (unsigned i = 0; i != NumElts; i += 2) {
4055 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4056 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4061 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4062 if (VT.is64BitVector() && EltSz == 32)
4068 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4069 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4070 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4071 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4072 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4076 unsigned NumElts = VT.getVectorNumElements();
4077 WhichResult = (M[0] == 0 ? 0 : 1);
4078 unsigned Idx = WhichResult * NumElts / 2;
4079 for (unsigned i = 0; i != NumElts; i += 2) {
4080 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4081 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4086 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4087 if (VT.is64BitVector() && EltSz == 32)
4093 // If N is an integer constant that can be moved into a register in one
4094 // instruction, return an SDValue of such a constant (will become a MOV
4095 // instruction). Otherwise return null.
4096 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4097 const ARMSubtarget *ST, DebugLoc dl) {
4099 if (!isa<ConstantSDNode>(N))
4101 Val = cast<ConstantSDNode>(N)->getZExtValue();
4103 if (ST->isThumb1Only()) {
4104 if (Val <= 255 || ~Val <= 255)
4105 return DAG.getConstant(Val, MVT::i32);
4107 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4108 return DAG.getConstant(Val, MVT::i32);
4113 // If this is a case we can't handle, return null and let the default
4114 // expansion code take care of it.
4115 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4116 const ARMSubtarget *ST) const {
4117 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4118 DebugLoc dl = Op.getDebugLoc();
4119 EVT VT = Op.getValueType();
4121 APInt SplatBits, SplatUndef;
4122 unsigned SplatBitSize;
4124 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4125 if (SplatBitSize <= 64) {
4126 // Check if an immediate VMOV works.
4128 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4129 SplatUndef.getZExtValue(), SplatBitSize,
4130 DAG, VmovVT, VT.is128BitVector(),
4132 if (Val.getNode()) {
4133 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4134 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4137 // Try an immediate VMVN.
4138 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4139 Val = isNEONModifiedImm(NegatedImm,
4140 SplatUndef.getZExtValue(), SplatBitSize,
4141 DAG, VmovVT, VT.is128BitVector(),
4143 if (Val.getNode()) {
4144 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4145 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4148 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4149 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4150 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4152 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4153 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4159 // Scan through the operands to see if only one value is used.
4160 unsigned NumElts = VT.getVectorNumElements();
4161 bool isOnlyLowElement = true;
4162 bool usesOnlyOneValue = true;
4163 bool isConstant = true;
4165 for (unsigned i = 0; i < NumElts; ++i) {
4166 SDValue V = Op.getOperand(i);
4167 if (V.getOpcode() == ISD::UNDEF)
4170 isOnlyLowElement = false;
4171 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4174 if (!Value.getNode())
4176 else if (V != Value)
4177 usesOnlyOneValue = false;
4180 if (!Value.getNode())
4181 return DAG.getUNDEF(VT);
4183 if (isOnlyLowElement)
4184 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4186 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4188 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4189 // i32 and try again.
4190 if (usesOnlyOneValue && EltSize <= 32) {
4192 return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4193 if (VT.getVectorElementType().isFloatingPoint()) {
4194 SmallVector<SDValue, 8> Ops;
4195 for (unsigned i = 0; i < NumElts; ++i)
4196 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4198 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4199 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4200 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4202 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4204 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4206 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4209 // If all elements are constants and the case above didn't get hit, fall back
4210 // to the default expansion, which will generate a load from the constant
4215 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4217 SDValue shuffle = ReconstructShuffle(Op, DAG);
4218 if (shuffle != SDValue())
4222 // Vectors with 32- or 64-bit elements can be built by directly assigning
4223 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4224 // will be legalized.
4225 if (EltSize >= 32) {
4226 // Do the expansion with floating-point types, since that is what the VFP
4227 // registers are defined to use, and since i64 is not legal.
4228 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4229 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4230 SmallVector<SDValue, 8> Ops;
4231 for (unsigned i = 0; i < NumElts; ++i)
4232 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4233 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4234 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4240 // Gather data to see if the operation can be modelled as a
4241 // shuffle in combination with VEXTs.
4242 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4243 SelectionDAG &DAG) const {
4244 DebugLoc dl = Op.getDebugLoc();
4245 EVT VT = Op.getValueType();
4246 unsigned NumElts = VT.getVectorNumElements();
4248 SmallVector<SDValue, 2> SourceVecs;
4249 SmallVector<unsigned, 2> MinElts;
4250 SmallVector<unsigned, 2> MaxElts;
4252 for (unsigned i = 0; i < NumElts; ++i) {
4253 SDValue V = Op.getOperand(i);
4254 if (V.getOpcode() == ISD::UNDEF)
4256 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4257 // A shuffle can only come from building a vector from various
4258 // elements of other vectors.
4260 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4261 VT.getVectorElementType()) {
4262 // This code doesn't know how to handle shuffles where the vector
4263 // element types do not match (this happens because type legalization
4264 // promotes the return type of EXTRACT_VECTOR_ELT).
4265 // FIXME: It might be appropriate to extend this code to handle
4266 // mismatched types.
4270 // Record this extraction against the appropriate vector if possible...
4271 SDValue SourceVec = V.getOperand(0);
4272 // If the element number isn't a constant, we can't effectively
4273 // analyze what's going on.
4274 if (!isa<ConstantSDNode>(V.getOperand(1)))
4276 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4277 bool FoundSource = false;
4278 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4279 if (SourceVecs[j] == SourceVec) {
4280 if (MinElts[j] > EltNo)
4282 if (MaxElts[j] < EltNo)
4289 // Or record a new source if not...
4291 SourceVecs.push_back(SourceVec);
4292 MinElts.push_back(EltNo);
4293 MaxElts.push_back(EltNo);
4297 // Currently only do something sane when at most two source vectors
4299 if (SourceVecs.size() > 2)
4302 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4303 int VEXTOffsets[2] = {0, 0};
4305 // This loop extracts the usage patterns of the source vectors
4306 // and prepares appropriate SDValues for a shuffle if possible.
4307 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4308 if (SourceVecs[i].getValueType() == VT) {
4309 // No VEXT necessary
4310 ShuffleSrcs[i] = SourceVecs[i];
4313 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4314 // It probably isn't worth padding out a smaller vector just to
4315 // break it down again in a shuffle.
4319 // Since only 64-bit and 128-bit vectors are legal on ARM and
4320 // we've eliminated the other cases...
4321 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4322 "unexpected vector sizes in ReconstructShuffle");
4324 if (MaxElts[i] - MinElts[i] >= NumElts) {
4325 // Span too large for a VEXT to cope
4329 if (MinElts[i] >= NumElts) {
4330 // The extraction can just take the second half
4331 VEXTOffsets[i] = NumElts;
4332 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4334 DAG.getIntPtrConstant(NumElts));
4335 } else if (MaxElts[i] < NumElts) {
4336 // The extraction can just take the first half
4338 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4340 DAG.getIntPtrConstant(0));
4342 // An actual VEXT is needed
4343 VEXTOffsets[i] = MinElts[i];
4344 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4346 DAG.getIntPtrConstant(0));
4347 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4349 DAG.getIntPtrConstant(NumElts));
4350 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4351 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4355 SmallVector<int, 8> Mask;
4357 for (unsigned i = 0; i < NumElts; ++i) {
4358 SDValue Entry = Op.getOperand(i);
4359 if (Entry.getOpcode() == ISD::UNDEF) {
4364 SDValue ExtractVec = Entry.getOperand(0);
4365 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4366 .getOperand(1))->getSExtValue();
4367 if (ExtractVec == SourceVecs[0]) {
4368 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4370 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4374 // Final check before we try to produce nonsense...
4375 if (isShuffleMaskLegal(Mask, VT))
4376 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4382 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4383 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4384 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4385 /// are assumed to be legal.
4387 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4389 if (VT.getVectorNumElements() == 4 &&
4390 (VT.is128BitVector() || VT.is64BitVector())) {
4391 unsigned PFIndexes[4];
4392 for (unsigned i = 0; i != 4; ++i) {
4396 PFIndexes[i] = M[i];
4399 // Compute the index in the perfect shuffle table.
4400 unsigned PFTableIndex =
4401 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4402 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4403 unsigned Cost = (PFEntry >> 30);
4410 unsigned Imm, WhichResult;
4412 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4413 return (EltSize >= 32 ||
4414 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4415 isVREVMask(M, VT, 64) ||
4416 isVREVMask(M, VT, 32) ||
4417 isVREVMask(M, VT, 16) ||
4418 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4419 isVTBLMask(M, VT) ||
4420 isVTRNMask(M, VT, WhichResult) ||
4421 isVUZPMask(M, VT, WhichResult) ||
4422 isVZIPMask(M, VT, WhichResult) ||
4423 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4424 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4425 isVZIP_v_undef_Mask(M, VT, WhichResult));
4428 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4429 /// the specified operations to build the shuffle.
4430 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4431 SDValue RHS, SelectionDAG &DAG,
4433 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4434 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4435 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4438 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4447 OP_VUZPL, // VUZP, left result
4448 OP_VUZPR, // VUZP, right result
4449 OP_VZIPL, // VZIP, left result
4450 OP_VZIPR, // VZIP, right result
4451 OP_VTRNL, // VTRN, left result
4452 OP_VTRNR // VTRN, right result
4455 if (OpNum == OP_COPY) {
4456 if (LHSID == (1*9+2)*9+3) return LHS;
4457 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4461 SDValue OpLHS, OpRHS;
4462 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4463 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4464 EVT VT = OpLHS.getValueType();
4467 default: llvm_unreachable("Unknown shuffle opcode!");
4469 // VREV divides the vector in half and swaps within the half.
4470 if (VT.getVectorElementType() == MVT::i32 ||
4471 VT.getVectorElementType() == MVT::f32)
4472 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4473 // vrev <4 x i16> -> VREV32
4474 if (VT.getVectorElementType() == MVT::i16)
4475 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4476 // vrev <4 x i8> -> VREV16
4477 assert(VT.getVectorElementType() == MVT::i8);
4478 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4483 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4484 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4488 return DAG.getNode(ARMISD::VEXT, dl, VT,
4490 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4493 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4494 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4497 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4498 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4501 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4502 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4506 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4507 ArrayRef<int> ShuffleMask,
4508 SelectionDAG &DAG) {
4509 // Check to see if we can use the VTBL instruction.
4510 SDValue V1 = Op.getOperand(0);
4511 SDValue V2 = Op.getOperand(1);
4512 DebugLoc DL = Op.getDebugLoc();
4514 SmallVector<SDValue, 8> VTBLMask;
4515 for (ArrayRef<int>::iterator
4516 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4517 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4519 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4520 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4521 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4524 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4525 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4529 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4530 SDValue V1 = Op.getOperand(0);
4531 SDValue V2 = Op.getOperand(1);
4532 DebugLoc dl = Op.getDebugLoc();
4533 EVT VT = Op.getValueType();
4534 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4536 // Convert shuffles that are directly supported on NEON to target-specific
4537 // DAG nodes, instead of keeping them as shuffles and matching them again
4538 // during code selection. This is more efficient and avoids the possibility
4539 // of inconsistencies between legalization and selection.
4540 // FIXME: floating-point vectors should be canonicalized to integer vectors
4541 // of the same time so that they get CSEd properly.
4542 ArrayRef<int> ShuffleMask = SVN->getMask();
4544 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4545 if (EltSize <= 32) {
4546 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4547 int Lane = SVN->getSplatIndex();
4548 // If this is undef splat, generate it via "just" vdup, if possible.
4549 if (Lane == -1) Lane = 0;
4551 // Test if V1 is a SCALAR_TO_VECTOR.
4552 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4553 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4555 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4556 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4558 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4559 !isa<ConstantSDNode>(V1.getOperand(0))) {
4560 bool IsScalarToVector = true;
4561 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4562 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4563 IsScalarToVector = false;
4566 if (IsScalarToVector)
4567 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4569 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4570 DAG.getConstant(Lane, MVT::i32));
4575 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4578 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4579 DAG.getConstant(Imm, MVT::i32));
4582 if (isVREVMask(ShuffleMask, VT, 64))
4583 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4584 if (isVREVMask(ShuffleMask, VT, 32))
4585 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4586 if (isVREVMask(ShuffleMask, VT, 16))
4587 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4589 // Check for Neon shuffles that modify both input vectors in place.
4590 // If both results are used, i.e., if there are two shuffles with the same
4591 // source operands and with masks corresponding to both results of one of
4592 // these operations, DAG memoization will ensure that a single node is
4593 // used for both shuffles.
4594 unsigned WhichResult;
4595 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4596 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4597 V1, V2).getValue(WhichResult);
4598 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4599 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4600 V1, V2).getValue(WhichResult);
4601 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4602 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4603 V1, V2).getValue(WhichResult);
4605 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4606 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4607 V1, V1).getValue(WhichResult);
4608 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4609 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4610 V1, V1).getValue(WhichResult);
4611 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4612 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4613 V1, V1).getValue(WhichResult);
4616 // If the shuffle is not directly supported and it has 4 elements, use
4617 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4618 unsigned NumElts = VT.getVectorNumElements();
4620 unsigned PFIndexes[4];
4621 for (unsigned i = 0; i != 4; ++i) {
4622 if (ShuffleMask[i] < 0)
4625 PFIndexes[i] = ShuffleMask[i];
4628 // Compute the index in the perfect shuffle table.
4629 unsigned PFTableIndex =
4630 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4631 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4632 unsigned Cost = (PFEntry >> 30);
4635 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4638 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4639 if (EltSize >= 32) {
4640 // Do the expansion with floating-point types, since that is what the VFP
4641 // registers are defined to use, and since i64 is not legal.
4642 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4643 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4644 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4645 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4646 SmallVector<SDValue, 8> Ops;
4647 for (unsigned i = 0; i < NumElts; ++i) {
4648 if (ShuffleMask[i] < 0)
4649 Ops.push_back(DAG.getUNDEF(EltVT));
4651 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4652 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4653 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4656 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4657 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4660 if (VT == MVT::v8i8) {
4661 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4662 if (NewOp.getNode())
4669 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4670 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4671 SDValue Lane = Op.getOperand(2);
4672 if (!isa<ConstantSDNode>(Lane))
4678 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4679 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4680 SDValue Lane = Op.getOperand(1);
4681 if (!isa<ConstantSDNode>(Lane))
4684 SDValue Vec = Op.getOperand(0);
4685 if (Op.getValueType() == MVT::i32 &&
4686 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4687 DebugLoc dl = Op.getDebugLoc();
4688 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4694 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4695 // The only time a CONCAT_VECTORS operation can have legal types is when
4696 // two 64-bit vectors are concatenated to a 128-bit vector.
4697 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4698 "unexpected CONCAT_VECTORS");
4699 DebugLoc dl = Op.getDebugLoc();
4700 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4701 SDValue Op0 = Op.getOperand(0);
4702 SDValue Op1 = Op.getOperand(1);
4703 if (Op0.getOpcode() != ISD::UNDEF)
4704 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4705 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4706 DAG.getIntPtrConstant(0));
4707 if (Op1.getOpcode() != ISD::UNDEF)
4708 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4709 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4710 DAG.getIntPtrConstant(1));
4711 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4714 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4715 /// element has been zero/sign-extended, depending on the isSigned parameter,
4716 /// from an integer type half its size.
4717 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4719 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4720 EVT VT = N->getValueType(0);
4721 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4722 SDNode *BVN = N->getOperand(0).getNode();
4723 if (BVN->getValueType(0) != MVT::v4i32 ||
4724 BVN->getOpcode() != ISD::BUILD_VECTOR)
4726 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4727 unsigned HiElt = 1 - LoElt;
4728 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4729 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4730 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4731 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4732 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4735 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4736 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4739 if (Hi0->isNullValue() && Hi1->isNullValue())
4745 if (N->getOpcode() != ISD::BUILD_VECTOR)
4748 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4749 SDNode *Elt = N->getOperand(i).getNode();
4750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4751 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4752 unsigned HalfSize = EltSize / 2;
4754 if (!isIntN(HalfSize, C->getSExtValue()))
4757 if (!isUIntN(HalfSize, C->getZExtValue()))
4768 /// isSignExtended - Check if a node is a vector value that is sign-extended
4769 /// or a constant BUILD_VECTOR with sign-extended elements.
4770 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4771 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4773 if (isExtendedBUILD_VECTOR(N, DAG, true))
4778 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4779 /// or a constant BUILD_VECTOR with zero-extended elements.
4780 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4781 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4783 if (isExtendedBUILD_VECTOR(N, DAG, false))
4788 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4789 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4790 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4791 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4792 return N->getOperand(0);
4793 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4794 return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4795 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4796 LD->isNonTemporal(), LD->isInvariant(),
4797 LD->getAlignment());
4798 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
4799 // have been legalized as a BITCAST from v4i32.
4800 if (N->getOpcode() == ISD::BITCAST) {
4801 SDNode *BVN = N->getOperand(0).getNode();
4802 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4803 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4804 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4805 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4806 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4808 // Construct a new BUILD_VECTOR with elements truncated to half the size.
4809 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4810 EVT VT = N->getValueType(0);
4811 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4812 unsigned NumElts = VT.getVectorNumElements();
4813 MVT TruncVT = MVT::getIntegerVT(EltSize);
4814 SmallVector<SDValue, 8> Ops;
4815 for (unsigned i = 0; i != NumElts; ++i) {
4816 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4817 const APInt &CInt = C->getAPIntValue();
4818 // Element types smaller than 32 bits are not legal, so use i32 elements.
4819 // The values are implicitly truncated so sext vs. zext doesn't matter.
4820 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4822 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4823 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4826 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4827 unsigned Opcode = N->getOpcode();
4828 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4829 SDNode *N0 = N->getOperand(0).getNode();
4830 SDNode *N1 = N->getOperand(1).getNode();
4831 return N0->hasOneUse() && N1->hasOneUse() &&
4832 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4837 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4838 unsigned Opcode = N->getOpcode();
4839 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4840 SDNode *N0 = N->getOperand(0).getNode();
4841 SDNode *N1 = N->getOperand(1).getNode();
4842 return N0->hasOneUse() && N1->hasOneUse() &&
4843 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4848 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4849 // Multiplications are only custom-lowered for 128-bit vectors so that
4850 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
4851 EVT VT = Op.getValueType();
4852 assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4853 SDNode *N0 = Op.getOperand(0).getNode();
4854 SDNode *N1 = Op.getOperand(1).getNode();
4855 unsigned NewOpc = 0;
4857 bool isN0SExt = isSignExtended(N0, DAG);
4858 bool isN1SExt = isSignExtended(N1, DAG);
4859 if (isN0SExt && isN1SExt)
4860 NewOpc = ARMISD::VMULLs;
4862 bool isN0ZExt = isZeroExtended(N0, DAG);
4863 bool isN1ZExt = isZeroExtended(N1, DAG);
4864 if (isN0ZExt && isN1ZExt)
4865 NewOpc = ARMISD::VMULLu;
4866 else if (isN1SExt || isN1ZExt) {
4867 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4868 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4869 if (isN1SExt && isAddSubSExt(N0, DAG)) {
4870 NewOpc = ARMISD::VMULLs;
4872 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4873 NewOpc = ARMISD::VMULLu;
4875 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4877 NewOpc = ARMISD::VMULLu;
4883 if (VT == MVT::v2i64)
4884 // Fall through to expand this. It is not legal.
4887 // Other vector multiplications are legal.
4892 // Legalize to a VMULL instruction.
4893 DebugLoc DL = Op.getDebugLoc();
4895 SDValue Op1 = SkipExtension(N1, DAG);
4897 Op0 = SkipExtension(N0, DAG);
4898 assert(Op0.getValueType().is64BitVector() &&
4899 Op1.getValueType().is64BitVector() &&
4900 "unexpected types for extended operands to VMULL");
4901 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4904 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4905 // isel lowering to take advantage of no-stall back to back vmul + vmla.
4912 SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4913 SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4914 EVT Op1VT = Op1.getValueType();
4915 return DAG.getNode(N0->getOpcode(), DL, VT,
4916 DAG.getNode(NewOpc, DL, VT,
4917 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4918 DAG.getNode(NewOpc, DL, VT,
4919 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4923 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4925 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4926 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4927 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4928 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4929 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4930 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4931 // Get reciprocal estimate.
4932 // float4 recip = vrecpeq_f32(yf);
4933 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4934 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4935 // Because char has a smaller range than uchar, we can actually get away
4936 // without any newton steps. This requires that we use a weird bias
4937 // of 0xb000, however (again, this has been exhaustively tested).
4938 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4939 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4940 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4941 Y = DAG.getConstant(0xb000, MVT::i32);
4942 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4943 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4944 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4945 // Convert back to short.
4946 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4947 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4952 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4954 // Convert to float.
4955 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4956 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4957 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4958 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4959 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4960 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4962 // Use reciprocal estimate and one refinement step.
4963 // float4 recip = vrecpeq_f32(yf);
4964 // recip *= vrecpsq_f32(yf, recip);
4965 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4966 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4967 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4968 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4970 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4971 // Because short has a smaller range than ushort, we can actually get away
4972 // with only a single newton step. This requires that we use a weird bias
4973 // of 89, however (again, this has been exhaustively tested).
4974 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4975 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4976 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4977 N1 = DAG.getConstant(0x89, MVT::i32);
4978 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4979 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4980 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4981 // Convert back to integer and return.
4982 // return vmovn_s32(vcvt_s32_f32(result));
4983 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4984 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4988 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4989 EVT VT = Op.getValueType();
4990 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4991 "unexpected type for custom-lowering ISD::SDIV");
4993 DebugLoc dl = Op.getDebugLoc();
4994 SDValue N0 = Op.getOperand(0);
4995 SDValue N1 = Op.getOperand(1);
4998 if (VT == MVT::v8i8) {
4999 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5000 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5002 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5003 DAG.getIntPtrConstant(4));
5004 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5005 DAG.getIntPtrConstant(4));
5006 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5007 DAG.getIntPtrConstant(0));
5008 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5009 DAG.getIntPtrConstant(0));
5011 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5012 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5014 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5015 N0 = LowerCONCAT_VECTORS(N0, DAG);
5017 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5020 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5023 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5024 EVT VT = Op.getValueType();
5025 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5026 "unexpected type for custom-lowering ISD::UDIV");
5028 DebugLoc dl = Op.getDebugLoc();
5029 SDValue N0 = Op.getOperand(0);
5030 SDValue N1 = Op.getOperand(1);
5033 if (VT == MVT::v8i8) {
5034 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5035 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5037 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5038 DAG.getIntPtrConstant(4));
5039 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5040 DAG.getIntPtrConstant(4));
5041 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5042 DAG.getIntPtrConstant(0));
5043 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5044 DAG.getIntPtrConstant(0));
5046 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5047 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5049 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5050 N0 = LowerCONCAT_VECTORS(N0, DAG);
5052 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5053 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5058 // v4i16 sdiv ... Convert to float.
5059 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5060 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5061 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5062 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5063 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5064 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5066 // Use reciprocal estimate and two refinement steps.
5067 // float4 recip = vrecpeq_f32(yf);
5068 // recip *= vrecpsq_f32(yf, recip);
5069 // recip *= vrecpsq_f32(yf, recip);
5070 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5071 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5072 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5073 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5075 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5076 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5077 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5079 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5080 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5081 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5082 // and that it will never cause us to return an answer too large).
5083 // float4 result = as_float4(as_int4(xf*recip) + 2);
5084 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5085 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5086 N1 = DAG.getConstant(2, MVT::i32);
5087 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5088 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5089 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5090 // Convert back to integer and return.
5091 // return vmovn_u32(vcvt_s32_f32(result));
5092 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5093 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5097 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5098 EVT VT = Op.getNode()->getValueType(0);
5099 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5102 bool ExtraOp = false;
5103 switch (Op.getOpcode()) {
5104 default: llvm_unreachable("Invalid code");
5105 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5106 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5107 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5108 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5112 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5114 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5115 Op.getOperand(1), Op.getOperand(2));
5118 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5119 // Monotonic load/store is legal for all targets
5120 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5123 // Aquire/Release load/store is not legal for targets without a
5124 // dmb or equivalent available.
5130 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5131 SelectionDAG &DAG, unsigned NewOp) {
5132 DebugLoc dl = Node->getDebugLoc();
5133 assert (Node->getValueType(0) == MVT::i64 &&
5134 "Only know how to expand i64 atomics");
5136 SmallVector<SDValue, 6> Ops;
5137 Ops.push_back(Node->getOperand(0)); // Chain
5138 Ops.push_back(Node->getOperand(1)); // Ptr
5140 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5141 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5142 // High part of Val1
5143 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5144 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5145 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5146 // High part of Val1
5147 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5148 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5149 // High part of Val2
5150 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5151 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5153 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5155 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5156 cast<MemSDNode>(Node)->getMemOperand());
5157 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5158 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5159 Results.push_back(Result.getValue(2));
5162 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5163 switch (Op.getOpcode()) {
5164 default: llvm_unreachable("Don't know how to custom lower this!");
5165 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5166 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5167 case ISD::GlobalAddress:
5168 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5169 LowerGlobalAddressELF(Op, DAG);
5170 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5171 case ISD::SELECT: return LowerSELECT(Op, DAG);
5172 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5173 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5174 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5175 case ISD::VASTART: return LowerVASTART(Op, DAG);
5176 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5177 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5178 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5179 case ISD::SINT_TO_FP:
5180 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5181 case ISD::FP_TO_SINT:
5182 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5183 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5184 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5185 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5186 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5187 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5188 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5189 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5191 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5194 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5195 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5196 case ISD::SRL_PARTS:
5197 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5198 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5199 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5200 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5201 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5202 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5203 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5204 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5205 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5206 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5207 case ISD::MUL: return LowerMUL(Op, DAG);
5208 case ISD::SDIV: return LowerSDIV(Op, DAG);
5209 case ISD::UDIV: return LowerUDIV(Op, DAG);
5213 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5214 case ISD::ATOMIC_LOAD:
5215 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5219 /// ReplaceNodeResults - Replace the results of node with an illegal result
5220 /// type with new values built out of custom code.
5221 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5222 SmallVectorImpl<SDValue>&Results,
5223 SelectionDAG &DAG) const {
5225 switch (N->getOpcode()) {
5227 llvm_unreachable("Don't know how to custom expand this!");
5229 Res = ExpandBITCAST(N, DAG);
5233 Res = Expand64BitShift(N, DAG, Subtarget);
5235 case ISD::ATOMIC_LOAD_ADD:
5236 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5238 case ISD::ATOMIC_LOAD_AND:
5239 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5241 case ISD::ATOMIC_LOAD_NAND:
5242 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5244 case ISD::ATOMIC_LOAD_OR:
5245 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5247 case ISD::ATOMIC_LOAD_SUB:
5248 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5250 case ISD::ATOMIC_LOAD_XOR:
5251 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5253 case ISD::ATOMIC_SWAP:
5254 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5256 case ISD::ATOMIC_CMP_SWAP:
5257 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5261 Results.push_back(Res);
5264 //===----------------------------------------------------------------------===//
5265 // ARM Scheduler Hooks
5266 //===----------------------------------------------------------------------===//
5269 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5270 MachineBasicBlock *BB,
5271 unsigned Size) const {
5272 unsigned dest = MI->getOperand(0).getReg();
5273 unsigned ptr = MI->getOperand(1).getReg();
5274 unsigned oldval = MI->getOperand(2).getReg();
5275 unsigned newval = MI->getOperand(3).getReg();
5276 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5277 DebugLoc dl = MI->getDebugLoc();
5278 bool isThumb2 = Subtarget->isThumb2();
5280 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5281 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5282 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5283 (const TargetRegisterClass*)&ARM::GPRRegClass);
5286 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5287 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5288 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5291 unsigned ldrOpc, strOpc;
5293 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5295 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5296 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5299 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5300 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5303 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5304 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5308 MachineFunction *MF = BB->getParent();
5309 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5310 MachineFunction::iterator It = BB;
5311 ++It; // insert the new blocks after the current block
5313 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5314 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5315 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5316 MF->insert(It, loop1MBB);
5317 MF->insert(It, loop2MBB);
5318 MF->insert(It, exitMBB);
5320 // Transfer the remainder of BB and its successor edges to exitMBB.
5321 exitMBB->splice(exitMBB->begin(), BB,
5322 llvm::next(MachineBasicBlock::iterator(MI)),
5324 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5328 // fallthrough --> loop1MBB
5329 BB->addSuccessor(loop1MBB);
5332 // ldrex dest, [ptr]
5336 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5337 if (ldrOpc == ARM::t2LDREX)
5339 AddDefaultPred(MIB);
5340 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5341 .addReg(dest).addReg(oldval));
5342 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5343 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5344 BB->addSuccessor(loop2MBB);
5345 BB->addSuccessor(exitMBB);
5348 // strex scratch, newval, [ptr]
5352 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5353 if (strOpc == ARM::t2STREX)
5355 AddDefaultPred(MIB);
5356 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5357 .addReg(scratch).addImm(0));
5358 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5359 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5360 BB->addSuccessor(loop1MBB);
5361 BB->addSuccessor(exitMBB);
5367 MI->eraseFromParent(); // The instruction is gone now.
5373 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5374 unsigned Size, unsigned BinOpcode) const {
5375 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5376 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5378 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5379 MachineFunction *MF = BB->getParent();
5380 MachineFunction::iterator It = BB;
5383 unsigned dest = MI->getOperand(0).getReg();
5384 unsigned ptr = MI->getOperand(1).getReg();
5385 unsigned incr = MI->getOperand(2).getReg();
5386 DebugLoc dl = MI->getDebugLoc();
5387 bool isThumb2 = Subtarget->isThumb2();
5389 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5391 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5392 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5395 unsigned ldrOpc, strOpc;
5397 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5399 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5400 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5403 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5404 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5407 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5408 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5412 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5413 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5414 MF->insert(It, loopMBB);
5415 MF->insert(It, exitMBB);
5417 // Transfer the remainder of BB and its successor edges to exitMBB.
5418 exitMBB->splice(exitMBB->begin(), BB,
5419 llvm::next(MachineBasicBlock::iterator(MI)),
5421 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5423 const TargetRegisterClass *TRC = isThumb2 ?
5424 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5425 (const TargetRegisterClass*)&ARM::GPRRegClass;
5426 unsigned scratch = MRI.createVirtualRegister(TRC);
5427 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5431 // fallthrough --> loopMBB
5432 BB->addSuccessor(loopMBB);
5436 // <binop> scratch2, dest, incr
5437 // strex scratch, scratch2, ptr
5440 // fallthrough --> exitMBB
5442 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5443 if (ldrOpc == ARM::t2LDREX)
5445 AddDefaultPred(MIB);
5447 // operand order needs to go the other way for NAND
5448 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5449 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5450 addReg(incr).addReg(dest)).addReg(0);
5452 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5453 addReg(dest).addReg(incr)).addReg(0);
5456 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5457 if (strOpc == ARM::t2STREX)
5459 AddDefaultPred(MIB);
5460 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5461 .addReg(scratch).addImm(0));
5462 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5463 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5465 BB->addSuccessor(loopMBB);
5466 BB->addSuccessor(exitMBB);
5472 MI->eraseFromParent(); // The instruction is gone now.
5478 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5479 MachineBasicBlock *BB,
5482 ARMCC::CondCodes Cond) const {
5483 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5485 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5486 MachineFunction *MF = BB->getParent();
5487 MachineFunction::iterator It = BB;
5490 unsigned dest = MI->getOperand(0).getReg();
5491 unsigned ptr = MI->getOperand(1).getReg();
5492 unsigned incr = MI->getOperand(2).getReg();
5493 unsigned oldval = dest;
5494 DebugLoc dl = MI->getDebugLoc();
5495 bool isThumb2 = Subtarget->isThumb2();
5497 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5499 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5500 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5503 unsigned ldrOpc, strOpc, extendOpc;
5505 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5507 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5508 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5509 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5512 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5513 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5514 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5517 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5518 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5523 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5524 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5525 MF->insert(It, loopMBB);
5526 MF->insert(It, exitMBB);
5528 // Transfer the remainder of BB and its successor edges to exitMBB.
5529 exitMBB->splice(exitMBB->begin(), BB,
5530 llvm::next(MachineBasicBlock::iterator(MI)),
5532 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5534 const TargetRegisterClass *TRC = isThumb2 ?
5535 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5536 (const TargetRegisterClass*)&ARM::GPRRegClass;
5537 unsigned scratch = MRI.createVirtualRegister(TRC);
5538 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5542 // fallthrough --> loopMBB
5543 BB->addSuccessor(loopMBB);
5547 // (sign extend dest, if required)
5549 // cmov.cond scratch2, dest, incr
5550 // strex scratch, scratch2, ptr
5553 // fallthrough --> exitMBB
5555 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5556 if (ldrOpc == ARM::t2LDREX)
5558 AddDefaultPred(MIB);
5560 // Sign extend the value, if necessary.
5561 if (signExtend && extendOpc) {
5562 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5563 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5568 // Build compare and cmov instructions.
5569 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5570 .addReg(oldval).addReg(incr));
5571 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5572 .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5574 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5575 if (strOpc == ARM::t2STREX)
5577 AddDefaultPred(MIB);
5578 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5579 .addReg(scratch).addImm(0));
5580 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5581 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5583 BB->addSuccessor(loopMBB);
5584 BB->addSuccessor(exitMBB);
5590 MI->eraseFromParent(); // The instruction is gone now.
5596 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5597 unsigned Op1, unsigned Op2,
5598 bool NeedsCarry, bool IsCmpxchg) const {
5599 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5600 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5602 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5603 MachineFunction *MF = BB->getParent();
5604 MachineFunction::iterator It = BB;
5607 unsigned destlo = MI->getOperand(0).getReg();
5608 unsigned desthi = MI->getOperand(1).getReg();
5609 unsigned ptr = MI->getOperand(2).getReg();
5610 unsigned vallo = MI->getOperand(3).getReg();
5611 unsigned valhi = MI->getOperand(4).getReg();
5612 DebugLoc dl = MI->getDebugLoc();
5613 bool isThumb2 = Subtarget->isThumb2();
5615 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5617 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5618 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5619 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5622 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5623 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5625 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5626 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5628 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5629 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5631 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5632 MF->insert(It, loopMBB);
5634 MF->insert(It, contBB);
5635 MF->insert(It, cont2BB);
5637 MF->insert(It, exitMBB);
5639 // Transfer the remainder of BB and its successor edges to exitMBB.
5640 exitMBB->splice(exitMBB->begin(), BB,
5641 llvm::next(MachineBasicBlock::iterator(MI)),
5643 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5645 const TargetRegisterClass *TRC = isThumb2 ?
5646 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5647 (const TargetRegisterClass*)&ARM::GPRRegClass;
5648 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5652 // fallthrough --> loopMBB
5653 BB->addSuccessor(loopMBB);
5656 // ldrexd r2, r3, ptr
5657 // <binopa> r0, r2, incr
5658 // <binopb> r1, r3, incr
5659 // strexd storesuccess, r0, r1, ptr
5660 // cmp storesuccess, #0
5662 // fallthrough --> exitMBB
5664 // Note that the registers are explicitly specified because there is not any
5665 // way to force the register allocator to allocate a register pair.
5667 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5668 // need to properly enforce the restriction that the two output registers
5669 // for ldrexd must be different.
5672 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5673 .addReg(ARM::R2, RegState::Define)
5674 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5675 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
5676 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5677 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5681 for (unsigned i = 0; i < 2; i++) {
5682 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5684 .addReg(i == 0 ? destlo : desthi)
5685 .addReg(i == 0 ? vallo : valhi));
5686 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5687 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5688 BB->addSuccessor(exitMBB);
5689 BB->addSuccessor(i == 0 ? contBB : cont2BB);
5690 BB = (i == 0 ? contBB : cont2BB);
5693 // Copy to physregs for strexd
5694 unsigned setlo = MI->getOperand(5).getReg();
5695 unsigned sethi = MI->getOperand(6).getReg();
5696 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5697 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5699 // Perform binary operation
5700 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5701 .addReg(destlo).addReg(vallo))
5702 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5703 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5704 .addReg(desthi).addReg(valhi)).addReg(0);
5706 // Copy to physregs for strexd
5707 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5708 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5712 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5713 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5715 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5716 .addReg(storesuccess).addImm(0));
5717 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5718 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5720 BB->addSuccessor(loopMBB);
5721 BB->addSuccessor(exitMBB);
5727 MI->eraseFromParent(); // The instruction is gone now.
5732 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5733 /// registers the function context.
5734 void ARMTargetLowering::
5735 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5736 MachineBasicBlock *DispatchBB, int FI) const {
5737 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5738 DebugLoc dl = MI->getDebugLoc();
5739 MachineFunction *MF = MBB->getParent();
5740 MachineRegisterInfo *MRI = &MF->getRegInfo();
5741 MachineConstantPool *MCP = MF->getConstantPool();
5742 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5743 const Function *F = MF->getFunction();
5745 bool isThumb = Subtarget->isThumb();
5746 bool isThumb2 = Subtarget->isThumb2();
5748 unsigned PCLabelId = AFI->createPICLabelUId();
5749 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5750 ARMConstantPoolValue *CPV =
5751 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5752 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5754 const TargetRegisterClass *TRC = isThumb ?
5755 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5756 (const TargetRegisterClass*)&ARM::GPRRegClass;
5758 // Grab constant pool and fixed stack memory operands.
5759 MachineMemOperand *CPMMO =
5760 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5761 MachineMemOperand::MOLoad, 4, 4);
5763 MachineMemOperand *FIMMOSt =
5764 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5765 MachineMemOperand::MOStore, 4, 4);
5767 // Load the address of the dispatch MBB into the jump buffer.
5769 // Incoming value: jbuf
5770 // ldr.n r5, LCPI1_1
5773 // str r5, [$jbuf, #+4] ; &jbuf[1]
5774 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5775 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5776 .addConstantPoolIndex(CPI)
5777 .addMemOperand(CPMMO));
5778 // Set the low bit because of thumb mode.
5779 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5781 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5782 .addReg(NewVReg1, RegState::Kill)
5784 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5785 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5786 .addReg(NewVReg2, RegState::Kill)
5788 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5789 .addReg(NewVReg3, RegState::Kill)
5791 .addImm(36) // &jbuf[1] :: pc
5792 .addMemOperand(FIMMOSt));
5793 } else if (isThumb) {
5794 // Incoming value: jbuf
5795 // ldr.n r1, LCPI1_4
5799 // add r2, $jbuf, #+4 ; &jbuf[1]
5801 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5802 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5803 .addConstantPoolIndex(CPI)
5804 .addMemOperand(CPMMO));
5805 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5806 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5807 .addReg(NewVReg1, RegState::Kill)
5809 // Set the low bit because of thumb mode.
5810 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5811 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5812 .addReg(ARM::CPSR, RegState::Define)
5814 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5815 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5816 .addReg(ARM::CPSR, RegState::Define)
5817 .addReg(NewVReg2, RegState::Kill)
5818 .addReg(NewVReg3, RegState::Kill));
5819 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5820 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5822 .addImm(36)); // &jbuf[1] :: pc
5823 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5824 .addReg(NewVReg4, RegState::Kill)
5825 .addReg(NewVReg5, RegState::Kill)
5827 .addMemOperand(FIMMOSt));
5829 // Incoming value: jbuf
5832 // str r1, [$jbuf, #+4] ; &jbuf[1]
5833 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5834 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
5835 .addConstantPoolIndex(CPI)
5837 .addMemOperand(CPMMO));
5838 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5839 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5840 .addReg(NewVReg1, RegState::Kill)
5841 .addImm(PCLabelId));
5842 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5843 .addReg(NewVReg2, RegState::Kill)
5845 .addImm(36) // &jbuf[1] :: pc
5846 .addMemOperand(FIMMOSt));
5850 MachineBasicBlock *ARMTargetLowering::
5851 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5852 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5853 DebugLoc dl = MI->getDebugLoc();
5854 MachineFunction *MF = MBB->getParent();
5855 MachineRegisterInfo *MRI = &MF->getRegInfo();
5856 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5857 MachineFrameInfo *MFI = MF->getFrameInfo();
5858 int FI = MFI->getFunctionContextIndex();
5860 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5861 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5862 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5864 // Get a mapping of the call site numbers to all of the landing pads they're
5866 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5867 unsigned MaxCSNum = 0;
5868 MachineModuleInfo &MMI = MF->getMMI();
5869 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5871 if (!BB->isLandingPad()) continue;
5873 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5875 for (MachineBasicBlock::iterator
5876 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5877 if (!II->isEHLabel()) continue;
5879 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5880 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5882 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5883 for (SmallVectorImpl<unsigned>::iterator
5884 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5885 CSI != CSE; ++CSI) {
5886 CallSiteNumToLPad[*CSI].push_back(BB);
5887 MaxCSNum = std::max(MaxCSNum, *CSI);
5893 // Get an ordered list of the machine basic blocks for the jump table.
5894 std::vector<MachineBasicBlock*> LPadList;
5895 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5896 LPadList.reserve(CallSiteNumToLPad.size());
5897 for (unsigned I = 1; I <= MaxCSNum; ++I) {
5898 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5899 for (SmallVectorImpl<MachineBasicBlock*>::iterator
5900 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5901 LPadList.push_back(*II);
5902 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5906 assert(!LPadList.empty() &&
5907 "No landing pad destinations for the dispatch jump table!");
5909 // Create the jump table and associated information.
5910 MachineJumpTableInfo *JTI =
5911 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5912 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5913 unsigned UId = AFI->createJumpTableUId();
5915 // Create the MBBs for the dispatch code.
5917 // Shove the dispatch's address into the return slot in the function context.
5918 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5919 DispatchBB->setIsLandingPad();
5921 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5922 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5923 DispatchBB->addSuccessor(TrapBB);
5925 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5926 DispatchBB->addSuccessor(DispContBB);
5929 MF->insert(MF->end(), DispatchBB);
5930 MF->insert(MF->end(), DispContBB);
5931 MF->insert(MF->end(), TrapBB);
5933 // Insert code into the entry block that creates and registers the function
5935 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5937 MachineMemOperand *FIMMOLd =
5938 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5939 MachineMemOperand::MOLoad |
5940 MachineMemOperand::MOVolatile, 4, 4);
5942 if (AFI->isThumb1OnlyFunction())
5943 BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5944 else if (!Subtarget->hasVFP2())
5945 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5947 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5949 unsigned NumLPads = LPadList.size();
5950 if (Subtarget->isThumb2()) {
5951 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5952 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5955 .addMemOperand(FIMMOLd));
5957 if (NumLPads < 256) {
5958 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5960 .addImm(LPadList.size()));
5962 unsigned VReg1 = MRI->createVirtualRegister(TRC);
5963 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5964 .addImm(NumLPads & 0xFFFF));
5966 unsigned VReg2 = VReg1;
5967 if ((NumLPads & 0xFFFF0000) != 0) {
5968 VReg2 = MRI->createVirtualRegister(TRC);
5969 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5971 .addImm(NumLPads >> 16));
5974 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5979 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5984 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5985 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5986 .addJumpTableIndex(MJTI)
5989 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5992 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5993 .addReg(NewVReg3, RegState::Kill)
5995 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5997 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5998 .addReg(NewVReg4, RegState::Kill)
6000 .addJumpTableIndex(MJTI)
6002 } else if (Subtarget->isThumb()) {
6003 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6004 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6007 .addMemOperand(FIMMOLd));
6009 if (NumLPads < 256) {
6010 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6014 MachineConstantPool *ConstantPool = MF->getConstantPool();
6015 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6016 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6018 // MachineConstantPool wants an explicit alignment.
6019 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6021 Align = getTargetData()->getTypeAllocSize(C->getType());
6022 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6024 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6025 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6026 .addReg(VReg1, RegState::Define)
6027 .addConstantPoolIndex(Idx));
6028 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6033 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6038 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6039 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6040 .addReg(ARM::CPSR, RegState::Define)
6044 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6045 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6046 .addJumpTableIndex(MJTI)
6049 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6050 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6051 .addReg(ARM::CPSR, RegState::Define)
6052 .addReg(NewVReg2, RegState::Kill)
6055 MachineMemOperand *JTMMOLd =
6056 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6057 MachineMemOperand::MOLoad, 4, 4);
6059 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6060 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6061 .addReg(NewVReg4, RegState::Kill)
6063 .addMemOperand(JTMMOLd));
6065 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6066 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6067 .addReg(ARM::CPSR, RegState::Define)
6068 .addReg(NewVReg5, RegState::Kill)
6071 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6072 .addReg(NewVReg6, RegState::Kill)
6073 .addJumpTableIndex(MJTI)
6076 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6077 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6080 .addMemOperand(FIMMOLd));
6082 if (NumLPads < 256) {
6083 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6086 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6087 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6088 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6089 .addImm(NumLPads & 0xFFFF));
6091 unsigned VReg2 = VReg1;
6092 if ((NumLPads & 0xFFFF0000) != 0) {
6093 VReg2 = MRI->createVirtualRegister(TRC);
6094 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6096 .addImm(NumLPads >> 16));
6099 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6103 MachineConstantPool *ConstantPool = MF->getConstantPool();
6104 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6105 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6107 // MachineConstantPool wants an explicit alignment.
6108 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6110 Align = getTargetData()->getTypeAllocSize(C->getType());
6111 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6113 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6114 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6115 .addReg(VReg1, RegState::Define)
6116 .addConstantPoolIndex(Idx)
6118 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6120 .addReg(VReg1, RegState::Kill));
6123 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6128 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6130 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6132 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6133 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6134 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6135 .addJumpTableIndex(MJTI)
6138 MachineMemOperand *JTMMOLd =
6139 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6140 MachineMemOperand::MOLoad, 4, 4);
6141 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6143 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6144 .addReg(NewVReg3, RegState::Kill)
6147 .addMemOperand(JTMMOLd));
6149 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6150 .addReg(NewVReg5, RegState::Kill)
6152 .addJumpTableIndex(MJTI)
6156 // Add the jump table entries as successors to the MBB.
6157 MachineBasicBlock *PrevMBB = 0;
6158 for (std::vector<MachineBasicBlock*>::iterator
6159 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6160 MachineBasicBlock *CurMBB = *I;
6161 if (PrevMBB != CurMBB)
6162 DispContBB->addSuccessor(CurMBB);
6166 // N.B. the order the invoke BBs are processed in doesn't matter here.
6167 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6168 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6169 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6170 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6171 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6172 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6173 MachineBasicBlock *BB = *I;
6175 // Remove the landing pad successor from the invoke block and replace it
6176 // with the new dispatch block.
6177 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6179 while (!Successors.empty()) {
6180 MachineBasicBlock *SMBB = Successors.pop_back_val();
6181 if (SMBB->isLandingPad()) {
6182 BB->removeSuccessor(SMBB);
6183 MBBLPads.push_back(SMBB);
6187 BB->addSuccessor(DispatchBB);
6189 // Find the invoke call and mark all of the callee-saved registers as
6190 // 'implicit defined' so that they're spilled. This prevents code from
6191 // moving instructions to before the EH block, where they will never be
6193 for (MachineBasicBlock::reverse_iterator
6194 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6195 if (!II->isCall()) continue;
6197 DenseMap<unsigned, bool> DefRegs;
6198 for (MachineInstr::mop_iterator
6199 OI = II->operands_begin(), OE = II->operands_end();
6201 if (!OI->isReg()) continue;
6202 DefRegs[OI->getReg()] = true;
6205 MachineInstrBuilder MIB(&*II);
6207 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6208 unsigned Reg = SavedRegs[i];
6209 if (Subtarget->isThumb2() &&
6210 !ARM::tGPRRegClass.contains(Reg) &&
6211 !ARM::hGPRRegClass.contains(Reg))
6213 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6215 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6218 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6225 // Mark all former landing pads as non-landing pads. The dispatch is the only
6227 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6228 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6229 (*I)->setIsLandingPad(false);
6231 // The instruction is gone now.
6232 MI->eraseFromParent();
6238 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6239 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6240 E = MBB->succ_end(); I != E; ++I)
6243 llvm_unreachable("Expecting a BB with two successors!");
6246 MachineBasicBlock *ARMTargetLowering::
6247 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6248 // This pseudo instruction has 3 operands: dst, src, size
6249 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6250 // Otherwise, we will generate unrolled scalar copies.
6251 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6252 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6253 MachineFunction::iterator It = BB;
6256 unsigned dest = MI->getOperand(0).getReg();
6257 unsigned src = MI->getOperand(1).getReg();
6258 unsigned SizeVal = MI->getOperand(2).getImm();
6259 unsigned Align = MI->getOperand(3).getImm();
6260 DebugLoc dl = MI->getDebugLoc();
6262 bool isThumb2 = Subtarget->isThumb2();
6263 MachineFunction *MF = BB->getParent();
6264 MachineRegisterInfo &MRI = MF->getRegInfo();
6265 unsigned ldrOpc, strOpc, UnitSize = 0;
6267 const TargetRegisterClass *TRC = isThumb2 ?
6268 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6269 (const TargetRegisterClass*)&ARM::GPRRegClass;
6270 const TargetRegisterClass *TRC_Vec = 0;
6273 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6274 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6276 } else if (Align & 2) {
6277 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6278 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6281 // Check whether we can use NEON instructions.
6282 if (!MF->getFunction()->hasFnAttr(Attribute::NoImplicitFloat) &&
6283 Subtarget->hasNEON()) {
6284 if ((Align % 16 == 0) && SizeVal >= 16) {
6285 ldrOpc = ARM::VLD1q32wb_fixed;
6286 strOpc = ARM::VST1q32wb_fixed;
6288 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6290 else if ((Align % 8 == 0) && SizeVal >= 8) {
6291 ldrOpc = ARM::VLD1d32wb_fixed;
6292 strOpc = ARM::VST1d32wb_fixed;
6294 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6297 // Can't use NEON instructions.
6298 if (UnitSize == 0) {
6299 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6300 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6305 unsigned BytesLeft = SizeVal % UnitSize;
6306 unsigned LoopSize = SizeVal - BytesLeft;
6308 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6309 // Use LDR and STR to copy.
6310 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6311 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6312 unsigned srcIn = src;
6313 unsigned destIn = dest;
6314 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6315 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6316 unsigned srcOut = MRI.createVirtualRegister(TRC);
6317 unsigned destOut = MRI.createVirtualRegister(TRC);
6318 if (UnitSize >= 8) {
6319 AddDefaultPred(BuildMI(*BB, MI, dl,
6320 TII->get(ldrOpc), scratch)
6321 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6323 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6324 .addReg(destIn).addImm(0).addReg(scratch));
6325 } else if (isThumb2) {
6326 AddDefaultPred(BuildMI(*BB, MI, dl,
6327 TII->get(ldrOpc), scratch)
6328 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6330 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6331 .addReg(scratch).addReg(destIn)
6334 AddDefaultPred(BuildMI(*BB, MI, dl,
6335 TII->get(ldrOpc), scratch)
6336 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6339 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6340 .addReg(scratch).addReg(destIn)
6341 .addReg(0).addImm(UnitSize));
6347 // Handle the leftover bytes with LDRB and STRB.
6348 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6349 // [destOut] = STRB_POST(scratch, destIn, 1)
6350 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6351 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6352 for (unsigned i = 0; i < BytesLeft; i++) {
6353 unsigned scratch = MRI.createVirtualRegister(TRC);
6354 unsigned srcOut = MRI.createVirtualRegister(TRC);
6355 unsigned destOut = MRI.createVirtualRegister(TRC);
6357 AddDefaultPred(BuildMI(*BB, MI, dl,
6358 TII->get(ldrOpc),scratch)
6359 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6361 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6362 .addReg(scratch).addReg(destIn)
6363 .addReg(0).addImm(1));
6365 AddDefaultPred(BuildMI(*BB, MI, dl,
6366 TII->get(ldrOpc),scratch)
6367 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6369 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6370 .addReg(scratch).addReg(destIn)
6371 .addReg(0).addImm(1));
6376 MI->eraseFromParent(); // The instruction is gone now.
6380 // Expand the pseudo op to a loop.
6383 // movw varEnd, # --> with thumb2
6385 // ldrcp varEnd, idx --> without thumb2
6386 // fallthrough --> loopMBB
6388 // PHI varPhi, varEnd, varLoop
6389 // PHI srcPhi, src, srcLoop
6390 // PHI destPhi, dst, destLoop
6391 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6392 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6393 // subs varLoop, varPhi, #UnitSize
6395 // fallthrough --> exitMBB
6397 // epilogue to handle left-over bytes
6398 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6399 // [destOut] = STRB_POST(scratch, destLoop, 1)
6400 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6401 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6402 MF->insert(It, loopMBB);
6403 MF->insert(It, exitMBB);
6405 // Transfer the remainder of BB and its successor edges to exitMBB.
6406 exitMBB->splice(exitMBB->begin(), BB,
6407 llvm::next(MachineBasicBlock::iterator(MI)),
6409 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6411 // Load an immediate to varEnd.
6412 unsigned varEnd = MRI.createVirtualRegister(TRC);
6414 unsigned VReg1 = varEnd;
6415 if ((LoopSize & 0xFFFF0000) != 0)
6416 VReg1 = MRI.createVirtualRegister(TRC);
6417 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6418 .addImm(LoopSize & 0xFFFF));
6420 if ((LoopSize & 0xFFFF0000) != 0)
6421 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6423 .addImm(LoopSize >> 16));
6425 MachineConstantPool *ConstantPool = MF->getConstantPool();
6426 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6427 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6429 // MachineConstantPool wants an explicit alignment.
6430 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6432 Align = getTargetData()->getTypeAllocSize(C->getType());
6433 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6435 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6436 .addReg(varEnd, RegState::Define)
6437 .addConstantPoolIndex(Idx)
6440 BB->addSuccessor(loopMBB);
6442 // Generate the loop body:
6443 // varPhi = PHI(varLoop, varEnd)
6444 // srcPhi = PHI(srcLoop, src)
6445 // destPhi = PHI(destLoop, dst)
6446 MachineBasicBlock *entryBB = BB;
6448 unsigned varLoop = MRI.createVirtualRegister(TRC);
6449 unsigned varPhi = MRI.createVirtualRegister(TRC);
6450 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6451 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6452 unsigned destLoop = MRI.createVirtualRegister(TRC);
6453 unsigned destPhi = MRI.createVirtualRegister(TRC);
6455 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6456 .addReg(varLoop).addMBB(loopMBB)
6457 .addReg(varEnd).addMBB(entryBB);
6458 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6459 .addReg(srcLoop).addMBB(loopMBB)
6460 .addReg(src).addMBB(entryBB);
6461 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6462 .addReg(destLoop).addMBB(loopMBB)
6463 .addReg(dest).addMBB(entryBB);
6465 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6466 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6467 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6468 if (UnitSize >= 8) {
6469 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6470 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6472 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6473 .addReg(destPhi).addImm(0).addReg(scratch));
6474 } else if (isThumb2) {
6475 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6476 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6478 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6479 .addReg(scratch).addReg(destPhi)
6482 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6483 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6486 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6487 .addReg(scratch).addReg(destPhi)
6488 .addReg(0).addImm(UnitSize));
6491 // Decrement loop variable by UnitSize.
6492 MachineInstrBuilder MIB = BuildMI(BB, dl,
6493 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6494 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6495 MIB->getOperand(5).setReg(ARM::CPSR);
6496 MIB->getOperand(5).setIsDef(true);
6498 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6499 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6501 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6502 BB->addSuccessor(loopMBB);
6503 BB->addSuccessor(exitMBB);
6505 // Add epilogue to handle BytesLeft.
6507 MachineInstr *StartOfExit = exitMBB->begin();
6508 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6509 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6511 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6512 // [destOut] = STRB_POST(scratch, destLoop, 1)
6513 unsigned srcIn = srcLoop;
6514 unsigned destIn = destLoop;
6515 for (unsigned i = 0; i < BytesLeft; i++) {
6516 unsigned scratch = MRI.createVirtualRegister(TRC);
6517 unsigned srcOut = MRI.createVirtualRegister(TRC);
6518 unsigned destOut = MRI.createVirtualRegister(TRC);
6520 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6521 TII->get(ldrOpc),scratch)
6522 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6524 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6525 .addReg(scratch).addReg(destIn)
6528 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6529 TII->get(ldrOpc),scratch)
6530 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6532 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6533 .addReg(scratch).addReg(destIn)
6534 .addReg(0).addImm(1));
6540 MI->eraseFromParent(); // The instruction is gone now.
6545 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6546 MachineBasicBlock *BB) const {
6547 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6548 DebugLoc dl = MI->getDebugLoc();
6549 bool isThumb2 = Subtarget->isThumb2();
6550 switch (MI->getOpcode()) {
6553 llvm_unreachable("Unexpected instr type to insert");
6555 // The Thumb2 pre-indexed stores have the same MI operands, they just
6556 // define them differently in the .td files from the isel patterns, so
6557 // they need pseudos.
6558 case ARM::t2STR_preidx:
6559 MI->setDesc(TII->get(ARM::t2STR_PRE));
6561 case ARM::t2STRB_preidx:
6562 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6564 case ARM::t2STRH_preidx:
6565 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6568 case ARM::STRi_preidx:
6569 case ARM::STRBi_preidx: {
6570 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6571 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6572 // Decode the offset.
6573 unsigned Offset = MI->getOperand(4).getImm();
6574 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6575 Offset = ARM_AM::getAM2Offset(Offset);
6579 MachineMemOperand *MMO = *MI->memoperands_begin();
6580 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6581 .addOperand(MI->getOperand(0)) // Rn_wb
6582 .addOperand(MI->getOperand(1)) // Rt
6583 .addOperand(MI->getOperand(2)) // Rn
6584 .addImm(Offset) // offset (skip GPR==zero_reg)
6585 .addOperand(MI->getOperand(5)) // pred
6586 .addOperand(MI->getOperand(6))
6587 .addMemOperand(MMO);
6588 MI->eraseFromParent();
6591 case ARM::STRr_preidx:
6592 case ARM::STRBr_preidx:
6593 case ARM::STRH_preidx: {
6595 switch (MI->getOpcode()) {
6596 default: llvm_unreachable("unexpected opcode!");
6597 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6598 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6599 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6601 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6602 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6603 MIB.addOperand(MI->getOperand(i));
6604 MI->eraseFromParent();
6607 case ARM::ATOMIC_LOAD_ADD_I8:
6608 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6609 case ARM::ATOMIC_LOAD_ADD_I16:
6610 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6611 case ARM::ATOMIC_LOAD_ADD_I32:
6612 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6614 case ARM::ATOMIC_LOAD_AND_I8:
6615 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6616 case ARM::ATOMIC_LOAD_AND_I16:
6617 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6618 case ARM::ATOMIC_LOAD_AND_I32:
6619 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6621 case ARM::ATOMIC_LOAD_OR_I8:
6622 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6623 case ARM::ATOMIC_LOAD_OR_I16:
6624 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6625 case ARM::ATOMIC_LOAD_OR_I32:
6626 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6628 case ARM::ATOMIC_LOAD_XOR_I8:
6629 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6630 case ARM::ATOMIC_LOAD_XOR_I16:
6631 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6632 case ARM::ATOMIC_LOAD_XOR_I32:
6633 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6635 case ARM::ATOMIC_LOAD_NAND_I8:
6636 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6637 case ARM::ATOMIC_LOAD_NAND_I16:
6638 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6639 case ARM::ATOMIC_LOAD_NAND_I32:
6640 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6642 case ARM::ATOMIC_LOAD_SUB_I8:
6643 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6644 case ARM::ATOMIC_LOAD_SUB_I16:
6645 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6646 case ARM::ATOMIC_LOAD_SUB_I32:
6647 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6649 case ARM::ATOMIC_LOAD_MIN_I8:
6650 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6651 case ARM::ATOMIC_LOAD_MIN_I16:
6652 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6653 case ARM::ATOMIC_LOAD_MIN_I32:
6654 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6656 case ARM::ATOMIC_LOAD_MAX_I8:
6657 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6658 case ARM::ATOMIC_LOAD_MAX_I16:
6659 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6660 case ARM::ATOMIC_LOAD_MAX_I32:
6661 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6663 case ARM::ATOMIC_LOAD_UMIN_I8:
6664 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6665 case ARM::ATOMIC_LOAD_UMIN_I16:
6666 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6667 case ARM::ATOMIC_LOAD_UMIN_I32:
6668 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6670 case ARM::ATOMIC_LOAD_UMAX_I8:
6671 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6672 case ARM::ATOMIC_LOAD_UMAX_I16:
6673 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6674 case ARM::ATOMIC_LOAD_UMAX_I32:
6675 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6677 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
6678 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6679 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6681 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
6682 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6683 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6686 case ARM::ATOMADD6432:
6687 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6688 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6689 /*NeedsCarry*/ true);
6690 case ARM::ATOMSUB6432:
6691 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6692 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6693 /*NeedsCarry*/ true);
6694 case ARM::ATOMOR6432:
6695 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6696 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6697 case ARM::ATOMXOR6432:
6698 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6699 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6700 case ARM::ATOMAND6432:
6701 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6702 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6703 case ARM::ATOMSWAP6432:
6704 return EmitAtomicBinary64(MI, BB, 0, 0, false);
6705 case ARM::ATOMCMPXCHG6432:
6706 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6707 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6708 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6710 case ARM::tMOVCCr_pseudo: {
6711 // To "insert" a SELECT_CC instruction, we actually have to insert the
6712 // diamond control-flow pattern. The incoming instruction knows the
6713 // destination vreg to set, the condition code register to branch on, the
6714 // true/false values to select between, and a branch opcode to use.
6715 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6716 MachineFunction::iterator It = BB;
6722 // cmpTY ccX, r1, r2
6724 // fallthrough --> copy0MBB
6725 MachineBasicBlock *thisMBB = BB;
6726 MachineFunction *F = BB->getParent();
6727 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6728 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6729 F->insert(It, copy0MBB);
6730 F->insert(It, sinkMBB);
6732 // Transfer the remainder of BB and its successor edges to sinkMBB.
6733 sinkMBB->splice(sinkMBB->begin(), BB,
6734 llvm::next(MachineBasicBlock::iterator(MI)),
6736 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6738 BB->addSuccessor(copy0MBB);
6739 BB->addSuccessor(sinkMBB);
6741 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6742 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6745 // %FalseValue = ...
6746 // # fallthrough to sinkMBB
6749 // Update machine-CFG edges
6750 BB->addSuccessor(sinkMBB);
6753 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6756 BuildMI(*BB, BB->begin(), dl,
6757 TII->get(ARM::PHI), MI->getOperand(0).getReg())
6758 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6759 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6761 MI->eraseFromParent(); // The pseudo instruction is gone now.
6766 case ARM::BCCZi64: {
6767 // If there is an unconditional branch to the other successor, remove it.
6768 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6770 // Compare both parts that make up the double comparison separately for
6772 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6774 unsigned LHS1 = MI->getOperand(1).getReg();
6775 unsigned LHS2 = MI->getOperand(2).getReg();
6777 AddDefaultPred(BuildMI(BB, dl,
6778 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6779 .addReg(LHS1).addImm(0));
6780 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6781 .addReg(LHS2).addImm(0)
6782 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6784 unsigned RHS1 = MI->getOperand(3).getReg();
6785 unsigned RHS2 = MI->getOperand(4).getReg();
6786 AddDefaultPred(BuildMI(BB, dl,
6787 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6788 .addReg(LHS1).addReg(RHS1));
6789 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6790 .addReg(LHS2).addReg(RHS2)
6791 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6794 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6795 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6796 if (MI->getOperand(0).getImm() == ARMCC::NE)
6797 std::swap(destMBB, exitMBB);
6799 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6800 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6802 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6804 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6806 MI->eraseFromParent(); // The pseudo instruction is gone now.
6810 case ARM::Int_eh_sjlj_setjmp:
6811 case ARM::Int_eh_sjlj_setjmp_nofp:
6812 case ARM::tInt_eh_sjlj_setjmp:
6813 case ARM::t2Int_eh_sjlj_setjmp:
6814 case ARM::t2Int_eh_sjlj_setjmp_nofp:
6815 EmitSjLjDispatchBlock(MI, BB);
6820 // To insert an ABS instruction, we have to insert the
6821 // diamond control-flow pattern. The incoming instruction knows the
6822 // source vreg to test against 0, the destination vreg to set,
6823 // the condition code register to branch on, the
6824 // true/false values to select between, and a branch opcode to use.
6829 // BCC (branch to SinkBB if V0 >= 0)
6830 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
6831 // SinkBB: V1 = PHI(V2, V3)
6832 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6833 MachineFunction::iterator BBI = BB;
6835 MachineFunction *Fn = BB->getParent();
6836 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6837 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6838 Fn->insert(BBI, RSBBB);
6839 Fn->insert(BBI, SinkBB);
6841 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6842 unsigned int ABSDstReg = MI->getOperand(0).getReg();
6843 bool isThumb2 = Subtarget->isThumb2();
6844 MachineRegisterInfo &MRI = Fn->getRegInfo();
6845 // In Thumb mode S must not be specified if source register is the SP or
6846 // PC and if destination register is the SP, so restrict register class
6847 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6848 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6849 (const TargetRegisterClass*)&ARM::GPRRegClass);
6851 // Transfer the remainder of BB and its successor edges to sinkMBB.
6852 SinkBB->splice(SinkBB->begin(), BB,
6853 llvm::next(MachineBasicBlock::iterator(MI)),
6855 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6857 BB->addSuccessor(RSBBB);
6858 BB->addSuccessor(SinkBB);
6860 // fall through to SinkMBB
6861 RSBBB->addSuccessor(SinkBB);
6863 // insert a cmp at the end of BB
6864 AddDefaultPred(BuildMI(BB, dl,
6865 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6866 .addReg(ABSSrcReg).addImm(0));
6868 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6870 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6871 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6873 // insert rsbri in RSBBB
6874 // Note: BCC and rsbri will be converted into predicated rsbmi
6875 // by if-conversion pass
6876 BuildMI(*RSBBB, RSBBB->begin(), dl,
6877 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6878 .addReg(ABSSrcReg, RegState::Kill)
6879 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6881 // insert PHI in SinkBB,
6882 // reuse ABSDstReg to not change uses of ABS instruction
6883 BuildMI(*SinkBB, SinkBB->begin(), dl,
6884 TII->get(ARM::PHI), ABSDstReg)
6885 .addReg(NewRsbDstReg).addMBB(RSBBB)
6886 .addReg(ABSSrcReg).addMBB(BB);
6888 // remove ABS instruction
6889 MI->eraseFromParent();
6891 // return last added BB
6894 case ARM::COPY_STRUCT_BYVAL_I32:
6896 return EmitStructByval(MI, BB);
6900 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6901 SDNode *Node) const {
6902 if (!MI->hasPostISelHook()) {
6903 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6904 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6908 const MCInstrDesc *MCID = &MI->getDesc();
6909 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6910 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6911 // operand is still set to noreg. If needed, set the optional operand's
6912 // register to CPSR, and remove the redundant implicit def.
6914 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6916 // Rename pseudo opcodes.
6917 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6919 const ARMBaseInstrInfo *TII =
6920 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6921 MCID = &TII->get(NewOpc);
6923 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6924 "converted opcode should be the same except for cc_out");
6928 // Add the optional cc_out operand
6929 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6931 unsigned ccOutIdx = MCID->getNumOperands() - 1;
6933 // Any ARM instruction that sets the 's' bit should specify an optional
6934 // "cc_out" operand in the last operand position.
6935 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6936 assert(!NewOpc && "Optional cc_out operand required");
6939 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6940 // since we already have an optional CPSR def.
6941 bool definesCPSR = false;
6942 bool deadCPSR = false;
6943 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6945 const MachineOperand &MO = MI->getOperand(i);
6946 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6950 MI->RemoveOperand(i);
6955 assert(!NewOpc && "Optional cc_out operand required");
6958 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6960 assert(!MI->getOperand(ccOutIdx).getReg() &&
6961 "expect uninitialized optional cc_out operand");
6965 // If this instruction was defined with an optional CPSR def and its dag node
6966 // had a live implicit CPSR def, then activate the optional CPSR def.
6967 MachineOperand &MO = MI->getOperand(ccOutIdx);
6968 MO.setReg(ARM::CPSR);
6972 //===----------------------------------------------------------------------===//
6973 // ARM Optimization Hooks
6974 //===----------------------------------------------------------------------===//
6976 // Helper function that checks if N is a null or all ones constant.
6977 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
6978 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
6981 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
6984 // Combine a constant select operand into its use:
6986 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
6987 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6988 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
6989 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
6990 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
6992 // The transform is rejected if the select doesn't have a constant operand that
6993 // is null, or all ones when AllOnes is set.
6995 // @param N The node to transform.
6996 // @param Slct The N operand that is a select.
6997 // @param OtherOp The other N operand (x above).
6998 // @param DCI Context.
6999 // @param AllOnes Require the select constant to be all ones instead of null.
7000 // @returns The new node, or SDValue() on failure.
7002 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7003 TargetLowering::DAGCombinerInfo &DCI,
7004 bool AllOnes = false) {
7005 SelectionDAG &DAG = DCI.DAG;
7006 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7007 EVT VT = N->getValueType(0);
7008 unsigned Opc = N->getOpcode();
7009 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
7010 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
7011 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
7012 ISD::CondCode CC = ISD::SETCC_INVALID;
7015 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
7017 SDValue CCOp = Slct.getOperand(0);
7018 if (CCOp.getOpcode() == ISD::SETCC)
7019 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
7022 bool DoXform = false;
7024 if (isZeroOrAllOnes(LHS, AllOnes)) {
7026 } else if (CC != ISD::SETCC_INVALID && isZeroOrAllOnes(RHS, AllOnes)) {
7027 std::swap(LHS, RHS);
7028 SDValue Op0 = Slct.getOperand(0);
7029 EVT OpVT = isSlctCC ? Op0.getValueType() : Op0.getOperand(0).getValueType();
7030 bool isInt = OpVT.isInteger();
7031 CC = ISD::getSetCCInverse(CC, isInt);
7033 if (!TLI.isCondCodeLegal(CC, OpVT))
7034 return SDValue(); // Inverse operator isn't legal.
7043 SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
7045 return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
7046 Slct.getOperand(0), Slct.getOperand(1), CC);
7047 SDValue CCOp = Slct.getOperand(0);
7049 CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
7050 CCOp.getOperand(0), CCOp.getOperand(1), CC);
7051 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7052 CCOp, OtherOp, Result);
7055 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7057 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7058 TargetLowering::DAGCombinerInfo &DCI) {
7059 SDValue N0 = N->getOperand(0);
7060 SDValue N1 = N->getOperand(1);
7061 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
7062 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7063 if (Result.getNode())
7066 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
7067 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7068 if (Result.getNode())
7074 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7075 // (only after legalization).
7076 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7077 TargetLowering::DAGCombinerInfo &DCI,
7078 const ARMSubtarget *Subtarget) {
7080 // Only perform optimization if after legalize, and if NEON is available. We
7081 // also expected both operands to be BUILD_VECTORs.
7082 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7083 || N0.getOpcode() != ISD::BUILD_VECTOR
7084 || N1.getOpcode() != ISD::BUILD_VECTOR)
7087 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7088 EVT VT = N->getValueType(0);
7089 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7092 // Check that the vector operands are of the right form.
7093 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7094 // operands, where N is the size of the formed vector.
7095 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7096 // index such that we have a pair wise add pattern.
7098 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7099 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7101 SDValue Vec = N0->getOperand(0)->getOperand(0);
7102 SDNode *V = Vec.getNode();
7103 unsigned nextIndex = 0;
7105 // For each operands to the ADD which are BUILD_VECTORs,
7106 // check to see if each of their operands are an EXTRACT_VECTOR with
7107 // the same vector and appropriate index.
7108 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7109 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7110 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7112 SDValue ExtVec0 = N0->getOperand(i);
7113 SDValue ExtVec1 = N1->getOperand(i);
7115 // First operand is the vector, verify its the same.
7116 if (V != ExtVec0->getOperand(0).getNode() ||
7117 V != ExtVec1->getOperand(0).getNode())
7120 // Second is the constant, verify its correct.
7121 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7122 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7124 // For the constant, we want to see all the even or all the odd.
7125 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7126 || C1->getZExtValue() != nextIndex+1)
7135 // Create VPADDL node.
7136 SelectionDAG &DAG = DCI.DAG;
7137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7139 // Build operand list.
7140 SmallVector<SDValue, 8> Ops;
7141 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7142 TLI.getPointerTy()));
7144 // Input is the vector.
7147 // Get widened type and narrowed type.
7149 unsigned numElem = VT.getVectorNumElements();
7150 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7151 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7152 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7153 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7155 llvm_unreachable("Invalid vector element type for padd optimization.");
7158 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7159 widenType, &Ops[0], Ops.size());
7160 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7163 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7164 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7165 /// called with the default operands, and if that fails, with commuted
7167 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7168 TargetLowering::DAGCombinerInfo &DCI,
7169 const ARMSubtarget *Subtarget){
7171 // Attempt to create vpaddl for this add.
7172 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7173 if (Result.getNode())
7176 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7177 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
7178 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7179 if (Result.getNode()) return Result;
7184 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7186 static SDValue PerformADDCombine(SDNode *N,
7187 TargetLowering::DAGCombinerInfo &DCI,
7188 const ARMSubtarget *Subtarget) {
7189 SDValue N0 = N->getOperand(0);
7190 SDValue N1 = N->getOperand(1);
7192 // First try with the default operand order.
7193 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7194 if (Result.getNode())
7197 // If that didn't work, try again with the operands commuted.
7198 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7201 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7203 static SDValue PerformSUBCombine(SDNode *N,
7204 TargetLowering::DAGCombinerInfo &DCI) {
7205 SDValue N0 = N->getOperand(0);
7206 SDValue N1 = N->getOperand(1);
7208 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7209 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
7210 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7211 if (Result.getNode()) return Result;
7217 /// PerformVMULCombine
7218 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7219 /// special multiplier accumulator forwarding.
7225 static SDValue PerformVMULCombine(SDNode *N,
7226 TargetLowering::DAGCombinerInfo &DCI,
7227 const ARMSubtarget *Subtarget) {
7228 if (!Subtarget->hasVMLxForwarding())
7231 SelectionDAG &DAG = DCI.DAG;
7232 SDValue N0 = N->getOperand(0);
7233 SDValue N1 = N->getOperand(1);
7234 unsigned Opcode = N0.getOpcode();
7235 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7236 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7237 Opcode = N1.getOpcode();
7238 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7239 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7244 EVT VT = N->getValueType(0);
7245 DebugLoc DL = N->getDebugLoc();
7246 SDValue N00 = N0->getOperand(0);
7247 SDValue N01 = N0->getOperand(1);
7248 return DAG.getNode(Opcode, DL, VT,
7249 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7250 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7253 static SDValue PerformMULCombine(SDNode *N,
7254 TargetLowering::DAGCombinerInfo &DCI,
7255 const ARMSubtarget *Subtarget) {
7256 SelectionDAG &DAG = DCI.DAG;
7258 if (Subtarget->isThumb1Only())
7261 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7264 EVT VT = N->getValueType(0);
7265 if (VT.is64BitVector() || VT.is128BitVector())
7266 return PerformVMULCombine(N, DCI, Subtarget);
7270 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7274 int64_t MulAmt = C->getSExtValue();
7275 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7277 ShiftAmt = ShiftAmt & (32 - 1);
7278 SDValue V = N->getOperand(0);
7279 DebugLoc DL = N->getDebugLoc();
7282 MulAmt >>= ShiftAmt;
7285 if (isPowerOf2_32(MulAmt - 1)) {
7286 // (mul x, 2^N + 1) => (add (shl x, N), x)
7287 Res = DAG.getNode(ISD::ADD, DL, VT,
7289 DAG.getNode(ISD::SHL, DL, VT,
7291 DAG.getConstant(Log2_32(MulAmt - 1),
7293 } else if (isPowerOf2_32(MulAmt + 1)) {
7294 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7295 Res = DAG.getNode(ISD::SUB, DL, VT,
7296 DAG.getNode(ISD::SHL, DL, VT,
7298 DAG.getConstant(Log2_32(MulAmt + 1),
7304 uint64_t MulAmtAbs = -MulAmt;
7305 if (isPowerOf2_32(MulAmtAbs + 1)) {
7306 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7307 Res = DAG.getNode(ISD::SUB, DL, VT,
7309 DAG.getNode(ISD::SHL, DL, VT,
7311 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7313 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7314 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7315 Res = DAG.getNode(ISD::ADD, DL, VT,
7317 DAG.getNode(ISD::SHL, DL, VT,
7319 DAG.getConstant(Log2_32(MulAmtAbs-1),
7321 Res = DAG.getNode(ISD::SUB, DL, VT,
7322 DAG.getConstant(0, MVT::i32),Res);
7329 Res = DAG.getNode(ISD::SHL, DL, VT,
7330 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7332 // Do not add new nodes to DAG combiner worklist.
7333 DCI.CombineTo(N, Res, false);
7337 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
7338 return N.getOpcode() == ARMISD::CMOV && N.getNode()->hasOneUse() &&
7339 isZeroOrAllOnes(N.getOperand(0), AllOnes);
7342 /// formConditionalOp - Combine an operation with a conditional move operand
7343 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7344 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7345 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7347 SDValue N0 = N->getOperand(0);
7348 SDValue N1 = N->getOperand(1);
7350 bool isAND = N->getOpcode() == ISD::AND;
7351 bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7352 if (!isCand && Commutable) {
7353 isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7361 switch (N->getOpcode()) {
7362 default: llvm_unreachable("Unexpected node");
7363 case ISD::AND: Opc = ARMISD::CAND; break;
7364 case ISD::OR: Opc = ARMISD::COR; break;
7365 case ISD::XOR: Opc = ARMISD::CXOR; break;
7367 return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7368 N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7372 static SDValue PerformANDCombine(SDNode *N,
7373 TargetLowering::DAGCombinerInfo &DCI,
7374 const ARMSubtarget *Subtarget) {
7376 // Attempt to use immediate-form VBIC
7377 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7378 DebugLoc dl = N->getDebugLoc();
7379 EVT VT = N->getValueType(0);
7380 SelectionDAG &DAG = DCI.DAG;
7382 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7385 APInt SplatBits, SplatUndef;
7386 unsigned SplatBitSize;
7389 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7390 if (SplatBitSize <= 64) {
7392 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7393 SplatUndef.getZExtValue(), SplatBitSize,
7394 DAG, VbicVT, VT.is128BitVector(),
7396 if (Val.getNode()) {
7398 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7399 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7400 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7405 if (!Subtarget->isThumb1Only()) {
7406 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7407 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7408 if (Result.getNode())
7410 // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7411 SDValue CAND = formConditionalOp(N, DAG, true);
7419 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7420 static SDValue PerformORCombine(SDNode *N,
7421 TargetLowering::DAGCombinerInfo &DCI,
7422 const ARMSubtarget *Subtarget) {
7423 // Attempt to use immediate-form VORR
7424 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7425 DebugLoc dl = N->getDebugLoc();
7426 EVT VT = N->getValueType(0);
7427 SelectionDAG &DAG = DCI.DAG;
7429 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7432 APInt SplatBits, SplatUndef;
7433 unsigned SplatBitSize;
7435 if (BVN && Subtarget->hasNEON() &&
7436 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7437 if (SplatBitSize <= 64) {
7439 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7440 SplatUndef.getZExtValue(), SplatBitSize,
7441 DAG, VorrVT, VT.is128BitVector(),
7443 if (Val.getNode()) {
7445 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7446 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7447 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7452 if (!Subtarget->isThumb1Only()) {
7453 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7454 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7455 if (Result.getNode())
7457 // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7458 SDValue COR = formConditionalOp(N, DAG, true);
7464 // The code below optimizes (or (and X, Y), Z).
7465 // The AND operand needs to have a single user to make these optimizations
7467 SDValue N0 = N->getOperand(0);
7468 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7470 SDValue N1 = N->getOperand(1);
7472 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7473 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7474 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7476 unsigned SplatBitSize;
7479 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7481 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7482 HasAnyUndefs) && !HasAnyUndefs) {
7483 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7485 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7486 HasAnyUndefs) && !HasAnyUndefs &&
7487 SplatBits0 == ~SplatBits1) {
7488 // Canonicalize the vector type to make instruction selection simpler.
7489 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7490 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7491 N0->getOperand(1), N0->getOperand(0),
7493 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7498 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7501 // BFI is only available on V6T2+
7502 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7505 DebugLoc DL = N->getDebugLoc();
7506 // 1) or (and A, mask), val => ARMbfi A, val, mask
7507 // iff (val & mask) == val
7509 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7510 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7511 // && mask == ~mask2
7512 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7513 // && ~mask == mask2
7514 // (i.e., copy a bitfield value into another bitfield of the same width)
7519 SDValue N00 = N0.getOperand(0);
7521 // The value and the mask need to be constants so we can verify this is
7522 // actually a bitfield set. If the mask is 0xffff, we can do better
7523 // via a movt instruction, so don't use BFI in that case.
7524 SDValue MaskOp = N0.getOperand(1);
7525 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7528 unsigned Mask = MaskC->getZExtValue();
7532 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7533 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7535 unsigned Val = N1C->getZExtValue();
7536 if ((Val & ~Mask) != Val)
7539 if (ARM::isBitFieldInvertedMask(Mask)) {
7540 Val >>= CountTrailingZeros_32(~Mask);
7542 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7543 DAG.getConstant(Val, MVT::i32),
7544 DAG.getConstant(Mask, MVT::i32));
7546 // Do not add new nodes to DAG combiner worklist.
7547 DCI.CombineTo(N, Res, false);
7550 } else if (N1.getOpcode() == ISD::AND) {
7551 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7552 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7555 unsigned Mask2 = N11C->getZExtValue();
7557 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7559 if (ARM::isBitFieldInvertedMask(Mask) &&
7561 // The pack halfword instruction works better for masks that fit it,
7562 // so use that when it's available.
7563 if (Subtarget->hasT2ExtractPack() &&
7564 (Mask == 0xffff || Mask == 0xffff0000))
7567 unsigned amt = CountTrailingZeros_32(Mask2);
7568 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7569 DAG.getConstant(amt, MVT::i32));
7570 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7571 DAG.getConstant(Mask, MVT::i32));
7572 // Do not add new nodes to DAG combiner worklist.
7573 DCI.CombineTo(N, Res, false);
7575 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7577 // The pack halfword instruction works better for masks that fit it,
7578 // so use that when it's available.
7579 if (Subtarget->hasT2ExtractPack() &&
7580 (Mask2 == 0xffff || Mask2 == 0xffff0000))
7583 unsigned lsb = CountTrailingZeros_32(Mask);
7584 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7585 DAG.getConstant(lsb, MVT::i32));
7586 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7587 DAG.getConstant(Mask2, MVT::i32));
7588 // Do not add new nodes to DAG combiner worklist.
7589 DCI.CombineTo(N, Res, false);
7594 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7595 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7596 ARM::isBitFieldInvertedMask(~Mask)) {
7597 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7598 // where lsb(mask) == #shamt and masked bits of B are known zero.
7599 SDValue ShAmt = N00.getOperand(1);
7600 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7601 unsigned LSB = CountTrailingZeros_32(Mask);
7605 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7606 DAG.getConstant(~Mask, MVT::i32));
7608 // Do not add new nodes to DAG combiner worklist.
7609 DCI.CombineTo(N, Res, false);
7615 static SDValue PerformXORCombine(SDNode *N,
7616 TargetLowering::DAGCombinerInfo &DCI,
7617 const ARMSubtarget *Subtarget) {
7618 EVT VT = N->getValueType(0);
7619 SelectionDAG &DAG = DCI.DAG;
7621 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7624 if (!Subtarget->isThumb1Only()) {
7625 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7626 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7627 if (Result.getNode())
7629 // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7630 SDValue CXOR = formConditionalOp(N, DAG, true);
7638 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7639 /// the bits being cleared by the AND are not demanded by the BFI.
7640 static SDValue PerformBFICombine(SDNode *N,
7641 TargetLowering::DAGCombinerInfo &DCI) {
7642 SDValue N1 = N->getOperand(1);
7643 if (N1.getOpcode() == ISD::AND) {
7644 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7647 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7648 unsigned LSB = CountTrailingZeros_32(~InvMask);
7649 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7650 unsigned Mask = (1 << Width)-1;
7651 unsigned Mask2 = N11C->getZExtValue();
7652 if ((Mask & (~Mask2)) == 0)
7653 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7654 N->getOperand(0), N1.getOperand(0),
7660 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7661 /// ARMISD::VMOVRRD.
7662 static SDValue PerformVMOVRRDCombine(SDNode *N,
7663 TargetLowering::DAGCombinerInfo &DCI) {
7664 // vmovrrd(vmovdrr x, y) -> x,y
7665 SDValue InDouble = N->getOperand(0);
7666 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7667 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7669 // vmovrrd(load f64) -> (load i32), (load i32)
7670 SDNode *InNode = InDouble.getNode();
7671 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7672 InNode->getValueType(0) == MVT::f64 &&
7673 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7674 !cast<LoadSDNode>(InNode)->isVolatile()) {
7675 // TODO: Should this be done for non-FrameIndex operands?
7676 LoadSDNode *LD = cast<LoadSDNode>(InNode);
7678 SelectionDAG &DAG = DCI.DAG;
7679 DebugLoc DL = LD->getDebugLoc();
7680 SDValue BasePtr = LD->getBasePtr();
7681 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7682 LD->getPointerInfo(), LD->isVolatile(),
7683 LD->isNonTemporal(), LD->isInvariant(),
7684 LD->getAlignment());
7686 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7687 DAG.getConstant(4, MVT::i32));
7688 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7689 LD->getPointerInfo(), LD->isVolatile(),
7690 LD->isNonTemporal(), LD->isInvariant(),
7691 std::min(4U, LD->getAlignment() / 2));
7693 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7694 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7695 DCI.RemoveFromWorklist(LD);
7703 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7704 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
7705 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7706 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7707 SDValue Op0 = N->getOperand(0);
7708 SDValue Op1 = N->getOperand(1);
7709 if (Op0.getOpcode() == ISD::BITCAST)
7710 Op0 = Op0.getOperand(0);
7711 if (Op1.getOpcode() == ISD::BITCAST)
7712 Op1 = Op1.getOperand(0);
7713 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7714 Op0.getNode() == Op1.getNode() &&
7715 Op0.getResNo() == 0 && Op1.getResNo() == 1)
7716 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7717 N->getValueType(0), Op0.getOperand(0));
7721 /// PerformSTORECombine - Target-specific dag combine xforms for
7723 static SDValue PerformSTORECombine(SDNode *N,
7724 TargetLowering::DAGCombinerInfo &DCI) {
7725 StoreSDNode *St = cast<StoreSDNode>(N);
7726 if (St->isVolatile())
7729 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
7730 // pack all of the elements in one place. Next, store to memory in fewer
7732 SDValue StVal = St->getValue();
7733 EVT VT = StVal.getValueType();
7734 if (St->isTruncatingStore() && VT.isVector()) {
7735 SelectionDAG &DAG = DCI.DAG;
7736 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7737 EVT StVT = St->getMemoryVT();
7738 unsigned NumElems = VT.getVectorNumElements();
7739 assert(StVT != VT && "Cannot truncate to the same type");
7740 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7741 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7743 // From, To sizes and ElemCount must be pow of two
7744 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7746 // We are going to use the original vector elt for storing.
7747 // Accumulated smaller vector elements must be a multiple of the store size.
7748 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7750 unsigned SizeRatio = FromEltSz / ToEltSz;
7751 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7753 // Create a type on which we perform the shuffle.
7754 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7755 NumElems*SizeRatio);
7756 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7758 DebugLoc DL = St->getDebugLoc();
7759 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7760 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7761 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7763 // Can't shuffle using an illegal type.
7764 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7766 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7767 DAG.getUNDEF(WideVec.getValueType()),
7769 // At this point all of the data is stored at the bottom of the
7770 // register. We now need to save it to mem.
7772 // Find the largest store unit
7773 MVT StoreType = MVT::i8;
7774 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7775 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7776 MVT Tp = (MVT::SimpleValueType)tp;
7777 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7780 // Didn't find a legal store type.
7781 if (!TLI.isTypeLegal(StoreType))
7784 // Bitcast the original vector into a vector of store-size units
7785 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7786 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7787 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7788 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7789 SmallVector<SDValue, 8> Chains;
7790 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7791 TLI.getPointerTy());
7792 SDValue BasePtr = St->getBasePtr();
7794 // Perform one or more big stores into memory.
7795 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7796 for (unsigned I = 0; I < E; I++) {
7797 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7798 StoreType, ShuffWide,
7799 DAG.getIntPtrConstant(I));
7800 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7801 St->getPointerInfo(), St->isVolatile(),
7802 St->isNonTemporal(), St->getAlignment());
7803 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7805 Chains.push_back(Ch);
7807 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7811 if (!ISD::isNormalStore(St))
7814 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7815 // ARM stores of arguments in the same cache line.
7816 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7817 StVal.getNode()->hasOneUse()) {
7818 SelectionDAG &DAG = DCI.DAG;
7819 DebugLoc DL = St->getDebugLoc();
7820 SDValue BasePtr = St->getBasePtr();
7821 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7822 StVal.getNode()->getOperand(0), BasePtr,
7823 St->getPointerInfo(), St->isVolatile(),
7824 St->isNonTemporal(), St->getAlignment());
7826 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7827 DAG.getConstant(4, MVT::i32));
7828 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7829 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7830 St->isNonTemporal(),
7831 std::min(4U, St->getAlignment() / 2));
7834 if (StVal.getValueType() != MVT::i64 ||
7835 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7838 // Bitcast an i64 store extracted from a vector to f64.
7839 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7840 SelectionDAG &DAG = DCI.DAG;
7841 DebugLoc dl = StVal.getDebugLoc();
7842 SDValue IntVec = StVal.getOperand(0);
7843 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7844 IntVec.getValueType().getVectorNumElements());
7845 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7846 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7847 Vec, StVal.getOperand(1));
7848 dl = N->getDebugLoc();
7849 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7850 // Make the DAGCombiner fold the bitcasts.
7851 DCI.AddToWorklist(Vec.getNode());
7852 DCI.AddToWorklist(ExtElt.getNode());
7853 DCI.AddToWorklist(V.getNode());
7854 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7855 St->getPointerInfo(), St->isVolatile(),
7856 St->isNonTemporal(), St->getAlignment(),
7860 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7861 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
7862 /// i64 vector to have f64 elements, since the value can then be loaded
7863 /// directly into a VFP register.
7864 static bool hasNormalLoadOperand(SDNode *N) {
7865 unsigned NumElts = N->getValueType(0).getVectorNumElements();
7866 for (unsigned i = 0; i < NumElts; ++i) {
7867 SDNode *Elt = N->getOperand(i).getNode();
7868 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7874 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7875 /// ISD::BUILD_VECTOR.
7876 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7877 TargetLowering::DAGCombinerInfo &DCI){
7878 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7879 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
7880 // into a pair of GPRs, which is fine when the value is used as a scalar,
7881 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7882 SelectionDAG &DAG = DCI.DAG;
7883 if (N->getNumOperands() == 2) {
7884 SDValue RV = PerformVMOVDRRCombine(N, DAG);
7889 // Load i64 elements as f64 values so that type legalization does not split
7890 // them up into i32 values.
7891 EVT VT = N->getValueType(0);
7892 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7894 DebugLoc dl = N->getDebugLoc();
7895 SmallVector<SDValue, 8> Ops;
7896 unsigned NumElts = VT.getVectorNumElements();
7897 for (unsigned i = 0; i < NumElts; ++i) {
7898 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7900 // Make the DAGCombiner fold the bitcast.
7901 DCI.AddToWorklist(V.getNode());
7903 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7904 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7905 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7908 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7909 /// ISD::INSERT_VECTOR_ELT.
7910 static SDValue PerformInsertEltCombine(SDNode *N,
7911 TargetLowering::DAGCombinerInfo &DCI) {
7912 // Bitcast an i64 load inserted into a vector to f64.
7913 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7914 EVT VT = N->getValueType(0);
7915 SDNode *Elt = N->getOperand(1).getNode();
7916 if (VT.getVectorElementType() != MVT::i64 ||
7917 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7920 SelectionDAG &DAG = DCI.DAG;
7921 DebugLoc dl = N->getDebugLoc();
7922 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7923 VT.getVectorNumElements());
7924 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7925 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7926 // Make the DAGCombiner fold the bitcasts.
7927 DCI.AddToWorklist(Vec.getNode());
7928 DCI.AddToWorklist(V.getNode());
7929 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7930 Vec, V, N->getOperand(2));
7931 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7934 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7935 /// ISD::VECTOR_SHUFFLE.
7936 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7937 // The LLVM shufflevector instruction does not require the shuffle mask
7938 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7939 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
7940 // operands do not match the mask length, they are extended by concatenating
7941 // them with undef vectors. That is probably the right thing for other
7942 // targets, but for NEON it is better to concatenate two double-register
7943 // size vector operands into a single quad-register size vector. Do that
7944 // transformation here:
7945 // shuffle(concat(v1, undef), concat(v2, undef)) ->
7946 // shuffle(concat(v1, v2), undef)
7947 SDValue Op0 = N->getOperand(0);
7948 SDValue Op1 = N->getOperand(1);
7949 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7950 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7951 Op0.getNumOperands() != 2 ||
7952 Op1.getNumOperands() != 2)
7954 SDValue Concat0Op1 = Op0.getOperand(1);
7955 SDValue Concat1Op1 = Op1.getOperand(1);
7956 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7957 Concat1Op1.getOpcode() != ISD::UNDEF)
7959 // Skip the transformation if any of the types are illegal.
7960 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7961 EVT VT = N->getValueType(0);
7962 if (!TLI.isTypeLegal(VT) ||
7963 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7964 !TLI.isTypeLegal(Concat1Op1.getValueType()))
7967 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7968 Op0.getOperand(0), Op1.getOperand(0));
7969 // Translate the shuffle mask.
7970 SmallVector<int, 16> NewMask;
7971 unsigned NumElts = VT.getVectorNumElements();
7972 unsigned HalfElts = NumElts/2;
7973 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7974 for (unsigned n = 0; n < NumElts; ++n) {
7975 int MaskElt = SVN->getMaskElt(n);
7977 if (MaskElt < (int)HalfElts)
7979 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7980 NewElt = HalfElts + MaskElt - NumElts;
7981 NewMask.push_back(NewElt);
7983 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7984 DAG.getUNDEF(VT), NewMask.data());
7987 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7988 /// NEON load/store intrinsics to merge base address updates.
7989 static SDValue CombineBaseUpdate(SDNode *N,
7990 TargetLowering::DAGCombinerInfo &DCI) {
7991 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7994 SelectionDAG &DAG = DCI.DAG;
7995 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7996 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7997 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7998 SDValue Addr = N->getOperand(AddrOpIdx);
8000 // Search for a use of the address operand that is an increment.
8001 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8002 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8004 if (User->getOpcode() != ISD::ADD ||
8005 UI.getUse().getResNo() != Addr.getResNo())
8008 // Check that the add is independent of the load/store. Otherwise, folding
8009 // it would create a cycle.
8010 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8013 // Find the new opcode for the updating load/store.
8015 bool isLaneOp = false;
8016 unsigned NewOpc = 0;
8017 unsigned NumVecs = 0;
8019 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8021 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8022 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8024 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8026 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8028 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8030 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8031 NumVecs = 2; isLaneOp = true; break;
8032 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8033 NumVecs = 3; isLaneOp = true; break;
8034 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8035 NumVecs = 4; isLaneOp = true; break;
8036 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8037 NumVecs = 1; isLoad = false; break;
8038 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8039 NumVecs = 2; isLoad = false; break;
8040 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8041 NumVecs = 3; isLoad = false; break;
8042 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8043 NumVecs = 4; isLoad = false; break;
8044 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8045 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8046 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8047 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8048 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8049 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8053 switch (N->getOpcode()) {
8054 default: llvm_unreachable("unexpected opcode for Neon base update");
8055 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8056 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8057 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8061 // Find the size of memory referenced by the load/store.
8064 VecTy = N->getValueType(0);
8066 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8067 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8069 NumBytes /= VecTy.getVectorNumElements();
8071 // If the increment is a constant, it must match the memory ref size.
8072 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8073 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8074 uint64_t IncVal = CInc->getZExtValue();
8075 if (IncVal != NumBytes)
8077 } else if (NumBytes >= 3 * 16) {
8078 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8079 // separate instructions that make it harder to use a non-constant update.
8083 // Create the new updating load/store node.
8085 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8087 for (n = 0; n < NumResultVecs; ++n)
8089 Tys[n++] = MVT::i32;
8090 Tys[n] = MVT::Other;
8091 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8092 SmallVector<SDValue, 8> Ops;
8093 Ops.push_back(N->getOperand(0)); // incoming chain
8094 Ops.push_back(N->getOperand(AddrOpIdx));
8096 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8097 Ops.push_back(N->getOperand(i));
8099 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8100 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8101 Ops.data(), Ops.size(),
8102 MemInt->getMemoryVT(),
8103 MemInt->getMemOperand());
8106 std::vector<SDValue> NewResults;
8107 for (unsigned i = 0; i < NumResultVecs; ++i) {
8108 NewResults.push_back(SDValue(UpdN.getNode(), i));
8110 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8111 DCI.CombineTo(N, NewResults);
8112 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8119 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8120 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8121 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8123 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8124 SelectionDAG &DAG = DCI.DAG;
8125 EVT VT = N->getValueType(0);
8126 // vldN-dup instructions only support 64-bit vectors for N > 1.
8127 if (!VT.is64BitVector())
8130 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8131 SDNode *VLD = N->getOperand(0).getNode();
8132 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8134 unsigned NumVecs = 0;
8135 unsigned NewOpc = 0;
8136 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8137 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8139 NewOpc = ARMISD::VLD2DUP;
8140 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8142 NewOpc = ARMISD::VLD3DUP;
8143 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8145 NewOpc = ARMISD::VLD4DUP;
8150 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8151 // numbers match the load.
8152 unsigned VLDLaneNo =
8153 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8154 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8156 // Ignore uses of the chain result.
8157 if (UI.getUse().getResNo() == NumVecs)
8160 if (User->getOpcode() != ARMISD::VDUPLANE ||
8161 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8165 // Create the vldN-dup node.
8168 for (n = 0; n < NumVecs; ++n)
8170 Tys[n] = MVT::Other;
8171 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8172 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8173 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8174 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8175 Ops, 2, VLDMemInt->getMemoryVT(),
8176 VLDMemInt->getMemOperand());
8179 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8181 unsigned ResNo = UI.getUse().getResNo();
8182 // Ignore uses of the chain result.
8183 if (ResNo == NumVecs)
8186 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8189 // Now the vldN-lane intrinsic is dead except for its chain result.
8190 // Update uses of the chain.
8191 std::vector<SDValue> VLDDupResults;
8192 for (unsigned n = 0; n < NumVecs; ++n)
8193 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8194 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8195 DCI.CombineTo(VLD, VLDDupResults);
8200 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8201 /// ARMISD::VDUPLANE.
8202 static SDValue PerformVDUPLANECombine(SDNode *N,
8203 TargetLowering::DAGCombinerInfo &DCI) {
8204 SDValue Op = N->getOperand(0);
8206 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8207 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8208 if (CombineVLDDUP(N, DCI))
8209 return SDValue(N, 0);
8211 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8212 // redundant. Ignore bit_converts for now; element sizes are checked below.
8213 while (Op.getOpcode() == ISD::BITCAST)
8214 Op = Op.getOperand(0);
8215 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8218 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8219 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8220 // The canonical VMOV for a zero vector uses a 32-bit element size.
8221 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8223 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8225 EVT VT = N->getValueType(0);
8226 if (EltSize > VT.getVectorElementType().getSizeInBits())
8229 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8232 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8233 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8234 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8238 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8240 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8245 APFloat APF = C->getValueAPF();
8246 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8247 != APFloat::opOK || !isExact)
8250 c0 = (I == 0) ? cN : c0;
8251 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8258 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8259 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8260 /// when the VMUL has a constant operand that is a power of 2.
8262 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8263 /// vmul.f32 d16, d17, d16
8264 /// vcvt.s32.f32 d16, d16
8266 /// vcvt.s32.f32 d16, d16, #3
8267 static SDValue PerformVCVTCombine(SDNode *N,
8268 TargetLowering::DAGCombinerInfo &DCI,
8269 const ARMSubtarget *Subtarget) {
8270 SelectionDAG &DAG = DCI.DAG;
8271 SDValue Op = N->getOperand(0);
8273 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8274 Op.getOpcode() != ISD::FMUL)
8278 SDValue N0 = Op->getOperand(0);
8279 SDValue ConstVec = Op->getOperand(1);
8280 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8282 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8283 !isConstVecPow2(ConstVec, isSigned, C))
8286 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8287 Intrinsic::arm_neon_vcvtfp2fxu;
8288 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8290 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8291 DAG.getConstant(Log2_64(C), MVT::i32));
8294 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8295 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8296 /// when the VDIV has a constant operand that is a power of 2.
8298 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8299 /// vcvt.f32.s32 d16, d16
8300 /// vdiv.f32 d16, d17, d16
8302 /// vcvt.f32.s32 d16, d16, #3
8303 static SDValue PerformVDIVCombine(SDNode *N,
8304 TargetLowering::DAGCombinerInfo &DCI,
8305 const ARMSubtarget *Subtarget) {
8306 SelectionDAG &DAG = DCI.DAG;
8307 SDValue Op = N->getOperand(0);
8308 unsigned OpOpcode = Op.getNode()->getOpcode();
8310 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8311 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8315 SDValue ConstVec = N->getOperand(1);
8316 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8318 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8319 !isConstVecPow2(ConstVec, isSigned, C))
8322 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8323 Intrinsic::arm_neon_vcvtfxu2fp;
8324 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8326 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8327 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8330 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8331 /// operand of a vector shift operation, where all the elements of the
8332 /// build_vector must have the same constant integer value.
8333 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8334 // Ignore bit_converts.
8335 while (Op.getOpcode() == ISD::BITCAST)
8336 Op = Op.getOperand(0);
8337 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8338 APInt SplatBits, SplatUndef;
8339 unsigned SplatBitSize;
8341 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8342 HasAnyUndefs, ElementBits) ||
8343 SplatBitSize > ElementBits)
8345 Cnt = SplatBits.getSExtValue();
8349 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8350 /// operand of a vector shift left operation. That value must be in the range:
8351 /// 0 <= Value < ElementBits for a left shift; or
8352 /// 0 <= Value <= ElementBits for a long left shift.
8353 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8354 assert(VT.isVector() && "vector shift count is not a vector type");
8355 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8356 if (! getVShiftImm(Op, ElementBits, Cnt))
8358 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8361 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8362 /// operand of a vector shift right operation. For a shift opcode, the value
8363 /// is positive, but for an intrinsic the value count must be negative. The
8364 /// absolute value must be in the range:
8365 /// 1 <= |Value| <= ElementBits for a right shift; or
8366 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8367 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8369 assert(VT.isVector() && "vector shift count is not a vector type");
8370 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8371 if (! getVShiftImm(Op, ElementBits, Cnt))
8375 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8378 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8379 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8380 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8383 // Don't do anything for most intrinsics.
8386 // Vector shifts: check for immediate versions and lower them.
8387 // Note: This is done during DAG combining instead of DAG legalizing because
8388 // the build_vectors for 64-bit vector element shift counts are generally
8389 // not legal, and it is hard to see their values after they get legalized to
8390 // loads from a constant pool.
8391 case Intrinsic::arm_neon_vshifts:
8392 case Intrinsic::arm_neon_vshiftu:
8393 case Intrinsic::arm_neon_vshiftls:
8394 case Intrinsic::arm_neon_vshiftlu:
8395 case Intrinsic::arm_neon_vshiftn:
8396 case Intrinsic::arm_neon_vrshifts:
8397 case Intrinsic::arm_neon_vrshiftu:
8398 case Intrinsic::arm_neon_vrshiftn:
8399 case Intrinsic::arm_neon_vqshifts:
8400 case Intrinsic::arm_neon_vqshiftu:
8401 case Intrinsic::arm_neon_vqshiftsu:
8402 case Intrinsic::arm_neon_vqshiftns:
8403 case Intrinsic::arm_neon_vqshiftnu:
8404 case Intrinsic::arm_neon_vqshiftnsu:
8405 case Intrinsic::arm_neon_vqrshiftns:
8406 case Intrinsic::arm_neon_vqrshiftnu:
8407 case Intrinsic::arm_neon_vqrshiftnsu: {
8408 EVT VT = N->getOperand(1).getValueType();
8410 unsigned VShiftOpc = 0;
8413 case Intrinsic::arm_neon_vshifts:
8414 case Intrinsic::arm_neon_vshiftu:
8415 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8416 VShiftOpc = ARMISD::VSHL;
8419 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8420 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8421 ARMISD::VSHRs : ARMISD::VSHRu);
8426 case Intrinsic::arm_neon_vshiftls:
8427 case Intrinsic::arm_neon_vshiftlu:
8428 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8430 llvm_unreachable("invalid shift count for vshll intrinsic");
8432 case Intrinsic::arm_neon_vrshifts:
8433 case Intrinsic::arm_neon_vrshiftu:
8434 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8438 case Intrinsic::arm_neon_vqshifts:
8439 case Intrinsic::arm_neon_vqshiftu:
8440 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8444 case Intrinsic::arm_neon_vqshiftsu:
8445 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8447 llvm_unreachable("invalid shift count for vqshlu intrinsic");
8449 case Intrinsic::arm_neon_vshiftn:
8450 case Intrinsic::arm_neon_vrshiftn:
8451 case Intrinsic::arm_neon_vqshiftns:
8452 case Intrinsic::arm_neon_vqshiftnu:
8453 case Intrinsic::arm_neon_vqshiftnsu:
8454 case Intrinsic::arm_neon_vqrshiftns:
8455 case Intrinsic::arm_neon_vqrshiftnu:
8456 case Intrinsic::arm_neon_vqrshiftnsu:
8457 // Narrowing shifts require an immediate right shift.
8458 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8460 llvm_unreachable("invalid shift count for narrowing vector shift "
8464 llvm_unreachable("unhandled vector shift");
8468 case Intrinsic::arm_neon_vshifts:
8469 case Intrinsic::arm_neon_vshiftu:
8470 // Opcode already set above.
8472 case Intrinsic::arm_neon_vshiftls:
8473 case Intrinsic::arm_neon_vshiftlu:
8474 if (Cnt == VT.getVectorElementType().getSizeInBits())
8475 VShiftOpc = ARMISD::VSHLLi;
8477 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8478 ARMISD::VSHLLs : ARMISD::VSHLLu);
8480 case Intrinsic::arm_neon_vshiftn:
8481 VShiftOpc = ARMISD::VSHRN; break;
8482 case Intrinsic::arm_neon_vrshifts:
8483 VShiftOpc = ARMISD::VRSHRs; break;
8484 case Intrinsic::arm_neon_vrshiftu:
8485 VShiftOpc = ARMISD::VRSHRu; break;
8486 case Intrinsic::arm_neon_vrshiftn:
8487 VShiftOpc = ARMISD::VRSHRN; break;
8488 case Intrinsic::arm_neon_vqshifts:
8489 VShiftOpc = ARMISD::VQSHLs; break;
8490 case Intrinsic::arm_neon_vqshiftu:
8491 VShiftOpc = ARMISD::VQSHLu; break;
8492 case Intrinsic::arm_neon_vqshiftsu:
8493 VShiftOpc = ARMISD::VQSHLsu; break;
8494 case Intrinsic::arm_neon_vqshiftns:
8495 VShiftOpc = ARMISD::VQSHRNs; break;
8496 case Intrinsic::arm_neon_vqshiftnu:
8497 VShiftOpc = ARMISD::VQSHRNu; break;
8498 case Intrinsic::arm_neon_vqshiftnsu:
8499 VShiftOpc = ARMISD::VQSHRNsu; break;
8500 case Intrinsic::arm_neon_vqrshiftns:
8501 VShiftOpc = ARMISD::VQRSHRNs; break;
8502 case Intrinsic::arm_neon_vqrshiftnu:
8503 VShiftOpc = ARMISD::VQRSHRNu; break;
8504 case Intrinsic::arm_neon_vqrshiftnsu:
8505 VShiftOpc = ARMISD::VQRSHRNsu; break;
8508 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8509 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8512 case Intrinsic::arm_neon_vshiftins: {
8513 EVT VT = N->getOperand(1).getValueType();
8515 unsigned VShiftOpc = 0;
8517 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8518 VShiftOpc = ARMISD::VSLI;
8519 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8520 VShiftOpc = ARMISD::VSRI;
8522 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8525 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8526 N->getOperand(1), N->getOperand(2),
8527 DAG.getConstant(Cnt, MVT::i32));
8530 case Intrinsic::arm_neon_vqrshifts:
8531 case Intrinsic::arm_neon_vqrshiftu:
8532 // No immediate versions of these to check for.
8539 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8540 /// lowers them. As with the vector shift intrinsics, this is done during DAG
8541 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8542 /// vector element shift counts are generally not legal, and it is hard to see
8543 /// their values after they get legalized to loads from a constant pool.
8544 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8545 const ARMSubtarget *ST) {
8546 EVT VT = N->getValueType(0);
8547 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8548 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8549 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8550 SDValue N1 = N->getOperand(1);
8551 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8552 SDValue N0 = N->getOperand(0);
8553 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8554 DAG.MaskedValueIsZero(N0.getOperand(0),
8555 APInt::getHighBitsSet(32, 16)))
8556 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8560 // Nothing to be done for scalar shifts.
8561 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8562 if (!VT.isVector() || !TLI.isTypeLegal(VT))
8565 assert(ST->hasNEON() && "unexpected vector shift");
8568 switch (N->getOpcode()) {
8569 default: llvm_unreachable("unexpected shift opcode");
8572 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8573 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8574 DAG.getConstant(Cnt, MVT::i32));
8579 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8580 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8581 ARMISD::VSHRs : ARMISD::VSHRu);
8582 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8583 DAG.getConstant(Cnt, MVT::i32));
8589 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8590 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8591 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8592 const ARMSubtarget *ST) {
8593 SDValue N0 = N->getOperand(0);
8595 // Check for sign- and zero-extensions of vector extract operations of 8-
8596 // and 16-bit vector elements. NEON supports these directly. They are
8597 // handled during DAG combining because type legalization will promote them
8598 // to 32-bit types and it is messy to recognize the operations after that.
8599 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8600 SDValue Vec = N0.getOperand(0);
8601 SDValue Lane = N0.getOperand(1);
8602 EVT VT = N->getValueType(0);
8603 EVT EltVT = N0.getValueType();
8604 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8606 if (VT == MVT::i32 &&
8607 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8608 TLI.isTypeLegal(Vec.getValueType()) &&
8609 isa<ConstantSDNode>(Lane)) {
8612 switch (N->getOpcode()) {
8613 default: llvm_unreachable("unexpected opcode");
8614 case ISD::SIGN_EXTEND:
8615 Opc = ARMISD::VGETLANEs;
8617 case ISD::ZERO_EXTEND:
8618 case ISD::ANY_EXTEND:
8619 Opc = ARMISD::VGETLANEu;
8622 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8629 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8630 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8631 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8632 const ARMSubtarget *ST) {
8633 // If the target supports NEON, try to use vmax/vmin instructions for f32
8634 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
8635 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
8636 // a NaN; only do the transformation when it matches that behavior.
8638 // For now only do this when using NEON for FP operations; if using VFP, it
8639 // is not obvious that the benefit outweighs the cost of switching to the
8641 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8642 N->getValueType(0) != MVT::f32)
8645 SDValue CondLHS = N->getOperand(0);
8646 SDValue CondRHS = N->getOperand(1);
8647 SDValue LHS = N->getOperand(2);
8648 SDValue RHS = N->getOperand(3);
8649 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8651 unsigned Opcode = 0;
8653 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8654 IsReversed = false; // x CC y ? x : y
8655 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8656 IsReversed = true ; // x CC y ? y : x
8670 // If LHS is NaN, an ordered comparison will be false and the result will
8671 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
8672 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8673 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8674 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8676 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8677 // will return -0, so vmin can only be used for unsafe math or if one of
8678 // the operands is known to be nonzero.
8679 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8680 !DAG.getTarget().Options.UnsafeFPMath &&
8681 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8683 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8692 // If LHS is NaN, an ordered comparison will be false and the result will
8693 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
8694 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8695 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8696 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8698 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8699 // will return +0, so vmax can only be used for unsafe math or if one of
8700 // the operands is known to be nonzero.
8701 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8702 !DAG.getTarget().Options.UnsafeFPMath &&
8703 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8705 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8711 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8714 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8716 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8717 SDValue Cmp = N->getOperand(4);
8718 if (Cmp.getOpcode() != ARMISD::CMPZ)
8719 // Only looking at EQ and NE cases.
8722 EVT VT = N->getValueType(0);
8723 DebugLoc dl = N->getDebugLoc();
8724 SDValue LHS = Cmp.getOperand(0);
8725 SDValue RHS = Cmp.getOperand(1);
8726 SDValue FalseVal = N->getOperand(0);
8727 SDValue TrueVal = N->getOperand(1);
8728 SDValue ARMcc = N->getOperand(2);
8729 ARMCC::CondCodes CC =
8730 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8748 /// FIXME: Turn this into a target neutral optimization?
8750 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8751 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8752 N->getOperand(3), Cmp);
8753 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8755 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8756 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8757 N->getOperand(3), NewCmp);
8760 if (Res.getNode()) {
8761 APInt KnownZero, KnownOne;
8762 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8763 // Capture demanded bits information that would be otherwise lost.
8764 if (KnownZero == 0xfffffffe)
8765 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8766 DAG.getValueType(MVT::i1));
8767 else if (KnownZero == 0xffffff00)
8768 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8769 DAG.getValueType(MVT::i8));
8770 else if (KnownZero == 0xffff0000)
8771 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8772 DAG.getValueType(MVT::i16));
8778 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8779 DAGCombinerInfo &DCI) const {
8780 switch (N->getOpcode()) {
8782 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
8783 case ISD::SUB: return PerformSUBCombine(N, DCI);
8784 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
8785 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
8786 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
8787 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
8788 case ARMISD::BFI: return PerformBFICombine(N, DCI);
8789 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8790 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8791 case ISD::STORE: return PerformSTORECombine(N, DCI);
8792 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8793 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8794 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8795 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8796 case ISD::FP_TO_SINT:
8797 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8798 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
8799 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8802 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
8803 case ISD::SIGN_EXTEND:
8804 case ISD::ZERO_EXTEND:
8805 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8806 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8807 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8808 case ARMISD::VLD2DUP:
8809 case ARMISD::VLD3DUP:
8810 case ARMISD::VLD4DUP:
8811 return CombineBaseUpdate(N, DCI);
8812 case ISD::INTRINSIC_VOID:
8813 case ISD::INTRINSIC_W_CHAIN:
8814 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8815 case Intrinsic::arm_neon_vld1:
8816 case Intrinsic::arm_neon_vld2:
8817 case Intrinsic::arm_neon_vld3:
8818 case Intrinsic::arm_neon_vld4:
8819 case Intrinsic::arm_neon_vld2lane:
8820 case Intrinsic::arm_neon_vld3lane:
8821 case Intrinsic::arm_neon_vld4lane:
8822 case Intrinsic::arm_neon_vst1:
8823 case Intrinsic::arm_neon_vst2:
8824 case Intrinsic::arm_neon_vst3:
8825 case Intrinsic::arm_neon_vst4:
8826 case Intrinsic::arm_neon_vst2lane:
8827 case Intrinsic::arm_neon_vst3lane:
8828 case Intrinsic::arm_neon_vst4lane:
8829 return CombineBaseUpdate(N, DCI);
8837 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8839 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8842 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8843 if (!Subtarget->allowsUnalignedMem())
8846 switch (VT.getSimpleVT().SimpleTy) {
8854 return Subtarget->hasNEON();
8855 // FIXME: VLD1 etc with standard alignment is legal.
8859 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8860 unsigned AlignCheck) {
8861 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8862 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8865 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8866 unsigned DstAlign, unsigned SrcAlign,
8869 MachineFunction &MF) const {
8870 const Function *F = MF.getFunction();
8872 // See if we can use NEON instructions for this...
8874 !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8875 Subtarget->hasNEON()) {
8876 if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8878 } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8883 // Lowering to i32/i16 if the size permits.
8886 } else if (Size >= 2) {
8890 // Let the target-independent logic figure it out.
8894 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8899 switch (VT.getSimpleVT().SimpleTy) {
8900 default: return false;
8915 if ((V & (Scale - 1)) != 0)
8918 return V == (V & ((1LL << 5) - 1));
8921 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8922 const ARMSubtarget *Subtarget) {
8929 switch (VT.getSimpleVT().SimpleTy) {
8930 default: return false;
8935 // + imm12 or - imm8
8937 return V == (V & ((1LL << 8) - 1));
8938 return V == (V & ((1LL << 12) - 1));
8941 // Same as ARM mode. FIXME: NEON?
8942 if (!Subtarget->hasVFP2())
8947 return V == (V & ((1LL << 8) - 1));
8951 /// isLegalAddressImmediate - Return true if the integer value can be used
8952 /// as the offset of the target addressing mode for load / store of the
8954 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8955 const ARMSubtarget *Subtarget) {
8962 if (Subtarget->isThumb1Only())
8963 return isLegalT1AddressImmediate(V, VT);
8964 else if (Subtarget->isThumb2())
8965 return isLegalT2AddressImmediate(V, VT, Subtarget);
8970 switch (VT.getSimpleVT().SimpleTy) {
8971 default: return false;
8976 return V == (V & ((1LL << 12) - 1));
8979 return V == (V & ((1LL << 8) - 1));
8982 if (!Subtarget->hasVFP2()) // FIXME: NEON?
8987 return V == (V & ((1LL << 8) - 1));
8991 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8993 int Scale = AM.Scale;
8997 switch (VT.getSimpleVT().SimpleTy) {
8998 default: return false;
9007 return Scale == 2 || Scale == 4 || Scale == 8;
9010 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9014 // Note, we allow "void" uses (basically, uses that aren't loads or
9015 // stores), because arm allows folding a scale into many arithmetic
9016 // operations. This should be made more precise and revisited later.
9018 // Allow r << imm, but the imm has to be a multiple of two.
9019 if (Scale & 1) return false;
9020 return isPowerOf2_32(Scale);
9024 /// isLegalAddressingMode - Return true if the addressing mode represented
9025 /// by AM is legal for this target, for a load/store of the specified type.
9026 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9028 EVT VT = getValueType(Ty, true);
9029 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9032 // Can never fold addr of global into load/store.
9037 case 0: // no scale reg, must be "r+i" or "r", or "i".
9040 if (Subtarget->isThumb1Only())
9044 // ARM doesn't support any R+R*scale+imm addr modes.
9051 if (Subtarget->isThumb2())
9052 return isLegalT2ScaledAddressingMode(AM, VT);
9054 int Scale = AM.Scale;
9055 switch (VT.getSimpleVT().SimpleTy) {
9056 default: return false;
9060 if (Scale < 0) Scale = -Scale;
9064 return isPowerOf2_32(Scale & ~1);
9068 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9073 // Note, we allow "void" uses (basically, uses that aren't loads or
9074 // stores), because arm allows folding a scale into many arithmetic
9075 // operations. This should be made more precise and revisited later.
9077 // Allow r << imm, but the imm has to be a multiple of two.
9078 if (Scale & 1) return false;
9079 return isPowerOf2_32(Scale);
9085 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9086 /// icmp immediate, that is the target has icmp instructions which can compare
9087 /// a register against the immediate without having to materialize the
9088 /// immediate into a register.
9089 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9090 // Thumb2 and ARM modes can use cmn for negative immediates.
9091 if (!Subtarget->isThumb())
9092 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9093 if (Subtarget->isThumb2())
9094 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9095 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9096 return Imm >= 0 && Imm <= 255;
9099 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9100 /// *or sub* immediate, that is the target has add or sub instructions which can
9101 /// add a register with the immediate without having to materialize the
9102 /// immediate into a register.
9103 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9104 // Same encoding for add/sub, just flip the sign.
9105 int64_t AbsImm = llvm::abs64(Imm);
9106 if (!Subtarget->isThumb())
9107 return ARM_AM::getSOImmVal(AbsImm) != -1;
9108 if (Subtarget->isThumb2())
9109 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9110 // Thumb1 only has 8-bit unsigned immediate.
9111 return AbsImm >= 0 && AbsImm <= 255;
9114 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9115 bool isSEXTLoad, SDValue &Base,
9116 SDValue &Offset, bool &isInc,
9117 SelectionDAG &DAG) {
9118 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9121 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9123 Base = Ptr->getOperand(0);
9124 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9125 int RHSC = (int)RHS->getZExtValue();
9126 if (RHSC < 0 && RHSC > -256) {
9127 assert(Ptr->getOpcode() == ISD::ADD);
9129 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9133 isInc = (Ptr->getOpcode() == ISD::ADD);
9134 Offset = Ptr->getOperand(1);
9136 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9138 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9139 int RHSC = (int)RHS->getZExtValue();
9140 if (RHSC < 0 && RHSC > -0x1000) {
9141 assert(Ptr->getOpcode() == ISD::ADD);
9143 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9144 Base = Ptr->getOperand(0);
9149 if (Ptr->getOpcode() == ISD::ADD) {
9151 ARM_AM::ShiftOpc ShOpcVal=
9152 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9153 if (ShOpcVal != ARM_AM::no_shift) {
9154 Base = Ptr->getOperand(1);
9155 Offset = Ptr->getOperand(0);
9157 Base = Ptr->getOperand(0);
9158 Offset = Ptr->getOperand(1);
9163 isInc = (Ptr->getOpcode() == ISD::ADD);
9164 Base = Ptr->getOperand(0);
9165 Offset = Ptr->getOperand(1);
9169 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9173 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9174 bool isSEXTLoad, SDValue &Base,
9175 SDValue &Offset, bool &isInc,
9176 SelectionDAG &DAG) {
9177 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9180 Base = Ptr->getOperand(0);
9181 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9182 int RHSC = (int)RHS->getZExtValue();
9183 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9184 assert(Ptr->getOpcode() == ISD::ADD);
9186 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9188 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9189 isInc = Ptr->getOpcode() == ISD::ADD;
9190 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9198 /// getPreIndexedAddressParts - returns true by value, base pointer and
9199 /// offset pointer and addressing mode by reference if the node's address
9200 /// can be legally represented as pre-indexed load / store address.
9202 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9204 ISD::MemIndexedMode &AM,
9205 SelectionDAG &DAG) const {
9206 if (Subtarget->isThumb1Only())
9211 bool isSEXTLoad = false;
9212 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9213 Ptr = LD->getBasePtr();
9214 VT = LD->getMemoryVT();
9215 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9216 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9217 Ptr = ST->getBasePtr();
9218 VT = ST->getMemoryVT();
9223 bool isLegal = false;
9224 if (Subtarget->isThumb2())
9225 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9226 Offset, isInc, DAG);
9228 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9229 Offset, isInc, DAG);
9233 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9237 /// getPostIndexedAddressParts - returns true by value, base pointer and
9238 /// offset pointer and addressing mode by reference if this node can be
9239 /// combined with a load / store to form a post-indexed load / store.
9240 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9243 ISD::MemIndexedMode &AM,
9244 SelectionDAG &DAG) const {
9245 if (Subtarget->isThumb1Only())
9250 bool isSEXTLoad = false;
9251 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9252 VT = LD->getMemoryVT();
9253 Ptr = LD->getBasePtr();
9254 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9255 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9256 VT = ST->getMemoryVT();
9257 Ptr = ST->getBasePtr();
9262 bool isLegal = false;
9263 if (Subtarget->isThumb2())
9264 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9267 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9273 // Swap base ptr and offset to catch more post-index load / store when
9274 // it's legal. In Thumb2 mode, offset must be an immediate.
9275 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9276 !Subtarget->isThumb2())
9277 std::swap(Base, Offset);
9279 // Post-indexed load / store update the base pointer.
9284 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9288 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9291 const SelectionDAG &DAG,
9292 unsigned Depth) const {
9293 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9294 switch (Op.getOpcode()) {
9296 case ARMISD::CMOV: {
9297 // Bits are known zero/one if known on the LHS and RHS.
9298 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9299 if (KnownZero == 0 && KnownOne == 0) return;
9301 APInt KnownZeroRHS, KnownOneRHS;
9302 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9303 KnownZero &= KnownZeroRHS;
9304 KnownOne &= KnownOneRHS;
9310 //===----------------------------------------------------------------------===//
9311 // ARM Inline Assembly Support
9312 //===----------------------------------------------------------------------===//
9314 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9315 // Looking for "rev" which is V6+.
9316 if (!Subtarget->hasV6Ops())
9319 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9320 std::string AsmStr = IA->getAsmString();
9321 SmallVector<StringRef, 4> AsmPieces;
9322 SplitString(AsmStr, AsmPieces, ";\n");
9324 switch (AsmPieces.size()) {
9325 default: return false;
9327 AsmStr = AsmPieces[0];
9329 SplitString(AsmStr, AsmPieces, " \t,");
9332 if (AsmPieces.size() == 3 &&
9333 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9334 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9335 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9336 if (Ty && Ty->getBitWidth() == 32)
9337 return IntrinsicLowering::LowerToByteSwap(CI);
9345 /// getConstraintType - Given a constraint letter, return the type of
9346 /// constraint it is for this target.
9347 ARMTargetLowering::ConstraintType
9348 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9349 if (Constraint.size() == 1) {
9350 switch (Constraint[0]) {
9352 case 'l': return C_RegisterClass;
9353 case 'w': return C_RegisterClass;
9354 case 'h': return C_RegisterClass;
9355 case 'x': return C_RegisterClass;
9356 case 't': return C_RegisterClass;
9357 case 'j': return C_Other; // Constant for movw.
9358 // An address with a single base register. Due to the way we
9359 // currently handle addresses it is the same as an 'r' memory constraint.
9360 case 'Q': return C_Memory;
9362 } else if (Constraint.size() == 2) {
9363 switch (Constraint[0]) {
9365 // All 'U+' constraints are addresses.
9366 case 'U': return C_Memory;
9369 return TargetLowering::getConstraintType(Constraint);
9372 /// Examine constraint type and operand type and determine a weight value.
9373 /// This object must already have been set up with the operand type
9374 /// and the current alternative constraint selected.
9375 TargetLowering::ConstraintWeight
9376 ARMTargetLowering::getSingleConstraintMatchWeight(
9377 AsmOperandInfo &info, const char *constraint) const {
9378 ConstraintWeight weight = CW_Invalid;
9379 Value *CallOperandVal = info.CallOperandVal;
9380 // If we don't have a value, we can't do a match,
9381 // but allow it at the lowest weight.
9382 if (CallOperandVal == NULL)
9384 Type *type = CallOperandVal->getType();
9385 // Look at the constraint type.
9386 switch (*constraint) {
9388 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9391 if (type->isIntegerTy()) {
9392 if (Subtarget->isThumb())
9393 weight = CW_SpecificReg;
9395 weight = CW_Register;
9399 if (type->isFloatingPointTy())
9400 weight = CW_Register;
9406 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9408 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9410 if (Constraint.size() == 1) {
9411 // GCC ARM Constraint Letters
9412 switch (Constraint[0]) {
9413 case 'l': // Low regs or general regs.
9414 if (Subtarget->isThumb())
9415 return RCPair(0U, &ARM::tGPRRegClass);
9416 return RCPair(0U, &ARM::GPRRegClass);
9417 case 'h': // High regs or no regs.
9418 if (Subtarget->isThumb())
9419 return RCPair(0U, &ARM::hGPRRegClass);
9422 return RCPair(0U, &ARM::GPRRegClass);
9425 return RCPair(0U, &ARM::SPRRegClass);
9426 if (VT.getSizeInBits() == 64)
9427 return RCPair(0U, &ARM::DPRRegClass);
9428 if (VT.getSizeInBits() == 128)
9429 return RCPair(0U, &ARM::QPRRegClass);
9433 return RCPair(0U, &ARM::SPR_8RegClass);
9434 if (VT.getSizeInBits() == 64)
9435 return RCPair(0U, &ARM::DPR_8RegClass);
9436 if (VT.getSizeInBits() == 128)
9437 return RCPair(0U, &ARM::QPR_8RegClass);
9441 return RCPair(0U, &ARM::SPRRegClass);
9445 if (StringRef("{cc}").equals_lower(Constraint))
9446 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9448 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9451 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9452 /// vector. If it is invalid, don't add anything to Ops.
9453 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9454 std::string &Constraint,
9455 std::vector<SDValue>&Ops,
9456 SelectionDAG &DAG) const {
9457 SDValue Result(0, 0);
9459 // Currently only support length 1 constraints.
9460 if (Constraint.length() != 1) return;
9462 char ConstraintLetter = Constraint[0];
9463 switch (ConstraintLetter) {
9466 case 'I': case 'J': case 'K': case 'L':
9467 case 'M': case 'N': case 'O':
9468 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9472 int64_t CVal64 = C->getSExtValue();
9473 int CVal = (int) CVal64;
9474 // None of these constraints allow values larger than 32 bits. Check
9475 // that the value fits in an int.
9479 switch (ConstraintLetter) {
9481 // Constant suitable for movw, must be between 0 and
9483 if (Subtarget->hasV6T2Ops())
9484 if (CVal >= 0 && CVal <= 65535)
9488 if (Subtarget->isThumb1Only()) {
9489 // This must be a constant between 0 and 255, for ADD
9491 if (CVal >= 0 && CVal <= 255)
9493 } else if (Subtarget->isThumb2()) {
9494 // A constant that can be used as an immediate value in a
9495 // data-processing instruction.
9496 if (ARM_AM::getT2SOImmVal(CVal) != -1)
9499 // A constant that can be used as an immediate value in a
9500 // data-processing instruction.
9501 if (ARM_AM::getSOImmVal(CVal) != -1)
9507 if (Subtarget->isThumb()) { // FIXME thumb2
9508 // This must be a constant between -255 and -1, for negated ADD
9509 // immediates. This can be used in GCC with an "n" modifier that
9510 // prints the negated value, for use with SUB instructions. It is
9511 // not useful otherwise but is implemented for compatibility.
9512 if (CVal >= -255 && CVal <= -1)
9515 // This must be a constant between -4095 and 4095. It is not clear
9516 // what this constraint is intended for. Implemented for
9517 // compatibility with GCC.
9518 if (CVal >= -4095 && CVal <= 4095)
9524 if (Subtarget->isThumb1Only()) {
9525 // A 32-bit value where only one byte has a nonzero value. Exclude
9526 // zero to match GCC. This constraint is used by GCC internally for
9527 // constants that can be loaded with a move/shift combination.
9528 // It is not useful otherwise but is implemented for compatibility.
9529 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9531 } else if (Subtarget->isThumb2()) {
9532 // A constant whose bitwise inverse can be used as an immediate
9533 // value in a data-processing instruction. This can be used in GCC
9534 // with a "B" modifier that prints the inverted value, for use with
9535 // BIC and MVN instructions. It is not useful otherwise but is
9536 // implemented for compatibility.
9537 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9540 // A constant whose bitwise inverse can be used as an immediate
9541 // value in a data-processing instruction. This can be used in GCC
9542 // with a "B" modifier that prints the inverted value, for use with
9543 // BIC and MVN instructions. It is not useful otherwise but is
9544 // implemented for compatibility.
9545 if (ARM_AM::getSOImmVal(~CVal) != -1)
9551 if (Subtarget->isThumb1Only()) {
9552 // This must be a constant between -7 and 7,
9553 // for 3-operand ADD/SUB immediate instructions.
9554 if (CVal >= -7 && CVal < 7)
9556 } else if (Subtarget->isThumb2()) {
9557 // A constant whose negation can be used as an immediate value in a
9558 // data-processing instruction. This can be used in GCC with an "n"
9559 // modifier that prints the negated value, for use with SUB
9560 // instructions. It is not useful otherwise but is implemented for
9562 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9565 // A constant whose negation can be used as an immediate value in a
9566 // data-processing instruction. This can be used in GCC with an "n"
9567 // modifier that prints the negated value, for use with SUB
9568 // instructions. It is not useful otherwise but is implemented for
9570 if (ARM_AM::getSOImmVal(-CVal) != -1)
9576 if (Subtarget->isThumb()) { // FIXME thumb2
9577 // This must be a multiple of 4 between 0 and 1020, for
9578 // ADD sp + immediate.
9579 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9582 // A power of two or a constant between 0 and 32. This is used in
9583 // GCC for the shift amount on shifted register operands, but it is
9584 // useful in general for any shift amounts.
9585 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9591 if (Subtarget->isThumb()) { // FIXME thumb2
9592 // This must be a constant between 0 and 31, for shift amounts.
9593 if (CVal >= 0 && CVal <= 31)
9599 if (Subtarget->isThumb()) { // FIXME thumb2
9600 // This must be a multiple of 4 between -508 and 508, for
9601 // ADD/SUB sp = sp + immediate.
9602 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9607 Result = DAG.getTargetConstant(CVal, Op.getValueType());
9611 if (Result.getNode()) {
9612 Ops.push_back(Result);
9615 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9619 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9620 // The ARM target isn't yet aware of offsets.
9624 bool ARM::isBitFieldInvertedMask(unsigned v) {
9625 if (v == 0xffffffff)
9627 // there can be 1's on either or both "outsides", all the "inside"
9629 unsigned int lsb = 0, msb = 31;
9630 while (v & (1 << msb)) --msb;
9631 while (v & (1 << lsb)) ++lsb;
9632 for (unsigned int i = lsb; i <= msb; ++i) {
9639 /// isFPImmLegal - Returns true if the target can instruction select the
9640 /// specified FP immediate natively. If false, the legalizer will
9641 /// materialize the FP immediate as a load from a constant pool.
9642 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9643 if (!Subtarget->hasVFP3())
9646 return ARM_AM::getFP32Imm(Imm) != -1;
9648 return ARM_AM::getFP64Imm(Imm) != -1;
9652 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9653 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9654 /// specified in the intrinsic calls.
9655 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9657 unsigned Intrinsic) const {
9658 switch (Intrinsic) {
9659 case Intrinsic::arm_neon_vld1:
9660 case Intrinsic::arm_neon_vld2:
9661 case Intrinsic::arm_neon_vld3:
9662 case Intrinsic::arm_neon_vld4:
9663 case Intrinsic::arm_neon_vld2lane:
9664 case Intrinsic::arm_neon_vld3lane:
9665 case Intrinsic::arm_neon_vld4lane: {
9666 Info.opc = ISD::INTRINSIC_W_CHAIN;
9667 // Conservatively set memVT to the entire set of vectors loaded.
9668 uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9669 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9670 Info.ptrVal = I.getArgOperand(0);
9672 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9673 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9674 Info.vol = false; // volatile loads with NEON intrinsics not supported
9675 Info.readMem = true;
9676 Info.writeMem = false;
9679 case Intrinsic::arm_neon_vst1:
9680 case Intrinsic::arm_neon_vst2:
9681 case Intrinsic::arm_neon_vst3:
9682 case Intrinsic::arm_neon_vst4:
9683 case Intrinsic::arm_neon_vst2lane:
9684 case Intrinsic::arm_neon_vst3lane:
9685 case Intrinsic::arm_neon_vst4lane: {
9686 Info.opc = ISD::INTRINSIC_VOID;
9687 // Conservatively set memVT to the entire set of vectors stored.
9688 unsigned NumElts = 0;
9689 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9690 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9691 if (!ArgTy->isVectorTy())
9693 NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9695 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9696 Info.ptrVal = I.getArgOperand(0);
9698 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9699 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9700 Info.vol = false; // volatile stores with NEON intrinsics not supported
9701 Info.readMem = false;
9702 Info.writeMem = true;
9705 case Intrinsic::arm_strexd: {
9706 Info.opc = ISD::INTRINSIC_W_CHAIN;
9707 Info.memVT = MVT::i64;
9708 Info.ptrVal = I.getArgOperand(2);
9712 Info.readMem = false;
9713 Info.writeMem = true;
9716 case Intrinsic::arm_ldrexd: {
9717 Info.opc = ISD::INTRINSIC_W_CHAIN;
9718 Info.memVT = MVT::i64;
9719 Info.ptrVal = I.getArgOperand(0);
9723 Info.readMem = true;
9724 Info.writeMem = false;