1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
59 EnableARMLongCalls("arm-long-calls", cl::Hidden,
60 cl::desc("Generate calls via indirect call instructions"),
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
73 LLVMContext &C, ParmContext PC)
74 : CCState(CC, isVarArg, MF, TM, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const uint16_t GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
147 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
148 addRegisterClass(VT, &ARM::DPRRegClass);
149 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
152 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPairRegClass);
154 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
157 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
158 if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
159 return new TargetLoweringObjectFileMachO();
161 return new ARMElfTargetObjectFile();
164 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
165 : TargetLowering(TM, createTLOF(TM)) {
166 Subtarget = &TM.getSubtarget<ARMSubtarget>();
167 RegInfo = TM.getRegisterInfo();
168 Itins = TM.getInstrItineraryData();
170 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172 if (Subtarget->isTargetMachO()) {
173 // Uses VFP for Thumb libfuncs if available.
174 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
175 Subtarget->hasARMOps()) {
176 // Single-precision floating-point arithmetic.
177 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
178 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
179 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
180 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
182 // Double-precision floating-point arithmetic.
183 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
184 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
185 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
186 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
188 // Single-precision comparisons.
189 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
190 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
191 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
192 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
193 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
194 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
195 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
196 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
198 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
207 // Double-precision comparisons.
208 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
209 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
210 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
211 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
212 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
213 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
214 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
215 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
217 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
226 // Floating-point to integer conversions.
227 // i64 conversions are done via library routines even when generating VFP
228 // instructions, so use the same ones.
229 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
230 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
231 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
232 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
234 // Conversions between floating types.
235 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
236 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
238 // Integer to floating-point conversions.
239 // i64 conversions are done via library routines even when generating VFP
240 // instructions, so use the same ones.
241 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
242 // e.g., __floatunsidf vs. __floatunssidfvfp.
243 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
244 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
245 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
246 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250 // These libcalls are not available in 32-bit.
251 setLibcallName(RTLIB::SHL_I128, 0);
252 setLibcallName(RTLIB::SRL_I128, 0);
253 setLibcallName(RTLIB::SRA_I128, 0);
255 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO()) {
256 // Double-precision floating-point arithmetic helper functions
257 // RTABI chapter 4.1.2, Table 2
258 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
259 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
260 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
261 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
262 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
263 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
264 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
265 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
267 // Double-precision floating-point comparison helper functions
268 // RTABI chapter 4.1.2, Table 3
269 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
270 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
271 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
272 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
273 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
274 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
275 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
276 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
277 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
278 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
279 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
280 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
281 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
282 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
283 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
284 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
285 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
286 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
287 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
288 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
289 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
294 // Single-precision floating-point arithmetic helper functions
295 // RTABI chapter 4.1.2, Table 4
296 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
297 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
298 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
299 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
300 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
301 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
302 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
303 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
305 // Single-precision floating-point comparison helper functions
306 // RTABI chapter 4.1.2, Table 5
307 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
308 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
309 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
310 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
311 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
312 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
313 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
314 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
315 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
316 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
317 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
318 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
319 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
320 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
321 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
322 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
323 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
324 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
325 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
326 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
327 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
332 // Floating-point to integer conversions.
333 // RTABI chapter 4.1.2, Table 6
334 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
335 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
336 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
337 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
338 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
339 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
340 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
341 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
342 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
343 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
344 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
345 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
346 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
351 // Conversions between floating types.
352 // RTABI chapter 4.1.2, Table 7
353 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
354 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
355 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
356 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
358 // Integer to floating-point conversions.
359 // RTABI chapter 4.1.2, Table 8
360 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
361 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
362 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
363 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
364 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
365 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
366 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
367 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
368 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
369 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
370 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
371 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
372 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
377 // Long long helper functions
378 // RTABI chapter 4.2, Table 9
379 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
380 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
381 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
382 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
383 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
384 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
385 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
386 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
387 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
390 // Integer division functions
391 // RTABI chapter 4.3.1
392 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
393 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
394 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
395 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
396 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
397 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
398 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
399 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
400 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
401 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
402 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
403 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
404 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
410 // RTABI chapter 4.3.4
411 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
412 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
413 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
414 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
415 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
416 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
419 // Use divmod compiler-rt calls for iOS 5.0 and later.
420 if (Subtarget->getTargetTriple().isiOS() &&
421 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
422 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
423 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
426 if (Subtarget->isThumb1Only())
427 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
429 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
430 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
431 !Subtarget->isThumb1Only()) {
432 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
433 if (!Subtarget->isFPOnlySP())
434 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
436 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
439 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
440 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
441 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
442 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
443 setTruncStoreAction((MVT::SimpleValueType)VT,
444 (MVT::SimpleValueType)InnerVT, Expand);
445 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
446 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
447 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
451 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
453 if (Subtarget->hasNEON()) {
454 addDRTypeForNEON(MVT::v2f32);
455 addDRTypeForNEON(MVT::v8i8);
456 addDRTypeForNEON(MVT::v4i16);
457 addDRTypeForNEON(MVT::v2i32);
458 addDRTypeForNEON(MVT::v1i64);
460 addQRTypeForNEON(MVT::v4f32);
461 addQRTypeForNEON(MVT::v2f64);
462 addQRTypeForNEON(MVT::v16i8);
463 addQRTypeForNEON(MVT::v8i16);
464 addQRTypeForNEON(MVT::v4i32);
465 addQRTypeForNEON(MVT::v2i64);
467 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
468 // neither Neon nor VFP support any arithmetic operations on it.
469 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
470 // supported for v4f32.
471 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
472 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
473 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
474 // FIXME: Code duplication: FDIV and FREM are expanded always, see
475 // ARMTargetLowering::addTypeForNEON method for details.
476 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
477 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
478 // FIXME: Create unittest.
479 // In another words, find a way when "copysign" appears in DAG with vector
481 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
482 // FIXME: Code duplication: SETCC has custom operation action, see
483 // ARMTargetLowering::addTypeForNEON method for details.
484 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
485 // FIXME: Create unittest for FNEG and for FABS.
486 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
487 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
488 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
489 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
490 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
491 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
492 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
493 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
494 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
495 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
496 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
497 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
498 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
499 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
500 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
501 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
502 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
503 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
504 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
506 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
507 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
508 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
509 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
510 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
511 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
512 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
513 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
514 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
515 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
516 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
517 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
518 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
519 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
520 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
522 // Mark v2f32 intrinsics.
523 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
524 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
525 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
526 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
527 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
528 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
529 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
530 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
531 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
532 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
533 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
534 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
535 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
536 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
537 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
539 // Neon does not support some operations on v1i64 and v2i64 types.
540 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
541 // Custom handling for some quad-vector types to detect VMULL.
542 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
543 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
544 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
545 // Custom handling for some vector types to avoid expensive expansions
546 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
547 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
548 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
549 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
550 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
551 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
552 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
553 // a destination type that is wider than the source, and nor does
554 // it have a FP_TO_[SU]INT instruction with a narrower destination than
556 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
557 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
558 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
559 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
561 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
562 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
564 // NEON does not have single instruction CTPOP for vectors with element
565 // types wider than 8-bits. However, custom lowering can leverage the
566 // v8i8/v16i8 vcnt instruction.
567 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
568 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
569 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
570 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
572 // NEON only has FMA instructions as of VFP4.
573 if (!Subtarget->hasVFP4()) {
574 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
575 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
578 setTargetDAGCombine(ISD::INTRINSIC_VOID);
579 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
580 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
581 setTargetDAGCombine(ISD::SHL);
582 setTargetDAGCombine(ISD::SRL);
583 setTargetDAGCombine(ISD::SRA);
584 setTargetDAGCombine(ISD::SIGN_EXTEND);
585 setTargetDAGCombine(ISD::ZERO_EXTEND);
586 setTargetDAGCombine(ISD::ANY_EXTEND);
587 setTargetDAGCombine(ISD::SELECT_CC);
588 setTargetDAGCombine(ISD::BUILD_VECTOR);
589 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
590 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
591 setTargetDAGCombine(ISD::STORE);
592 setTargetDAGCombine(ISD::FP_TO_SINT);
593 setTargetDAGCombine(ISD::FP_TO_UINT);
594 setTargetDAGCombine(ISD::FDIV);
596 // It is legal to extload from v4i8 to v4i16 or v4i32.
597 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
598 MVT::v4i16, MVT::v2i16,
600 for (unsigned i = 0; i < 6; ++i) {
601 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
602 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
603 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
607 // ARM and Thumb2 support UMLAL/SMLAL.
608 if (!Subtarget->isThumb1Only())
609 setTargetDAGCombine(ISD::ADDC);
612 computeRegisterProperties();
614 // ARM does not have f32 extending load.
615 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
617 // ARM does not have i1 sign extending load.
618 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
620 // ARM supports all 4 flavors of integer indexed load / store.
621 if (!Subtarget->isThumb1Only()) {
622 for (unsigned im = (unsigned)ISD::PRE_INC;
623 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
624 setIndexedLoadAction(im, MVT::i1, Legal);
625 setIndexedLoadAction(im, MVT::i8, Legal);
626 setIndexedLoadAction(im, MVT::i16, Legal);
627 setIndexedLoadAction(im, MVT::i32, Legal);
628 setIndexedStoreAction(im, MVT::i1, Legal);
629 setIndexedStoreAction(im, MVT::i8, Legal);
630 setIndexedStoreAction(im, MVT::i16, Legal);
631 setIndexedStoreAction(im, MVT::i32, Legal);
635 // i64 operation support.
636 setOperationAction(ISD::MUL, MVT::i64, Expand);
637 setOperationAction(ISD::MULHU, MVT::i32, Expand);
638 if (Subtarget->isThumb1Only()) {
639 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
640 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
642 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
643 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
644 setOperationAction(ISD::MULHS, MVT::i32, Expand);
646 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
647 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
648 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
649 setOperationAction(ISD::SRL, MVT::i64, Custom);
650 setOperationAction(ISD::SRA, MVT::i64, Custom);
652 if (!Subtarget->isThumb1Only()) {
653 // FIXME: We should do this for Thumb1 as well.
654 setOperationAction(ISD::ADDC, MVT::i32, Custom);
655 setOperationAction(ISD::ADDE, MVT::i32, Custom);
656 setOperationAction(ISD::SUBC, MVT::i32, Custom);
657 setOperationAction(ISD::SUBE, MVT::i32, Custom);
660 // ARM does not have ROTL.
661 setOperationAction(ISD::ROTL, MVT::i32, Expand);
662 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
663 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
664 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
665 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
667 // These just redirect to CTTZ and CTLZ on ARM.
668 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
669 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
671 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
673 // Only ARMv6 has BSWAP.
674 if (!Subtarget->hasV6Ops())
675 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
677 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
678 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
679 // These are expanded into libcalls if the cpu doesn't have HW divider.
680 setOperationAction(ISD::SDIV, MVT::i32, Expand);
681 setOperationAction(ISD::UDIV, MVT::i32, Expand);
684 // FIXME: Also set divmod for SREM on EABI
685 setOperationAction(ISD::SREM, MVT::i32, Expand);
686 setOperationAction(ISD::UREM, MVT::i32, Expand);
687 // Register based DivRem for AEABI (RTABI 4.2)
688 if (Subtarget->isTargetAEABI()) {
689 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
690 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
691 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
692 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
693 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
694 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
695 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
696 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
698 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
699 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
700 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
701 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
702 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
703 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
704 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
705 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
707 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
708 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
710 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
711 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
714 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
715 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
716 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
717 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
718 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
720 setOperationAction(ISD::TRAP, MVT::Other, Legal);
722 // Use the default implementation.
723 setOperationAction(ISD::VASTART, MVT::Other, Custom);
724 setOperationAction(ISD::VAARG, MVT::Other, Expand);
725 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
726 setOperationAction(ISD::VAEND, MVT::Other, Expand);
727 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
728 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
730 if (!Subtarget->isTargetMachO()) {
731 // Non-MachO platforms may return values in these registers via the
732 // personality function.
733 setExceptionPointerRegister(ARM::R0);
734 setExceptionSelectorRegister(ARM::R1);
737 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
738 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
739 // the default expansion.
740 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
741 // ATOMIC_FENCE needs custom lowering; the other 32-bit ones are legal and
743 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
744 // Custom lowering for 64-bit ops
745 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
746 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
747 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
748 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
749 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
750 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
751 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
752 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
753 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
754 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
755 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
756 // On v8, we have particularly efficient implementations of atomic fences
757 // if they can be combined with nearby atomic loads and stores.
758 if (!Subtarget->hasV8Ops()) {
759 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
760 setInsertFencesForAtomic(true);
762 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
764 // If there's anything we can use as a barrier, go through custom lowering
766 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
767 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
769 // Set them all for expansion, which will force libcalls.
770 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
771 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
772 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
773 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
774 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
775 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
776 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
777 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
778 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
779 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
780 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
781 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
782 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
783 // Unordered/Monotonic case.
784 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
785 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
788 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
790 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
791 if (!Subtarget->hasV6Ops()) {
792 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
793 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
795 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
797 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
798 !Subtarget->isThumb1Only()) {
799 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
800 // iff target supports vfp2.
801 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
802 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
805 // We want to custom lower some of our intrinsics.
806 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
807 if (Subtarget->isTargetDarwin()) {
808 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
809 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
810 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
813 setOperationAction(ISD::SETCC, MVT::i32, Expand);
814 setOperationAction(ISD::SETCC, MVT::f32, Expand);
815 setOperationAction(ISD::SETCC, MVT::f64, Expand);
816 setOperationAction(ISD::SELECT, MVT::i32, Custom);
817 setOperationAction(ISD::SELECT, MVT::f32, Custom);
818 setOperationAction(ISD::SELECT, MVT::f64, Custom);
819 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
820 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
821 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
823 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
824 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
825 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
826 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
827 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
829 // We don't support sin/cos/fmod/copysign/pow
830 setOperationAction(ISD::FSIN, MVT::f64, Expand);
831 setOperationAction(ISD::FSIN, MVT::f32, Expand);
832 setOperationAction(ISD::FCOS, MVT::f32, Expand);
833 setOperationAction(ISD::FCOS, MVT::f64, Expand);
834 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
835 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
836 setOperationAction(ISD::FREM, MVT::f64, Expand);
837 setOperationAction(ISD::FREM, MVT::f32, Expand);
838 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
839 !Subtarget->isThumb1Only()) {
840 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
841 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
843 setOperationAction(ISD::FPOW, MVT::f64, Expand);
844 setOperationAction(ISD::FPOW, MVT::f32, Expand);
846 if (!Subtarget->hasVFP4()) {
847 setOperationAction(ISD::FMA, MVT::f64, Expand);
848 setOperationAction(ISD::FMA, MVT::f32, Expand);
851 // Various VFP goodness
852 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
853 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
854 if (Subtarget->hasVFP2()) {
855 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
856 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
857 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
858 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
860 // Special handling for half-precision FP.
861 if (!Subtarget->hasFP16()) {
862 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
863 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
867 // Combine sin / cos into one node or libcall if possible.
868 if (Subtarget->hasSinCos()) {
869 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
870 setLibcallName(RTLIB::SINCOS_F64, "sincos");
871 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
872 // For iOS, we don't want to the normal expansion of a libcall to
873 // sincos. We want to issue a libcall to __sincos_stret.
874 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
875 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
879 // We have target-specific dag combine patterns for the following nodes:
880 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
881 setTargetDAGCombine(ISD::ADD);
882 setTargetDAGCombine(ISD::SUB);
883 setTargetDAGCombine(ISD::MUL);
884 setTargetDAGCombine(ISD::AND);
885 setTargetDAGCombine(ISD::OR);
886 setTargetDAGCombine(ISD::XOR);
888 if (Subtarget->hasV6Ops())
889 setTargetDAGCombine(ISD::SRL);
891 setStackPointerRegisterToSaveRestore(ARM::SP);
893 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
894 !Subtarget->hasVFP2())
895 setSchedulingPreference(Sched::RegPressure);
897 setSchedulingPreference(Sched::Hybrid);
899 //// temporary - rewrite interface to use type
900 MaxStoresPerMemset = 8;
901 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
902 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
903 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
904 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
905 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
907 // On ARM arguments smaller than 4 bytes are extended, so all arguments
908 // are at least 4 bytes aligned.
909 setMinStackArgumentAlignment(4);
911 // Prefer likely predicted branches to selects on out-of-order cores.
912 PredictableSelectIsExpensive = Subtarget->isLikeA9();
914 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
917 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
918 bool isThumb2, unsigned &LdrOpc,
920 static const unsigned LoadBares[4][2] = {{ARM::LDREXB, ARM::t2LDREXB},
921 {ARM::LDREXH, ARM::t2LDREXH},
922 {ARM::LDREX, ARM::t2LDREX},
923 {ARM::LDREXD, ARM::t2LDREXD}};
924 static const unsigned LoadAcqs[4][2] = {{ARM::LDAEXB, ARM::t2LDAEXB},
925 {ARM::LDAEXH, ARM::t2LDAEXH},
926 {ARM::LDAEX, ARM::t2LDAEX},
927 {ARM::LDAEXD, ARM::t2LDAEXD}};
928 static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
929 {ARM::STREXH, ARM::t2STREXH},
930 {ARM::STREX, ARM::t2STREX},
931 {ARM::STREXD, ARM::t2STREXD}};
932 static const unsigned StoreRels[4][2] = {{ARM::STLEXB, ARM::t2STLEXB},
933 {ARM::STLEXH, ARM::t2STLEXH},
934 {ARM::STLEX, ARM::t2STLEX},
935 {ARM::STLEXD, ARM::t2STLEXD}};
937 const unsigned (*LoadOps)[2], (*StoreOps)[2];
938 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
943 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
944 StoreOps = StoreRels;
946 StoreOps = StoreBares;
948 assert(isPowerOf2_32(Size) && Size <= 8 &&
949 "unsupported size for atomic binary op!");
951 LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
952 StrOpc = StoreOps[Log2_32(Size)][isThumb2];
955 // FIXME: It might make sense to define the representative register class as the
956 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
957 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
958 // SPR's representative would be DPR_VFP2. This should work well if register
959 // pressure tracking were modified such that a register use would increment the
960 // pressure of the register class's representative and all of it's super
961 // classes' representatives transitively. We have not implemented this because
962 // of the difficulty prior to coalescing of modeling operand register classes
963 // due to the common occurrence of cross class copies and subregister insertions
965 std::pair<const TargetRegisterClass*, uint8_t>
966 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
967 const TargetRegisterClass *RRC = 0;
969 switch (VT.SimpleTy) {
971 return TargetLowering::findRepresentativeClass(VT);
972 // Use DPR as representative register class for all floating point
973 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
974 // the cost is 1 for both f32 and f64.
975 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
976 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
977 RRC = &ARM::DPRRegClass;
978 // When NEON is used for SP, only half of the register file is available
979 // because operations that define both SP and DP results will be constrained
980 // to the VFP2 class (D0-D15). We currently model this constraint prior to
981 // coalescing by double-counting the SP regs. See the FIXME above.
982 if (Subtarget->useNEONForSinglePrecisionFP())
985 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
986 case MVT::v4f32: case MVT::v2f64:
987 RRC = &ARM::DPRRegClass;
991 RRC = &ARM::DPRRegClass;
995 RRC = &ARM::DPRRegClass;
999 return std::make_pair(RRC, Cost);
1002 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1005 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1006 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1007 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1008 case ARMISD::CALL: return "ARMISD::CALL";
1009 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1010 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1011 case ARMISD::tCALL: return "ARMISD::tCALL";
1012 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1013 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1014 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1015 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1016 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1017 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1018 case ARMISD::CMP: return "ARMISD::CMP";
1019 case ARMISD::CMN: return "ARMISD::CMN";
1020 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1021 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1022 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1023 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1024 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1026 case ARMISD::CMOV: return "ARMISD::CMOV";
1028 case ARMISD::RBIT: return "ARMISD::RBIT";
1030 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1031 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1032 case ARMISD::SITOF: return "ARMISD::SITOF";
1033 case ARMISD::UITOF: return "ARMISD::UITOF";
1035 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1036 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1037 case ARMISD::RRX: return "ARMISD::RRX";
1039 case ARMISD::ADDC: return "ARMISD::ADDC";
1040 case ARMISD::ADDE: return "ARMISD::ADDE";
1041 case ARMISD::SUBC: return "ARMISD::SUBC";
1042 case ARMISD::SUBE: return "ARMISD::SUBE";
1044 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1045 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1047 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1048 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1050 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1052 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1054 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1056 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1058 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1060 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1061 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1062 case ARMISD::VCGE: return "ARMISD::VCGE";
1063 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1064 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1065 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1066 case ARMISD::VCGT: return "ARMISD::VCGT";
1067 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1068 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1069 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1070 case ARMISD::VTST: return "ARMISD::VTST";
1072 case ARMISD::VSHL: return "ARMISD::VSHL";
1073 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1074 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1075 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1076 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1077 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1078 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1079 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1080 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1081 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1082 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1083 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1084 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1085 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1086 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1087 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1088 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1089 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1090 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1091 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1092 case ARMISD::VDUP: return "ARMISD::VDUP";
1093 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1094 case ARMISD::VEXT: return "ARMISD::VEXT";
1095 case ARMISD::VREV64: return "ARMISD::VREV64";
1096 case ARMISD::VREV32: return "ARMISD::VREV32";
1097 case ARMISD::VREV16: return "ARMISD::VREV16";
1098 case ARMISD::VZIP: return "ARMISD::VZIP";
1099 case ARMISD::VUZP: return "ARMISD::VUZP";
1100 case ARMISD::VTRN: return "ARMISD::VTRN";
1101 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1102 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1103 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1104 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1105 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1106 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1107 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1108 case ARMISD::FMAX: return "ARMISD::FMAX";
1109 case ARMISD::FMIN: return "ARMISD::FMIN";
1110 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1111 case ARMISD::VMINNM: return "ARMISD::VMIN";
1112 case ARMISD::BFI: return "ARMISD::BFI";
1113 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1114 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1115 case ARMISD::VBSL: return "ARMISD::VBSL";
1116 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1117 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1118 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1119 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1120 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1121 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1122 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1123 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1124 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1125 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1126 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1127 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1128 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1129 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1130 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1131 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1132 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1133 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1134 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1135 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1139 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1140 if (!VT.isVector()) return getPointerTy();
1141 return VT.changeVectorElementTypeToInteger();
1144 /// getRegClassFor - Return the register class that should be used for the
1145 /// specified value type.
1146 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1147 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1148 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1149 // load / store 4 to 8 consecutive D registers.
1150 if (Subtarget->hasNEON()) {
1151 if (VT == MVT::v4i64)
1152 return &ARM::QQPRRegClass;
1153 if (VT == MVT::v8i64)
1154 return &ARM::QQQQPRRegClass;
1156 return TargetLowering::getRegClassFor(VT);
1159 // Create a fast isel object.
1161 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1162 const TargetLibraryInfo *libInfo) const {
1163 return ARM::createFastISel(funcInfo, libInfo);
1166 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1167 /// be used for loads / stores from the global.
1168 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1169 return (Subtarget->isThumb1Only() ? 127 : 4095);
1172 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1173 unsigned NumVals = N->getNumValues();
1175 return Sched::RegPressure;
1177 for (unsigned i = 0; i != NumVals; ++i) {
1178 EVT VT = N->getValueType(i);
1179 if (VT == MVT::Glue || VT == MVT::Other)
1181 if (VT.isFloatingPoint() || VT.isVector())
1185 if (!N->isMachineOpcode())
1186 return Sched::RegPressure;
1188 // Load are scheduled for latency even if there instruction itinerary
1189 // is not available.
1190 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1191 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1193 if (MCID.getNumDefs() == 0)
1194 return Sched::RegPressure;
1195 if (!Itins->isEmpty() &&
1196 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1199 return Sched::RegPressure;
1202 //===----------------------------------------------------------------------===//
1204 //===----------------------------------------------------------------------===//
1206 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1207 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1209 default: llvm_unreachable("Unknown condition code!");
1210 case ISD::SETNE: return ARMCC::NE;
1211 case ISD::SETEQ: return ARMCC::EQ;
1212 case ISD::SETGT: return ARMCC::GT;
1213 case ISD::SETGE: return ARMCC::GE;
1214 case ISD::SETLT: return ARMCC::LT;
1215 case ISD::SETLE: return ARMCC::LE;
1216 case ISD::SETUGT: return ARMCC::HI;
1217 case ISD::SETUGE: return ARMCC::HS;
1218 case ISD::SETULT: return ARMCC::LO;
1219 case ISD::SETULE: return ARMCC::LS;
1223 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1224 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1225 ARMCC::CondCodes &CondCode2) {
1226 CondCode2 = ARMCC::AL;
1228 default: llvm_unreachable("Unknown FP condition!");
1230 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1232 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1234 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1235 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1236 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1237 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1238 case ISD::SETO: CondCode = ARMCC::VC; break;
1239 case ISD::SETUO: CondCode = ARMCC::VS; break;
1240 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1241 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1242 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1244 case ISD::SETULT: CondCode = ARMCC::LT; break;
1246 case ISD::SETULE: CondCode = ARMCC::LE; break;
1248 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1252 //===----------------------------------------------------------------------===//
1253 // Calling Convention Implementation
1254 //===----------------------------------------------------------------------===//
1256 #include "ARMGenCallingConv.inc"
1258 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1259 /// given CallingConvention value.
1260 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1262 bool isVarArg) const {
1265 llvm_unreachable("Unsupported calling convention");
1266 case CallingConv::Fast:
1267 if (Subtarget->hasVFP2() && !isVarArg) {
1268 if (!Subtarget->isAAPCS_ABI())
1269 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1270 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1271 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1274 case CallingConv::C: {
1275 // Use target triple & subtarget features to do actual dispatch.
1276 if (!Subtarget->isAAPCS_ABI())
1277 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1278 else if (Subtarget->hasVFP2() &&
1279 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1281 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1282 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1284 case CallingConv::ARM_AAPCS_VFP:
1286 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1288 case CallingConv::ARM_AAPCS:
1289 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1290 case CallingConv::ARM_APCS:
1291 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1292 case CallingConv::GHC:
1293 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1297 /// LowerCallResult - Lower the result values of a call into the
1298 /// appropriate copies out of appropriate physical registers.
1300 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1301 CallingConv::ID CallConv, bool isVarArg,
1302 const SmallVectorImpl<ISD::InputArg> &Ins,
1303 SDLoc dl, SelectionDAG &DAG,
1304 SmallVectorImpl<SDValue> &InVals,
1305 bool isThisReturn, SDValue ThisVal) const {
1307 // Assign locations to each value returned by this call.
1308 SmallVector<CCValAssign, 16> RVLocs;
1309 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1310 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1311 CCInfo.AnalyzeCallResult(Ins,
1312 CCAssignFnForNode(CallConv, /* Return*/ true,
1315 // Copy all of the result registers out of their specified physreg.
1316 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1317 CCValAssign VA = RVLocs[i];
1319 // Pass 'this' value directly from the argument to return value, to avoid
1320 // reg unit interference
1321 if (i == 0 && isThisReturn) {
1322 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1323 "unexpected return calling convention register assignment");
1324 InVals.push_back(ThisVal);
1329 if (VA.needsCustom()) {
1330 // Handle f64 or half of a v2f64.
1331 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1333 Chain = Lo.getValue(1);
1334 InFlag = Lo.getValue(2);
1335 VA = RVLocs[++i]; // skip ahead to next loc
1336 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1338 Chain = Hi.getValue(1);
1339 InFlag = Hi.getValue(2);
1340 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1342 if (VA.getLocVT() == MVT::v2f64) {
1343 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1344 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1345 DAG.getConstant(0, MVT::i32));
1347 VA = RVLocs[++i]; // skip ahead to next loc
1348 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1349 Chain = Lo.getValue(1);
1350 InFlag = Lo.getValue(2);
1351 VA = RVLocs[++i]; // skip ahead to next loc
1352 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1353 Chain = Hi.getValue(1);
1354 InFlag = Hi.getValue(2);
1355 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1356 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1357 DAG.getConstant(1, MVT::i32));
1360 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1362 Chain = Val.getValue(1);
1363 InFlag = Val.getValue(2);
1366 switch (VA.getLocInfo()) {
1367 default: llvm_unreachable("Unknown loc info!");
1368 case CCValAssign::Full: break;
1369 case CCValAssign::BCvt:
1370 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1374 InVals.push_back(Val);
1380 /// LowerMemOpCallTo - Store the argument to the stack.
1382 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1383 SDValue StackPtr, SDValue Arg,
1384 SDLoc dl, SelectionDAG &DAG,
1385 const CCValAssign &VA,
1386 ISD::ArgFlagsTy Flags) const {
1387 unsigned LocMemOffset = VA.getLocMemOffset();
1388 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1389 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1390 return DAG.getStore(Chain, dl, Arg, PtrOff,
1391 MachinePointerInfo::getStack(LocMemOffset),
1395 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1396 SDValue Chain, SDValue &Arg,
1397 RegsToPassVector &RegsToPass,
1398 CCValAssign &VA, CCValAssign &NextVA,
1400 SmallVectorImpl<SDValue> &MemOpChains,
1401 ISD::ArgFlagsTy Flags) const {
1403 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1404 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1405 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1407 if (NextVA.isRegLoc())
1408 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1410 assert(NextVA.isMemLoc());
1411 if (StackPtr.getNode() == 0)
1412 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1414 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1420 /// LowerCall - Lowering a call into a callseq_start <-
1421 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1424 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1425 SmallVectorImpl<SDValue> &InVals) const {
1426 SelectionDAG &DAG = CLI.DAG;
1428 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1429 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1430 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1431 SDValue Chain = CLI.Chain;
1432 SDValue Callee = CLI.Callee;
1433 bool &isTailCall = CLI.IsTailCall;
1434 CallingConv::ID CallConv = CLI.CallConv;
1435 bool doesNotRet = CLI.DoesNotReturn;
1436 bool isVarArg = CLI.IsVarArg;
1438 MachineFunction &MF = DAG.getMachineFunction();
1439 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1440 bool isThisReturn = false;
1441 bool isSibCall = false;
1442 // Disable tail calls if they're not supported.
1443 if (!Subtarget->supportsTailCall())
1446 // Check if it's really possible to do a tail call.
1447 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1448 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1449 Outs, OutVals, Ins, DAG);
1450 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1451 // detected sibcalls.
1458 // Analyze operands of the call, assigning locations to each operand.
1459 SmallVector<CCValAssign, 16> ArgLocs;
1460 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1461 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1462 CCInfo.AnalyzeCallOperands(Outs,
1463 CCAssignFnForNode(CallConv, /* Return*/ false,
1466 // Get a count of how many bytes are to be pushed on the stack.
1467 unsigned NumBytes = CCInfo.getNextStackOffset();
1469 // For tail calls, memory operands are available in our caller's stack.
1473 // Adjust the stack pointer for the new arguments...
1474 // These operations are automatically eliminated by the prolog/epilog pass
1476 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1479 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1481 RegsToPassVector RegsToPass;
1482 SmallVector<SDValue, 8> MemOpChains;
1484 // Walk the register/memloc assignments, inserting copies/loads. In the case
1485 // of tail call optimization, arguments are handled later.
1486 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1488 ++i, ++realArgIdx) {
1489 CCValAssign &VA = ArgLocs[i];
1490 SDValue Arg = OutVals[realArgIdx];
1491 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1492 bool isByVal = Flags.isByVal();
1494 // Promote the value if needed.
1495 switch (VA.getLocInfo()) {
1496 default: llvm_unreachable("Unknown loc info!");
1497 case CCValAssign::Full: break;
1498 case CCValAssign::SExt:
1499 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1501 case CCValAssign::ZExt:
1502 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1504 case CCValAssign::AExt:
1505 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1507 case CCValAssign::BCvt:
1508 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1512 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1513 if (VA.needsCustom()) {
1514 if (VA.getLocVT() == MVT::v2f64) {
1515 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1516 DAG.getConstant(0, MVT::i32));
1517 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1518 DAG.getConstant(1, MVT::i32));
1520 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1521 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1523 VA = ArgLocs[++i]; // skip ahead to next loc
1524 if (VA.isRegLoc()) {
1525 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1526 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1528 assert(VA.isMemLoc());
1530 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1531 dl, DAG, VA, Flags));
1534 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1535 StackPtr, MemOpChains, Flags);
1537 } else if (VA.isRegLoc()) {
1538 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1539 assert(VA.getLocVT() == MVT::i32 &&
1540 "unexpected calling convention register assignment");
1541 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1542 "unexpected use of 'returned'");
1543 isThisReturn = true;
1545 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1546 } else if (isByVal) {
1547 assert(VA.isMemLoc());
1548 unsigned offset = 0;
1550 // True if this byval aggregate will be split between registers
1552 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1553 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1555 if (CurByValIdx < ByValArgsCount) {
1557 unsigned RegBegin, RegEnd;
1558 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1560 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1562 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1563 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1564 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1565 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1566 MachinePointerInfo(),
1567 false, false, false,
1568 DAG.InferPtrAlignment(AddArg));
1569 MemOpChains.push_back(Load.getValue(1));
1570 RegsToPass.push_back(std::make_pair(j, Load));
1573 // If parameter size outsides register area, "offset" value
1574 // helps us to calculate stack slot for remained part properly.
1575 offset = RegEnd - RegBegin;
1577 CCInfo.nextInRegsParam();
1580 if (Flags.getByValSize() > 4*offset) {
1581 unsigned LocMemOffset = VA.getLocMemOffset();
1582 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1583 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1585 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1586 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1587 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1589 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1591 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1592 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1593 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1594 Ops, array_lengthof(Ops)));
1596 } else if (!isSibCall) {
1597 assert(VA.isMemLoc());
1599 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1600 dl, DAG, VA, Flags));
1604 if (!MemOpChains.empty())
1605 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1606 &MemOpChains[0], MemOpChains.size());
1608 // Build a sequence of copy-to-reg nodes chained together with token chain
1609 // and flag operands which copy the outgoing args into the appropriate regs.
1611 // Tail call byval lowering might overwrite argument registers so in case of
1612 // tail call optimization the copies to registers are lowered later.
1614 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1615 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1616 RegsToPass[i].second, InFlag);
1617 InFlag = Chain.getValue(1);
1620 // For tail calls lower the arguments to the 'real' stack slot.
1622 // Force all the incoming stack arguments to be loaded from the stack
1623 // before any new outgoing arguments are stored to the stack, because the
1624 // outgoing stack slots may alias the incoming argument stack slots, and
1625 // the alias isn't otherwise explicit. This is slightly more conservative
1626 // than necessary, because it means that each store effectively depends
1627 // on every argument instead of just those arguments it would clobber.
1629 // Do not flag preceding copytoreg stuff together with the following stuff.
1631 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1632 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1633 RegsToPass[i].second, InFlag);
1634 InFlag = Chain.getValue(1);
1639 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1640 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1641 // node so that legalize doesn't hack it.
1642 bool isDirect = false;
1643 bool isARMFunc = false;
1644 bool isLocalARMFunc = false;
1645 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1647 if (EnableARMLongCalls) {
1648 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1649 && "long-calls with non-static relocation model!");
1650 // Handle a global address or an external symbol. If it's not one of
1651 // those, the target's already in a register, so we don't need to do
1653 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1654 const GlobalValue *GV = G->getGlobal();
1655 // Create a constant pool entry for the callee address
1656 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1657 ARMConstantPoolValue *CPV =
1658 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1660 // Get the address of the callee into a register
1661 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1662 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1663 Callee = DAG.getLoad(getPointerTy(), dl,
1664 DAG.getEntryNode(), CPAddr,
1665 MachinePointerInfo::getConstantPool(),
1666 false, false, false, 0);
1667 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1668 const char *Sym = S->getSymbol();
1670 // Create a constant pool entry for the callee address
1671 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1672 ARMConstantPoolValue *CPV =
1673 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1674 ARMPCLabelIndex, 0);
1675 // Get the address of the callee into a register
1676 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1677 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1678 Callee = DAG.getLoad(getPointerTy(), dl,
1679 DAG.getEntryNode(), CPAddr,
1680 MachinePointerInfo::getConstantPool(),
1681 false, false, false, 0);
1683 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1684 const GlobalValue *GV = G->getGlobal();
1686 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1687 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1688 getTargetMachine().getRelocationModel() != Reloc::Static;
1689 isARMFunc = !Subtarget->isThumb() || isStub;
1690 // ARM call to a local ARM function is predicable.
1691 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1692 // tBX takes a register source operand.
1693 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1694 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1695 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1696 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1698 // On ELF targets for PIC code, direct calls should go through the PLT
1699 unsigned OpFlags = 0;
1700 if (Subtarget->isTargetELF() &&
1701 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1702 OpFlags = ARMII::MO_PLT;
1703 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1705 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1707 bool isStub = Subtarget->isTargetMachO() &&
1708 getTargetMachine().getRelocationModel() != Reloc::Static;
1709 isARMFunc = !Subtarget->isThumb() || isStub;
1710 // tBX takes a register source operand.
1711 const char *Sym = S->getSymbol();
1712 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1713 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1714 ARMConstantPoolValue *CPV =
1715 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1716 ARMPCLabelIndex, 4);
1717 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1718 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1719 Callee = DAG.getLoad(getPointerTy(), dl,
1720 DAG.getEntryNode(), CPAddr,
1721 MachinePointerInfo::getConstantPool(),
1722 false, false, false, 0);
1723 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1724 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1725 getPointerTy(), Callee, PICLabel);
1727 unsigned OpFlags = 0;
1728 // On ELF targets for PIC code, direct calls should go through the PLT
1729 if (Subtarget->isTargetELF() &&
1730 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1731 OpFlags = ARMII::MO_PLT;
1732 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1736 // FIXME: handle tail calls differently.
1738 bool HasMinSizeAttr = Subtarget->isMinSize();
1739 if (Subtarget->isThumb()) {
1740 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1741 CallOpc = ARMISD::CALL_NOLINK;
1743 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1745 if (!isDirect && !Subtarget->hasV5TOps())
1746 CallOpc = ARMISD::CALL_NOLINK;
1747 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1748 // Emit regular call when code size is the priority
1750 // "mov lr, pc; b _foo" to avoid confusing the RSP
1751 CallOpc = ARMISD::CALL_NOLINK;
1753 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1756 std::vector<SDValue> Ops;
1757 Ops.push_back(Chain);
1758 Ops.push_back(Callee);
1760 // Add argument registers to the end of the list so that they are known live
1762 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1763 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1764 RegsToPass[i].second.getValueType()));
1766 // Add a register mask operand representing the call-preserved registers.
1768 const uint32_t *Mask;
1769 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1770 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1772 // For 'this' returns, use the R0-preserving mask if applicable
1773 Mask = ARI->getThisReturnPreservedMask(CallConv);
1775 // Set isThisReturn to false if the calling convention is not one that
1776 // allows 'returned' to be modeled in this way, so LowerCallResult does
1777 // not try to pass 'this' straight through
1778 isThisReturn = false;
1779 Mask = ARI->getCallPreservedMask(CallConv);
1782 Mask = ARI->getCallPreservedMask(CallConv);
1784 assert(Mask && "Missing call preserved mask for calling convention");
1785 Ops.push_back(DAG.getRegisterMask(Mask));
1788 if (InFlag.getNode())
1789 Ops.push_back(InFlag);
1791 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1793 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1795 // Returns a chain and a flag for retval copy to use.
1796 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1797 InFlag = Chain.getValue(1);
1799 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1800 DAG.getIntPtrConstant(0, true), InFlag, dl);
1802 InFlag = Chain.getValue(1);
1804 // Handle result values, copying them out of physregs into vregs that we
1806 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1807 InVals, isThisReturn,
1808 isThisReturn ? OutVals[0] : SDValue());
1811 /// HandleByVal - Every parameter *after* a byval parameter is passed
1812 /// on the stack. Remember the next parameter register to allocate,
1813 /// and then confiscate the rest of the parameter registers to insure
1816 ARMTargetLowering::HandleByVal(
1817 CCState *State, unsigned &size, unsigned Align) const {
1818 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1819 assert((State->getCallOrPrologue() == Prologue ||
1820 State->getCallOrPrologue() == Call) &&
1821 "unhandled ParmContext");
1823 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1824 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1825 unsigned AlignInRegs = Align / 4;
1826 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1827 for (unsigned i = 0; i < Waste; ++i)
1828 reg = State->AllocateReg(GPRArgRegs, 4);
1831 unsigned excess = 4 * (ARM::R4 - reg);
1833 // Special case when NSAA != SP and parameter size greater than size of
1834 // all remained GPR regs. In that case we can't split parameter, we must
1835 // send it to stack. We also must set NCRN to R4, so waste all
1836 // remained registers.
1837 const unsigned NSAAOffset = State->getNextStackOffset();
1838 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1839 while (State->AllocateReg(GPRArgRegs, 4))
1844 // First register for byval parameter is the first register that wasn't
1845 // allocated before this method call, so it would be "reg".
1846 // If parameter is small enough to be saved in range [reg, r4), then
1847 // the end (first after last) register would be reg + param-size-in-regs,
1848 // else parameter would be splitted between registers and stack,
1849 // end register would be r4 in this case.
1850 unsigned ByValRegBegin = reg;
1851 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1852 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1853 // Note, first register is allocated in the beginning of function already,
1854 // allocate remained amount of registers we need.
1855 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1856 State->AllocateReg(GPRArgRegs, 4);
1857 // A byval parameter that is split between registers and memory needs its
1858 // size truncated here.
1859 // In the case where the entire structure fits in registers, we set the
1860 // size in memory to zero.
1869 /// MatchingStackOffset - Return true if the given stack call argument is
1870 /// already available in the same position (relatively) of the caller's
1871 /// incoming argument stack.
1873 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1874 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1875 const TargetInstrInfo *TII) {
1876 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1878 if (Arg.getOpcode() == ISD::CopyFromReg) {
1879 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1880 if (!TargetRegisterInfo::isVirtualRegister(VR))
1882 MachineInstr *Def = MRI->getVRegDef(VR);
1885 if (!Flags.isByVal()) {
1886 if (!TII->isLoadFromStackSlot(Def, FI))
1891 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1892 if (Flags.isByVal())
1893 // ByVal argument is passed in as a pointer but it's now being
1894 // dereferenced. e.g.
1895 // define @foo(%struct.X* %A) {
1896 // tail call @bar(%struct.X* byval %A)
1899 SDValue Ptr = Ld->getBasePtr();
1900 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1903 FI = FINode->getIndex();
1907 assert(FI != INT_MAX);
1908 if (!MFI->isFixedObjectIndex(FI))
1910 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1913 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1914 /// for tail call optimization. Targets which want to do tail call
1915 /// optimization should implement this function.
1917 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1918 CallingConv::ID CalleeCC,
1920 bool isCalleeStructRet,
1921 bool isCallerStructRet,
1922 const SmallVectorImpl<ISD::OutputArg> &Outs,
1923 const SmallVectorImpl<SDValue> &OutVals,
1924 const SmallVectorImpl<ISD::InputArg> &Ins,
1925 SelectionDAG& DAG) const {
1926 const Function *CallerF = DAG.getMachineFunction().getFunction();
1927 CallingConv::ID CallerCC = CallerF->getCallingConv();
1928 bool CCMatch = CallerCC == CalleeCC;
1930 // Look for obvious safe cases to perform tail call optimization that do not
1931 // require ABI changes. This is what gcc calls sibcall.
1933 // Do not sibcall optimize vararg calls unless the call site is not passing
1935 if (isVarArg && !Outs.empty())
1938 // Exception-handling functions need a special set of instructions to indicate
1939 // a return to the hardware. Tail-calling another function would probably
1941 if (CallerF->hasFnAttribute("interrupt"))
1944 // Also avoid sibcall optimization if either caller or callee uses struct
1945 // return semantics.
1946 if (isCalleeStructRet || isCallerStructRet)
1949 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1950 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1951 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1952 // support in the assembler and linker to be used. This would need to be
1953 // fixed to fully support tail calls in Thumb1.
1955 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1956 // LR. This means if we need to reload LR, it takes an extra instructions,
1957 // which outweighs the value of the tail call; but here we don't know yet
1958 // whether LR is going to be used. Probably the right approach is to
1959 // generate the tail call here and turn it back into CALL/RET in
1960 // emitEpilogue if LR is used.
1962 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1963 // but we need to make sure there are enough registers; the only valid
1964 // registers are the 4 used for parameters. We don't currently do this
1966 if (Subtarget->isThumb1Only())
1969 // If the calling conventions do not match, then we'd better make sure the
1970 // results are returned in the same way as what the caller expects.
1972 SmallVector<CCValAssign, 16> RVLocs1;
1973 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1974 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1975 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1977 SmallVector<CCValAssign, 16> RVLocs2;
1978 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1979 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1980 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1982 if (RVLocs1.size() != RVLocs2.size())
1984 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1985 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1987 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1989 if (RVLocs1[i].isRegLoc()) {
1990 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1993 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1999 // If Caller's vararg or byval argument has been split between registers and
2000 // stack, do not perform tail call, since part of the argument is in caller's
2002 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2003 getInfo<ARMFunctionInfo>();
2004 if (AFI_Caller->getArgRegsSaveSize())
2007 // If the callee takes no arguments then go on to check the results of the
2009 if (!Outs.empty()) {
2010 // Check if stack adjustment is needed. For now, do not do this if any
2011 // argument is passed on the stack.
2012 SmallVector<CCValAssign, 16> ArgLocs;
2013 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2014 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2015 CCInfo.AnalyzeCallOperands(Outs,
2016 CCAssignFnForNode(CalleeCC, false, isVarArg));
2017 if (CCInfo.getNextStackOffset()) {
2018 MachineFunction &MF = DAG.getMachineFunction();
2020 // Check if the arguments are already laid out in the right way as
2021 // the caller's fixed stack objects.
2022 MachineFrameInfo *MFI = MF.getFrameInfo();
2023 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2024 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2025 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2027 ++i, ++realArgIdx) {
2028 CCValAssign &VA = ArgLocs[i];
2029 EVT RegVT = VA.getLocVT();
2030 SDValue Arg = OutVals[realArgIdx];
2031 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2032 if (VA.getLocInfo() == CCValAssign::Indirect)
2034 if (VA.needsCustom()) {
2035 // f64 and vector types are split into multiple registers or
2036 // register/stack-slot combinations. The types will not match
2037 // the registers; give up on memory f64 refs until we figure
2038 // out what to do about this.
2041 if (!ArgLocs[++i].isRegLoc())
2043 if (RegVT == MVT::v2f64) {
2044 if (!ArgLocs[++i].isRegLoc())
2046 if (!ArgLocs[++i].isRegLoc())
2049 } else if (!VA.isRegLoc()) {
2050 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2062 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2063 MachineFunction &MF, bool isVarArg,
2064 const SmallVectorImpl<ISD::OutputArg> &Outs,
2065 LLVMContext &Context) const {
2066 SmallVector<CCValAssign, 16> RVLocs;
2067 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2068 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2072 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2073 SDLoc DL, SelectionDAG &DAG) {
2074 const MachineFunction &MF = DAG.getMachineFunction();
2075 const Function *F = MF.getFunction();
2077 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2079 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2080 // version of the "preferred return address". These offsets affect the return
2081 // instruction if this is a return from PL1 without hypervisor extensions.
2082 // IRQ/FIQ: +4 "subs pc, lr, #4"
2083 // SWI: 0 "subs pc, lr, #0"
2084 // ABORT: +4 "subs pc, lr, #4"
2085 // UNDEF: +4/+2 "subs pc, lr, #0"
2086 // UNDEF varies depending on where the exception came from ARM or Thumb
2087 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2090 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2093 else if (IntKind == "SWI" || IntKind == "UNDEF")
2096 report_fatal_error("Unsupported interrupt attribute. If present, value "
2097 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2099 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2101 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2102 RetOps.data(), RetOps.size());
2106 ARMTargetLowering::LowerReturn(SDValue Chain,
2107 CallingConv::ID CallConv, bool isVarArg,
2108 const SmallVectorImpl<ISD::OutputArg> &Outs,
2109 const SmallVectorImpl<SDValue> &OutVals,
2110 SDLoc dl, SelectionDAG &DAG) const {
2112 // CCValAssign - represent the assignment of the return value to a location.
2113 SmallVector<CCValAssign, 16> RVLocs;
2115 // CCState - Info about the registers and stack slots.
2116 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2117 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2119 // Analyze outgoing return values.
2120 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2124 SmallVector<SDValue, 4> RetOps;
2125 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2127 // Copy the result values into the output registers.
2128 for (unsigned i = 0, realRVLocIdx = 0;
2130 ++i, ++realRVLocIdx) {
2131 CCValAssign &VA = RVLocs[i];
2132 assert(VA.isRegLoc() && "Can only return in registers!");
2134 SDValue Arg = OutVals[realRVLocIdx];
2136 switch (VA.getLocInfo()) {
2137 default: llvm_unreachable("Unknown loc info!");
2138 case CCValAssign::Full: break;
2139 case CCValAssign::BCvt:
2140 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2144 if (VA.needsCustom()) {
2145 if (VA.getLocVT() == MVT::v2f64) {
2146 // Extract the first half and return it in two registers.
2147 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2148 DAG.getConstant(0, MVT::i32));
2149 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2150 DAG.getVTList(MVT::i32, MVT::i32), Half);
2152 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2153 Flag = Chain.getValue(1);
2154 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2155 VA = RVLocs[++i]; // skip ahead to next loc
2156 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2157 HalfGPRs.getValue(1), Flag);
2158 Flag = Chain.getValue(1);
2159 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2160 VA = RVLocs[++i]; // skip ahead to next loc
2162 // Extract the 2nd half and fall through to handle it as an f64 value.
2163 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2164 DAG.getConstant(1, MVT::i32));
2166 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2168 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2169 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2170 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2171 Flag = Chain.getValue(1);
2172 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2173 VA = RVLocs[++i]; // skip ahead to next loc
2174 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2177 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2179 // Guarantee that all emitted copies are
2180 // stuck together, avoiding something bad.
2181 Flag = Chain.getValue(1);
2182 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2185 // Update chain and glue.
2188 RetOps.push_back(Flag);
2190 // CPUs which aren't M-class use a special sequence to return from
2191 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2192 // though we use "subs pc, lr, #N").
2194 // M-class CPUs actually use a normal return sequence with a special
2195 // (hardware-provided) value in LR, so the normal code path works.
2196 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2197 !Subtarget->isMClass()) {
2198 if (Subtarget->isThumb1Only())
2199 report_fatal_error("interrupt attribute is not supported in Thumb1");
2200 return LowerInterruptReturn(RetOps, dl, DAG);
2203 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2204 RetOps.data(), RetOps.size());
2207 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2208 if (N->getNumValues() != 1)
2210 if (!N->hasNUsesOfValue(1, 0))
2213 SDValue TCChain = Chain;
2214 SDNode *Copy = *N->use_begin();
2215 if (Copy->getOpcode() == ISD::CopyToReg) {
2216 // If the copy has a glue operand, we conservatively assume it isn't safe to
2217 // perform a tail call.
2218 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2220 TCChain = Copy->getOperand(0);
2221 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2222 SDNode *VMov = Copy;
2223 // f64 returned in a pair of GPRs.
2224 SmallPtrSet<SDNode*, 2> Copies;
2225 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2227 if (UI->getOpcode() != ISD::CopyToReg)
2231 if (Copies.size() > 2)
2234 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2236 SDValue UseChain = UI->getOperand(0);
2237 if (Copies.count(UseChain.getNode()))
2244 } else if (Copy->getOpcode() == ISD::BITCAST) {
2245 // f32 returned in a single GPR.
2246 if (!Copy->hasOneUse())
2248 Copy = *Copy->use_begin();
2249 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2251 TCChain = Copy->getOperand(0);
2256 bool HasRet = false;
2257 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2259 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2260 UI->getOpcode() != ARMISD::INTRET_FLAG)
2272 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2273 if (!Subtarget->supportsTailCall())
2276 if (!CI->isTailCall())
2279 return !Subtarget->isThumb1Only();
2282 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2283 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2284 // one of the above mentioned nodes. It has to be wrapped because otherwise
2285 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2286 // be used to form addressing mode. These wrapped nodes will be selected
2288 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2289 EVT PtrVT = Op.getValueType();
2290 // FIXME there is no actual debug info here
2292 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2294 if (CP->isMachineConstantPoolEntry())
2295 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2296 CP->getAlignment());
2298 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2299 CP->getAlignment());
2300 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2303 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2304 return MachineJumpTableInfo::EK_Inline;
2307 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2308 SelectionDAG &DAG) const {
2309 MachineFunction &MF = DAG.getMachineFunction();
2310 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2311 unsigned ARMPCLabelIndex = 0;
2313 EVT PtrVT = getPointerTy();
2314 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2315 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2317 if (RelocM == Reloc::Static) {
2318 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2320 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2321 ARMPCLabelIndex = AFI->createPICLabelUId();
2322 ARMConstantPoolValue *CPV =
2323 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2324 ARMCP::CPBlockAddress, PCAdj);
2325 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2327 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2328 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2329 MachinePointerInfo::getConstantPool(),
2330 false, false, false, 0);
2331 if (RelocM == Reloc::Static)
2333 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2334 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2337 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2339 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2340 SelectionDAG &DAG) const {
2342 EVT PtrVT = getPointerTy();
2343 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2344 MachineFunction &MF = DAG.getMachineFunction();
2345 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2346 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2347 ARMConstantPoolValue *CPV =
2348 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2349 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2350 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2351 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2352 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2353 MachinePointerInfo::getConstantPool(),
2354 false, false, false, 0);
2355 SDValue Chain = Argument.getValue(1);
2357 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2358 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2360 // call __tls_get_addr.
2363 Entry.Node = Argument;
2364 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2365 Args.push_back(Entry);
2366 // FIXME: is there useful debug info available here?
2367 TargetLowering::CallLoweringInfo CLI(Chain,
2368 (Type *) Type::getInt32Ty(*DAG.getContext()),
2369 false, false, false, false,
2370 0, CallingConv::C, /*isTailCall=*/false,
2371 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2372 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2373 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2374 return CallResult.first;
2377 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2378 // "local exec" model.
2380 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2382 TLSModel::Model model) const {
2383 const GlobalValue *GV = GA->getGlobal();
2386 SDValue Chain = DAG.getEntryNode();
2387 EVT PtrVT = getPointerTy();
2388 // Get the Thread Pointer
2389 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2391 if (model == TLSModel::InitialExec) {
2392 MachineFunction &MF = DAG.getMachineFunction();
2393 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2394 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2395 // Initial exec model.
2396 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2397 ARMConstantPoolValue *CPV =
2398 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2399 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2401 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2402 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2403 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2404 MachinePointerInfo::getConstantPool(),
2405 false, false, false, 0);
2406 Chain = Offset.getValue(1);
2408 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2409 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2411 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2412 MachinePointerInfo::getConstantPool(),
2413 false, false, false, 0);
2416 assert(model == TLSModel::LocalExec);
2417 ARMConstantPoolValue *CPV =
2418 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2419 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2420 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2421 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2422 MachinePointerInfo::getConstantPool(),
2423 false, false, false, 0);
2426 // The address of the thread local variable is the add of the thread
2427 // pointer with the offset of the variable.
2428 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2432 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2433 // TODO: implement the "local dynamic" model
2434 assert(Subtarget->isTargetELF() &&
2435 "TLS not implemented for non-ELF targets");
2436 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2438 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2441 case TLSModel::GeneralDynamic:
2442 case TLSModel::LocalDynamic:
2443 return LowerToTLSGeneralDynamicModel(GA, DAG);
2444 case TLSModel::InitialExec:
2445 case TLSModel::LocalExec:
2446 return LowerToTLSExecModels(GA, DAG, model);
2448 llvm_unreachable("bogus TLS model");
2451 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2452 SelectionDAG &DAG) const {
2453 EVT PtrVT = getPointerTy();
2455 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2456 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2457 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2458 ARMConstantPoolValue *CPV =
2459 ARMConstantPoolConstant::Create(GV,
2460 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2461 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2462 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2463 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2465 MachinePointerInfo::getConstantPool(),
2466 false, false, false, 0);
2467 SDValue Chain = Result.getValue(1);
2468 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2469 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2471 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2472 MachinePointerInfo::getGOT(),
2473 false, false, false, 0);
2477 // If we have T2 ops, we can materialize the address directly via movt/movw
2478 // pair. This is always cheaper.
2479 if (Subtarget->useMovt()) {
2481 // FIXME: Once remat is capable of dealing with instructions with register
2482 // operands, expand this into two nodes.
2483 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2484 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2486 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2487 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2488 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2489 MachinePointerInfo::getConstantPool(),
2490 false, false, false, 0);
2494 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2495 SelectionDAG &DAG) const {
2496 EVT PtrVT = getPointerTy();
2498 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2499 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2501 if (Subtarget->useMovt())
2504 // FIXME: Once remat is capable of dealing with instructions with register
2505 // operands, expand this into multiple nodes
2507 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2509 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2510 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2512 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2513 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2514 MachinePointerInfo::getGOT(), false, false, false, 0);
2518 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2519 SelectionDAG &DAG) const {
2520 assert(Subtarget->isTargetELF() &&
2521 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2522 MachineFunction &MF = DAG.getMachineFunction();
2523 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2524 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2525 EVT PtrVT = getPointerTy();
2527 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2528 ARMConstantPoolValue *CPV =
2529 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2530 ARMPCLabelIndex, PCAdj);
2531 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2532 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2533 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2534 MachinePointerInfo::getConstantPool(),
2535 false, false, false, 0);
2536 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2537 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2541 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2543 SDValue Val = DAG.getConstant(0, MVT::i32);
2544 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2545 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2546 Op.getOperand(1), Val);
2550 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2552 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2553 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2557 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2558 const ARMSubtarget *Subtarget) const {
2559 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2562 default: return SDValue(); // Don't custom lower most intrinsics.
2563 case Intrinsic::arm_thread_pointer: {
2564 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2565 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2567 case Intrinsic::eh_sjlj_lsda: {
2568 MachineFunction &MF = DAG.getMachineFunction();
2569 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2570 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2571 EVT PtrVT = getPointerTy();
2572 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2574 unsigned PCAdj = (RelocM != Reloc::PIC_)
2575 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2576 ARMConstantPoolValue *CPV =
2577 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2578 ARMCP::CPLSDA, PCAdj);
2579 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2580 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2582 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2583 MachinePointerInfo::getConstantPool(),
2584 false, false, false, 0);
2586 if (RelocM == Reloc::PIC_) {
2587 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2588 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2592 case Intrinsic::arm_neon_vmulls:
2593 case Intrinsic::arm_neon_vmullu: {
2594 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2595 ? ARMISD::VMULLs : ARMISD::VMULLu;
2596 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2597 Op.getOperand(1), Op.getOperand(2));
2602 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2603 const ARMSubtarget *Subtarget) {
2604 // FIXME: handle "fence singlethread" more efficiently.
2606 if (!Subtarget->hasDataBarrier()) {
2607 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2608 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2610 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2611 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2612 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2613 DAG.getConstant(0, MVT::i32));
2616 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2617 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2618 unsigned Domain = ARM_MB::ISH;
2619 if (Subtarget->isMClass()) {
2620 // Only a full system barrier exists in the M-class architectures.
2621 Domain = ARM_MB::SY;
2622 } else if (Subtarget->isSwift() && Ord == Release) {
2623 // Swift happens to implement ISHST barriers in a way that's compatible with
2624 // Release semantics but weaker than ISH so we'd be fools not to use
2625 // it. Beware: other processors probably don't!
2626 Domain = ARM_MB::ISHST;
2629 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2630 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2631 DAG.getConstant(Domain, MVT::i32));
2634 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2635 const ARMSubtarget *Subtarget) {
2636 // ARM pre v5TE and Thumb1 does not have preload instructions.
2637 if (!(Subtarget->isThumb2() ||
2638 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2639 // Just preserve the chain.
2640 return Op.getOperand(0);
2643 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2645 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2646 // ARMv7 with MP extension has PLDW.
2647 return Op.getOperand(0);
2649 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2650 if (Subtarget->isThumb()) {
2652 isRead = ~isRead & 1;
2653 isData = ~isData & 1;
2656 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2657 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2658 DAG.getConstant(isData, MVT::i32));
2661 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2662 MachineFunction &MF = DAG.getMachineFunction();
2663 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2665 // vastart just stores the address of the VarArgsFrameIndex slot into the
2666 // memory location argument.
2668 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2669 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2670 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2671 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2672 MachinePointerInfo(SV), false, false, 0);
2676 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2677 SDValue &Root, SelectionDAG &DAG,
2679 MachineFunction &MF = DAG.getMachineFunction();
2680 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2682 const TargetRegisterClass *RC;
2683 if (AFI->isThumb1OnlyFunction())
2684 RC = &ARM::tGPRRegClass;
2686 RC = &ARM::GPRRegClass;
2688 // Transform the arguments stored in physical registers into virtual ones.
2689 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2690 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2693 if (NextVA.isMemLoc()) {
2694 MachineFrameInfo *MFI = MF.getFrameInfo();
2695 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2697 // Create load node to retrieve arguments from the stack.
2698 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2699 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2700 MachinePointerInfo::getFixedStack(FI),
2701 false, false, false, 0);
2703 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2704 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2707 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2711 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2712 unsigned InRegsParamRecordIdx,
2714 unsigned &ArgRegsSize,
2715 unsigned &ArgRegsSaveSize)
2718 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2719 unsigned RBegin, REnd;
2720 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2721 NumGPRs = REnd - RBegin;
2723 unsigned int firstUnalloced;
2724 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2725 sizeof(GPRArgRegs) /
2726 sizeof(GPRArgRegs[0]));
2727 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2730 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2731 ArgRegsSize = NumGPRs * 4;
2733 // If parameter is split between stack and GPRs...
2734 if (NumGPRs && Align > 4 &&
2735 (ArgRegsSize < ArgSize ||
2736 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2737 // Add padding for part of param recovered from GPRs. For example,
2738 // if Align == 8, its last byte must be at address K*8 - 1.
2739 // We need to do it, since remained (stack) part of parameter has
2740 // stack alignment, and we need to "attach" "GPRs head" without gaps
2743 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2744 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2746 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2748 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2749 ArgRegsSaveSize = ArgRegsSize + Padding;
2751 // We don't need to extend regs save size for byval parameters if they
2752 // are passed via GPRs only.
2753 ArgRegsSaveSize = ArgRegsSize;
2756 // The remaining GPRs hold either the beginning of variable-argument
2757 // data, or the beginning of an aggregate passed by value (usually
2758 // byval). Either way, we allocate stack slots adjacent to the data
2759 // provided by our caller, and store the unallocated registers there.
2760 // If this is a variadic function, the va_list pointer will begin with
2761 // these values; otherwise, this reassembles a (byval) structure that
2762 // was split between registers and memory.
2763 // Return: The frame index registers were stored into.
2765 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2766 SDLoc dl, SDValue &Chain,
2767 const Value *OrigArg,
2768 unsigned InRegsParamRecordIdx,
2769 unsigned OffsetFromOrigArg,
2773 unsigned ByValStoreOffset,
2774 unsigned TotalArgRegsSaveSize) const {
2776 // Currently, two use-cases possible:
2777 // Case #1. Non-var-args function, and we meet first byval parameter.
2778 // Setup first unallocated register as first byval register;
2779 // eat all remained registers
2780 // (these two actions are performed by HandleByVal method).
2781 // Then, here, we initialize stack frame with
2782 // "store-reg" instructions.
2783 // Case #2. Var-args function, that doesn't contain byval parameters.
2784 // The same: eat all remained unallocated registers,
2785 // initialize stack frame.
2787 MachineFunction &MF = DAG.getMachineFunction();
2788 MachineFrameInfo *MFI = MF.getFrameInfo();
2789 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2790 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2791 unsigned RBegin, REnd;
2792 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2793 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2794 firstRegToSaveIndex = RBegin - ARM::R0;
2795 lastRegToSaveIndex = REnd - ARM::R0;
2797 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2798 (GPRArgRegs, array_lengthof(GPRArgRegs));
2799 lastRegToSaveIndex = 4;
2802 unsigned ArgRegsSize, ArgRegsSaveSize;
2803 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2804 ArgRegsSize, ArgRegsSaveSize);
2806 // Store any by-val regs to their spots on the stack so that they may be
2807 // loaded by deferencing the result of formal parameter pointer or va_next.
2808 // Note: once stack area for byval/varargs registers
2809 // was initialized, it can't be initialized again.
2810 if (ArgRegsSaveSize) {
2811 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2814 assert(AFI->getStoredByValParamsPadding() == 0 &&
2815 "The only parameter may be padded.");
2816 AFI->setStoredByValParamsPadding(Padding);
2819 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2822 (int64_t)TotalArgRegsSaveSize,
2824 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2826 MFI->CreateFixedObject(Padding,
2827 ArgOffset + ByValStoreOffset -
2828 (int64_t)ArgRegsSaveSize,
2832 SmallVector<SDValue, 4> MemOps;
2833 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2834 ++firstRegToSaveIndex, ++i) {
2835 const TargetRegisterClass *RC;
2836 if (AFI->isThumb1OnlyFunction())
2837 RC = &ARM::tGPRRegClass;
2839 RC = &ARM::GPRRegClass;
2841 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2842 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2844 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2845 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2847 MemOps.push_back(Store);
2848 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2849 DAG.getConstant(4, getPointerTy()));
2852 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2854 if (!MemOps.empty())
2855 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2856 &MemOps[0], MemOps.size());
2860 // We cannot allocate a zero-byte object for the first variadic argument,
2861 // so just make up a size.
2864 // This will point to the next argument passed via stack.
2865 return MFI->CreateFixedObject(
2866 ArgSize, ArgOffset, !ForceMutable);
2870 // Setup stack frame, the va_list pointer will start from.
2872 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2873 SDLoc dl, SDValue &Chain,
2875 unsigned TotalArgRegsSaveSize,
2876 bool ForceMutable) const {
2877 MachineFunction &MF = DAG.getMachineFunction();
2878 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2880 // Try to store any remaining integer argument regs
2881 // to their spots on the stack so that they may be loaded by deferencing
2882 // the result of va_next.
2883 // If there is no regs to be stored, just point address after last
2884 // argument passed via stack.
2886 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2887 0, ArgOffset, 0, ForceMutable, 0, TotalArgRegsSaveSize);
2889 AFI->setVarArgsFrameIndex(FrameIndex);
2893 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2894 CallingConv::ID CallConv, bool isVarArg,
2895 const SmallVectorImpl<ISD::InputArg>
2897 SDLoc dl, SelectionDAG &DAG,
2898 SmallVectorImpl<SDValue> &InVals)
2900 MachineFunction &MF = DAG.getMachineFunction();
2901 MachineFrameInfo *MFI = MF.getFrameInfo();
2903 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2905 // Assign locations to all of the incoming arguments.
2906 SmallVector<CCValAssign, 16> ArgLocs;
2907 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2908 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2909 CCInfo.AnalyzeFormalArguments(Ins,
2910 CCAssignFnForNode(CallConv, /* Return*/ false,
2913 SmallVector<SDValue, 16> ArgValues;
2914 int lastInsIndex = -1;
2916 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2917 unsigned CurArgIdx = 0;
2919 // Initially ArgRegsSaveSize is zero.
2920 // Then we increase this value each time we meet byval parameter.
2921 // We also increase this value in case of varargs function.
2922 AFI->setArgRegsSaveSize(0);
2924 unsigned ByValStoreOffset = 0;
2925 unsigned TotalArgRegsSaveSize = 0;
2926 unsigned ArgRegsSaveSizeMaxAlign = 4;
2928 // Calculate the amount of stack space that we need to allocate to store
2929 // byval and variadic arguments that are passed in registers.
2930 // We need to know this before we allocate the first byval or variadic
2931 // argument, as they will be allocated a stack slot below the CFA (Canonical
2932 // Frame Address, the stack pointer at entry to the function).
2933 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2934 CCValAssign &VA = ArgLocs[i];
2935 if (VA.isMemLoc()) {
2936 int index = VA.getValNo();
2937 if (index != lastInsIndex) {
2938 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2939 if (Flags.isByVal()) {
2940 unsigned ExtraArgRegsSize;
2941 unsigned ExtraArgRegsSaveSize;
2942 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2943 Flags.getByValSize(),
2944 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2946 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2947 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2948 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2949 CCInfo.nextInRegsParam();
2951 lastInsIndex = index;
2955 CCInfo.rewindByValRegsInfo();
2958 unsigned ExtraArgRegsSize;
2959 unsigned ExtraArgRegsSaveSize;
2960 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2961 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2962 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2964 // If the arg regs save area contains N-byte aligned values, the
2965 // bottom of it must be at least N-byte aligned.
2966 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2967 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2969 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2970 CCValAssign &VA = ArgLocs[i];
2971 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2972 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2973 // Arguments stored in registers.
2974 if (VA.isRegLoc()) {
2975 EVT RegVT = VA.getLocVT();
2977 if (VA.needsCustom()) {
2978 // f64 and vector types are split up into multiple registers or
2979 // combinations of registers and stack slots.
2980 if (VA.getLocVT() == MVT::v2f64) {
2981 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2983 VA = ArgLocs[++i]; // skip ahead to next loc
2985 if (VA.isMemLoc()) {
2986 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2987 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2988 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2989 MachinePointerInfo::getFixedStack(FI),
2990 false, false, false, 0);
2992 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2995 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2996 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2997 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2998 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2999 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3001 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3004 const TargetRegisterClass *RC;
3006 if (RegVT == MVT::f32)
3007 RC = &ARM::SPRRegClass;
3008 else if (RegVT == MVT::f64)
3009 RC = &ARM::DPRRegClass;
3010 else if (RegVT == MVT::v2f64)
3011 RC = &ARM::QPRRegClass;
3012 else if (RegVT == MVT::i32)
3013 RC = AFI->isThumb1OnlyFunction() ?
3014 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3015 (const TargetRegisterClass*)&ARM::GPRRegClass;
3017 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3019 // Transform the arguments in physical registers into virtual ones.
3020 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3021 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3024 // If this is an 8 or 16-bit value, it is really passed promoted
3025 // to 32 bits. Insert an assert[sz]ext to capture this, then
3026 // truncate to the right size.
3027 switch (VA.getLocInfo()) {
3028 default: llvm_unreachable("Unknown loc info!");
3029 case CCValAssign::Full: break;
3030 case CCValAssign::BCvt:
3031 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3033 case CCValAssign::SExt:
3034 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3035 DAG.getValueType(VA.getValVT()));
3036 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3038 case CCValAssign::ZExt:
3039 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3040 DAG.getValueType(VA.getValVT()));
3041 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3045 InVals.push_back(ArgValue);
3047 } else { // VA.isRegLoc()
3050 assert(VA.isMemLoc());
3051 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3053 int index = ArgLocs[i].getValNo();
3055 // Some Ins[] entries become multiple ArgLoc[] entries.
3056 // Process them only once.
3057 if (index != lastInsIndex)
3059 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3060 // FIXME: For now, all byval parameter objects are marked mutable.
3061 // This can be changed with more analysis.
3062 // In case of tail call optimization mark all arguments mutable.
3063 // Since they could be overwritten by lowering of arguments in case of
3065 if (Flags.isByVal()) {
3066 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3068 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3069 int FrameIndex = StoreByValRegs(
3070 CCInfo, DAG, dl, Chain, CurOrigArg,
3072 Ins[VA.getValNo()].PartOffset,
3073 VA.getLocMemOffset(),
3074 Flags.getByValSize(),
3075 true /*force mutable frames*/,
3077 TotalArgRegsSaveSize);
3078 ByValStoreOffset += Flags.getByValSize();
3079 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3080 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3081 CCInfo.nextInRegsParam();
3083 unsigned FIOffset = VA.getLocMemOffset();
3084 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3087 // Create load nodes to retrieve arguments from the stack.
3088 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3089 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3090 MachinePointerInfo::getFixedStack(FI),
3091 false, false, false, 0));
3093 lastInsIndex = index;
3100 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3101 CCInfo.getNextStackOffset(),
3102 TotalArgRegsSaveSize);
3107 /// isFloatingPointZero - Return true if this is +0.0.
3108 static bool isFloatingPointZero(SDValue Op) {
3109 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3110 return CFP->getValueAPF().isPosZero();
3111 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3112 // Maybe this has already been legalized into the constant pool?
3113 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3114 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3115 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3116 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3117 return CFP->getValueAPF().isPosZero();
3123 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3124 /// the given operands.
3126 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3127 SDValue &ARMcc, SelectionDAG &DAG,
3129 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3130 unsigned C = RHSC->getZExtValue();
3131 if (!isLegalICmpImmediate(C)) {
3132 // Constant does not fit, try adjusting it by one?
3137 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3138 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3139 RHS = DAG.getConstant(C-1, MVT::i32);
3144 if (C != 0 && isLegalICmpImmediate(C-1)) {
3145 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3146 RHS = DAG.getConstant(C-1, MVT::i32);
3151 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3152 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3153 RHS = DAG.getConstant(C+1, MVT::i32);
3158 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3159 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3160 RHS = DAG.getConstant(C+1, MVT::i32);
3167 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3168 ARMISD::NodeType CompareType;
3171 CompareType = ARMISD::CMP;
3176 CompareType = ARMISD::CMPZ;
3179 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3180 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3183 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3185 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3188 if (!isFloatingPointZero(RHS))
3189 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3191 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3192 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3195 /// duplicateCmp - Glue values can have only one use, so this function
3196 /// duplicates a comparison node.
3198 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3199 unsigned Opc = Cmp.getOpcode();
3201 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3202 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3204 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3205 Cmp = Cmp.getOperand(0);
3206 Opc = Cmp.getOpcode();
3207 if (Opc == ARMISD::CMPFP)
3208 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3210 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3211 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3213 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3216 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3217 SDValue Cond = Op.getOperand(0);
3218 SDValue SelectTrue = Op.getOperand(1);
3219 SDValue SelectFalse = Op.getOperand(2);
3224 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3225 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3227 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3228 const ConstantSDNode *CMOVTrue =
3229 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3230 const ConstantSDNode *CMOVFalse =
3231 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3233 if (CMOVTrue && CMOVFalse) {
3234 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3235 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3239 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3241 False = SelectFalse;
3242 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3247 if (True.getNode() && False.getNode()) {
3248 EVT VT = Op.getValueType();
3249 SDValue ARMcc = Cond.getOperand(2);
3250 SDValue CCR = Cond.getOperand(3);
3251 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3252 assert(True.getValueType() == VT);
3253 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3258 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3259 // undefined bits before doing a full-word comparison with zero.
3260 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3261 DAG.getConstant(1, Cond.getValueType()));
3263 return DAG.getSelectCC(dl, Cond,
3264 DAG.getConstant(0, Cond.getValueType()),
3265 SelectTrue, SelectFalse, ISD::SETNE);
3268 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3269 if (CC == ISD::SETNE)
3271 return ISD::getSetCCInverse(CC, true);
3274 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3275 bool &swpCmpOps, bool &swpVselOps) {
3276 // Start by selecting the GE condition code for opcodes that return true for
3278 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3280 CondCode = ARMCC::GE;
3282 // and GT for opcodes that return false for 'equality'.
3283 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3285 CondCode = ARMCC::GT;
3287 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3288 // to swap the compare operands.
3289 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3293 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3294 // If we have an unordered opcode, we need to swap the operands to the VSEL
3295 // instruction (effectively negating the condition).
3297 // This also has the effect of swapping which one of 'less' or 'greater'
3298 // returns true, so we also swap the compare operands. It also switches
3299 // whether we return true for 'equality', so we compensate by picking the
3300 // opposite condition code to our original choice.
3301 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3302 CC == ISD::SETUGT) {
3303 swpCmpOps = !swpCmpOps;
3304 swpVselOps = !swpVselOps;
3305 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3308 // 'ordered' is 'anything but unordered', so use the VS condition code and
3309 // swap the VSEL operands.
3310 if (CC == ISD::SETO) {
3311 CondCode = ARMCC::VS;
3315 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3316 // code and swap the VSEL operands.
3317 if (CC == ISD::SETUNE) {
3318 CondCode = ARMCC::EQ;
3323 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3324 EVT VT = Op.getValueType();
3325 SDValue LHS = Op.getOperand(0);
3326 SDValue RHS = Op.getOperand(1);
3327 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3328 SDValue TrueVal = Op.getOperand(2);
3329 SDValue FalseVal = Op.getOperand(3);
3332 if (LHS.getValueType() == MVT::i32) {
3333 // Try to generate VSEL on ARMv8.
3334 // The VSEL instruction can't use all the usual ARM condition
3335 // codes: it only has two bits to select the condition code, so it's
3336 // constrained to use only GE, GT, VS and EQ.
3338 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3339 // swap the operands of the previous compare instruction (effectively
3340 // inverting the compare condition, swapping 'less' and 'greater') and
3341 // sometimes need to swap the operands to the VSEL (which inverts the
3342 // condition in the sense of firing whenever the previous condition didn't)
3343 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3344 TrueVal.getValueType() == MVT::f64)) {
3345 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3346 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3347 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3348 CC = getInverseCCForVSEL(CC);
3349 std::swap(TrueVal, FalseVal);
3354 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3355 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3356 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3360 ARMCC::CondCodes CondCode, CondCode2;
3361 FPCCToARMCC(CC, CondCode, CondCode2);
3363 // Try to generate VSEL on ARMv8.
3364 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3365 TrueVal.getValueType() == MVT::f64)) {
3366 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3367 // same operands, as follows:
3368 // c = fcmp [ogt, olt, ugt, ult] a, b
3370 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3371 // handled differently than the original code sequence.
3372 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3374 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3375 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3376 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3377 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3380 bool swpCmpOps = false;
3381 bool swpVselOps = false;
3382 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3384 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3385 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3387 std::swap(LHS, RHS);
3389 std::swap(TrueVal, FalseVal);
3393 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3394 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3395 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3396 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3398 if (CondCode2 != ARMCC::AL) {
3399 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3400 // FIXME: Needs another CMP because flag can have but one use.
3401 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3402 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3403 Result, TrueVal, ARMcc2, CCR, Cmp2);
3408 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3409 /// to morph to an integer compare sequence.
3410 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3411 const ARMSubtarget *Subtarget) {
3412 SDNode *N = Op.getNode();
3413 if (!N->hasOneUse())
3414 // Otherwise it requires moving the value from fp to integer registers.
3416 if (!N->getNumValues())
3418 EVT VT = Op.getValueType();
3419 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3420 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3421 // vmrs are very slow, e.g. cortex-a8.
3424 if (isFloatingPointZero(Op)) {
3428 return ISD::isNormalLoad(N);
3431 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3432 if (isFloatingPointZero(Op))
3433 return DAG.getConstant(0, MVT::i32);
3435 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3436 return DAG.getLoad(MVT::i32, SDLoc(Op),
3437 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3438 Ld->isVolatile(), Ld->isNonTemporal(),
3439 Ld->isInvariant(), Ld->getAlignment());
3441 llvm_unreachable("Unknown VFP cmp argument!");
3444 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3445 SDValue &RetVal1, SDValue &RetVal2) {
3446 if (isFloatingPointZero(Op)) {
3447 RetVal1 = DAG.getConstant(0, MVT::i32);
3448 RetVal2 = DAG.getConstant(0, MVT::i32);
3452 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3453 SDValue Ptr = Ld->getBasePtr();
3454 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3455 Ld->getChain(), Ptr,
3456 Ld->getPointerInfo(),
3457 Ld->isVolatile(), Ld->isNonTemporal(),
3458 Ld->isInvariant(), Ld->getAlignment());
3460 EVT PtrType = Ptr.getValueType();
3461 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3462 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3463 PtrType, Ptr, DAG.getConstant(4, PtrType));
3464 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3465 Ld->getChain(), NewPtr,
3466 Ld->getPointerInfo().getWithOffset(4),
3467 Ld->isVolatile(), Ld->isNonTemporal(),
3468 Ld->isInvariant(), NewAlign);
3472 llvm_unreachable("Unknown VFP cmp argument!");
3475 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3476 /// f32 and even f64 comparisons to integer ones.
3478 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3479 SDValue Chain = Op.getOperand(0);
3480 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3481 SDValue LHS = Op.getOperand(2);
3482 SDValue RHS = Op.getOperand(3);
3483 SDValue Dest = Op.getOperand(4);
3486 bool LHSSeenZero = false;
3487 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3488 bool RHSSeenZero = false;
3489 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3490 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3491 // If unsafe fp math optimization is enabled and there are no other uses of
3492 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3493 // to an integer comparison.
3494 if (CC == ISD::SETOEQ)
3496 else if (CC == ISD::SETUNE)
3499 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3501 if (LHS.getValueType() == MVT::f32) {
3502 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3503 bitcastf32Toi32(LHS, DAG), Mask);
3504 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3505 bitcastf32Toi32(RHS, DAG), Mask);
3506 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3507 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3508 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3509 Chain, Dest, ARMcc, CCR, Cmp);
3514 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3515 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3516 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3517 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3518 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3519 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3520 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3521 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3522 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3528 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3529 SDValue Chain = Op.getOperand(0);
3530 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3531 SDValue LHS = Op.getOperand(2);
3532 SDValue RHS = Op.getOperand(3);
3533 SDValue Dest = Op.getOperand(4);
3536 if (LHS.getValueType() == MVT::i32) {
3538 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3539 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3540 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3541 Chain, Dest, ARMcc, CCR, Cmp);
3544 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3546 if (getTargetMachine().Options.UnsafeFPMath &&
3547 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3548 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3549 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3550 if (Result.getNode())
3554 ARMCC::CondCodes CondCode, CondCode2;
3555 FPCCToARMCC(CC, CondCode, CondCode2);
3557 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3558 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3559 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3560 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3561 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3562 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3563 if (CondCode2 != ARMCC::AL) {
3564 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3565 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3566 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3571 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3572 SDValue Chain = Op.getOperand(0);
3573 SDValue Table = Op.getOperand(1);
3574 SDValue Index = Op.getOperand(2);
3577 EVT PTy = getPointerTy();
3578 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3579 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3580 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3581 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3582 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3583 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3584 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3585 if (Subtarget->isThumb2()) {
3586 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3587 // which does another jump to the destination. This also makes it easier
3588 // to translate it to TBB / TBH later.
3589 // FIXME: This might not work if the function is extremely large.
3590 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3591 Addr, Op.getOperand(2), JTI, UId);
3593 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3594 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3595 MachinePointerInfo::getJumpTable(),
3596 false, false, false, 0);
3597 Chain = Addr.getValue(1);
3598 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3599 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3601 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3602 MachinePointerInfo::getJumpTable(),
3603 false, false, false, 0);
3604 Chain = Addr.getValue(1);
3605 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3609 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3610 EVT VT = Op.getValueType();
3613 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3614 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3616 return DAG.UnrollVectorOp(Op.getNode());
3619 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3620 "Invalid type for custom lowering!");
3621 if (VT != MVT::v4i16)
3622 return DAG.UnrollVectorOp(Op.getNode());
3624 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3625 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3628 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3629 EVT VT = Op.getValueType();
3631 return LowerVectorFP_TO_INT(Op, DAG);
3636 switch (Op.getOpcode()) {
3637 default: llvm_unreachable("Invalid opcode!");
3638 case ISD::FP_TO_SINT:
3639 Opc = ARMISD::FTOSI;
3641 case ISD::FP_TO_UINT:
3642 Opc = ARMISD::FTOUI;
3645 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3646 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3649 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3650 EVT VT = Op.getValueType();
3653 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3654 if (VT.getVectorElementType() == MVT::f32)
3656 return DAG.UnrollVectorOp(Op.getNode());
3659 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3660 "Invalid type for custom lowering!");
3661 if (VT != MVT::v4f32)
3662 return DAG.UnrollVectorOp(Op.getNode());
3666 switch (Op.getOpcode()) {
3667 default: llvm_unreachable("Invalid opcode!");
3668 case ISD::SINT_TO_FP:
3669 CastOpc = ISD::SIGN_EXTEND;
3670 Opc = ISD::SINT_TO_FP;
3672 case ISD::UINT_TO_FP:
3673 CastOpc = ISD::ZERO_EXTEND;
3674 Opc = ISD::UINT_TO_FP;
3678 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3679 return DAG.getNode(Opc, dl, VT, Op);
3682 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3683 EVT VT = Op.getValueType();
3685 return LowerVectorINT_TO_FP(Op, DAG);
3690 switch (Op.getOpcode()) {
3691 default: llvm_unreachable("Invalid opcode!");
3692 case ISD::SINT_TO_FP:
3693 Opc = ARMISD::SITOF;
3695 case ISD::UINT_TO_FP:
3696 Opc = ARMISD::UITOF;
3700 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3701 return DAG.getNode(Opc, dl, VT, Op);
3704 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3705 // Implement fcopysign with a fabs and a conditional fneg.
3706 SDValue Tmp0 = Op.getOperand(0);
3707 SDValue Tmp1 = Op.getOperand(1);
3709 EVT VT = Op.getValueType();
3710 EVT SrcVT = Tmp1.getValueType();
3711 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3712 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3713 bool UseNEON = !InGPR && Subtarget->hasNEON();
3716 // Use VBSL to copy the sign bit.
3717 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3718 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3719 DAG.getTargetConstant(EncodedVal, MVT::i32));
3720 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3722 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3723 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3724 DAG.getConstant(32, MVT::i32));
3725 else /*if (VT == MVT::f32)*/
3726 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3727 if (SrcVT == MVT::f32) {
3728 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3730 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3731 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3732 DAG.getConstant(32, MVT::i32));
3733 } else if (VT == MVT::f32)
3734 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3735 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3736 DAG.getConstant(32, MVT::i32));
3737 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3738 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3740 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3742 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3743 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3744 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3746 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3747 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3748 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3749 if (VT == MVT::f32) {
3750 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3751 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3752 DAG.getConstant(0, MVT::i32));
3754 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3760 // Bitcast operand 1 to i32.
3761 if (SrcVT == MVT::f64)
3762 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3763 &Tmp1, 1).getValue(1);
3764 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3766 // Or in the signbit with integer operations.
3767 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3768 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3769 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3770 if (VT == MVT::f32) {
3771 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3772 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3773 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3774 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3777 // f64: Or the high part with signbit and then combine two parts.
3778 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3780 SDValue Lo = Tmp0.getValue(0);
3781 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3782 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3783 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3786 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3787 MachineFunction &MF = DAG.getMachineFunction();
3788 MachineFrameInfo *MFI = MF.getFrameInfo();
3789 MFI->setReturnAddressIsTaken(true);
3791 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3794 EVT VT = Op.getValueType();
3796 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3798 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3799 SDValue Offset = DAG.getConstant(4, MVT::i32);
3800 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3801 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3802 MachinePointerInfo(), false, false, false, 0);
3805 // Return LR, which contains the return address. Mark it an implicit live-in.
3806 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3807 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3810 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3811 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3812 MFI->setFrameAddressIsTaken(true);
3814 EVT VT = Op.getValueType();
3815 SDLoc dl(Op); // FIXME probably not meaningful
3816 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3817 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3818 ? ARM::R7 : ARM::R11;
3819 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3821 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3822 MachinePointerInfo(),
3823 false, false, false, 0);
3827 /// ExpandBITCAST - If the target supports VFP, this function is called to
3828 /// expand a bit convert where either the source or destination type is i64 to
3829 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3830 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3831 /// vectors), since the legalizer won't know what to do with that.
3832 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3833 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3835 SDValue Op = N->getOperand(0);
3837 // This function is only supposed to be called for i64 types, either as the
3838 // source or destination of the bit convert.
3839 EVT SrcVT = Op.getValueType();
3840 EVT DstVT = N->getValueType(0);
3841 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3842 "ExpandBITCAST called for non-i64 type");
3844 // Turn i64->f64 into VMOVDRR.
3845 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3846 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3847 DAG.getConstant(0, MVT::i32));
3848 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3849 DAG.getConstant(1, MVT::i32));
3850 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3851 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3854 // Turn f64->i64 into VMOVRRD.
3855 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3856 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3857 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3858 // Merge the pieces into a single i64 value.
3859 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3865 /// getZeroVector - Returns a vector of specified type with all zero elements.
3866 /// Zero vectors are used to represent vector negation and in those cases
3867 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3868 /// not support i64 elements, so sometimes the zero vectors will need to be
3869 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3871 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3872 assert(VT.isVector() && "Expected a vector type");
3873 // The canonical modified immediate encoding of a zero vector is....0!
3874 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3875 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3876 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3877 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3880 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3881 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3882 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3883 SelectionDAG &DAG) const {
3884 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3885 EVT VT = Op.getValueType();
3886 unsigned VTBits = VT.getSizeInBits();
3888 SDValue ShOpLo = Op.getOperand(0);
3889 SDValue ShOpHi = Op.getOperand(1);
3890 SDValue ShAmt = Op.getOperand(2);
3892 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3894 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3896 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3897 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3898 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3899 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3900 DAG.getConstant(VTBits, MVT::i32));
3901 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3902 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3903 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3905 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3906 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3908 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3909 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3912 SDValue Ops[2] = { Lo, Hi };
3913 return DAG.getMergeValues(Ops, 2, dl);
3916 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3917 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3918 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3919 SelectionDAG &DAG) const {
3920 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3921 EVT VT = Op.getValueType();
3922 unsigned VTBits = VT.getSizeInBits();
3924 SDValue ShOpLo = Op.getOperand(0);
3925 SDValue ShOpHi = Op.getOperand(1);
3926 SDValue ShAmt = Op.getOperand(2);
3929 assert(Op.getOpcode() == ISD::SHL_PARTS);
3930 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3931 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3932 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3933 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3934 DAG.getConstant(VTBits, MVT::i32));
3935 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3936 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3938 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3939 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3940 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3942 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3943 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3946 SDValue Ops[2] = { Lo, Hi };
3947 return DAG.getMergeValues(Ops, 2, dl);
3950 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3951 SelectionDAG &DAG) const {
3952 // The rounding mode is in bits 23:22 of the FPSCR.
3953 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3954 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3955 // so that the shift + and get folded into a bitfield extract.
3957 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3958 DAG.getConstant(Intrinsic::arm_get_fpscr,
3960 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3961 DAG.getConstant(1U << 22, MVT::i32));
3962 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3963 DAG.getConstant(22, MVT::i32));
3964 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3965 DAG.getConstant(3, MVT::i32));
3968 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3969 const ARMSubtarget *ST) {
3970 EVT VT = N->getValueType(0);
3973 if (!ST->hasV6T2Ops())
3976 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3977 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3980 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3981 /// for each 16-bit element from operand, repeated. The basic idea is to
3982 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3984 /// Trace for v4i16:
3985 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3986 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3987 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3988 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3989 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3990 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3991 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3992 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3993 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3994 EVT VT = N->getValueType(0);
3997 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3998 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3999 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4000 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4001 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4002 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4005 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4006 /// bit-count for each 16-bit element from the operand. We need slightly
4007 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4008 /// 64/128-bit registers.
4010 /// Trace for v4i16:
4011 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4012 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4013 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4014 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4015 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4016 EVT VT = N->getValueType(0);
4019 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4020 if (VT.is64BitVector()) {
4021 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4022 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4023 DAG.getIntPtrConstant(0));
4025 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4026 BitCounts, DAG.getIntPtrConstant(0));
4027 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4031 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4032 /// bit-count for each 32-bit element from the operand. The idea here is
4033 /// to split the vector into 16-bit elements, leverage the 16-bit count
4034 /// routine, and then combine the results.
4036 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4037 /// input = [v0 v1 ] (vi: 32-bit elements)
4038 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4039 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4040 /// vrev: N0 = [k1 k0 k3 k2 ]
4042 /// N1 =+[k1 k0 k3 k2 ]
4044 /// N2 =+[k1 k3 k0 k2 ]
4046 /// Extended =+[k1 k3 k0 k2 ]
4048 /// Extracted=+[k1 k3 ]
4050 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4051 EVT VT = N->getValueType(0);
4054 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4056 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4057 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4058 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4059 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4060 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4062 if (VT.is64BitVector()) {
4063 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4064 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4065 DAG.getIntPtrConstant(0));
4067 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4068 DAG.getIntPtrConstant(0));
4069 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4073 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4074 const ARMSubtarget *ST) {
4075 EVT VT = N->getValueType(0);
4077 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4078 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4079 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4080 "Unexpected type for custom ctpop lowering");
4082 if (VT.getVectorElementType() == MVT::i32)
4083 return lowerCTPOP32BitElements(N, DAG);
4085 return lowerCTPOP16BitElements(N, DAG);
4088 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4089 const ARMSubtarget *ST) {
4090 EVT VT = N->getValueType(0);
4096 // Lower vector shifts on NEON to use VSHL.
4097 assert(ST->hasNEON() && "unexpected vector shift");
4099 // Left shifts translate directly to the vshiftu intrinsic.
4100 if (N->getOpcode() == ISD::SHL)
4101 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4102 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4103 N->getOperand(0), N->getOperand(1));
4105 assert((N->getOpcode() == ISD::SRA ||
4106 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4108 // NEON uses the same intrinsics for both left and right shifts. For
4109 // right shifts, the shift amounts are negative, so negate the vector of
4111 EVT ShiftVT = N->getOperand(1).getValueType();
4112 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4113 getZeroVector(ShiftVT, DAG, dl),
4115 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4116 Intrinsic::arm_neon_vshifts :
4117 Intrinsic::arm_neon_vshiftu);
4118 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4119 DAG.getConstant(vshiftInt, MVT::i32),
4120 N->getOperand(0), NegatedCount);
4123 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4124 const ARMSubtarget *ST) {
4125 EVT VT = N->getValueType(0);
4128 // We can get here for a node like i32 = ISD::SHL i32, i64
4132 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4133 "Unknown shift to lower!");
4135 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4136 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4137 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4140 // If we are in thumb mode, we don't have RRX.
4141 if (ST->isThumb1Only()) return SDValue();
4143 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4144 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4145 DAG.getConstant(0, MVT::i32));
4146 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4147 DAG.getConstant(1, MVT::i32));
4149 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4150 // captures the result into a carry flag.
4151 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4152 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4154 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4155 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4157 // Merge the pieces into a single i64 value.
4158 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4161 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4162 SDValue TmpOp0, TmpOp1;
4163 bool Invert = false;
4167 SDValue Op0 = Op.getOperand(0);
4168 SDValue Op1 = Op.getOperand(1);
4169 SDValue CC = Op.getOperand(2);
4170 EVT VT = Op.getValueType();
4171 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4174 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4175 switch (SetCCOpcode) {
4176 default: llvm_unreachable("Illegal FP comparison");
4178 case ISD::SETNE: Invert = true; // Fallthrough
4180 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4182 case ISD::SETLT: Swap = true; // Fallthrough
4184 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4186 case ISD::SETLE: Swap = true; // Fallthrough
4188 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4189 case ISD::SETUGE: Swap = true; // Fallthrough
4190 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4191 case ISD::SETUGT: Swap = true; // Fallthrough
4192 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4193 case ISD::SETUEQ: Invert = true; // Fallthrough
4195 // Expand this to (OLT | OGT).
4199 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4200 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4202 case ISD::SETUO: Invert = true; // Fallthrough
4204 // Expand this to (OLT | OGE).
4208 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4209 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4213 // Integer comparisons.
4214 switch (SetCCOpcode) {
4215 default: llvm_unreachable("Illegal integer comparison");
4216 case ISD::SETNE: Invert = true;
4217 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4218 case ISD::SETLT: Swap = true;
4219 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4220 case ISD::SETLE: Swap = true;
4221 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4222 case ISD::SETULT: Swap = true;
4223 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4224 case ISD::SETULE: Swap = true;
4225 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4228 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4229 if (Opc == ARMISD::VCEQ) {
4232 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4234 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4237 // Ignore bitconvert.
4238 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4239 AndOp = AndOp.getOperand(0);
4241 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4243 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4244 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4251 std::swap(Op0, Op1);
4253 // If one of the operands is a constant vector zero, attempt to fold the
4254 // comparison to a specialized compare-against-zero form.
4256 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4258 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4259 if (Opc == ARMISD::VCGE)
4260 Opc = ARMISD::VCLEZ;
4261 else if (Opc == ARMISD::VCGT)
4262 Opc = ARMISD::VCLTZ;
4267 if (SingleOp.getNode()) {
4270 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4272 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4274 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4276 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4278 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4280 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4283 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4287 Result = DAG.getNOT(dl, Result, VT);
4292 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4293 /// valid vector constant for a NEON instruction with a "modified immediate"
4294 /// operand (e.g., VMOV). If so, return the encoded value.
4295 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4296 unsigned SplatBitSize, SelectionDAG &DAG,
4297 EVT &VT, bool is128Bits, NEONModImmType type) {
4298 unsigned OpCmode, Imm;
4300 // SplatBitSize is set to the smallest size that splats the vector, so a
4301 // zero vector will always have SplatBitSize == 8. However, NEON modified
4302 // immediate instructions others than VMOV do not support the 8-bit encoding
4303 // of a zero vector, and the default encoding of zero is supposed to be the
4308 switch (SplatBitSize) {
4310 if (type != VMOVModImm)
4312 // Any 1-byte value is OK. Op=0, Cmode=1110.
4313 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4316 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4320 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4321 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4322 if ((SplatBits & ~0xff) == 0) {
4323 // Value = 0x00nn: Op=x, Cmode=100x.
4328 if ((SplatBits & ~0xff00) == 0) {
4329 // Value = 0xnn00: Op=x, Cmode=101x.
4331 Imm = SplatBits >> 8;
4337 // NEON's 32-bit VMOV supports splat values where:
4338 // * only one byte is nonzero, or
4339 // * the least significant byte is 0xff and the second byte is nonzero, or
4340 // * the least significant 2 bytes are 0xff and the third is nonzero.
4341 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4342 if ((SplatBits & ~0xff) == 0) {
4343 // Value = 0x000000nn: Op=x, Cmode=000x.
4348 if ((SplatBits & ~0xff00) == 0) {
4349 // Value = 0x0000nn00: Op=x, Cmode=001x.
4351 Imm = SplatBits >> 8;
4354 if ((SplatBits & ~0xff0000) == 0) {
4355 // Value = 0x00nn0000: Op=x, Cmode=010x.
4357 Imm = SplatBits >> 16;
4360 if ((SplatBits & ~0xff000000) == 0) {
4361 // Value = 0xnn000000: Op=x, Cmode=011x.
4363 Imm = SplatBits >> 24;
4367 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4368 if (type == OtherModImm) return SDValue();
4370 if ((SplatBits & ~0xffff) == 0 &&
4371 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4372 // Value = 0x0000nnff: Op=x, Cmode=1100.
4374 Imm = SplatBits >> 8;
4379 if ((SplatBits & ~0xffffff) == 0 &&
4380 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4381 // Value = 0x00nnffff: Op=x, Cmode=1101.
4383 Imm = SplatBits >> 16;
4384 SplatBits |= 0xffff;
4388 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4389 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4390 // VMOV.I32. A (very) minor optimization would be to replicate the value
4391 // and fall through here to test for a valid 64-bit splat. But, then the
4392 // caller would also need to check and handle the change in size.
4396 if (type != VMOVModImm)
4398 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4399 uint64_t BitMask = 0xff;
4401 unsigned ImmMask = 1;
4403 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4404 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4407 } else if ((SplatBits & BitMask) != 0) {
4413 // Op=1, Cmode=1110.
4416 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4421 llvm_unreachable("unexpected size for isNEONModifiedImm");
4424 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4425 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4428 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4429 const ARMSubtarget *ST) const {
4433 bool IsDouble = Op.getValueType() == MVT::f64;
4434 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4436 // Try splatting with a VMOV.f32...
4437 APFloat FPVal = CFP->getValueAPF();
4438 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4441 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4442 // We have code in place to select a valid ConstantFP already, no need to
4447 // It's a float and we are trying to use NEON operations where
4448 // possible. Lower it to a splat followed by an extract.
4450 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4451 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4453 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4454 DAG.getConstant(0, MVT::i32));
4457 // The rest of our options are NEON only, make sure that's allowed before
4459 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4463 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4465 // It wouldn't really be worth bothering for doubles except for one very
4466 // important value, which does happen to match: 0.0. So make sure we don't do
4468 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4471 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4472 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4474 if (NewVal != SDValue()) {
4476 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4479 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4481 // It's a float: cast and extract a vector element.
4482 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4484 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4485 DAG.getConstant(0, MVT::i32));
4488 // Finally, try a VMVN.i32
4489 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4491 if (NewVal != SDValue()) {
4493 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4496 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4498 // It's a float: cast and extract a vector element.
4499 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4501 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4502 DAG.getConstant(0, MVT::i32));
4508 // check if an VEXT instruction can handle the shuffle mask when the
4509 // vector sources of the shuffle are the same.
4510 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4511 unsigned NumElts = VT.getVectorNumElements();
4513 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4519 // If this is a VEXT shuffle, the immediate value is the index of the first
4520 // element. The other shuffle indices must be the successive elements after
4522 unsigned ExpectedElt = Imm;
4523 for (unsigned i = 1; i < NumElts; ++i) {
4524 // Increment the expected index. If it wraps around, just follow it
4525 // back to index zero and keep going.
4527 if (ExpectedElt == NumElts)
4530 if (M[i] < 0) continue; // ignore UNDEF indices
4531 if (ExpectedElt != static_cast<unsigned>(M[i]))
4539 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4540 bool &ReverseVEXT, unsigned &Imm) {
4541 unsigned NumElts = VT.getVectorNumElements();
4542 ReverseVEXT = false;
4544 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4550 // If this is a VEXT shuffle, the immediate value is the index of the first
4551 // element. The other shuffle indices must be the successive elements after
4553 unsigned ExpectedElt = Imm;
4554 for (unsigned i = 1; i < NumElts; ++i) {
4555 // Increment the expected index. If it wraps around, it may still be
4556 // a VEXT but the source vectors must be swapped.
4558 if (ExpectedElt == NumElts * 2) {
4563 if (M[i] < 0) continue; // ignore UNDEF indices
4564 if (ExpectedElt != static_cast<unsigned>(M[i]))
4568 // Adjust the index value if the source operands will be swapped.
4575 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4576 /// instruction with the specified blocksize. (The order of the elements
4577 /// within each block of the vector is reversed.)
4578 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4579 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4580 "Only possible block sizes for VREV are: 16, 32, 64");
4582 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4586 unsigned NumElts = VT.getVectorNumElements();
4587 unsigned BlockElts = M[0] + 1;
4588 // If the first shuffle index is UNDEF, be optimistic.
4590 BlockElts = BlockSize / EltSz;
4592 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4595 for (unsigned i = 0; i < NumElts; ++i) {
4596 if (M[i] < 0) continue; // ignore UNDEF indices
4597 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4604 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4605 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4606 // range, then 0 is placed into the resulting vector. So pretty much any mask
4607 // of 8 elements can work here.
4608 return VT == MVT::v8i8 && M.size() == 8;
4611 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4612 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4616 unsigned NumElts = VT.getVectorNumElements();
4617 WhichResult = (M[0] == 0 ? 0 : 1);
4618 for (unsigned i = 0; i < NumElts; i += 2) {
4619 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4620 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4626 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4627 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4628 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4629 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4630 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4634 unsigned NumElts = VT.getVectorNumElements();
4635 WhichResult = (M[0] == 0 ? 0 : 1);
4636 for (unsigned i = 0; i < NumElts; i += 2) {
4637 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4638 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4644 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4645 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4649 unsigned NumElts = VT.getVectorNumElements();
4650 WhichResult = (M[0] == 0 ? 0 : 1);
4651 for (unsigned i = 0; i != NumElts; ++i) {
4652 if (M[i] < 0) continue; // ignore UNDEF indices
4653 if ((unsigned) M[i] != 2 * i + WhichResult)
4657 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4658 if (VT.is64BitVector() && EltSz == 32)
4664 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4665 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4666 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4667 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4668 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4672 unsigned Half = VT.getVectorNumElements() / 2;
4673 WhichResult = (M[0] == 0 ? 0 : 1);
4674 for (unsigned j = 0; j != 2; ++j) {
4675 unsigned Idx = WhichResult;
4676 for (unsigned i = 0; i != Half; ++i) {
4677 int MIdx = M[i + j * Half];
4678 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4684 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4685 if (VT.is64BitVector() && EltSz == 32)
4691 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4692 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4696 unsigned NumElts = VT.getVectorNumElements();
4697 WhichResult = (M[0] == 0 ? 0 : 1);
4698 unsigned Idx = WhichResult * NumElts / 2;
4699 for (unsigned i = 0; i != NumElts; i += 2) {
4700 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4701 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4706 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4707 if (VT.is64BitVector() && EltSz == 32)
4713 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4714 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4715 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4716 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4717 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4721 unsigned NumElts = VT.getVectorNumElements();
4722 WhichResult = (M[0] == 0 ? 0 : 1);
4723 unsigned Idx = WhichResult * NumElts / 2;
4724 for (unsigned i = 0; i != NumElts; i += 2) {
4725 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4726 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4731 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4732 if (VT.is64BitVector() && EltSz == 32)
4738 /// \return true if this is a reverse operation on an vector.
4739 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4740 unsigned NumElts = VT.getVectorNumElements();
4741 // Make sure the mask has the right size.
4742 if (NumElts != M.size())
4745 // Look for <15, ..., 3, -1, 1, 0>.
4746 for (unsigned i = 0; i != NumElts; ++i)
4747 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4753 // If N is an integer constant that can be moved into a register in one
4754 // instruction, return an SDValue of such a constant (will become a MOV
4755 // instruction). Otherwise return null.
4756 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4757 const ARMSubtarget *ST, SDLoc dl) {
4759 if (!isa<ConstantSDNode>(N))
4761 Val = cast<ConstantSDNode>(N)->getZExtValue();
4763 if (ST->isThumb1Only()) {
4764 if (Val <= 255 || ~Val <= 255)
4765 return DAG.getConstant(Val, MVT::i32);
4767 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4768 return DAG.getConstant(Val, MVT::i32);
4773 // If this is a case we can't handle, return null and let the default
4774 // expansion code take care of it.
4775 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4776 const ARMSubtarget *ST) const {
4777 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4779 EVT VT = Op.getValueType();
4781 APInt SplatBits, SplatUndef;
4782 unsigned SplatBitSize;
4784 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4785 if (SplatBitSize <= 64) {
4786 // Check if an immediate VMOV works.
4788 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4789 SplatUndef.getZExtValue(), SplatBitSize,
4790 DAG, VmovVT, VT.is128BitVector(),
4792 if (Val.getNode()) {
4793 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4794 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4797 // Try an immediate VMVN.
4798 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4799 Val = isNEONModifiedImm(NegatedImm,
4800 SplatUndef.getZExtValue(), SplatBitSize,
4801 DAG, VmovVT, VT.is128BitVector(),
4803 if (Val.getNode()) {
4804 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4805 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4808 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4809 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4810 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4812 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4813 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4819 // Scan through the operands to see if only one value is used.
4821 // As an optimisation, even if more than one value is used it may be more
4822 // profitable to splat with one value then change some lanes.
4824 // Heuristically we decide to do this if the vector has a "dominant" value,
4825 // defined as splatted to more than half of the lanes.
4826 unsigned NumElts = VT.getVectorNumElements();
4827 bool isOnlyLowElement = true;
4828 bool usesOnlyOneValue = true;
4829 bool hasDominantValue = false;
4830 bool isConstant = true;
4832 // Map of the number of times a particular SDValue appears in the
4834 DenseMap<SDValue, unsigned> ValueCounts;
4836 for (unsigned i = 0; i < NumElts; ++i) {
4837 SDValue V = Op.getOperand(i);
4838 if (V.getOpcode() == ISD::UNDEF)
4841 isOnlyLowElement = false;
4842 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4845 ValueCounts.insert(std::make_pair(V, 0));
4846 unsigned &Count = ValueCounts[V];
4848 // Is this value dominant? (takes up more than half of the lanes)
4849 if (++Count > (NumElts / 2)) {
4850 hasDominantValue = true;
4854 if (ValueCounts.size() != 1)
4855 usesOnlyOneValue = false;
4856 if (!Value.getNode() && ValueCounts.size() > 0)
4857 Value = ValueCounts.begin()->first;
4859 if (ValueCounts.size() == 0)
4860 return DAG.getUNDEF(VT);
4862 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4863 // Keep going if we are hitting this case.
4864 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4865 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4867 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4869 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4870 // i32 and try again.
4871 if (hasDominantValue && EltSize <= 32) {
4875 // If we are VDUPing a value that comes directly from a vector, that will
4876 // cause an unnecessary move to and from a GPR, where instead we could
4877 // just use VDUPLANE. We can only do this if the lane being extracted
4878 // is at a constant index, as the VDUP from lane instructions only have
4879 // constant-index forms.
4880 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4881 isa<ConstantSDNode>(Value->getOperand(1))) {
4882 // We need to create a new undef vector to use for the VDUPLANE if the
4883 // size of the vector from which we get the value is different than the
4884 // size of the vector that we need to create. We will insert the element
4885 // such that the register coalescer will remove unnecessary copies.
4886 if (VT != Value->getOperand(0).getValueType()) {
4887 ConstantSDNode *constIndex;
4888 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4889 assert(constIndex && "The index is not a constant!");
4890 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4891 VT.getVectorNumElements();
4892 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4893 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4894 Value, DAG.getConstant(index, MVT::i32)),
4895 DAG.getConstant(index, MVT::i32));
4897 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4898 Value->getOperand(0), Value->getOperand(1));
4900 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4902 if (!usesOnlyOneValue) {
4903 // The dominant value was splatted as 'N', but we now have to insert
4904 // all differing elements.
4905 for (unsigned I = 0; I < NumElts; ++I) {
4906 if (Op.getOperand(I) == Value)
4908 SmallVector<SDValue, 3> Ops;
4910 Ops.push_back(Op.getOperand(I));
4911 Ops.push_back(DAG.getConstant(I, MVT::i32));
4912 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4917 if (VT.getVectorElementType().isFloatingPoint()) {
4918 SmallVector<SDValue, 8> Ops;
4919 for (unsigned i = 0; i < NumElts; ++i)
4920 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4922 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4923 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4924 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4926 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4928 if (usesOnlyOneValue) {
4929 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4930 if (isConstant && Val.getNode())
4931 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4935 // If all elements are constants and the case above didn't get hit, fall back
4936 // to the default expansion, which will generate a load from the constant
4941 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4943 SDValue shuffle = ReconstructShuffle(Op, DAG);
4944 if (shuffle != SDValue())
4948 // Vectors with 32- or 64-bit elements can be built by directly assigning
4949 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4950 // will be legalized.
4951 if (EltSize >= 32) {
4952 // Do the expansion with floating-point types, since that is what the VFP
4953 // registers are defined to use, and since i64 is not legal.
4954 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4955 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4956 SmallVector<SDValue, 8> Ops;
4957 for (unsigned i = 0; i < NumElts; ++i)
4958 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4959 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4960 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4963 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4964 // know the default expansion would otherwise fall back on something even
4965 // worse. For a vector with one or two non-undef values, that's
4966 // scalar_to_vector for the elements followed by a shuffle (provided the
4967 // shuffle is valid for the target) and materialization element by element
4968 // on the stack followed by a load for everything else.
4969 if (!isConstant && !usesOnlyOneValue) {
4970 SDValue Vec = DAG.getUNDEF(VT);
4971 for (unsigned i = 0 ; i < NumElts; ++i) {
4972 SDValue V = Op.getOperand(i);
4973 if (V.getOpcode() == ISD::UNDEF)
4975 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4976 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4984 // Gather data to see if the operation can be modelled as a
4985 // shuffle in combination with VEXTs.
4986 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4987 SelectionDAG &DAG) const {
4989 EVT VT = Op.getValueType();
4990 unsigned NumElts = VT.getVectorNumElements();
4992 SmallVector<SDValue, 2> SourceVecs;
4993 SmallVector<unsigned, 2> MinElts;
4994 SmallVector<unsigned, 2> MaxElts;
4996 for (unsigned i = 0; i < NumElts; ++i) {
4997 SDValue V = Op.getOperand(i);
4998 if (V.getOpcode() == ISD::UNDEF)
5000 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5001 // A shuffle can only come from building a vector from various
5002 // elements of other vectors.
5004 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5005 VT.getVectorElementType()) {
5006 // This code doesn't know how to handle shuffles where the vector
5007 // element types do not match (this happens because type legalization
5008 // promotes the return type of EXTRACT_VECTOR_ELT).
5009 // FIXME: It might be appropriate to extend this code to handle
5010 // mismatched types.
5014 // Record this extraction against the appropriate vector if possible...
5015 SDValue SourceVec = V.getOperand(0);
5016 // If the element number isn't a constant, we can't effectively
5017 // analyze what's going on.
5018 if (!isa<ConstantSDNode>(V.getOperand(1)))
5020 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5021 bool FoundSource = false;
5022 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5023 if (SourceVecs[j] == SourceVec) {
5024 if (MinElts[j] > EltNo)
5026 if (MaxElts[j] < EltNo)
5033 // Or record a new source if not...
5035 SourceVecs.push_back(SourceVec);
5036 MinElts.push_back(EltNo);
5037 MaxElts.push_back(EltNo);
5041 // Currently only do something sane when at most two source vectors
5043 if (SourceVecs.size() > 2)
5046 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5047 int VEXTOffsets[2] = {0, 0};
5049 // This loop extracts the usage patterns of the source vectors
5050 // and prepares appropriate SDValues for a shuffle if possible.
5051 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5052 if (SourceVecs[i].getValueType() == VT) {
5053 // No VEXT necessary
5054 ShuffleSrcs[i] = SourceVecs[i];
5057 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5058 // It probably isn't worth padding out a smaller vector just to
5059 // break it down again in a shuffle.
5063 // Since only 64-bit and 128-bit vectors are legal on ARM and
5064 // we've eliminated the other cases...
5065 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5066 "unexpected vector sizes in ReconstructShuffle");
5068 if (MaxElts[i] - MinElts[i] >= NumElts) {
5069 // Span too large for a VEXT to cope
5073 if (MinElts[i] >= NumElts) {
5074 // The extraction can just take the second half
5075 VEXTOffsets[i] = NumElts;
5076 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5078 DAG.getIntPtrConstant(NumElts));
5079 } else if (MaxElts[i] < NumElts) {
5080 // The extraction can just take the first half
5082 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5084 DAG.getIntPtrConstant(0));
5086 // An actual VEXT is needed
5087 VEXTOffsets[i] = MinElts[i];
5088 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5090 DAG.getIntPtrConstant(0));
5091 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5093 DAG.getIntPtrConstant(NumElts));
5094 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5095 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5099 SmallVector<int, 8> Mask;
5101 for (unsigned i = 0; i < NumElts; ++i) {
5102 SDValue Entry = Op.getOperand(i);
5103 if (Entry.getOpcode() == ISD::UNDEF) {
5108 SDValue ExtractVec = Entry.getOperand(0);
5109 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5110 .getOperand(1))->getSExtValue();
5111 if (ExtractVec == SourceVecs[0]) {
5112 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5114 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5118 // Final check before we try to produce nonsense...
5119 if (isShuffleMaskLegal(Mask, VT))
5120 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5126 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5127 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5128 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5129 /// are assumed to be legal.
5131 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5133 if (VT.getVectorNumElements() == 4 &&
5134 (VT.is128BitVector() || VT.is64BitVector())) {
5135 unsigned PFIndexes[4];
5136 for (unsigned i = 0; i != 4; ++i) {
5140 PFIndexes[i] = M[i];
5143 // Compute the index in the perfect shuffle table.
5144 unsigned PFTableIndex =
5145 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5146 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5147 unsigned Cost = (PFEntry >> 30);
5154 unsigned Imm, WhichResult;
5156 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5157 return (EltSize >= 32 ||
5158 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5159 isVREVMask(M, VT, 64) ||
5160 isVREVMask(M, VT, 32) ||
5161 isVREVMask(M, VT, 16) ||
5162 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5163 isVTBLMask(M, VT) ||
5164 isVTRNMask(M, VT, WhichResult) ||
5165 isVUZPMask(M, VT, WhichResult) ||
5166 isVZIPMask(M, VT, WhichResult) ||
5167 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5168 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5169 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5170 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5173 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5174 /// the specified operations to build the shuffle.
5175 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5176 SDValue RHS, SelectionDAG &DAG,
5178 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5179 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5180 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5183 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5192 OP_VUZPL, // VUZP, left result
5193 OP_VUZPR, // VUZP, right result
5194 OP_VZIPL, // VZIP, left result
5195 OP_VZIPR, // VZIP, right result
5196 OP_VTRNL, // VTRN, left result
5197 OP_VTRNR // VTRN, right result
5200 if (OpNum == OP_COPY) {
5201 if (LHSID == (1*9+2)*9+3) return LHS;
5202 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5206 SDValue OpLHS, OpRHS;
5207 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5208 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5209 EVT VT = OpLHS.getValueType();
5212 default: llvm_unreachable("Unknown shuffle opcode!");
5214 // VREV divides the vector in half and swaps within the half.
5215 if (VT.getVectorElementType() == MVT::i32 ||
5216 VT.getVectorElementType() == MVT::f32)
5217 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5218 // vrev <4 x i16> -> VREV32
5219 if (VT.getVectorElementType() == MVT::i16)
5220 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5221 // vrev <4 x i8> -> VREV16
5222 assert(VT.getVectorElementType() == MVT::i8);
5223 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5228 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5229 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5233 return DAG.getNode(ARMISD::VEXT, dl, VT,
5235 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5238 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5239 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5242 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5243 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5246 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5247 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5251 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5252 ArrayRef<int> ShuffleMask,
5253 SelectionDAG &DAG) {
5254 // Check to see if we can use the VTBL instruction.
5255 SDValue V1 = Op.getOperand(0);
5256 SDValue V2 = Op.getOperand(1);
5259 SmallVector<SDValue, 8> VTBLMask;
5260 for (ArrayRef<int>::iterator
5261 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5262 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5264 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5265 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5266 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5269 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5270 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5274 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5275 SelectionDAG &DAG) {
5277 SDValue OpLHS = Op.getOperand(0);
5278 EVT VT = OpLHS.getValueType();
5280 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5281 "Expect an v8i16/v16i8 type");
5282 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5283 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5284 // extract the first 8 bytes into the top double word and the last 8 bytes
5285 // into the bottom double word. The v8i16 case is similar.
5286 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5287 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5288 DAG.getConstant(ExtractNum, MVT::i32));
5291 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5292 SDValue V1 = Op.getOperand(0);
5293 SDValue V2 = Op.getOperand(1);
5295 EVT VT = Op.getValueType();
5296 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5298 // Convert shuffles that are directly supported on NEON to target-specific
5299 // DAG nodes, instead of keeping them as shuffles and matching them again
5300 // during code selection. This is more efficient and avoids the possibility
5301 // of inconsistencies between legalization and selection.
5302 // FIXME: floating-point vectors should be canonicalized to integer vectors
5303 // of the same time so that they get CSEd properly.
5304 ArrayRef<int> ShuffleMask = SVN->getMask();
5306 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5307 if (EltSize <= 32) {
5308 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5309 int Lane = SVN->getSplatIndex();
5310 // If this is undef splat, generate it via "just" vdup, if possible.
5311 if (Lane == -1) Lane = 0;
5313 // Test if V1 is a SCALAR_TO_VECTOR.
5314 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5315 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5317 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5318 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5320 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5321 !isa<ConstantSDNode>(V1.getOperand(0))) {
5322 bool IsScalarToVector = true;
5323 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5324 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5325 IsScalarToVector = false;
5328 if (IsScalarToVector)
5329 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5331 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5332 DAG.getConstant(Lane, MVT::i32));
5337 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5340 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5341 DAG.getConstant(Imm, MVT::i32));
5344 if (isVREVMask(ShuffleMask, VT, 64))
5345 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5346 if (isVREVMask(ShuffleMask, VT, 32))
5347 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5348 if (isVREVMask(ShuffleMask, VT, 16))
5349 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5351 if (V2->getOpcode() == ISD::UNDEF &&
5352 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5353 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5354 DAG.getConstant(Imm, MVT::i32));
5357 // Check for Neon shuffles that modify both input vectors in place.
5358 // If both results are used, i.e., if there are two shuffles with the same
5359 // source operands and with masks corresponding to both results of one of
5360 // these operations, DAG memoization will ensure that a single node is
5361 // used for both shuffles.
5362 unsigned WhichResult;
5363 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5364 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5365 V1, V2).getValue(WhichResult);
5366 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5367 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5368 V1, V2).getValue(WhichResult);
5369 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5370 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5371 V1, V2).getValue(WhichResult);
5373 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5374 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5375 V1, V1).getValue(WhichResult);
5376 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5377 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5378 V1, V1).getValue(WhichResult);
5379 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5380 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5381 V1, V1).getValue(WhichResult);
5384 // If the shuffle is not directly supported and it has 4 elements, use
5385 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5386 unsigned NumElts = VT.getVectorNumElements();
5388 unsigned PFIndexes[4];
5389 for (unsigned i = 0; i != 4; ++i) {
5390 if (ShuffleMask[i] < 0)
5393 PFIndexes[i] = ShuffleMask[i];
5396 // Compute the index in the perfect shuffle table.
5397 unsigned PFTableIndex =
5398 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5399 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5400 unsigned Cost = (PFEntry >> 30);
5403 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5406 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5407 if (EltSize >= 32) {
5408 // Do the expansion with floating-point types, since that is what the VFP
5409 // registers are defined to use, and since i64 is not legal.
5410 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5411 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5412 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5413 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5414 SmallVector<SDValue, 8> Ops;
5415 for (unsigned i = 0; i < NumElts; ++i) {
5416 if (ShuffleMask[i] < 0)
5417 Ops.push_back(DAG.getUNDEF(EltVT));
5419 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5420 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5421 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5424 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5425 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5428 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5429 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5431 if (VT == MVT::v8i8) {
5432 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5433 if (NewOp.getNode())
5440 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5441 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5442 SDValue Lane = Op.getOperand(2);
5443 if (!isa<ConstantSDNode>(Lane))
5449 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5450 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5451 SDValue Lane = Op.getOperand(1);
5452 if (!isa<ConstantSDNode>(Lane))
5455 SDValue Vec = Op.getOperand(0);
5456 if (Op.getValueType() == MVT::i32 &&
5457 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5459 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5465 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5466 // The only time a CONCAT_VECTORS operation can have legal types is when
5467 // two 64-bit vectors are concatenated to a 128-bit vector.
5468 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5469 "unexpected CONCAT_VECTORS");
5471 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5472 SDValue Op0 = Op.getOperand(0);
5473 SDValue Op1 = Op.getOperand(1);
5474 if (Op0.getOpcode() != ISD::UNDEF)
5475 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5476 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5477 DAG.getIntPtrConstant(0));
5478 if (Op1.getOpcode() != ISD::UNDEF)
5479 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5480 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5481 DAG.getIntPtrConstant(1));
5482 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5485 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5486 /// element has been zero/sign-extended, depending on the isSigned parameter,
5487 /// from an integer type half its size.
5488 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5490 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5491 EVT VT = N->getValueType(0);
5492 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5493 SDNode *BVN = N->getOperand(0).getNode();
5494 if (BVN->getValueType(0) != MVT::v4i32 ||
5495 BVN->getOpcode() != ISD::BUILD_VECTOR)
5497 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5498 unsigned HiElt = 1 - LoElt;
5499 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5500 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5501 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5502 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5503 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5506 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5507 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5510 if (Hi0->isNullValue() && Hi1->isNullValue())
5516 if (N->getOpcode() != ISD::BUILD_VECTOR)
5519 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5520 SDNode *Elt = N->getOperand(i).getNode();
5521 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5522 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5523 unsigned HalfSize = EltSize / 2;
5525 if (!isIntN(HalfSize, C->getSExtValue()))
5528 if (!isUIntN(HalfSize, C->getZExtValue()))
5539 /// isSignExtended - Check if a node is a vector value that is sign-extended
5540 /// or a constant BUILD_VECTOR with sign-extended elements.
5541 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5542 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5544 if (isExtendedBUILD_VECTOR(N, DAG, true))
5549 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5550 /// or a constant BUILD_VECTOR with zero-extended elements.
5551 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5552 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5554 if (isExtendedBUILD_VECTOR(N, DAG, false))
5559 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5560 if (OrigVT.getSizeInBits() >= 64)
5563 assert(OrigVT.isSimple() && "Expecting a simple value type");
5565 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5566 switch (OrigSimpleTy) {
5567 default: llvm_unreachable("Unexpected Vector Type");
5576 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5577 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5578 /// We insert the required extension here to get the vector to fill a D register.
5579 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5582 unsigned ExtOpcode) {
5583 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5584 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5585 // 64-bits we need to insert a new extension so that it will be 64-bits.
5586 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5587 if (OrigTy.getSizeInBits() >= 64)
5590 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5591 EVT NewVT = getExtensionTo64Bits(OrigTy);
5593 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5596 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5597 /// does not do any sign/zero extension. If the original vector is less
5598 /// than 64 bits, an appropriate extension will be added after the load to
5599 /// reach a total size of 64 bits. We have to add the extension separately
5600 /// because ARM does not have a sign/zero extending load for vectors.
5601 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5602 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5604 // The load already has the right type.
5605 if (ExtendedTy == LD->getMemoryVT())
5606 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5607 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5608 LD->isNonTemporal(), LD->isInvariant(),
5609 LD->getAlignment());
5611 // We need to create a zextload/sextload. We cannot just create a load
5612 // followed by a zext/zext node because LowerMUL is also run during normal
5613 // operation legalization where we can't create illegal types.
5614 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5615 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5616 LD->getMemoryVT(), LD->isVolatile(),
5617 LD->isNonTemporal(), LD->getAlignment());
5620 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5621 /// extending load, or BUILD_VECTOR with extended elements, return the
5622 /// unextended value. The unextended vector should be 64 bits so that it can
5623 /// be used as an operand to a VMULL instruction. If the original vector size
5624 /// before extension is less than 64 bits we add a an extension to resize
5625 /// the vector to 64 bits.
5626 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5627 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5628 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5629 N->getOperand(0)->getValueType(0),
5633 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5634 return SkipLoadExtensionForVMULL(LD, DAG);
5636 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5637 // have been legalized as a BITCAST from v4i32.
5638 if (N->getOpcode() == ISD::BITCAST) {
5639 SDNode *BVN = N->getOperand(0).getNode();
5640 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5641 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5642 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5643 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5644 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5646 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5647 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5648 EVT VT = N->getValueType(0);
5649 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5650 unsigned NumElts = VT.getVectorNumElements();
5651 MVT TruncVT = MVT::getIntegerVT(EltSize);
5652 SmallVector<SDValue, 8> Ops;
5653 for (unsigned i = 0; i != NumElts; ++i) {
5654 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5655 const APInt &CInt = C->getAPIntValue();
5656 // Element types smaller than 32 bits are not legal, so use i32 elements.
5657 // The values are implicitly truncated so sext vs. zext doesn't matter.
5658 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5660 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5661 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5664 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5665 unsigned Opcode = N->getOpcode();
5666 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5667 SDNode *N0 = N->getOperand(0).getNode();
5668 SDNode *N1 = N->getOperand(1).getNode();
5669 return N0->hasOneUse() && N1->hasOneUse() &&
5670 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5675 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5676 unsigned Opcode = N->getOpcode();
5677 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5678 SDNode *N0 = N->getOperand(0).getNode();
5679 SDNode *N1 = N->getOperand(1).getNode();
5680 return N0->hasOneUse() && N1->hasOneUse() &&
5681 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5686 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5687 // Multiplications are only custom-lowered for 128-bit vectors so that
5688 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5689 EVT VT = Op.getValueType();
5690 assert(VT.is128BitVector() && VT.isInteger() &&
5691 "unexpected type for custom-lowering ISD::MUL");
5692 SDNode *N0 = Op.getOperand(0).getNode();
5693 SDNode *N1 = Op.getOperand(1).getNode();
5694 unsigned NewOpc = 0;
5696 bool isN0SExt = isSignExtended(N0, DAG);
5697 bool isN1SExt = isSignExtended(N1, DAG);
5698 if (isN0SExt && isN1SExt)
5699 NewOpc = ARMISD::VMULLs;
5701 bool isN0ZExt = isZeroExtended(N0, DAG);
5702 bool isN1ZExt = isZeroExtended(N1, DAG);
5703 if (isN0ZExt && isN1ZExt)
5704 NewOpc = ARMISD::VMULLu;
5705 else if (isN1SExt || isN1ZExt) {
5706 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5707 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5708 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5709 NewOpc = ARMISD::VMULLs;
5711 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5712 NewOpc = ARMISD::VMULLu;
5714 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5716 NewOpc = ARMISD::VMULLu;
5722 if (VT == MVT::v2i64)
5723 // Fall through to expand this. It is not legal.
5726 // Other vector multiplications are legal.
5731 // Legalize to a VMULL instruction.
5734 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5736 Op0 = SkipExtensionForVMULL(N0, DAG);
5737 assert(Op0.getValueType().is64BitVector() &&
5738 Op1.getValueType().is64BitVector() &&
5739 "unexpected types for extended operands to VMULL");
5740 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5743 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5744 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5751 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5752 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5753 EVT Op1VT = Op1.getValueType();
5754 return DAG.getNode(N0->getOpcode(), DL, VT,
5755 DAG.getNode(NewOpc, DL, VT,
5756 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5757 DAG.getNode(NewOpc, DL, VT,
5758 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5762 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5764 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5765 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5766 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5767 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5768 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5769 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5770 // Get reciprocal estimate.
5771 // float4 recip = vrecpeq_f32(yf);
5772 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5773 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5774 // Because char has a smaller range than uchar, we can actually get away
5775 // without any newton steps. This requires that we use a weird bias
5776 // of 0xb000, however (again, this has been exhaustively tested).
5777 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5778 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5779 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5780 Y = DAG.getConstant(0xb000, MVT::i32);
5781 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5782 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5783 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5784 // Convert back to short.
5785 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5786 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5791 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5793 // Convert to float.
5794 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5795 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5796 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5797 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5798 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5799 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5801 // Use reciprocal estimate and one refinement step.
5802 // float4 recip = vrecpeq_f32(yf);
5803 // recip *= vrecpsq_f32(yf, recip);
5804 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5805 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5806 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5807 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5809 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5810 // Because short has a smaller range than ushort, we can actually get away
5811 // with only a single newton step. This requires that we use a weird bias
5812 // of 89, however (again, this has been exhaustively tested).
5813 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5814 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5815 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5816 N1 = DAG.getConstant(0x89, MVT::i32);
5817 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5818 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5819 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5820 // Convert back to integer and return.
5821 // return vmovn_s32(vcvt_s32_f32(result));
5822 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5823 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5827 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5828 EVT VT = Op.getValueType();
5829 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5830 "unexpected type for custom-lowering ISD::SDIV");
5833 SDValue N0 = Op.getOperand(0);
5834 SDValue N1 = Op.getOperand(1);
5837 if (VT == MVT::v8i8) {
5838 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5839 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5841 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5842 DAG.getIntPtrConstant(4));
5843 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5844 DAG.getIntPtrConstant(4));
5845 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5846 DAG.getIntPtrConstant(0));
5847 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5848 DAG.getIntPtrConstant(0));
5850 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5851 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5853 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5854 N0 = LowerCONCAT_VECTORS(N0, DAG);
5856 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5859 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5862 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5863 EVT VT = Op.getValueType();
5864 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5865 "unexpected type for custom-lowering ISD::UDIV");
5868 SDValue N0 = Op.getOperand(0);
5869 SDValue N1 = Op.getOperand(1);
5872 if (VT == MVT::v8i8) {
5873 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5874 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5876 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5877 DAG.getIntPtrConstant(4));
5878 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5879 DAG.getIntPtrConstant(4));
5880 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5881 DAG.getIntPtrConstant(0));
5882 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5883 DAG.getIntPtrConstant(0));
5885 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5886 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5888 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5889 N0 = LowerCONCAT_VECTORS(N0, DAG);
5891 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5892 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5897 // v4i16 sdiv ... Convert to float.
5898 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5899 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5900 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5901 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5902 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5903 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5905 // Use reciprocal estimate and two refinement steps.
5906 // float4 recip = vrecpeq_f32(yf);
5907 // recip *= vrecpsq_f32(yf, recip);
5908 // recip *= vrecpsq_f32(yf, recip);
5909 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5910 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5911 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5912 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5914 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5915 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5916 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5918 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5919 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5920 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5921 // and that it will never cause us to return an answer too large).
5922 // float4 result = as_float4(as_int4(xf*recip) + 2);
5923 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5924 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5925 N1 = DAG.getConstant(2, MVT::i32);
5926 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5927 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5928 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5929 // Convert back to integer and return.
5930 // return vmovn_u32(vcvt_s32_f32(result));
5931 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5932 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5936 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5937 EVT VT = Op.getNode()->getValueType(0);
5938 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5941 bool ExtraOp = false;
5942 switch (Op.getOpcode()) {
5943 default: llvm_unreachable("Invalid code");
5944 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5945 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5946 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5947 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5951 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5953 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5954 Op.getOperand(1), Op.getOperand(2));
5957 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5958 assert(Subtarget->isTargetDarwin());
5960 // For iOS, we want to call an alternative entry point: __sincos_stret,
5961 // return values are passed via sret.
5963 SDValue Arg = Op.getOperand(0);
5964 EVT ArgVT = Arg.getValueType();
5965 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5967 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5968 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5970 // Pair of floats / doubles used to pass the result.
5971 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5973 // Create stack object for sret.
5974 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5975 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5976 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5977 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5983 Entry.Ty = RetTy->getPointerTo();
5984 Entry.isSExt = false;
5985 Entry.isZExt = false;
5986 Entry.isSRet = true;
5987 Args.push_back(Entry);
5991 Entry.isSExt = false;
5992 Entry.isZExt = false;
5993 Args.push_back(Entry);
5995 const char *LibcallName = (ArgVT == MVT::f64)
5996 ? "__sincos_stret" : "__sincosf_stret";
5997 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6000 CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6001 false, false, false, false, 0,
6002 CallingConv::C, /*isTaillCall=*/false,
6003 /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6004 Callee, Args, DAG, dl);
6005 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6007 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6008 MachinePointerInfo(), false, false, false, 0);
6010 // Address of cos field.
6011 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6012 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6013 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6014 MachinePointerInfo(), false, false, false, 0);
6016 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6017 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6018 LoadSin.getValue(0), LoadCos.getValue(0));
6021 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6022 // Monotonic load/store is legal for all targets
6023 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6026 // Acquire/Release load/store is not legal for targets without a
6027 // dmb or equivalent available.
6032 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6033 SelectionDAG &DAG) {
6035 assert (Node->getValueType(0) == MVT::i64 &&
6036 "Only know how to expand i64 atomics");
6037 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6039 SmallVector<SDValue, 6> Ops;
6040 Ops.push_back(Node->getOperand(0)); // Chain
6041 Ops.push_back(Node->getOperand(1)); // Ptr
6042 for(unsigned i=2; i<Node->getNumOperands(); i++) {
6044 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6045 Node->getOperand(i), DAG.getIntPtrConstant(0)));
6047 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6048 Node->getOperand(i), DAG.getIntPtrConstant(1)));
6050 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6051 SDValue Result = DAG.getAtomic(
6052 Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6053 cast<MemSDNode>(Node)->getMemOperand(), AN->getSuccessOrdering(),
6054 AN->getFailureOrdering(), AN->getSynchScope());
6055 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6056 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6057 Results.push_back(Result.getValue(2));
6060 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6061 SmallVectorImpl<SDValue> &Results,
6063 const ARMSubtarget *Subtarget) {
6065 SDValue Cycles32, OutChain;
6067 if (Subtarget->hasPerfMon()) {
6068 // Under Power Management extensions, the cycle-count is:
6069 // mrc p15, #0, <Rt>, c9, c13, #0
6070 SDValue Ops[] = { N->getOperand(0), // Chain
6071 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6072 DAG.getConstant(15, MVT::i32),
6073 DAG.getConstant(0, MVT::i32),
6074 DAG.getConstant(9, MVT::i32),
6075 DAG.getConstant(13, MVT::i32),
6076 DAG.getConstant(0, MVT::i32)
6079 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6080 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6081 array_lengthof(Ops));
6082 OutChain = Cycles32.getValue(1);
6084 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6085 // there are older ARM CPUs that have implementation-specific ways of
6086 // obtaining this information (FIXME!).
6087 Cycles32 = DAG.getConstant(0, MVT::i32);
6088 OutChain = DAG.getEntryNode();
6092 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6093 Cycles32, DAG.getConstant(0, MVT::i32));
6094 Results.push_back(Cycles64);
6095 Results.push_back(OutChain);
6098 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6099 switch (Op.getOpcode()) {
6100 default: llvm_unreachable("Don't know how to custom lower this!");
6101 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6102 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6103 case ISD::GlobalAddress:
6104 return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6105 LowerGlobalAddressELF(Op, DAG);
6106 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6107 case ISD::SELECT: return LowerSELECT(Op, DAG);
6108 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6109 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6110 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6111 case ISD::VASTART: return LowerVASTART(Op, DAG);
6112 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6113 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6114 case ISD::SINT_TO_FP:
6115 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6116 case ISD::FP_TO_SINT:
6117 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6118 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6119 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6120 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6121 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6122 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6123 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6124 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6126 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6129 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6130 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6131 case ISD::SRL_PARTS:
6132 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6133 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6134 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6135 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6136 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6137 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6138 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6139 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6140 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6141 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6142 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6143 case ISD::MUL: return LowerMUL(Op, DAG);
6144 case ISD::SDIV: return LowerSDIV(Op, DAG);
6145 case ISD::UDIV: return LowerUDIV(Op, DAG);
6149 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6150 case ISD::ATOMIC_LOAD:
6151 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6152 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6154 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6158 /// ReplaceNodeResults - Replace the results of node with an illegal result
6159 /// type with new values built out of custom code.
6160 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6161 SmallVectorImpl<SDValue>&Results,
6162 SelectionDAG &DAG) const {
6164 switch (N->getOpcode()) {
6166 llvm_unreachable("Don't know how to custom expand this!");
6168 Res = ExpandBITCAST(N, DAG);
6172 Res = Expand64BitShift(N, DAG, Subtarget);
6174 case ISD::READCYCLECOUNTER:
6175 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6177 case ISD::ATOMIC_STORE:
6178 case ISD::ATOMIC_LOAD:
6179 case ISD::ATOMIC_LOAD_ADD:
6180 case ISD::ATOMIC_LOAD_AND:
6181 case ISD::ATOMIC_LOAD_NAND:
6182 case ISD::ATOMIC_LOAD_OR:
6183 case ISD::ATOMIC_LOAD_SUB:
6184 case ISD::ATOMIC_LOAD_XOR:
6185 case ISD::ATOMIC_SWAP:
6186 case ISD::ATOMIC_CMP_SWAP:
6187 case ISD::ATOMIC_LOAD_MIN:
6188 case ISD::ATOMIC_LOAD_UMIN:
6189 case ISD::ATOMIC_LOAD_MAX:
6190 case ISD::ATOMIC_LOAD_UMAX:
6191 ReplaceATOMIC_OP_64(N, Results, DAG);
6195 Results.push_back(Res);
6198 //===----------------------------------------------------------------------===//
6199 // ARM Scheduler Hooks
6200 //===----------------------------------------------------------------------===//
6203 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6204 MachineBasicBlock *BB,
6205 unsigned Size) const {
6206 unsigned dest = MI->getOperand(0).getReg();
6207 unsigned ptr = MI->getOperand(1).getReg();
6208 unsigned oldval = MI->getOperand(2).getReg();
6209 unsigned newval = MI->getOperand(3).getReg();
6210 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6211 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6212 DebugLoc dl = MI->getDebugLoc();
6213 bool isThumb2 = Subtarget->isThumb2();
6215 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6216 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6217 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6218 (const TargetRegisterClass*)&ARM::GPRRegClass);
6221 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6222 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6223 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6226 unsigned ldrOpc, strOpc;
6227 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6229 MachineFunction *MF = BB->getParent();
6230 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6231 MachineFunction::iterator It = BB;
6232 ++It; // insert the new blocks after the current block
6234 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6235 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6236 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6237 MF->insert(It, loop1MBB);
6238 MF->insert(It, loop2MBB);
6239 MF->insert(It, exitMBB);
6241 // Transfer the remainder of BB and its successor edges to exitMBB.
6242 exitMBB->splice(exitMBB->begin(), BB,
6243 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6244 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6248 // fallthrough --> loop1MBB
6249 BB->addSuccessor(loop1MBB);
6252 // ldrex dest, [ptr]
6256 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6257 if (ldrOpc == ARM::t2LDREX)
6259 AddDefaultPred(MIB);
6260 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6261 .addReg(dest).addReg(oldval));
6262 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6263 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6264 BB->addSuccessor(loop2MBB);
6265 BB->addSuccessor(exitMBB);
6268 // strex scratch, newval, [ptr]
6272 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6273 if (strOpc == ARM::t2STREX)
6275 AddDefaultPred(MIB);
6276 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6277 .addReg(scratch).addImm(0));
6278 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6279 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6280 BB->addSuccessor(loop1MBB);
6281 BB->addSuccessor(exitMBB);
6287 MI->eraseFromParent(); // The instruction is gone now.
6293 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6294 unsigned Size, unsigned BinOpcode) const {
6295 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6296 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6298 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6299 MachineFunction *MF = BB->getParent();
6300 MachineFunction::iterator It = BB;
6303 unsigned dest = MI->getOperand(0).getReg();
6304 unsigned ptr = MI->getOperand(1).getReg();
6305 unsigned incr = MI->getOperand(2).getReg();
6306 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6307 DebugLoc dl = MI->getDebugLoc();
6308 bool isThumb2 = Subtarget->isThumb2();
6310 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6312 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6313 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6314 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6317 unsigned ldrOpc, strOpc;
6318 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6320 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6321 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6322 MF->insert(It, loopMBB);
6323 MF->insert(It, exitMBB);
6325 // Transfer the remainder of BB and its successor edges to exitMBB.
6326 exitMBB->splice(exitMBB->begin(), BB,
6327 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6328 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6330 const TargetRegisterClass *TRC = isThumb2 ?
6331 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6332 (const TargetRegisterClass*)&ARM::GPRRegClass;
6333 unsigned scratch = MRI.createVirtualRegister(TRC);
6334 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6338 // fallthrough --> loopMBB
6339 BB->addSuccessor(loopMBB);
6343 // <binop> scratch2, dest, incr
6344 // strex scratch, scratch2, ptr
6347 // fallthrough --> exitMBB
6349 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6350 if (ldrOpc == ARM::t2LDREX)
6352 AddDefaultPred(MIB);
6354 // operand order needs to go the other way for NAND
6355 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6356 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6357 addReg(incr).addReg(dest)).addReg(0);
6359 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6360 addReg(dest).addReg(incr)).addReg(0);
6363 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6364 if (strOpc == ARM::t2STREX)
6366 AddDefaultPred(MIB);
6367 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6368 .addReg(scratch).addImm(0));
6369 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6370 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6372 BB->addSuccessor(loopMBB);
6373 BB->addSuccessor(exitMBB);
6379 MI->eraseFromParent(); // The instruction is gone now.
6385 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6386 MachineBasicBlock *BB,
6389 ARMCC::CondCodes Cond) const {
6390 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6392 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6393 MachineFunction *MF = BB->getParent();
6394 MachineFunction::iterator It = BB;
6397 unsigned dest = MI->getOperand(0).getReg();
6398 unsigned ptr = MI->getOperand(1).getReg();
6399 unsigned incr = MI->getOperand(2).getReg();
6400 unsigned oldval = dest;
6401 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6402 DebugLoc dl = MI->getDebugLoc();
6403 bool isThumb2 = Subtarget->isThumb2();
6405 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6407 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6408 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6409 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6412 unsigned ldrOpc, strOpc, extendOpc;
6413 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6415 default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6417 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6420 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6427 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6428 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6429 MF->insert(It, loopMBB);
6430 MF->insert(It, exitMBB);
6432 // Transfer the remainder of BB and its successor edges to exitMBB.
6433 exitMBB->splice(exitMBB->begin(), BB,
6434 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6435 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6437 const TargetRegisterClass *TRC = isThumb2 ?
6438 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6439 (const TargetRegisterClass*)&ARM::GPRRegClass;
6440 unsigned scratch = MRI.createVirtualRegister(TRC);
6441 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6445 // fallthrough --> loopMBB
6446 BB->addSuccessor(loopMBB);
6450 // (sign extend dest, if required)
6452 // cmov.cond scratch2, incr, dest
6453 // strex scratch, scratch2, ptr
6456 // fallthrough --> exitMBB
6458 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6459 if (ldrOpc == ARM::t2LDREX)
6461 AddDefaultPred(MIB);
6463 // Sign extend the value, if necessary.
6464 if (signExtend && extendOpc) {
6465 oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6466 : &ARM::GPRnopcRegClass);
6468 MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6469 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6474 // Build compare and cmov instructions.
6475 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6476 .addReg(oldval).addReg(incr));
6477 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6478 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6480 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6481 if (strOpc == ARM::t2STREX)
6483 AddDefaultPred(MIB);
6484 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6485 .addReg(scratch).addImm(0));
6486 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6487 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6489 BB->addSuccessor(loopMBB);
6490 BB->addSuccessor(exitMBB);
6496 MI->eraseFromParent(); // The instruction is gone now.
6502 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6503 unsigned Op1, unsigned Op2,
6504 bool NeedsCarry, bool IsCmpxchg,
6505 bool IsMinMax, ARMCC::CondCodes CC) const {
6506 // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6507 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6509 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6510 MachineFunction *MF = BB->getParent();
6511 MachineFunction::iterator It = BB;
6514 unsigned destlo = MI->getOperand(0).getReg();
6515 unsigned desthi = MI->getOperand(1).getReg();
6516 unsigned ptr = MI->getOperand(2).getReg();
6517 unsigned vallo = MI->getOperand(3).getReg();
6518 unsigned valhi = MI->getOperand(4).getReg();
6519 AtomicOrdering Ord =
6520 static_cast<AtomicOrdering>(MI->getOperand(IsCmpxchg ? 7 : 5).getImm());
6521 DebugLoc dl = MI->getDebugLoc();
6522 bool isThumb2 = Subtarget->isThumb2();
6524 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6526 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6527 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6528 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6529 MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6530 MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6533 unsigned ldrOpc, strOpc;
6534 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6536 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6537 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6538 if (IsCmpxchg || IsMinMax)
6539 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6541 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6542 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6544 MF->insert(It, loopMBB);
6545 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6546 if (IsCmpxchg) MF->insert(It, cont2BB);
6547 MF->insert(It, exitMBB);
6549 // Transfer the remainder of BB and its successor edges to exitMBB.
6550 exitMBB->splice(exitMBB->begin(), BB,
6551 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6552 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6554 const TargetRegisterClass *TRC = isThumb2 ?
6555 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6556 (const TargetRegisterClass*)&ARM::GPRRegClass;
6557 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6561 // fallthrough --> loopMBB
6562 BB->addSuccessor(loopMBB);
6565 // ldrexd r2, r3, ptr
6566 // <binopa> r0, r2, incr
6567 // <binopb> r1, r3, incr
6568 // strexd storesuccess, r0, r1, ptr
6569 // cmp storesuccess, #0
6571 // fallthrough --> exitMBB
6576 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6577 .addReg(destlo, RegState::Define)
6578 .addReg(desthi, RegState::Define)
6581 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6582 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6583 .addReg(GPRPair0, RegState::Define)
6585 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6586 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6587 .addReg(GPRPair0, 0, ARM::gsub_0);
6588 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6589 .addReg(GPRPair0, 0, ARM::gsub_1);
6592 unsigned StoreLo, StoreHi;
6595 for (unsigned i = 0; i < 2; i++) {
6596 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6598 .addReg(i == 0 ? destlo : desthi)
6599 .addReg(i == 0 ? vallo : valhi));
6600 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6601 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6602 BB->addSuccessor(exitMBB);
6603 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6604 BB = (i == 0 ? contBB : cont2BB);
6607 // Copy to physregs for strexd
6608 StoreLo = MI->getOperand(5).getReg();
6609 StoreHi = MI->getOperand(6).getReg();
6611 // Perform binary operation
6612 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6613 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6614 .addReg(destlo).addReg(vallo))
6615 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6616 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6617 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6618 .addReg(desthi).addReg(valhi))
6619 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6624 // Copy to physregs for strexd
6629 // Compare and branch to exit block.
6630 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6631 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6632 BB->addSuccessor(exitMBB);
6633 BB->addSuccessor(contBB);
6641 MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6642 MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6643 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6644 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6646 // Marshal a pair...
6647 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6648 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6649 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6650 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6651 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6654 .addImm(ARM::gsub_0);
6655 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6658 .addImm(ARM::gsub_1);
6661 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6662 .addReg(StorePair).addReg(ptr));
6665 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6666 .addReg(storesuccess).addImm(0));
6667 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6668 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6670 BB->addSuccessor(loopMBB);
6671 BB->addSuccessor(exitMBB);
6677 MI->eraseFromParent(); // The instruction is gone now.
6683 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6685 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6687 unsigned destlo = MI->getOperand(0).getReg();
6688 unsigned desthi = MI->getOperand(1).getReg();
6689 unsigned ptr = MI->getOperand(2).getReg();
6690 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6691 DebugLoc dl = MI->getDebugLoc();
6692 bool isThumb2 = Subtarget->isThumb2();
6694 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6696 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6697 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6698 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6700 unsigned ldrOpc, strOpc;
6701 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6703 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6706 MIB.addReg(destlo, RegState::Define)
6707 .addReg(desthi, RegState::Define)
6711 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6712 MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6714 // Copy GPRPair0 into dest. (This copy will normally be coalesced.)
6715 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6716 .addReg(GPRPair0, 0, ARM::gsub_0);
6717 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6718 .addReg(GPRPair0, 0, ARM::gsub_1);
6720 AddDefaultPred(MIB);
6722 MI->eraseFromParent(); // The instruction is gone now.
6727 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6728 /// registers the function context.
6729 void ARMTargetLowering::
6730 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6731 MachineBasicBlock *DispatchBB, int FI) const {
6732 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6733 DebugLoc dl = MI->getDebugLoc();
6734 MachineFunction *MF = MBB->getParent();
6735 MachineRegisterInfo *MRI = &MF->getRegInfo();
6736 MachineConstantPool *MCP = MF->getConstantPool();
6737 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6738 const Function *F = MF->getFunction();
6740 bool isThumb = Subtarget->isThumb();
6741 bool isThumb2 = Subtarget->isThumb2();
6743 unsigned PCLabelId = AFI->createPICLabelUId();
6744 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6745 ARMConstantPoolValue *CPV =
6746 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6747 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6749 const TargetRegisterClass *TRC = isThumb ?
6750 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6751 (const TargetRegisterClass*)&ARM::GPRRegClass;
6753 // Grab constant pool and fixed stack memory operands.
6754 MachineMemOperand *CPMMO =
6755 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6756 MachineMemOperand::MOLoad, 4, 4);
6758 MachineMemOperand *FIMMOSt =
6759 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6760 MachineMemOperand::MOStore, 4, 4);
6762 // Load the address of the dispatch MBB into the jump buffer.
6764 // Incoming value: jbuf
6765 // ldr.n r5, LCPI1_1
6768 // str r5, [$jbuf, #+4] ; &jbuf[1]
6769 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6770 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6771 .addConstantPoolIndex(CPI)
6772 .addMemOperand(CPMMO));
6773 // Set the low bit because of thumb mode.
6774 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6776 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6777 .addReg(NewVReg1, RegState::Kill)
6779 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6780 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6781 .addReg(NewVReg2, RegState::Kill)
6783 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6784 .addReg(NewVReg3, RegState::Kill)
6786 .addImm(36) // &jbuf[1] :: pc
6787 .addMemOperand(FIMMOSt));
6788 } else if (isThumb) {
6789 // Incoming value: jbuf
6790 // ldr.n r1, LCPI1_4
6794 // add r2, $jbuf, #+4 ; &jbuf[1]
6796 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6797 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6798 .addConstantPoolIndex(CPI)
6799 .addMemOperand(CPMMO));
6800 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6801 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6802 .addReg(NewVReg1, RegState::Kill)
6804 // Set the low bit because of thumb mode.
6805 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6806 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6807 .addReg(ARM::CPSR, RegState::Define)
6809 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6810 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6811 .addReg(ARM::CPSR, RegState::Define)
6812 .addReg(NewVReg2, RegState::Kill)
6813 .addReg(NewVReg3, RegState::Kill));
6814 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6815 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6817 .addImm(36)); // &jbuf[1] :: pc
6818 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6819 .addReg(NewVReg4, RegState::Kill)
6820 .addReg(NewVReg5, RegState::Kill)
6822 .addMemOperand(FIMMOSt));
6824 // Incoming value: jbuf
6827 // str r1, [$jbuf, #+4] ; &jbuf[1]
6828 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6829 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6830 .addConstantPoolIndex(CPI)
6832 .addMemOperand(CPMMO));
6833 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6834 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6835 .addReg(NewVReg1, RegState::Kill)
6836 .addImm(PCLabelId));
6837 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6838 .addReg(NewVReg2, RegState::Kill)
6840 .addImm(36) // &jbuf[1] :: pc
6841 .addMemOperand(FIMMOSt));
6845 MachineBasicBlock *ARMTargetLowering::
6846 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6847 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6848 DebugLoc dl = MI->getDebugLoc();
6849 MachineFunction *MF = MBB->getParent();
6850 MachineRegisterInfo *MRI = &MF->getRegInfo();
6851 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6852 MachineFrameInfo *MFI = MF->getFrameInfo();
6853 int FI = MFI->getFunctionContextIndex();
6855 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6856 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6857 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6859 // Get a mapping of the call site numbers to all of the landing pads they're
6861 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6862 unsigned MaxCSNum = 0;
6863 MachineModuleInfo &MMI = MF->getMMI();
6864 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6866 if (!BB->isLandingPad()) continue;
6868 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6870 for (MachineBasicBlock::iterator
6871 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6872 if (!II->isEHLabel()) continue;
6874 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6875 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6877 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6878 for (SmallVectorImpl<unsigned>::iterator
6879 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6880 CSI != CSE; ++CSI) {
6881 CallSiteNumToLPad[*CSI].push_back(BB);
6882 MaxCSNum = std::max(MaxCSNum, *CSI);
6888 // Get an ordered list of the machine basic blocks for the jump table.
6889 std::vector<MachineBasicBlock*> LPadList;
6890 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6891 LPadList.reserve(CallSiteNumToLPad.size());
6892 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6893 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6894 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6895 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6896 LPadList.push_back(*II);
6897 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6901 assert(!LPadList.empty() &&
6902 "No landing pad destinations for the dispatch jump table!");
6904 // Create the jump table and associated information.
6905 MachineJumpTableInfo *JTI =
6906 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6907 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6908 unsigned UId = AFI->createJumpTableUId();
6909 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6911 // Create the MBBs for the dispatch code.
6913 // Shove the dispatch's address into the return slot in the function context.
6914 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6915 DispatchBB->setIsLandingPad();
6917 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6918 unsigned trap_opcode;
6919 if (Subtarget->isThumb())
6920 trap_opcode = ARM::tTRAP;
6922 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6924 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6925 DispatchBB->addSuccessor(TrapBB);
6927 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6928 DispatchBB->addSuccessor(DispContBB);
6931 MF->insert(MF->end(), DispatchBB);
6932 MF->insert(MF->end(), DispContBB);
6933 MF->insert(MF->end(), TrapBB);
6935 // Insert code into the entry block that creates and registers the function
6937 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6939 MachineMemOperand *FIMMOLd =
6940 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6941 MachineMemOperand::MOLoad |
6942 MachineMemOperand::MOVolatile, 4, 4);
6944 MachineInstrBuilder MIB;
6945 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6947 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6948 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6950 // Add a register mask with no preserved registers. This results in all
6951 // registers being marked as clobbered.
6952 MIB.addRegMask(RI.getNoPreservedMask());
6954 unsigned NumLPads = LPadList.size();
6955 if (Subtarget->isThumb2()) {
6956 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6957 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6960 .addMemOperand(FIMMOLd));
6962 if (NumLPads < 256) {
6963 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6965 .addImm(LPadList.size()));
6967 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6968 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6969 .addImm(NumLPads & 0xFFFF));
6971 unsigned VReg2 = VReg1;
6972 if ((NumLPads & 0xFFFF0000) != 0) {
6973 VReg2 = MRI->createVirtualRegister(TRC);
6974 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6976 .addImm(NumLPads >> 16));
6979 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6984 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6989 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6990 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6991 .addJumpTableIndex(MJTI)
6994 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6997 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6998 .addReg(NewVReg3, RegState::Kill)
7000 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7002 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7003 .addReg(NewVReg4, RegState::Kill)
7005 .addJumpTableIndex(MJTI)
7007 } else if (Subtarget->isThumb()) {
7008 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7009 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7012 .addMemOperand(FIMMOLd));
7014 if (NumLPads < 256) {
7015 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7019 MachineConstantPool *ConstantPool = MF->getConstantPool();
7020 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7021 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7023 // MachineConstantPool wants an explicit alignment.
7024 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7026 Align = getDataLayout()->getTypeAllocSize(C->getType());
7027 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7029 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7030 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7031 .addReg(VReg1, RegState::Define)
7032 .addConstantPoolIndex(Idx));
7033 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7038 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7043 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7044 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7045 .addReg(ARM::CPSR, RegState::Define)
7049 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7050 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7051 .addJumpTableIndex(MJTI)
7054 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7055 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7056 .addReg(ARM::CPSR, RegState::Define)
7057 .addReg(NewVReg2, RegState::Kill)
7060 MachineMemOperand *JTMMOLd =
7061 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7062 MachineMemOperand::MOLoad, 4, 4);
7064 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7065 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7066 .addReg(NewVReg4, RegState::Kill)
7068 .addMemOperand(JTMMOLd));
7070 unsigned NewVReg6 = NewVReg5;
7071 if (RelocM == Reloc::PIC_) {
7072 NewVReg6 = MRI->createVirtualRegister(TRC);
7073 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7074 .addReg(ARM::CPSR, RegState::Define)
7075 .addReg(NewVReg5, RegState::Kill)
7079 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7080 .addReg(NewVReg6, RegState::Kill)
7081 .addJumpTableIndex(MJTI)
7084 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7085 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7088 .addMemOperand(FIMMOLd));
7090 if (NumLPads < 256) {
7091 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7094 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7095 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7096 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7097 .addImm(NumLPads & 0xFFFF));
7099 unsigned VReg2 = VReg1;
7100 if ((NumLPads & 0xFFFF0000) != 0) {
7101 VReg2 = MRI->createVirtualRegister(TRC);
7102 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7104 .addImm(NumLPads >> 16));
7107 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7111 MachineConstantPool *ConstantPool = MF->getConstantPool();
7112 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7113 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7115 // MachineConstantPool wants an explicit alignment.
7116 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7118 Align = getDataLayout()->getTypeAllocSize(C->getType());
7119 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7121 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7122 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7123 .addReg(VReg1, RegState::Define)
7124 .addConstantPoolIndex(Idx)
7126 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7128 .addReg(VReg1, RegState::Kill));
7131 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7136 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7138 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7140 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7141 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7142 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7143 .addJumpTableIndex(MJTI)
7146 MachineMemOperand *JTMMOLd =
7147 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7148 MachineMemOperand::MOLoad, 4, 4);
7149 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7151 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7152 .addReg(NewVReg3, RegState::Kill)
7155 .addMemOperand(JTMMOLd));
7157 if (RelocM == Reloc::PIC_) {
7158 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7159 .addReg(NewVReg5, RegState::Kill)
7161 .addJumpTableIndex(MJTI)
7164 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7165 .addReg(NewVReg5, RegState::Kill)
7166 .addJumpTableIndex(MJTI)
7171 // Add the jump table entries as successors to the MBB.
7172 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7173 for (std::vector<MachineBasicBlock*>::iterator
7174 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7175 MachineBasicBlock *CurMBB = *I;
7176 if (SeenMBBs.insert(CurMBB))
7177 DispContBB->addSuccessor(CurMBB);
7180 // N.B. the order the invoke BBs are processed in doesn't matter here.
7181 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7182 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7183 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7184 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7185 MachineBasicBlock *BB = *I;
7187 // Remove the landing pad successor from the invoke block and replace it
7188 // with the new dispatch block.
7189 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7191 while (!Successors.empty()) {
7192 MachineBasicBlock *SMBB = Successors.pop_back_val();
7193 if (SMBB->isLandingPad()) {
7194 BB->removeSuccessor(SMBB);
7195 MBBLPads.push_back(SMBB);
7199 BB->addSuccessor(DispatchBB);
7201 // Find the invoke call and mark all of the callee-saved registers as
7202 // 'implicit defined' so that they're spilled. This prevents code from
7203 // moving instructions to before the EH block, where they will never be
7205 for (MachineBasicBlock::reverse_iterator
7206 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7207 if (!II->isCall()) continue;
7209 DenseMap<unsigned, bool> DefRegs;
7210 for (MachineInstr::mop_iterator
7211 OI = II->operands_begin(), OE = II->operands_end();
7213 if (!OI->isReg()) continue;
7214 DefRegs[OI->getReg()] = true;
7217 MachineInstrBuilder MIB(*MF, &*II);
7219 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7220 unsigned Reg = SavedRegs[i];
7221 if (Subtarget->isThumb2() &&
7222 !ARM::tGPRRegClass.contains(Reg) &&
7223 !ARM::hGPRRegClass.contains(Reg))
7225 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7227 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7230 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7237 // Mark all former landing pads as non-landing pads. The dispatch is the only
7239 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7240 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7241 (*I)->setIsLandingPad(false);
7243 // The instruction is gone now.
7244 MI->eraseFromParent();
7250 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7251 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7252 E = MBB->succ_end(); I != E; ++I)
7255 llvm_unreachable("Expecting a BB with two successors!");
7258 /// Return the load opcode for a given load size. If load size >= 8,
7259 /// neon opcode will be returned.
7260 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7262 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7263 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7265 return LdSize == 4 ? ARM::tLDRi
7266 : LdSize == 2 ? ARM::tLDRHi
7267 : LdSize == 1 ? ARM::tLDRBi : 0;
7269 return LdSize == 4 ? ARM::t2LDR_POST
7270 : LdSize == 2 ? ARM::t2LDRH_POST
7271 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7272 return LdSize == 4 ? ARM::LDR_POST_IMM
7273 : LdSize == 2 ? ARM::LDRH_POST
7274 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7277 /// Return the store opcode for a given store size. If store size >= 8,
7278 /// neon opcode will be returned.
7279 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7281 return StSize == 16 ? ARM::VST1q32wb_fixed
7282 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7284 return StSize == 4 ? ARM::tSTRi
7285 : StSize == 2 ? ARM::tSTRHi
7286 : StSize == 1 ? ARM::tSTRBi : 0;
7288 return StSize == 4 ? ARM::t2STR_POST
7289 : StSize == 2 ? ARM::t2STRH_POST
7290 : StSize == 1 ? ARM::t2STRB_POST : 0;
7291 return StSize == 4 ? ARM::STR_POST_IMM
7292 : StSize == 2 ? ARM::STRH_POST
7293 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7296 /// Emit a post-increment load operation with given size. The instructions
7297 /// will be added to BB at Pos.
7298 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7299 const TargetInstrInfo *TII, DebugLoc dl,
7300 unsigned LdSize, unsigned Data, unsigned AddrIn,
7301 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7302 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7303 assert(LdOpc != 0 && "Should have a load opcode");
7305 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7306 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7308 } else if (IsThumb1) {
7309 // load + update AddrIn
7310 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7311 .addReg(AddrIn).addImm(0));
7312 MachineInstrBuilder MIB =
7313 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7314 MIB = AddDefaultT1CC(MIB);
7315 MIB.addReg(AddrIn).addImm(LdSize);
7316 AddDefaultPred(MIB);
7317 } else if (IsThumb2) {
7318 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7319 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7322 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7323 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7324 .addReg(0).addImm(LdSize));
7328 /// Emit a post-increment store operation with given size. The instructions
7329 /// will be added to BB at Pos.
7330 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7331 const TargetInstrInfo *TII, DebugLoc dl,
7332 unsigned StSize, unsigned Data, unsigned AddrIn,
7333 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7334 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7335 assert(StOpc != 0 && "Should have a store opcode");
7337 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7338 .addReg(AddrIn).addImm(0).addReg(Data));
7339 } else if (IsThumb1) {
7340 // store + update AddrIn
7341 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7342 .addReg(AddrIn).addImm(0));
7343 MachineInstrBuilder MIB =
7344 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7345 MIB = AddDefaultT1CC(MIB);
7346 MIB.addReg(AddrIn).addImm(StSize);
7347 AddDefaultPred(MIB);
7348 } else if (IsThumb2) {
7349 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7350 .addReg(Data).addReg(AddrIn).addImm(StSize));
7352 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7353 .addReg(Data).addReg(AddrIn).addReg(0)
7359 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7360 MachineBasicBlock *BB) const {
7361 // This pseudo instruction has 3 operands: dst, src, size
7362 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7363 // Otherwise, we will generate unrolled scalar copies.
7364 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7365 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7366 MachineFunction::iterator It = BB;
7369 unsigned dest = MI->getOperand(0).getReg();
7370 unsigned src = MI->getOperand(1).getReg();
7371 unsigned SizeVal = MI->getOperand(2).getImm();
7372 unsigned Align = MI->getOperand(3).getImm();
7373 DebugLoc dl = MI->getDebugLoc();
7375 MachineFunction *MF = BB->getParent();
7376 MachineRegisterInfo &MRI = MF->getRegInfo();
7377 unsigned UnitSize = 0;
7378 const TargetRegisterClass *TRC = 0;
7379 const TargetRegisterClass *VecTRC = 0;
7381 bool IsThumb1 = Subtarget->isThumb1Only();
7382 bool IsThumb2 = Subtarget->isThumb2();
7386 } else if (Align & 2) {
7389 // Check whether we can use NEON instructions.
7390 if (!MF->getFunction()->getAttributes().
7391 hasAttribute(AttributeSet::FunctionIndex,
7392 Attribute::NoImplicitFloat) &&
7393 Subtarget->hasNEON()) {
7394 if ((Align % 16 == 0) && SizeVal >= 16)
7396 else if ((Align % 8 == 0) && SizeVal >= 8)
7399 // Can't use NEON instructions.
7404 // Select the correct opcode and register class for unit size load/store
7405 bool IsNeon = UnitSize >= 8;
7406 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7407 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7409 VecTRC = UnitSize == 16
7410 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7412 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7415 unsigned BytesLeft = SizeVal % UnitSize;
7416 unsigned LoopSize = SizeVal - BytesLeft;
7418 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7419 // Use LDR and STR to copy.
7420 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7421 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7422 unsigned srcIn = src;
7423 unsigned destIn = dest;
7424 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7425 unsigned srcOut = MRI.createVirtualRegister(TRC);
7426 unsigned destOut = MRI.createVirtualRegister(TRC);
7427 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7428 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7429 IsThumb1, IsThumb2);
7430 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7431 IsThumb1, IsThumb2);
7436 // Handle the leftover bytes with LDRB and STRB.
7437 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7438 // [destOut] = STRB_POST(scratch, destIn, 1)
7439 for (unsigned i = 0; i < BytesLeft; i++) {
7440 unsigned srcOut = MRI.createVirtualRegister(TRC);
7441 unsigned destOut = MRI.createVirtualRegister(TRC);
7442 unsigned scratch = MRI.createVirtualRegister(TRC);
7443 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7444 IsThumb1, IsThumb2);
7445 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7446 IsThumb1, IsThumb2);
7450 MI->eraseFromParent(); // The instruction is gone now.
7454 // Expand the pseudo op to a loop.
7457 // movw varEnd, # --> with thumb2
7459 // ldrcp varEnd, idx --> without thumb2
7460 // fallthrough --> loopMBB
7462 // PHI varPhi, varEnd, varLoop
7463 // PHI srcPhi, src, srcLoop
7464 // PHI destPhi, dst, destLoop
7465 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7466 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7467 // subs varLoop, varPhi, #UnitSize
7469 // fallthrough --> exitMBB
7471 // epilogue to handle left-over bytes
7472 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7473 // [destOut] = STRB_POST(scratch, destLoop, 1)
7474 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7475 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7476 MF->insert(It, loopMBB);
7477 MF->insert(It, exitMBB);
7479 // Transfer the remainder of BB and its successor edges to exitMBB.
7480 exitMBB->splice(exitMBB->begin(), BB,
7481 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7482 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7484 // Load an immediate to varEnd.
7485 unsigned varEnd = MRI.createVirtualRegister(TRC);
7487 unsigned Vtmp = varEnd;
7488 if ((LoopSize & 0xFFFF0000) != 0)
7489 Vtmp = MRI.createVirtualRegister(TRC);
7490 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7491 .addImm(LoopSize & 0xFFFF));
7493 if ((LoopSize & 0xFFFF0000) != 0)
7494 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7495 .addReg(Vtmp).addImm(LoopSize >> 16));
7497 MachineConstantPool *ConstantPool = MF->getConstantPool();
7498 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7499 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7501 // MachineConstantPool wants an explicit alignment.
7502 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7504 Align = getDataLayout()->getTypeAllocSize(C->getType());
7505 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7508 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7509 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7511 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7512 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7514 BB->addSuccessor(loopMBB);
7516 // Generate the loop body:
7517 // varPhi = PHI(varLoop, varEnd)
7518 // srcPhi = PHI(srcLoop, src)
7519 // destPhi = PHI(destLoop, dst)
7520 MachineBasicBlock *entryBB = BB;
7522 unsigned varLoop = MRI.createVirtualRegister(TRC);
7523 unsigned varPhi = MRI.createVirtualRegister(TRC);
7524 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7525 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7526 unsigned destLoop = MRI.createVirtualRegister(TRC);
7527 unsigned destPhi = MRI.createVirtualRegister(TRC);
7529 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7530 .addReg(varLoop).addMBB(loopMBB)
7531 .addReg(varEnd).addMBB(entryBB);
7532 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7533 .addReg(srcLoop).addMBB(loopMBB)
7534 .addReg(src).addMBB(entryBB);
7535 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7536 .addReg(destLoop).addMBB(loopMBB)
7537 .addReg(dest).addMBB(entryBB);
7539 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7540 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7541 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7542 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7543 IsThumb1, IsThumb2);
7544 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7545 IsThumb1, IsThumb2);
7547 // Decrement loop variable by UnitSize.
7549 MachineInstrBuilder MIB =
7550 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7551 MIB = AddDefaultT1CC(MIB);
7552 MIB.addReg(varPhi).addImm(UnitSize);
7553 AddDefaultPred(MIB);
7555 MachineInstrBuilder MIB =
7556 BuildMI(*BB, BB->end(), dl,
7557 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7558 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7559 MIB->getOperand(5).setReg(ARM::CPSR);
7560 MIB->getOperand(5).setIsDef(true);
7562 BuildMI(*BB, BB->end(), dl,
7563 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7564 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7566 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7567 BB->addSuccessor(loopMBB);
7568 BB->addSuccessor(exitMBB);
7570 // Add epilogue to handle BytesLeft.
7572 MachineInstr *StartOfExit = exitMBB->begin();
7574 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7575 // [destOut] = STRB_POST(scratch, destLoop, 1)
7576 unsigned srcIn = srcLoop;
7577 unsigned destIn = destLoop;
7578 for (unsigned i = 0; i < BytesLeft; i++) {
7579 unsigned srcOut = MRI.createVirtualRegister(TRC);
7580 unsigned destOut = MRI.createVirtualRegister(TRC);
7581 unsigned scratch = MRI.createVirtualRegister(TRC);
7582 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7583 IsThumb1, IsThumb2);
7584 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7585 IsThumb1, IsThumb2);
7590 MI->eraseFromParent(); // The instruction is gone now.
7595 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7596 MachineBasicBlock *BB) const {
7597 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7598 DebugLoc dl = MI->getDebugLoc();
7599 bool isThumb2 = Subtarget->isThumb2();
7600 switch (MI->getOpcode()) {
7603 llvm_unreachable("Unexpected instr type to insert");
7605 // The Thumb2 pre-indexed stores have the same MI operands, they just
7606 // define them differently in the .td files from the isel patterns, so
7607 // they need pseudos.
7608 case ARM::t2STR_preidx:
7609 MI->setDesc(TII->get(ARM::t2STR_PRE));
7611 case ARM::t2STRB_preidx:
7612 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7614 case ARM::t2STRH_preidx:
7615 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7618 case ARM::STRi_preidx:
7619 case ARM::STRBi_preidx: {
7620 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7621 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7622 // Decode the offset.
7623 unsigned Offset = MI->getOperand(4).getImm();
7624 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7625 Offset = ARM_AM::getAM2Offset(Offset);
7629 MachineMemOperand *MMO = *MI->memoperands_begin();
7630 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7631 .addOperand(MI->getOperand(0)) // Rn_wb
7632 .addOperand(MI->getOperand(1)) // Rt
7633 .addOperand(MI->getOperand(2)) // Rn
7634 .addImm(Offset) // offset (skip GPR==zero_reg)
7635 .addOperand(MI->getOperand(5)) // pred
7636 .addOperand(MI->getOperand(6))
7637 .addMemOperand(MMO);
7638 MI->eraseFromParent();
7641 case ARM::STRr_preidx:
7642 case ARM::STRBr_preidx:
7643 case ARM::STRH_preidx: {
7645 switch (MI->getOpcode()) {
7646 default: llvm_unreachable("unexpected opcode!");
7647 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7648 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7649 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7651 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7652 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7653 MIB.addOperand(MI->getOperand(i));
7654 MI->eraseFromParent();
7657 case ARM::ATOMIC_LOAD_ADD_I8:
7658 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7659 case ARM::ATOMIC_LOAD_ADD_I16:
7660 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7661 case ARM::ATOMIC_LOAD_ADD_I32:
7662 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7664 case ARM::ATOMIC_LOAD_AND_I8:
7665 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7666 case ARM::ATOMIC_LOAD_AND_I16:
7667 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7668 case ARM::ATOMIC_LOAD_AND_I32:
7669 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7671 case ARM::ATOMIC_LOAD_OR_I8:
7672 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7673 case ARM::ATOMIC_LOAD_OR_I16:
7674 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7675 case ARM::ATOMIC_LOAD_OR_I32:
7676 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7678 case ARM::ATOMIC_LOAD_XOR_I8:
7679 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7680 case ARM::ATOMIC_LOAD_XOR_I16:
7681 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7682 case ARM::ATOMIC_LOAD_XOR_I32:
7683 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7685 case ARM::ATOMIC_LOAD_NAND_I8:
7686 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7687 case ARM::ATOMIC_LOAD_NAND_I16:
7688 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7689 case ARM::ATOMIC_LOAD_NAND_I32:
7690 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7692 case ARM::ATOMIC_LOAD_SUB_I8:
7693 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7694 case ARM::ATOMIC_LOAD_SUB_I16:
7695 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7696 case ARM::ATOMIC_LOAD_SUB_I32:
7697 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7699 case ARM::ATOMIC_LOAD_MIN_I8:
7700 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7701 case ARM::ATOMIC_LOAD_MIN_I16:
7702 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7703 case ARM::ATOMIC_LOAD_MIN_I32:
7704 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7706 case ARM::ATOMIC_LOAD_MAX_I8:
7707 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7708 case ARM::ATOMIC_LOAD_MAX_I16:
7709 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7710 case ARM::ATOMIC_LOAD_MAX_I32:
7711 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7713 case ARM::ATOMIC_LOAD_UMIN_I8:
7714 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7715 case ARM::ATOMIC_LOAD_UMIN_I16:
7716 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7717 case ARM::ATOMIC_LOAD_UMIN_I32:
7718 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7720 case ARM::ATOMIC_LOAD_UMAX_I8:
7721 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7722 case ARM::ATOMIC_LOAD_UMAX_I16:
7723 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7724 case ARM::ATOMIC_LOAD_UMAX_I32:
7725 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7727 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7728 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7729 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7731 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7732 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7733 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7735 case ARM::ATOMIC_LOAD_I64:
7736 return EmitAtomicLoad64(MI, BB);
7738 case ARM::ATOMIC_LOAD_ADD_I64:
7739 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7740 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7741 /*NeedsCarry*/ true);
7742 case ARM::ATOMIC_LOAD_SUB_I64:
7743 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7744 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7745 /*NeedsCarry*/ true);
7746 case ARM::ATOMIC_LOAD_OR_I64:
7747 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7748 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7749 case ARM::ATOMIC_LOAD_XOR_I64:
7750 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7751 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7752 case ARM::ATOMIC_LOAD_AND_I64:
7753 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7754 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7755 case ARM::ATOMIC_SWAP_I64:
7756 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7757 case ARM::ATOMIC_CMP_SWAP_I64:
7758 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7759 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7760 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7761 case ARM::ATOMIC_LOAD_MIN_I64:
7762 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7763 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7764 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7765 /*IsMinMax*/ true, ARMCC::LT);
7766 case ARM::ATOMIC_LOAD_MAX_I64:
7767 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7768 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7769 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7770 /*IsMinMax*/ true, ARMCC::GE);
7771 case ARM::ATOMIC_LOAD_UMIN_I64:
7772 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7773 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7774 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7775 /*IsMinMax*/ true, ARMCC::LO);
7776 case ARM::ATOMIC_LOAD_UMAX_I64:
7777 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7778 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7779 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7780 /*IsMinMax*/ true, ARMCC::HS);
7782 case ARM::tMOVCCr_pseudo: {
7783 // To "insert" a SELECT_CC instruction, we actually have to insert the
7784 // diamond control-flow pattern. The incoming instruction knows the
7785 // destination vreg to set, the condition code register to branch on, the
7786 // true/false values to select between, and a branch opcode to use.
7787 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7788 MachineFunction::iterator It = BB;
7794 // cmpTY ccX, r1, r2
7796 // fallthrough --> copy0MBB
7797 MachineBasicBlock *thisMBB = BB;
7798 MachineFunction *F = BB->getParent();
7799 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7800 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7801 F->insert(It, copy0MBB);
7802 F->insert(It, sinkMBB);
7804 // Transfer the remainder of BB and its successor edges to sinkMBB.
7805 sinkMBB->splice(sinkMBB->begin(), BB,
7806 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7807 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7809 BB->addSuccessor(copy0MBB);
7810 BB->addSuccessor(sinkMBB);
7812 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7813 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7816 // %FalseValue = ...
7817 // # fallthrough to sinkMBB
7820 // Update machine-CFG edges
7821 BB->addSuccessor(sinkMBB);
7824 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7827 BuildMI(*BB, BB->begin(), dl,
7828 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7829 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7830 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7832 MI->eraseFromParent(); // The pseudo instruction is gone now.
7837 case ARM::BCCZi64: {
7838 // If there is an unconditional branch to the other successor, remove it.
7839 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7841 // Compare both parts that make up the double comparison separately for
7843 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7845 unsigned LHS1 = MI->getOperand(1).getReg();
7846 unsigned LHS2 = MI->getOperand(2).getReg();
7848 AddDefaultPred(BuildMI(BB, dl,
7849 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7850 .addReg(LHS1).addImm(0));
7851 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7852 .addReg(LHS2).addImm(0)
7853 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7855 unsigned RHS1 = MI->getOperand(3).getReg();
7856 unsigned RHS2 = MI->getOperand(4).getReg();
7857 AddDefaultPred(BuildMI(BB, dl,
7858 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7859 .addReg(LHS1).addReg(RHS1));
7860 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7861 .addReg(LHS2).addReg(RHS2)
7862 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7865 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7866 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7867 if (MI->getOperand(0).getImm() == ARMCC::NE)
7868 std::swap(destMBB, exitMBB);
7870 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7871 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7873 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7875 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7877 MI->eraseFromParent(); // The pseudo instruction is gone now.
7881 case ARM::Int_eh_sjlj_setjmp:
7882 case ARM::Int_eh_sjlj_setjmp_nofp:
7883 case ARM::tInt_eh_sjlj_setjmp:
7884 case ARM::t2Int_eh_sjlj_setjmp:
7885 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7886 EmitSjLjDispatchBlock(MI, BB);
7891 // To insert an ABS instruction, we have to insert the
7892 // diamond control-flow pattern. The incoming instruction knows the
7893 // source vreg to test against 0, the destination vreg to set,
7894 // the condition code register to branch on, the
7895 // true/false values to select between, and a branch opcode to use.
7900 // BCC (branch to SinkBB if V0 >= 0)
7901 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7902 // SinkBB: V1 = PHI(V2, V3)
7903 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7904 MachineFunction::iterator BBI = BB;
7906 MachineFunction *Fn = BB->getParent();
7907 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7908 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7909 Fn->insert(BBI, RSBBB);
7910 Fn->insert(BBI, SinkBB);
7912 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7913 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7914 bool isThumb2 = Subtarget->isThumb2();
7915 MachineRegisterInfo &MRI = Fn->getRegInfo();
7916 // In Thumb mode S must not be specified if source register is the SP or
7917 // PC and if destination register is the SP, so restrict register class
7918 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7919 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7920 (const TargetRegisterClass*)&ARM::GPRRegClass);
7922 // Transfer the remainder of BB and its successor edges to sinkMBB.
7923 SinkBB->splice(SinkBB->begin(), BB,
7924 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7925 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7927 BB->addSuccessor(RSBBB);
7928 BB->addSuccessor(SinkBB);
7930 // fall through to SinkMBB
7931 RSBBB->addSuccessor(SinkBB);
7933 // insert a cmp at the end of BB
7934 AddDefaultPred(BuildMI(BB, dl,
7935 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7936 .addReg(ABSSrcReg).addImm(0));
7938 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7940 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7941 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7943 // insert rsbri in RSBBB
7944 // Note: BCC and rsbri will be converted into predicated rsbmi
7945 // by if-conversion pass
7946 BuildMI(*RSBBB, RSBBB->begin(), dl,
7947 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7948 .addReg(ABSSrcReg, RegState::Kill)
7949 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7951 // insert PHI in SinkBB,
7952 // reuse ABSDstReg to not change uses of ABS instruction
7953 BuildMI(*SinkBB, SinkBB->begin(), dl,
7954 TII->get(ARM::PHI), ABSDstReg)
7955 .addReg(NewRsbDstReg).addMBB(RSBBB)
7956 .addReg(ABSSrcReg).addMBB(BB);
7958 // remove ABS instruction
7959 MI->eraseFromParent();
7961 // return last added BB
7964 case ARM::COPY_STRUCT_BYVAL_I32:
7966 return EmitStructByval(MI, BB);
7970 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7971 SDNode *Node) const {
7972 if (!MI->hasPostISelHook()) {
7973 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7974 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7978 const MCInstrDesc *MCID = &MI->getDesc();
7979 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7980 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7981 // operand is still set to noreg. If needed, set the optional operand's
7982 // register to CPSR, and remove the redundant implicit def.
7984 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7986 // Rename pseudo opcodes.
7987 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7989 const ARMBaseInstrInfo *TII =
7990 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7991 MCID = &TII->get(NewOpc);
7993 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7994 "converted opcode should be the same except for cc_out");
7998 // Add the optional cc_out operand
7999 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8001 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8003 // Any ARM instruction that sets the 's' bit should specify an optional
8004 // "cc_out" operand in the last operand position.
8005 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8006 assert(!NewOpc && "Optional cc_out operand required");
8009 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8010 // since we already have an optional CPSR def.
8011 bool definesCPSR = false;
8012 bool deadCPSR = false;
8013 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8015 const MachineOperand &MO = MI->getOperand(i);
8016 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8020 MI->RemoveOperand(i);
8025 assert(!NewOpc && "Optional cc_out operand required");
8028 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8030 assert(!MI->getOperand(ccOutIdx).getReg() &&
8031 "expect uninitialized optional cc_out operand");
8035 // If this instruction was defined with an optional CPSR def and its dag node
8036 // had a live implicit CPSR def, then activate the optional CPSR def.
8037 MachineOperand &MO = MI->getOperand(ccOutIdx);
8038 MO.setReg(ARM::CPSR);
8042 //===----------------------------------------------------------------------===//
8043 // ARM Optimization Hooks
8044 //===----------------------------------------------------------------------===//
8046 // Helper function that checks if N is a null or all ones constant.
8047 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8051 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8054 // Return true if N is conditionally 0 or all ones.
8055 // Detects these expressions where cc is an i1 value:
8057 // (select cc 0, y) [AllOnes=0]
8058 // (select cc y, 0) [AllOnes=0]
8059 // (zext cc) [AllOnes=0]
8060 // (sext cc) [AllOnes=0/1]
8061 // (select cc -1, y) [AllOnes=1]
8062 // (select cc y, -1) [AllOnes=1]
8064 // Invert is set when N is the null/all ones constant when CC is false.
8065 // OtherOp is set to the alternative value of N.
8066 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8067 SDValue &CC, bool &Invert,
8069 SelectionDAG &DAG) {
8070 switch (N->getOpcode()) {
8071 default: return false;
8073 CC = N->getOperand(0);
8074 SDValue N1 = N->getOperand(1);
8075 SDValue N2 = N->getOperand(2);
8076 if (isZeroOrAllOnes(N1, AllOnes)) {
8081 if (isZeroOrAllOnes(N2, AllOnes)) {
8088 case ISD::ZERO_EXTEND:
8089 // (zext cc) can never be the all ones value.
8093 case ISD::SIGN_EXTEND: {
8094 EVT VT = N->getValueType(0);
8095 CC = N->getOperand(0);
8096 if (CC.getValueType() != MVT::i1)
8100 // When looking for an AllOnes constant, N is an sext, and the 'other'
8102 OtherOp = DAG.getConstant(0, VT);
8103 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8104 // When looking for a 0 constant, N can be zext or sext.
8105 OtherOp = DAG.getConstant(1, VT);
8107 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8113 // Combine a constant select operand into its use:
8115 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8116 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8117 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8118 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8119 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8121 // The transform is rejected if the select doesn't have a constant operand that
8122 // is null, or all ones when AllOnes is set.
8124 // Also recognize sext/zext from i1:
8126 // (add (zext cc), x) -> (select cc (add x, 1), x)
8127 // (add (sext cc), x) -> (select cc (add x, -1), x)
8129 // These transformations eventually create predicated instructions.
8131 // @param N The node to transform.
8132 // @param Slct The N operand that is a select.
8133 // @param OtherOp The other N operand (x above).
8134 // @param DCI Context.
8135 // @param AllOnes Require the select constant to be all ones instead of null.
8136 // @returns The new node, or SDValue() on failure.
8138 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8139 TargetLowering::DAGCombinerInfo &DCI,
8140 bool AllOnes = false) {
8141 SelectionDAG &DAG = DCI.DAG;
8142 EVT VT = N->getValueType(0);
8143 SDValue NonConstantVal;
8146 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8147 NonConstantVal, DAG))
8150 // Slct is now know to be the desired identity constant when CC is true.
8151 SDValue TrueVal = OtherOp;
8152 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8153 OtherOp, NonConstantVal);
8154 // Unless SwapSelectOps says CC should be false.
8156 std::swap(TrueVal, FalseVal);
8158 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8159 CCOp, TrueVal, FalseVal);
8162 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8164 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8165 TargetLowering::DAGCombinerInfo &DCI) {
8166 SDValue N0 = N->getOperand(0);
8167 SDValue N1 = N->getOperand(1);
8168 if (N0.getNode()->hasOneUse()) {
8169 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8170 if (Result.getNode())
8173 if (N1.getNode()->hasOneUse()) {
8174 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8175 if (Result.getNode())
8181 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8182 // (only after legalization).
8183 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8184 TargetLowering::DAGCombinerInfo &DCI,
8185 const ARMSubtarget *Subtarget) {
8187 // Only perform optimization if after legalize, and if NEON is available. We
8188 // also expected both operands to be BUILD_VECTORs.
8189 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8190 || N0.getOpcode() != ISD::BUILD_VECTOR
8191 || N1.getOpcode() != ISD::BUILD_VECTOR)
8194 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8195 EVT VT = N->getValueType(0);
8196 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8199 // Check that the vector operands are of the right form.
8200 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8201 // operands, where N is the size of the formed vector.
8202 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8203 // index such that we have a pair wise add pattern.
8205 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8206 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8208 SDValue Vec = N0->getOperand(0)->getOperand(0);
8209 SDNode *V = Vec.getNode();
8210 unsigned nextIndex = 0;
8212 // For each operands to the ADD which are BUILD_VECTORs,
8213 // check to see if each of their operands are an EXTRACT_VECTOR with
8214 // the same vector and appropriate index.
8215 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8216 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8217 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8219 SDValue ExtVec0 = N0->getOperand(i);
8220 SDValue ExtVec1 = N1->getOperand(i);
8222 // First operand is the vector, verify its the same.
8223 if (V != ExtVec0->getOperand(0).getNode() ||
8224 V != ExtVec1->getOperand(0).getNode())
8227 // Second is the constant, verify its correct.
8228 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8229 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8231 // For the constant, we want to see all the even or all the odd.
8232 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8233 || C1->getZExtValue() != nextIndex+1)
8242 // Create VPADDL node.
8243 SelectionDAG &DAG = DCI.DAG;
8244 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8246 // Build operand list.
8247 SmallVector<SDValue, 8> Ops;
8248 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8249 TLI.getPointerTy()));
8251 // Input is the vector.
8254 // Get widened type and narrowed type.
8256 unsigned numElem = VT.getVectorNumElements();
8257 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8258 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8259 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8260 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8262 llvm_unreachable("Invalid vector element type for padd optimization.");
8265 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8266 widenType, &Ops[0], Ops.size());
8267 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8270 static SDValue findMUL_LOHI(SDValue V) {
8271 if (V->getOpcode() == ISD::UMUL_LOHI ||
8272 V->getOpcode() == ISD::SMUL_LOHI)
8277 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8278 TargetLowering::DAGCombinerInfo &DCI,
8279 const ARMSubtarget *Subtarget) {
8281 if (Subtarget->isThumb1Only()) return SDValue();
8283 // Only perform the checks after legalize when the pattern is available.
8284 if (DCI.isBeforeLegalize()) return SDValue();
8286 // Look for multiply add opportunities.
8287 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8288 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8289 // a glue link from the first add to the second add.
8290 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8291 // a S/UMLAL instruction.
8294 // \ / \ [no multiline comment]
8300 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8301 SDValue AddcOp0 = AddcNode->getOperand(0);
8302 SDValue AddcOp1 = AddcNode->getOperand(1);
8304 // Check if the two operands are from the same mul_lohi node.
8305 if (AddcOp0.getNode() == AddcOp1.getNode())
8308 assert(AddcNode->getNumValues() == 2 &&
8309 AddcNode->getValueType(0) == MVT::i32 &&
8310 "Expect ADDC with two result values. First: i32");
8312 // Check that we have a glued ADDC node.
8313 if (AddcNode->getValueType(1) != MVT::Glue)
8316 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8317 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8318 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8319 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8320 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8323 // Look for the glued ADDE.
8324 SDNode* AddeNode = AddcNode->getGluedUser();
8325 if (AddeNode == NULL)
8328 // Make sure it is really an ADDE.
8329 if (AddeNode->getOpcode() != ISD::ADDE)
8332 assert(AddeNode->getNumOperands() == 3 &&
8333 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8334 "ADDE node has the wrong inputs");
8336 // Check for the triangle shape.
8337 SDValue AddeOp0 = AddeNode->getOperand(0);
8338 SDValue AddeOp1 = AddeNode->getOperand(1);
8340 // Make sure that the ADDE operands are not coming from the same node.
8341 if (AddeOp0.getNode() == AddeOp1.getNode())
8344 // Find the MUL_LOHI node walking up ADDE's operands.
8345 bool IsLeftOperandMUL = false;
8346 SDValue MULOp = findMUL_LOHI(AddeOp0);
8347 if (MULOp == SDValue())
8348 MULOp = findMUL_LOHI(AddeOp1);
8350 IsLeftOperandMUL = true;
8351 if (MULOp == SDValue())
8354 // Figure out the right opcode.
8355 unsigned Opc = MULOp->getOpcode();
8356 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8358 // Figure out the high and low input values to the MLAL node.
8359 SDValue* HiMul = &MULOp;
8360 SDValue* HiAdd = NULL;
8361 SDValue* LoMul = NULL;
8362 SDValue* LowAdd = NULL;
8364 if (IsLeftOperandMUL)
8370 if (AddcOp0->getOpcode() == Opc) {
8374 if (AddcOp1->getOpcode() == Opc) {
8382 if (LoMul->getNode() != HiMul->getNode())
8385 // Create the merged node.
8386 SelectionDAG &DAG = DCI.DAG;
8388 // Build operand list.
8389 SmallVector<SDValue, 8> Ops;
8390 Ops.push_back(LoMul->getOperand(0));
8391 Ops.push_back(LoMul->getOperand(1));
8392 Ops.push_back(*LowAdd);
8393 Ops.push_back(*HiAdd);
8395 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8396 DAG.getVTList(MVT::i32, MVT::i32),
8397 &Ops[0], Ops.size());
8399 // Replace the ADDs' nodes uses by the MLA node's values.
8400 SDValue HiMLALResult(MLALNode.getNode(), 1);
8401 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8403 SDValue LoMLALResult(MLALNode.getNode(), 0);
8404 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8406 // Return original node to notify the driver to stop replacing.
8407 SDValue resNode(AddcNode, 0);
8411 /// PerformADDCCombine - Target-specific dag combine transform from
8412 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8413 static SDValue PerformADDCCombine(SDNode *N,
8414 TargetLowering::DAGCombinerInfo &DCI,
8415 const ARMSubtarget *Subtarget) {
8417 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8421 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8422 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8423 /// called with the default operands, and if that fails, with commuted
8425 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8426 TargetLowering::DAGCombinerInfo &DCI,
8427 const ARMSubtarget *Subtarget){
8429 // Attempt to create vpaddl for this add.
8430 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8431 if (Result.getNode())
8434 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8435 if (N0.getNode()->hasOneUse()) {
8436 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8437 if (Result.getNode()) return Result;
8442 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8444 static SDValue PerformADDCombine(SDNode *N,
8445 TargetLowering::DAGCombinerInfo &DCI,
8446 const ARMSubtarget *Subtarget) {
8447 SDValue N0 = N->getOperand(0);
8448 SDValue N1 = N->getOperand(1);
8450 // First try with the default operand order.
8451 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8452 if (Result.getNode())
8455 // If that didn't work, try again with the operands commuted.
8456 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8459 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8461 static SDValue PerformSUBCombine(SDNode *N,
8462 TargetLowering::DAGCombinerInfo &DCI) {
8463 SDValue N0 = N->getOperand(0);
8464 SDValue N1 = N->getOperand(1);
8466 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8467 if (N1.getNode()->hasOneUse()) {
8468 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8469 if (Result.getNode()) return Result;
8475 /// PerformVMULCombine
8476 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8477 /// special multiplier accumulator forwarding.
8483 // However, for (A + B) * (A + B),
8490 static SDValue PerformVMULCombine(SDNode *N,
8491 TargetLowering::DAGCombinerInfo &DCI,
8492 const ARMSubtarget *Subtarget) {
8493 if (!Subtarget->hasVMLxForwarding())
8496 SelectionDAG &DAG = DCI.DAG;
8497 SDValue N0 = N->getOperand(0);
8498 SDValue N1 = N->getOperand(1);
8499 unsigned Opcode = N0.getOpcode();
8500 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8501 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8502 Opcode = N1.getOpcode();
8503 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8504 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8512 EVT VT = N->getValueType(0);
8514 SDValue N00 = N0->getOperand(0);
8515 SDValue N01 = N0->getOperand(1);
8516 return DAG.getNode(Opcode, DL, VT,
8517 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8518 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8521 static SDValue PerformMULCombine(SDNode *N,
8522 TargetLowering::DAGCombinerInfo &DCI,
8523 const ARMSubtarget *Subtarget) {
8524 SelectionDAG &DAG = DCI.DAG;
8526 if (Subtarget->isThumb1Only())
8529 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8532 EVT VT = N->getValueType(0);
8533 if (VT.is64BitVector() || VT.is128BitVector())
8534 return PerformVMULCombine(N, DCI, Subtarget);
8538 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8542 int64_t MulAmt = C->getSExtValue();
8543 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8545 ShiftAmt = ShiftAmt & (32 - 1);
8546 SDValue V = N->getOperand(0);
8550 MulAmt >>= ShiftAmt;
8553 if (isPowerOf2_32(MulAmt - 1)) {
8554 // (mul x, 2^N + 1) => (add (shl x, N), x)
8555 Res = DAG.getNode(ISD::ADD, DL, VT,
8557 DAG.getNode(ISD::SHL, DL, VT,
8559 DAG.getConstant(Log2_32(MulAmt - 1),
8561 } else if (isPowerOf2_32(MulAmt + 1)) {
8562 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8563 Res = DAG.getNode(ISD::SUB, DL, VT,
8564 DAG.getNode(ISD::SHL, DL, VT,
8566 DAG.getConstant(Log2_32(MulAmt + 1),
8572 uint64_t MulAmtAbs = -MulAmt;
8573 if (isPowerOf2_32(MulAmtAbs + 1)) {
8574 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8575 Res = DAG.getNode(ISD::SUB, DL, VT,
8577 DAG.getNode(ISD::SHL, DL, VT,
8579 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8581 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8582 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8583 Res = DAG.getNode(ISD::ADD, DL, VT,
8585 DAG.getNode(ISD::SHL, DL, VT,
8587 DAG.getConstant(Log2_32(MulAmtAbs-1),
8589 Res = DAG.getNode(ISD::SUB, DL, VT,
8590 DAG.getConstant(0, MVT::i32),Res);
8597 Res = DAG.getNode(ISD::SHL, DL, VT,
8598 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8600 // Do not add new nodes to DAG combiner worklist.
8601 DCI.CombineTo(N, Res, false);
8605 static SDValue PerformANDCombine(SDNode *N,
8606 TargetLowering::DAGCombinerInfo &DCI,
8607 const ARMSubtarget *Subtarget) {
8609 // Attempt to use immediate-form VBIC
8610 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8612 EVT VT = N->getValueType(0);
8613 SelectionDAG &DAG = DCI.DAG;
8615 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8618 APInt SplatBits, SplatUndef;
8619 unsigned SplatBitSize;
8622 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8623 if (SplatBitSize <= 64) {
8625 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8626 SplatUndef.getZExtValue(), SplatBitSize,
8627 DAG, VbicVT, VT.is128BitVector(),
8629 if (Val.getNode()) {
8631 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8632 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8633 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8638 if (!Subtarget->isThumb1Only()) {
8639 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8640 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8641 if (Result.getNode())
8648 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8649 static SDValue PerformORCombine(SDNode *N,
8650 TargetLowering::DAGCombinerInfo &DCI,
8651 const ARMSubtarget *Subtarget) {
8652 // Attempt to use immediate-form VORR
8653 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8655 EVT VT = N->getValueType(0);
8656 SelectionDAG &DAG = DCI.DAG;
8658 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8661 APInt SplatBits, SplatUndef;
8662 unsigned SplatBitSize;
8664 if (BVN && Subtarget->hasNEON() &&
8665 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8666 if (SplatBitSize <= 64) {
8668 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8669 SplatUndef.getZExtValue(), SplatBitSize,
8670 DAG, VorrVT, VT.is128BitVector(),
8672 if (Val.getNode()) {
8674 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8675 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8676 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8681 if (!Subtarget->isThumb1Only()) {
8682 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8683 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8684 if (Result.getNode())
8688 // The code below optimizes (or (and X, Y), Z).
8689 // The AND operand needs to have a single user to make these optimizations
8691 SDValue N0 = N->getOperand(0);
8692 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8694 SDValue N1 = N->getOperand(1);
8696 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8697 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8698 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8700 unsigned SplatBitSize;
8703 APInt SplatBits0, SplatBits1;
8704 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8705 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8706 // Ensure that the second operand of both ands are constants
8707 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8708 HasAnyUndefs) && !HasAnyUndefs) {
8709 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8710 HasAnyUndefs) && !HasAnyUndefs) {
8711 // Ensure that the bit width of the constants are the same and that
8712 // the splat arguments are logical inverses as per the pattern we
8713 // are trying to simplify.
8714 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8715 SplatBits0 == ~SplatBits1) {
8716 // Canonicalize the vector type to make instruction selection
8718 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8719 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8723 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8729 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8732 // BFI is only available on V6T2+
8733 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8737 // 1) or (and A, mask), val => ARMbfi A, val, mask
8738 // iff (val & mask) == val
8740 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8741 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8742 // && mask == ~mask2
8743 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8744 // && ~mask == mask2
8745 // (i.e., copy a bitfield value into another bitfield of the same width)
8750 SDValue N00 = N0.getOperand(0);
8752 // The value and the mask need to be constants so we can verify this is
8753 // actually a bitfield set. If the mask is 0xffff, we can do better
8754 // via a movt instruction, so don't use BFI in that case.
8755 SDValue MaskOp = N0.getOperand(1);
8756 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8759 unsigned Mask = MaskC->getZExtValue();
8763 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8766 unsigned Val = N1C->getZExtValue();
8767 if ((Val & ~Mask) != Val)
8770 if (ARM::isBitFieldInvertedMask(Mask)) {
8771 Val >>= countTrailingZeros(~Mask);
8773 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8774 DAG.getConstant(Val, MVT::i32),
8775 DAG.getConstant(Mask, MVT::i32));
8777 // Do not add new nodes to DAG combiner worklist.
8778 DCI.CombineTo(N, Res, false);
8781 } else if (N1.getOpcode() == ISD::AND) {
8782 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8783 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8786 unsigned Mask2 = N11C->getZExtValue();
8788 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8790 if (ARM::isBitFieldInvertedMask(Mask) &&
8792 // The pack halfword instruction works better for masks that fit it,
8793 // so use that when it's available.
8794 if (Subtarget->hasT2ExtractPack() &&
8795 (Mask == 0xffff || Mask == 0xffff0000))
8798 unsigned amt = countTrailingZeros(Mask2);
8799 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8800 DAG.getConstant(amt, MVT::i32));
8801 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8802 DAG.getConstant(Mask, MVT::i32));
8803 // Do not add new nodes to DAG combiner worklist.
8804 DCI.CombineTo(N, Res, false);
8806 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8808 // The pack halfword instruction works better for masks that fit it,
8809 // so use that when it's available.
8810 if (Subtarget->hasT2ExtractPack() &&
8811 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8814 unsigned lsb = countTrailingZeros(Mask);
8815 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8816 DAG.getConstant(lsb, MVT::i32));
8817 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8818 DAG.getConstant(Mask2, MVT::i32));
8819 // Do not add new nodes to DAG combiner worklist.
8820 DCI.CombineTo(N, Res, false);
8825 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8826 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8827 ARM::isBitFieldInvertedMask(~Mask)) {
8828 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8829 // where lsb(mask) == #shamt and masked bits of B are known zero.
8830 SDValue ShAmt = N00.getOperand(1);
8831 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8832 unsigned LSB = countTrailingZeros(Mask);
8836 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8837 DAG.getConstant(~Mask, MVT::i32));
8839 // Do not add new nodes to DAG combiner worklist.
8840 DCI.CombineTo(N, Res, false);
8846 static SDValue PerformXORCombine(SDNode *N,
8847 TargetLowering::DAGCombinerInfo &DCI,
8848 const ARMSubtarget *Subtarget) {
8849 EVT VT = N->getValueType(0);
8850 SelectionDAG &DAG = DCI.DAG;
8852 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8855 if (!Subtarget->isThumb1Only()) {
8856 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8857 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8858 if (Result.getNode())
8865 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8866 /// the bits being cleared by the AND are not demanded by the BFI.
8867 static SDValue PerformBFICombine(SDNode *N,
8868 TargetLowering::DAGCombinerInfo &DCI) {
8869 SDValue N1 = N->getOperand(1);
8870 if (N1.getOpcode() == ISD::AND) {
8871 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8874 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8875 unsigned LSB = countTrailingZeros(~InvMask);
8876 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8877 unsigned Mask = (1 << Width)-1;
8878 unsigned Mask2 = N11C->getZExtValue();
8879 if ((Mask & (~Mask2)) == 0)
8880 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8881 N->getOperand(0), N1.getOperand(0),
8887 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8888 /// ARMISD::VMOVRRD.
8889 static SDValue PerformVMOVRRDCombine(SDNode *N,
8890 TargetLowering::DAGCombinerInfo &DCI) {
8891 // vmovrrd(vmovdrr x, y) -> x,y
8892 SDValue InDouble = N->getOperand(0);
8893 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8894 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8896 // vmovrrd(load f64) -> (load i32), (load i32)
8897 SDNode *InNode = InDouble.getNode();
8898 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8899 InNode->getValueType(0) == MVT::f64 &&
8900 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8901 !cast<LoadSDNode>(InNode)->isVolatile()) {
8902 // TODO: Should this be done for non-FrameIndex operands?
8903 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8905 SelectionDAG &DAG = DCI.DAG;
8907 SDValue BasePtr = LD->getBasePtr();
8908 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8909 LD->getPointerInfo(), LD->isVolatile(),
8910 LD->isNonTemporal(), LD->isInvariant(),
8911 LD->getAlignment());
8913 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8914 DAG.getConstant(4, MVT::i32));
8915 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8916 LD->getPointerInfo(), LD->isVolatile(),
8917 LD->isNonTemporal(), LD->isInvariant(),
8918 std::min(4U, LD->getAlignment() / 2));
8920 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8921 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8922 DCI.RemoveFromWorklist(LD);
8930 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8931 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8932 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8933 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8934 SDValue Op0 = N->getOperand(0);
8935 SDValue Op1 = N->getOperand(1);
8936 if (Op0.getOpcode() == ISD::BITCAST)
8937 Op0 = Op0.getOperand(0);
8938 if (Op1.getOpcode() == ISD::BITCAST)
8939 Op1 = Op1.getOperand(0);
8940 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8941 Op0.getNode() == Op1.getNode() &&
8942 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8943 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8944 N->getValueType(0), Op0.getOperand(0));
8948 /// PerformSTORECombine - Target-specific dag combine xforms for
8950 static SDValue PerformSTORECombine(SDNode *N,
8951 TargetLowering::DAGCombinerInfo &DCI) {
8952 StoreSDNode *St = cast<StoreSDNode>(N);
8953 if (St->isVolatile())
8956 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8957 // pack all of the elements in one place. Next, store to memory in fewer
8959 SDValue StVal = St->getValue();
8960 EVT VT = StVal.getValueType();
8961 if (St->isTruncatingStore() && VT.isVector()) {
8962 SelectionDAG &DAG = DCI.DAG;
8963 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8964 EVT StVT = St->getMemoryVT();
8965 unsigned NumElems = VT.getVectorNumElements();
8966 assert(StVT != VT && "Cannot truncate to the same type");
8967 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8968 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8970 // From, To sizes and ElemCount must be pow of two
8971 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8973 // We are going to use the original vector elt for storing.
8974 // Accumulated smaller vector elements must be a multiple of the store size.
8975 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8977 unsigned SizeRatio = FromEltSz / ToEltSz;
8978 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8980 // Create a type on which we perform the shuffle.
8981 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8982 NumElems*SizeRatio);
8983 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8986 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8987 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8988 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8990 // Can't shuffle using an illegal type.
8991 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8993 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8994 DAG.getUNDEF(WideVec.getValueType()),
8996 // At this point all of the data is stored at the bottom of the
8997 // register. We now need to save it to mem.
8999 // Find the largest store unit
9000 MVT StoreType = MVT::i8;
9001 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
9002 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9003 MVT Tp = (MVT::SimpleValueType)tp;
9004 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9007 // Didn't find a legal store type.
9008 if (!TLI.isTypeLegal(StoreType))
9011 // Bitcast the original vector into a vector of store-size units
9012 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9013 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9014 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9015 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9016 SmallVector<SDValue, 8> Chains;
9017 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9018 TLI.getPointerTy());
9019 SDValue BasePtr = St->getBasePtr();
9021 // Perform one or more big stores into memory.
9022 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9023 for (unsigned I = 0; I < E; I++) {
9024 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9025 StoreType, ShuffWide,
9026 DAG.getIntPtrConstant(I));
9027 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9028 St->getPointerInfo(), St->isVolatile(),
9029 St->isNonTemporal(), St->getAlignment());
9030 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9032 Chains.push_back(Ch);
9034 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9038 if (!ISD::isNormalStore(St))
9041 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9042 // ARM stores of arguments in the same cache line.
9043 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9044 StVal.getNode()->hasOneUse()) {
9045 SelectionDAG &DAG = DCI.DAG;
9047 SDValue BasePtr = St->getBasePtr();
9048 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9049 StVal.getNode()->getOperand(0), BasePtr,
9050 St->getPointerInfo(), St->isVolatile(),
9051 St->isNonTemporal(), St->getAlignment());
9053 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9054 DAG.getConstant(4, MVT::i32));
9055 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9056 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9057 St->isNonTemporal(),
9058 std::min(4U, St->getAlignment() / 2));
9061 if (StVal.getValueType() != MVT::i64 ||
9062 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9065 // Bitcast an i64 store extracted from a vector to f64.
9066 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9067 SelectionDAG &DAG = DCI.DAG;
9069 SDValue IntVec = StVal.getOperand(0);
9070 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9071 IntVec.getValueType().getVectorNumElements());
9072 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9073 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9074 Vec, StVal.getOperand(1));
9076 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9077 // Make the DAGCombiner fold the bitcasts.
9078 DCI.AddToWorklist(Vec.getNode());
9079 DCI.AddToWorklist(ExtElt.getNode());
9080 DCI.AddToWorklist(V.getNode());
9081 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9082 St->getPointerInfo(), St->isVolatile(),
9083 St->isNonTemporal(), St->getAlignment(),
9087 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9088 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9089 /// i64 vector to have f64 elements, since the value can then be loaded
9090 /// directly into a VFP register.
9091 static bool hasNormalLoadOperand(SDNode *N) {
9092 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9093 for (unsigned i = 0; i < NumElts; ++i) {
9094 SDNode *Elt = N->getOperand(i).getNode();
9095 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9101 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9102 /// ISD::BUILD_VECTOR.
9103 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9104 TargetLowering::DAGCombinerInfo &DCI){
9105 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9106 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9107 // into a pair of GPRs, which is fine when the value is used as a scalar,
9108 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9109 SelectionDAG &DAG = DCI.DAG;
9110 if (N->getNumOperands() == 2) {
9111 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9116 // Load i64 elements as f64 values so that type legalization does not split
9117 // them up into i32 values.
9118 EVT VT = N->getValueType(0);
9119 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9122 SmallVector<SDValue, 8> Ops;
9123 unsigned NumElts = VT.getVectorNumElements();
9124 for (unsigned i = 0; i < NumElts; ++i) {
9125 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9127 // Make the DAGCombiner fold the bitcast.
9128 DCI.AddToWorklist(V.getNode());
9130 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9131 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9132 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9135 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9137 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9138 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9139 // At that time, we may have inserted bitcasts from integer to float.
9140 // If these bitcasts have survived DAGCombine, change the lowering of this
9141 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9142 // force to use floating point types.
9144 // Make sure we can change the type of the vector.
9145 // This is possible iff:
9146 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9147 // 1.1. Vector is used only once.
9148 // 1.2. Use is a bit convert to an integer type.
9149 // 2. The size of its operands are 32-bits (64-bits are not legal).
9150 EVT VT = N->getValueType(0);
9151 EVT EltVT = VT.getVectorElementType();
9153 // Check 1.1. and 2.
9154 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9157 // By construction, the input type must be float.
9158 assert(EltVT == MVT::f32 && "Unexpected type!");
9161 SDNode *Use = *N->use_begin();
9162 if (Use->getOpcode() != ISD::BITCAST ||
9163 Use->getValueType(0).isFloatingPoint())
9166 // Check profitability.
9167 // Model is, if more than half of the relevant operands are bitcast from
9168 // i32, turn the build_vector into a sequence of insert_vector_elt.
9169 // Relevant operands are everything that is not statically
9170 // (i.e., at compile time) bitcasted.
9171 unsigned NumOfBitCastedElts = 0;
9172 unsigned NumElts = VT.getVectorNumElements();
9173 unsigned NumOfRelevantElts = NumElts;
9174 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9175 SDValue Elt = N->getOperand(Idx);
9176 if (Elt->getOpcode() == ISD::BITCAST) {
9177 // Assume only bit cast to i32 will go away.
9178 if (Elt->getOperand(0).getValueType() == MVT::i32)
9179 ++NumOfBitCastedElts;
9180 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9181 // Constants are statically casted, thus do not count them as
9182 // relevant operands.
9183 --NumOfRelevantElts;
9186 // Check if more than half of the elements require a non-free bitcast.
9187 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9190 SelectionDAG &DAG = DCI.DAG;
9191 // Create the new vector type.
9192 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9193 // Check if the type is legal.
9194 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9195 if (!TLI.isTypeLegal(VecVT))
9199 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9200 // => BITCAST INSERT_VECTOR_ELT
9201 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9203 SDValue Vec = DAG.getUNDEF(VecVT);
9205 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9206 SDValue V = N->getOperand(Idx);
9207 if (V.getOpcode() == ISD::UNDEF)
9209 if (V.getOpcode() == ISD::BITCAST &&
9210 V->getOperand(0).getValueType() == MVT::i32)
9211 // Fold obvious case.
9212 V = V.getOperand(0);
9214 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9215 // Make the DAGCombiner fold the bitcasts.
9216 DCI.AddToWorklist(V.getNode());
9218 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9219 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9221 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9222 // Make the DAGCombiner fold the bitcasts.
9223 DCI.AddToWorklist(Vec.getNode());
9227 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9228 /// ISD::INSERT_VECTOR_ELT.
9229 static SDValue PerformInsertEltCombine(SDNode *N,
9230 TargetLowering::DAGCombinerInfo &DCI) {
9231 // Bitcast an i64 load inserted into a vector to f64.
9232 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9233 EVT VT = N->getValueType(0);
9234 SDNode *Elt = N->getOperand(1).getNode();
9235 if (VT.getVectorElementType() != MVT::i64 ||
9236 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9239 SelectionDAG &DAG = DCI.DAG;
9241 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9242 VT.getVectorNumElements());
9243 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9244 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9245 // Make the DAGCombiner fold the bitcasts.
9246 DCI.AddToWorklist(Vec.getNode());
9247 DCI.AddToWorklist(V.getNode());
9248 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9249 Vec, V, N->getOperand(2));
9250 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9253 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9254 /// ISD::VECTOR_SHUFFLE.
9255 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9256 // The LLVM shufflevector instruction does not require the shuffle mask
9257 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9258 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9259 // operands do not match the mask length, they are extended by concatenating
9260 // them with undef vectors. That is probably the right thing for other
9261 // targets, but for NEON it is better to concatenate two double-register
9262 // size vector operands into a single quad-register size vector. Do that
9263 // transformation here:
9264 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9265 // shuffle(concat(v1, v2), undef)
9266 SDValue Op0 = N->getOperand(0);
9267 SDValue Op1 = N->getOperand(1);
9268 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9269 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9270 Op0.getNumOperands() != 2 ||
9271 Op1.getNumOperands() != 2)
9273 SDValue Concat0Op1 = Op0.getOperand(1);
9274 SDValue Concat1Op1 = Op1.getOperand(1);
9275 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9276 Concat1Op1.getOpcode() != ISD::UNDEF)
9278 // Skip the transformation if any of the types are illegal.
9279 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9280 EVT VT = N->getValueType(0);
9281 if (!TLI.isTypeLegal(VT) ||
9282 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9283 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9286 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9287 Op0.getOperand(0), Op1.getOperand(0));
9288 // Translate the shuffle mask.
9289 SmallVector<int, 16> NewMask;
9290 unsigned NumElts = VT.getVectorNumElements();
9291 unsigned HalfElts = NumElts/2;
9292 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9293 for (unsigned n = 0; n < NumElts; ++n) {
9294 int MaskElt = SVN->getMaskElt(n);
9296 if (MaskElt < (int)HalfElts)
9298 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9299 NewElt = HalfElts + MaskElt - NumElts;
9300 NewMask.push_back(NewElt);
9302 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9303 DAG.getUNDEF(VT), NewMask.data());
9306 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9307 /// NEON load/store intrinsics to merge base address updates.
9308 static SDValue CombineBaseUpdate(SDNode *N,
9309 TargetLowering::DAGCombinerInfo &DCI) {
9310 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9313 SelectionDAG &DAG = DCI.DAG;
9314 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9315 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9316 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9317 SDValue Addr = N->getOperand(AddrOpIdx);
9319 // Search for a use of the address operand that is an increment.
9320 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9321 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9323 if (User->getOpcode() != ISD::ADD ||
9324 UI.getUse().getResNo() != Addr.getResNo())
9327 // Check that the add is independent of the load/store. Otherwise, folding
9328 // it would create a cycle.
9329 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9332 // Find the new opcode for the updating load/store.
9334 bool isLaneOp = false;
9335 unsigned NewOpc = 0;
9336 unsigned NumVecs = 0;
9338 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9340 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9341 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9343 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9345 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9347 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9349 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9350 NumVecs = 2; isLaneOp = true; break;
9351 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9352 NumVecs = 3; isLaneOp = true; break;
9353 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9354 NumVecs = 4; isLaneOp = true; break;
9355 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9356 NumVecs = 1; isLoad = false; break;
9357 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9358 NumVecs = 2; isLoad = false; break;
9359 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9360 NumVecs = 3; isLoad = false; break;
9361 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9362 NumVecs = 4; isLoad = false; break;
9363 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9364 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9365 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9366 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9367 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9368 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9372 switch (N->getOpcode()) {
9373 default: llvm_unreachable("unexpected opcode for Neon base update");
9374 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9375 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9376 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9380 // Find the size of memory referenced by the load/store.
9383 VecTy = N->getValueType(0);
9385 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9386 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9388 NumBytes /= VecTy.getVectorNumElements();
9390 // If the increment is a constant, it must match the memory ref size.
9391 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9392 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9393 uint64_t IncVal = CInc->getZExtValue();
9394 if (IncVal != NumBytes)
9396 } else if (NumBytes >= 3 * 16) {
9397 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9398 // separate instructions that make it harder to use a non-constant update.
9402 // Create the new updating load/store node.
9404 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9406 for (n = 0; n < NumResultVecs; ++n)
9408 Tys[n++] = MVT::i32;
9409 Tys[n] = MVT::Other;
9410 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9411 SmallVector<SDValue, 8> Ops;
9412 Ops.push_back(N->getOperand(0)); // incoming chain
9413 Ops.push_back(N->getOperand(AddrOpIdx));
9415 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9416 Ops.push_back(N->getOperand(i));
9418 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9419 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9420 Ops.data(), Ops.size(),
9421 MemInt->getMemoryVT(),
9422 MemInt->getMemOperand());
9425 std::vector<SDValue> NewResults;
9426 for (unsigned i = 0; i < NumResultVecs; ++i) {
9427 NewResults.push_back(SDValue(UpdN.getNode(), i));
9429 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9430 DCI.CombineTo(N, NewResults);
9431 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9438 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9439 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9440 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9442 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9443 SelectionDAG &DAG = DCI.DAG;
9444 EVT VT = N->getValueType(0);
9445 // vldN-dup instructions only support 64-bit vectors for N > 1.
9446 if (!VT.is64BitVector())
9449 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9450 SDNode *VLD = N->getOperand(0).getNode();
9451 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9453 unsigned NumVecs = 0;
9454 unsigned NewOpc = 0;
9455 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9456 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9458 NewOpc = ARMISD::VLD2DUP;
9459 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9461 NewOpc = ARMISD::VLD3DUP;
9462 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9464 NewOpc = ARMISD::VLD4DUP;
9469 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9470 // numbers match the load.
9471 unsigned VLDLaneNo =
9472 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9473 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9475 // Ignore uses of the chain result.
9476 if (UI.getUse().getResNo() == NumVecs)
9479 if (User->getOpcode() != ARMISD::VDUPLANE ||
9480 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9484 // Create the vldN-dup node.
9487 for (n = 0; n < NumVecs; ++n)
9489 Tys[n] = MVT::Other;
9490 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9491 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9492 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9493 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9494 Ops, 2, VLDMemInt->getMemoryVT(),
9495 VLDMemInt->getMemOperand());
9498 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9500 unsigned ResNo = UI.getUse().getResNo();
9501 // Ignore uses of the chain result.
9502 if (ResNo == NumVecs)
9505 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9508 // Now the vldN-lane intrinsic is dead except for its chain result.
9509 // Update uses of the chain.
9510 std::vector<SDValue> VLDDupResults;
9511 for (unsigned n = 0; n < NumVecs; ++n)
9512 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9513 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9514 DCI.CombineTo(VLD, VLDDupResults);
9519 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9520 /// ARMISD::VDUPLANE.
9521 static SDValue PerformVDUPLANECombine(SDNode *N,
9522 TargetLowering::DAGCombinerInfo &DCI) {
9523 SDValue Op = N->getOperand(0);
9525 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9526 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9527 if (CombineVLDDUP(N, DCI))
9528 return SDValue(N, 0);
9530 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9531 // redundant. Ignore bit_converts for now; element sizes are checked below.
9532 while (Op.getOpcode() == ISD::BITCAST)
9533 Op = Op.getOperand(0);
9534 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9537 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9538 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9539 // The canonical VMOV for a zero vector uses a 32-bit element size.
9540 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9542 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9544 EVT VT = N->getValueType(0);
9545 if (EltSize > VT.getVectorElementType().getSizeInBits())
9548 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9551 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9552 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9553 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9557 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9559 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9564 APFloat APF = C->getValueAPF();
9565 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9566 != APFloat::opOK || !isExact)
9569 c0 = (I == 0) ? cN : c0;
9570 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9577 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9578 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9579 /// when the VMUL has a constant operand that is a power of 2.
9581 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9582 /// vmul.f32 d16, d17, d16
9583 /// vcvt.s32.f32 d16, d16
9585 /// vcvt.s32.f32 d16, d16, #3
9586 static SDValue PerformVCVTCombine(SDNode *N,
9587 TargetLowering::DAGCombinerInfo &DCI,
9588 const ARMSubtarget *Subtarget) {
9589 SelectionDAG &DAG = DCI.DAG;
9590 SDValue Op = N->getOperand(0);
9592 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9593 Op.getOpcode() != ISD::FMUL)
9597 SDValue N0 = Op->getOperand(0);
9598 SDValue ConstVec = Op->getOperand(1);
9599 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9601 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9602 !isConstVecPow2(ConstVec, isSigned, C))
9605 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9606 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9607 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9608 // These instructions only exist converting from f32 to i32. We can handle
9609 // smaller integers by generating an extra truncate, but larger ones would
9614 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9615 Intrinsic::arm_neon_vcvtfp2fxu;
9616 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9617 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9618 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9619 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9620 DAG.getConstant(Log2_64(C), MVT::i32));
9622 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9623 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9628 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9629 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9630 /// when the VDIV has a constant operand that is a power of 2.
9632 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9633 /// vcvt.f32.s32 d16, d16
9634 /// vdiv.f32 d16, d17, d16
9636 /// vcvt.f32.s32 d16, d16, #3
9637 static SDValue PerformVDIVCombine(SDNode *N,
9638 TargetLowering::DAGCombinerInfo &DCI,
9639 const ARMSubtarget *Subtarget) {
9640 SelectionDAG &DAG = DCI.DAG;
9641 SDValue Op = N->getOperand(0);
9642 unsigned OpOpcode = Op.getNode()->getOpcode();
9644 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9645 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9649 SDValue ConstVec = N->getOperand(1);
9650 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9652 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9653 !isConstVecPow2(ConstVec, isSigned, C))
9656 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9657 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9658 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9659 // These instructions only exist converting from i32 to f32. We can handle
9660 // smaller integers by generating an extra extend, but larger ones would
9665 SDValue ConvInput = Op.getOperand(0);
9666 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9667 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9668 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9669 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9672 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9673 Intrinsic::arm_neon_vcvtfxu2fp;
9674 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9676 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9677 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9680 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9681 /// operand of a vector shift operation, where all the elements of the
9682 /// build_vector must have the same constant integer value.
9683 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9684 // Ignore bit_converts.
9685 while (Op.getOpcode() == ISD::BITCAST)
9686 Op = Op.getOperand(0);
9687 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9688 APInt SplatBits, SplatUndef;
9689 unsigned SplatBitSize;
9691 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9692 HasAnyUndefs, ElementBits) ||
9693 SplatBitSize > ElementBits)
9695 Cnt = SplatBits.getSExtValue();
9699 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9700 /// operand of a vector shift left operation. That value must be in the range:
9701 /// 0 <= Value < ElementBits for a left shift; or
9702 /// 0 <= Value <= ElementBits for a long left shift.
9703 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9704 assert(VT.isVector() && "vector shift count is not a vector type");
9705 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9706 if (! getVShiftImm(Op, ElementBits, Cnt))
9708 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9711 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9712 /// operand of a vector shift right operation. For a shift opcode, the value
9713 /// is positive, but for an intrinsic the value count must be negative. The
9714 /// absolute value must be in the range:
9715 /// 1 <= |Value| <= ElementBits for a right shift; or
9716 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9717 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9719 assert(VT.isVector() && "vector shift count is not a vector type");
9720 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9721 if (! getVShiftImm(Op, ElementBits, Cnt))
9725 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9728 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9729 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9730 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9733 // Don't do anything for most intrinsics.
9736 // Vector shifts: check for immediate versions and lower them.
9737 // Note: This is done during DAG combining instead of DAG legalizing because
9738 // the build_vectors for 64-bit vector element shift counts are generally
9739 // not legal, and it is hard to see their values after they get legalized to
9740 // loads from a constant pool.
9741 case Intrinsic::arm_neon_vshifts:
9742 case Intrinsic::arm_neon_vshiftu:
9743 case Intrinsic::arm_neon_vrshifts:
9744 case Intrinsic::arm_neon_vrshiftu:
9745 case Intrinsic::arm_neon_vrshiftn:
9746 case Intrinsic::arm_neon_vqshifts:
9747 case Intrinsic::arm_neon_vqshiftu:
9748 case Intrinsic::arm_neon_vqshiftsu:
9749 case Intrinsic::arm_neon_vqshiftns:
9750 case Intrinsic::arm_neon_vqshiftnu:
9751 case Intrinsic::arm_neon_vqshiftnsu:
9752 case Intrinsic::arm_neon_vqrshiftns:
9753 case Intrinsic::arm_neon_vqrshiftnu:
9754 case Intrinsic::arm_neon_vqrshiftnsu: {
9755 EVT VT = N->getOperand(1).getValueType();
9757 unsigned VShiftOpc = 0;
9760 case Intrinsic::arm_neon_vshifts:
9761 case Intrinsic::arm_neon_vshiftu:
9762 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9763 VShiftOpc = ARMISD::VSHL;
9766 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9767 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9768 ARMISD::VSHRs : ARMISD::VSHRu);
9773 case Intrinsic::arm_neon_vrshifts:
9774 case Intrinsic::arm_neon_vrshiftu:
9775 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9779 case Intrinsic::arm_neon_vqshifts:
9780 case Intrinsic::arm_neon_vqshiftu:
9781 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9785 case Intrinsic::arm_neon_vqshiftsu:
9786 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9788 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9790 case Intrinsic::arm_neon_vrshiftn:
9791 case Intrinsic::arm_neon_vqshiftns:
9792 case Intrinsic::arm_neon_vqshiftnu:
9793 case Intrinsic::arm_neon_vqshiftnsu:
9794 case Intrinsic::arm_neon_vqrshiftns:
9795 case Intrinsic::arm_neon_vqrshiftnu:
9796 case Intrinsic::arm_neon_vqrshiftnsu:
9797 // Narrowing shifts require an immediate right shift.
9798 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9800 llvm_unreachable("invalid shift count for narrowing vector shift "
9804 llvm_unreachable("unhandled vector shift");
9808 case Intrinsic::arm_neon_vshifts:
9809 case Intrinsic::arm_neon_vshiftu:
9810 // Opcode already set above.
9812 case Intrinsic::arm_neon_vrshifts:
9813 VShiftOpc = ARMISD::VRSHRs; break;
9814 case Intrinsic::arm_neon_vrshiftu:
9815 VShiftOpc = ARMISD::VRSHRu; break;
9816 case Intrinsic::arm_neon_vrshiftn:
9817 VShiftOpc = ARMISD::VRSHRN; break;
9818 case Intrinsic::arm_neon_vqshifts:
9819 VShiftOpc = ARMISD::VQSHLs; break;
9820 case Intrinsic::arm_neon_vqshiftu:
9821 VShiftOpc = ARMISD::VQSHLu; break;
9822 case Intrinsic::arm_neon_vqshiftsu:
9823 VShiftOpc = ARMISD::VQSHLsu; break;
9824 case Intrinsic::arm_neon_vqshiftns:
9825 VShiftOpc = ARMISD::VQSHRNs; break;
9826 case Intrinsic::arm_neon_vqshiftnu:
9827 VShiftOpc = ARMISD::VQSHRNu; break;
9828 case Intrinsic::arm_neon_vqshiftnsu:
9829 VShiftOpc = ARMISD::VQSHRNsu; break;
9830 case Intrinsic::arm_neon_vqrshiftns:
9831 VShiftOpc = ARMISD::VQRSHRNs; break;
9832 case Intrinsic::arm_neon_vqrshiftnu:
9833 VShiftOpc = ARMISD::VQRSHRNu; break;
9834 case Intrinsic::arm_neon_vqrshiftnsu:
9835 VShiftOpc = ARMISD::VQRSHRNsu; break;
9838 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9839 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9842 case Intrinsic::arm_neon_vshiftins: {
9843 EVT VT = N->getOperand(1).getValueType();
9845 unsigned VShiftOpc = 0;
9847 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9848 VShiftOpc = ARMISD::VSLI;
9849 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9850 VShiftOpc = ARMISD::VSRI;
9852 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9855 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9856 N->getOperand(1), N->getOperand(2),
9857 DAG.getConstant(Cnt, MVT::i32));
9860 case Intrinsic::arm_neon_vqrshifts:
9861 case Intrinsic::arm_neon_vqrshiftu:
9862 // No immediate versions of these to check for.
9869 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9870 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9871 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9872 /// vector element shift counts are generally not legal, and it is hard to see
9873 /// their values after they get legalized to loads from a constant pool.
9874 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9875 const ARMSubtarget *ST) {
9876 EVT VT = N->getValueType(0);
9877 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9878 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9879 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9880 SDValue N1 = N->getOperand(1);
9881 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9882 SDValue N0 = N->getOperand(0);
9883 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9884 DAG.MaskedValueIsZero(N0.getOperand(0),
9885 APInt::getHighBitsSet(32, 16)))
9886 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9890 // Nothing to be done for scalar shifts.
9891 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9892 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9895 assert(ST->hasNEON() && "unexpected vector shift");
9898 switch (N->getOpcode()) {
9899 default: llvm_unreachable("unexpected shift opcode");
9902 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9903 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9904 DAG.getConstant(Cnt, MVT::i32));
9909 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9910 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9911 ARMISD::VSHRs : ARMISD::VSHRu);
9912 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9913 DAG.getConstant(Cnt, MVT::i32));
9919 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9920 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9921 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9922 const ARMSubtarget *ST) {
9923 SDValue N0 = N->getOperand(0);
9925 // Check for sign- and zero-extensions of vector extract operations of 8-
9926 // and 16-bit vector elements. NEON supports these directly. They are
9927 // handled during DAG combining because type legalization will promote them
9928 // to 32-bit types and it is messy to recognize the operations after that.
9929 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9930 SDValue Vec = N0.getOperand(0);
9931 SDValue Lane = N0.getOperand(1);
9932 EVT VT = N->getValueType(0);
9933 EVT EltVT = N0.getValueType();
9934 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9936 if (VT == MVT::i32 &&
9937 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9938 TLI.isTypeLegal(Vec.getValueType()) &&
9939 isa<ConstantSDNode>(Lane)) {
9942 switch (N->getOpcode()) {
9943 default: llvm_unreachable("unexpected opcode");
9944 case ISD::SIGN_EXTEND:
9945 Opc = ARMISD::VGETLANEs;
9947 case ISD::ZERO_EXTEND:
9948 case ISD::ANY_EXTEND:
9949 Opc = ARMISD::VGETLANEu;
9952 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9959 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9960 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9961 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9962 const ARMSubtarget *ST) {
9963 // If the target supports NEON, try to use vmax/vmin instructions for f32
9964 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9965 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9966 // a NaN; only do the transformation when it matches that behavior.
9968 // For now only do this when using NEON for FP operations; if using VFP, it
9969 // is not obvious that the benefit outweighs the cost of switching to the
9971 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9972 N->getValueType(0) != MVT::f32)
9975 SDValue CondLHS = N->getOperand(0);
9976 SDValue CondRHS = N->getOperand(1);
9977 SDValue LHS = N->getOperand(2);
9978 SDValue RHS = N->getOperand(3);
9979 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9981 unsigned Opcode = 0;
9983 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9984 IsReversed = false; // x CC y ? x : y
9985 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9986 IsReversed = true ; // x CC y ? y : x
10000 // If LHS is NaN, an ordered comparison will be false and the result will
10001 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
10002 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10003 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10004 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10006 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10007 // will return -0, so vmin can only be used for unsafe math or if one of
10008 // the operands is known to be nonzero.
10009 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10010 !DAG.getTarget().Options.UnsafeFPMath &&
10011 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10013 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10022 // If LHS is NaN, an ordered comparison will be false and the result will
10023 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
10024 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10025 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10026 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10028 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10029 // will return +0, so vmax can only be used for unsafe math or if one of
10030 // the operands is known to be nonzero.
10031 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10032 !DAG.getTarget().Options.UnsafeFPMath &&
10033 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10035 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10041 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10044 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10046 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10047 SDValue Cmp = N->getOperand(4);
10048 if (Cmp.getOpcode() != ARMISD::CMPZ)
10049 // Only looking at EQ and NE cases.
10052 EVT VT = N->getValueType(0);
10054 SDValue LHS = Cmp.getOperand(0);
10055 SDValue RHS = Cmp.getOperand(1);
10056 SDValue FalseVal = N->getOperand(0);
10057 SDValue TrueVal = N->getOperand(1);
10058 SDValue ARMcc = N->getOperand(2);
10059 ARMCC::CondCodes CC =
10060 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10078 /// FIXME: Turn this into a target neutral optimization?
10080 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10081 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10082 N->getOperand(3), Cmp);
10083 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10085 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10086 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10087 N->getOperand(3), NewCmp);
10090 if (Res.getNode()) {
10091 APInt KnownZero, KnownOne;
10092 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10093 // Capture demanded bits information that would be otherwise lost.
10094 if (KnownZero == 0xfffffffe)
10095 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10096 DAG.getValueType(MVT::i1));
10097 else if (KnownZero == 0xffffff00)
10098 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10099 DAG.getValueType(MVT::i8));
10100 else if (KnownZero == 0xffff0000)
10101 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10102 DAG.getValueType(MVT::i16));
10108 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10109 DAGCombinerInfo &DCI) const {
10110 switch (N->getOpcode()) {
10112 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10113 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10114 case ISD::SUB: return PerformSUBCombine(N, DCI);
10115 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10116 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10117 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10118 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10119 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10120 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10121 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10122 case ISD::STORE: return PerformSTORECombine(N, DCI);
10123 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10124 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10125 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10126 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10127 case ISD::FP_TO_SINT:
10128 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10129 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10130 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10133 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10134 case ISD::SIGN_EXTEND:
10135 case ISD::ZERO_EXTEND:
10136 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10137 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10138 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10139 case ARMISD::VLD2DUP:
10140 case ARMISD::VLD3DUP:
10141 case ARMISD::VLD4DUP:
10142 return CombineBaseUpdate(N, DCI);
10143 case ARMISD::BUILD_VECTOR:
10144 return PerformARMBUILD_VECTORCombine(N, DCI);
10145 case ISD::INTRINSIC_VOID:
10146 case ISD::INTRINSIC_W_CHAIN:
10147 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10148 case Intrinsic::arm_neon_vld1:
10149 case Intrinsic::arm_neon_vld2:
10150 case Intrinsic::arm_neon_vld3:
10151 case Intrinsic::arm_neon_vld4:
10152 case Intrinsic::arm_neon_vld2lane:
10153 case Intrinsic::arm_neon_vld3lane:
10154 case Intrinsic::arm_neon_vld4lane:
10155 case Intrinsic::arm_neon_vst1:
10156 case Intrinsic::arm_neon_vst2:
10157 case Intrinsic::arm_neon_vst3:
10158 case Intrinsic::arm_neon_vst4:
10159 case Intrinsic::arm_neon_vst2lane:
10160 case Intrinsic::arm_neon_vst3lane:
10161 case Intrinsic::arm_neon_vst4lane:
10162 return CombineBaseUpdate(N, DCI);
10170 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10172 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10175 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
10176 bool *Fast) const {
10177 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10178 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10180 switch (VT.getSimpleVT().SimpleTy) {
10186 // Unaligned access can use (for example) LRDB, LRDH, LDR
10187 if (AllowsUnaligned) {
10189 *Fast = Subtarget->hasV7Ops();
10196 // For any little-endian targets with neon, we can support unaligned ld/st
10197 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10198 // A big-endian target may also explicitly support unaligned accesses
10199 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10209 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10210 unsigned AlignCheck) {
10211 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10212 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10215 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10216 unsigned DstAlign, unsigned SrcAlign,
10217 bool IsMemset, bool ZeroMemset,
10219 MachineFunction &MF) const {
10220 const Function *F = MF.getFunction();
10222 // See if we can use NEON instructions for this...
10223 if ((!IsMemset || ZeroMemset) &&
10224 Subtarget->hasNEON() &&
10225 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10226 Attribute::NoImplicitFloat)) {
10229 (memOpAlign(SrcAlign, DstAlign, 16) ||
10230 (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
10232 } else if (Size >= 8 &&
10233 (memOpAlign(SrcAlign, DstAlign, 8) ||
10234 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
10239 // Lowering to i32/i16 if the size permits.
10242 else if (Size >= 2)
10245 // Let the target-independent logic figure it out.
10249 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10250 if (Val.getOpcode() != ISD::LOAD)
10253 EVT VT1 = Val.getValueType();
10254 if (!VT1.isSimple() || !VT1.isInteger() ||
10255 !VT2.isSimple() || !VT2.isInteger())
10258 switch (VT1.getSimpleVT().SimpleTy) {
10263 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10270 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10271 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10274 if (!isTypeLegal(EVT::getEVT(Ty1)))
10277 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10279 // Assuming the caller doesn't have a zeroext or signext return parameter,
10280 // truncation all the way down to i1 is valid.
10285 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10289 unsigned Scale = 1;
10290 switch (VT.getSimpleVT().SimpleTy) {
10291 default: return false;
10306 if ((V & (Scale - 1)) != 0)
10309 return V == (V & ((1LL << 5) - 1));
10312 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10313 const ARMSubtarget *Subtarget) {
10314 bool isNeg = false;
10320 switch (VT.getSimpleVT().SimpleTy) {
10321 default: return false;
10326 // + imm12 or - imm8
10328 return V == (V & ((1LL << 8) - 1));
10329 return V == (V & ((1LL << 12) - 1));
10332 // Same as ARM mode. FIXME: NEON?
10333 if (!Subtarget->hasVFP2())
10338 return V == (V & ((1LL << 8) - 1));
10342 /// isLegalAddressImmediate - Return true if the integer value can be used
10343 /// as the offset of the target addressing mode for load / store of the
10345 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10346 const ARMSubtarget *Subtarget) {
10350 if (!VT.isSimple())
10353 if (Subtarget->isThumb1Only())
10354 return isLegalT1AddressImmediate(V, VT);
10355 else if (Subtarget->isThumb2())
10356 return isLegalT2AddressImmediate(V, VT, Subtarget);
10361 switch (VT.getSimpleVT().SimpleTy) {
10362 default: return false;
10367 return V == (V & ((1LL << 12) - 1));
10370 return V == (V & ((1LL << 8) - 1));
10373 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10378 return V == (V & ((1LL << 8) - 1));
10382 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10384 int Scale = AM.Scale;
10388 switch (VT.getSimpleVT().SimpleTy) {
10389 default: return false;
10397 Scale = Scale & ~1;
10398 return Scale == 2 || Scale == 4 || Scale == 8;
10401 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10405 // Note, we allow "void" uses (basically, uses that aren't loads or
10406 // stores), because arm allows folding a scale into many arithmetic
10407 // operations. This should be made more precise and revisited later.
10409 // Allow r << imm, but the imm has to be a multiple of two.
10410 if (Scale & 1) return false;
10411 return isPowerOf2_32(Scale);
10415 /// isLegalAddressingMode - Return true if the addressing mode represented
10416 /// by AM is legal for this target, for a load/store of the specified type.
10417 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10419 EVT VT = getValueType(Ty, true);
10420 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10423 // Can never fold addr of global into load/store.
10427 switch (AM.Scale) {
10428 case 0: // no scale reg, must be "r+i" or "r", or "i".
10431 if (Subtarget->isThumb1Only())
10435 // ARM doesn't support any R+R*scale+imm addr modes.
10439 if (!VT.isSimple())
10442 if (Subtarget->isThumb2())
10443 return isLegalT2ScaledAddressingMode(AM, VT);
10445 int Scale = AM.Scale;
10446 switch (VT.getSimpleVT().SimpleTy) {
10447 default: return false;
10451 if (Scale < 0) Scale = -Scale;
10455 return isPowerOf2_32(Scale & ~1);
10459 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10464 // Note, we allow "void" uses (basically, uses that aren't loads or
10465 // stores), because arm allows folding a scale into many arithmetic
10466 // operations. This should be made more precise and revisited later.
10468 // Allow r << imm, but the imm has to be a multiple of two.
10469 if (Scale & 1) return false;
10470 return isPowerOf2_32(Scale);
10476 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10477 /// icmp immediate, that is the target has icmp instructions which can compare
10478 /// a register against the immediate without having to materialize the
10479 /// immediate into a register.
10480 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10481 // Thumb2 and ARM modes can use cmn for negative immediates.
10482 if (!Subtarget->isThumb())
10483 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10484 if (Subtarget->isThumb2())
10485 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10486 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10487 return Imm >= 0 && Imm <= 255;
10490 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10491 /// *or sub* immediate, that is the target has add or sub instructions which can
10492 /// add a register with the immediate without having to materialize the
10493 /// immediate into a register.
10494 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10495 // Same encoding for add/sub, just flip the sign.
10496 int64_t AbsImm = llvm::abs64(Imm);
10497 if (!Subtarget->isThumb())
10498 return ARM_AM::getSOImmVal(AbsImm) != -1;
10499 if (Subtarget->isThumb2())
10500 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10501 // Thumb1 only has 8-bit unsigned immediate.
10502 return AbsImm >= 0 && AbsImm <= 255;
10505 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10506 bool isSEXTLoad, SDValue &Base,
10507 SDValue &Offset, bool &isInc,
10508 SelectionDAG &DAG) {
10509 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10512 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10513 // AddressingMode 3
10514 Base = Ptr->getOperand(0);
10515 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10516 int RHSC = (int)RHS->getZExtValue();
10517 if (RHSC < 0 && RHSC > -256) {
10518 assert(Ptr->getOpcode() == ISD::ADD);
10520 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10524 isInc = (Ptr->getOpcode() == ISD::ADD);
10525 Offset = Ptr->getOperand(1);
10527 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10528 // AddressingMode 2
10529 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10530 int RHSC = (int)RHS->getZExtValue();
10531 if (RHSC < 0 && RHSC > -0x1000) {
10532 assert(Ptr->getOpcode() == ISD::ADD);
10534 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10535 Base = Ptr->getOperand(0);
10540 if (Ptr->getOpcode() == ISD::ADD) {
10542 ARM_AM::ShiftOpc ShOpcVal=
10543 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10544 if (ShOpcVal != ARM_AM::no_shift) {
10545 Base = Ptr->getOperand(1);
10546 Offset = Ptr->getOperand(0);
10548 Base = Ptr->getOperand(0);
10549 Offset = Ptr->getOperand(1);
10554 isInc = (Ptr->getOpcode() == ISD::ADD);
10555 Base = Ptr->getOperand(0);
10556 Offset = Ptr->getOperand(1);
10560 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10564 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10565 bool isSEXTLoad, SDValue &Base,
10566 SDValue &Offset, bool &isInc,
10567 SelectionDAG &DAG) {
10568 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10571 Base = Ptr->getOperand(0);
10572 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10573 int RHSC = (int)RHS->getZExtValue();
10574 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10575 assert(Ptr->getOpcode() == ISD::ADD);
10577 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10579 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10580 isInc = Ptr->getOpcode() == ISD::ADD;
10581 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10589 /// getPreIndexedAddressParts - returns true by value, base pointer and
10590 /// offset pointer and addressing mode by reference if the node's address
10591 /// can be legally represented as pre-indexed load / store address.
10593 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10595 ISD::MemIndexedMode &AM,
10596 SelectionDAG &DAG) const {
10597 if (Subtarget->isThumb1Only())
10602 bool isSEXTLoad = false;
10603 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10604 Ptr = LD->getBasePtr();
10605 VT = LD->getMemoryVT();
10606 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10607 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10608 Ptr = ST->getBasePtr();
10609 VT = ST->getMemoryVT();
10614 bool isLegal = false;
10615 if (Subtarget->isThumb2())
10616 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10617 Offset, isInc, DAG);
10619 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10620 Offset, isInc, DAG);
10624 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10628 /// getPostIndexedAddressParts - returns true by value, base pointer and
10629 /// offset pointer and addressing mode by reference if this node can be
10630 /// combined with a load / store to form a post-indexed load / store.
10631 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10634 ISD::MemIndexedMode &AM,
10635 SelectionDAG &DAG) const {
10636 if (Subtarget->isThumb1Only())
10641 bool isSEXTLoad = false;
10642 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10643 VT = LD->getMemoryVT();
10644 Ptr = LD->getBasePtr();
10645 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10646 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10647 VT = ST->getMemoryVT();
10648 Ptr = ST->getBasePtr();
10653 bool isLegal = false;
10654 if (Subtarget->isThumb2())
10655 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10658 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10664 // Swap base ptr and offset to catch more post-index load / store when
10665 // it's legal. In Thumb2 mode, offset must be an immediate.
10666 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10667 !Subtarget->isThumb2())
10668 std::swap(Base, Offset);
10670 // Post-indexed load / store update the base pointer.
10675 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10679 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10682 const SelectionDAG &DAG,
10683 unsigned Depth) const {
10684 unsigned BitWidth = KnownOne.getBitWidth();
10685 KnownZero = KnownOne = APInt(BitWidth, 0);
10686 switch (Op.getOpcode()) {
10692 // These nodes' second result is a boolean
10693 if (Op.getResNo() == 0)
10695 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10697 case ARMISD::CMOV: {
10698 // Bits are known zero/one if known on the LHS and RHS.
10699 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10700 if (KnownZero == 0 && KnownOne == 0) return;
10702 APInt KnownZeroRHS, KnownOneRHS;
10703 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10704 KnownZero &= KnownZeroRHS;
10705 KnownOne &= KnownOneRHS;
10711 //===----------------------------------------------------------------------===//
10712 // ARM Inline Assembly Support
10713 //===----------------------------------------------------------------------===//
10715 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10716 // Looking for "rev" which is V6+.
10717 if (!Subtarget->hasV6Ops())
10720 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10721 std::string AsmStr = IA->getAsmString();
10722 SmallVector<StringRef, 4> AsmPieces;
10723 SplitString(AsmStr, AsmPieces, ";\n");
10725 switch (AsmPieces.size()) {
10726 default: return false;
10728 AsmStr = AsmPieces[0];
10730 SplitString(AsmStr, AsmPieces, " \t,");
10733 if (AsmPieces.size() == 3 &&
10734 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10735 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10736 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10737 if (Ty && Ty->getBitWidth() == 32)
10738 return IntrinsicLowering::LowerToByteSwap(CI);
10746 /// getConstraintType - Given a constraint letter, return the type of
10747 /// constraint it is for this target.
10748 ARMTargetLowering::ConstraintType
10749 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10750 if (Constraint.size() == 1) {
10751 switch (Constraint[0]) {
10753 case 'l': return C_RegisterClass;
10754 case 'w': return C_RegisterClass;
10755 case 'h': return C_RegisterClass;
10756 case 'x': return C_RegisterClass;
10757 case 't': return C_RegisterClass;
10758 case 'j': return C_Other; // Constant for movw.
10759 // An address with a single base register. Due to the way we
10760 // currently handle addresses it is the same as an 'r' memory constraint.
10761 case 'Q': return C_Memory;
10763 } else if (Constraint.size() == 2) {
10764 switch (Constraint[0]) {
10766 // All 'U+' constraints are addresses.
10767 case 'U': return C_Memory;
10770 return TargetLowering::getConstraintType(Constraint);
10773 /// Examine constraint type and operand type and determine a weight value.
10774 /// This object must already have been set up with the operand type
10775 /// and the current alternative constraint selected.
10776 TargetLowering::ConstraintWeight
10777 ARMTargetLowering::getSingleConstraintMatchWeight(
10778 AsmOperandInfo &info, const char *constraint) const {
10779 ConstraintWeight weight = CW_Invalid;
10780 Value *CallOperandVal = info.CallOperandVal;
10781 // If we don't have a value, we can't do a match,
10782 // but allow it at the lowest weight.
10783 if (CallOperandVal == NULL)
10785 Type *type = CallOperandVal->getType();
10786 // Look at the constraint type.
10787 switch (*constraint) {
10789 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10792 if (type->isIntegerTy()) {
10793 if (Subtarget->isThumb())
10794 weight = CW_SpecificReg;
10796 weight = CW_Register;
10800 if (type->isFloatingPointTy())
10801 weight = CW_Register;
10807 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10809 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10811 if (Constraint.size() == 1) {
10812 // GCC ARM Constraint Letters
10813 switch (Constraint[0]) {
10814 case 'l': // Low regs or general regs.
10815 if (Subtarget->isThumb())
10816 return RCPair(0U, &ARM::tGPRRegClass);
10817 return RCPair(0U, &ARM::GPRRegClass);
10818 case 'h': // High regs or no regs.
10819 if (Subtarget->isThumb())
10820 return RCPair(0U, &ARM::hGPRRegClass);
10823 return RCPair(0U, &ARM::GPRRegClass);
10825 if (VT == MVT::Other)
10827 if (VT == MVT::f32)
10828 return RCPair(0U, &ARM::SPRRegClass);
10829 if (VT.getSizeInBits() == 64)
10830 return RCPair(0U, &ARM::DPRRegClass);
10831 if (VT.getSizeInBits() == 128)
10832 return RCPair(0U, &ARM::QPRRegClass);
10835 if (VT == MVT::Other)
10837 if (VT == MVT::f32)
10838 return RCPair(0U, &ARM::SPR_8RegClass);
10839 if (VT.getSizeInBits() == 64)
10840 return RCPair(0U, &ARM::DPR_8RegClass);
10841 if (VT.getSizeInBits() == 128)
10842 return RCPair(0U, &ARM::QPR_8RegClass);
10845 if (VT == MVT::f32)
10846 return RCPair(0U, &ARM::SPRRegClass);
10850 if (StringRef("{cc}").equals_lower(Constraint))
10851 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10853 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10856 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10857 /// vector. If it is invalid, don't add anything to Ops.
10858 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10859 std::string &Constraint,
10860 std::vector<SDValue>&Ops,
10861 SelectionDAG &DAG) const {
10862 SDValue Result(0, 0);
10864 // Currently only support length 1 constraints.
10865 if (Constraint.length() != 1) return;
10867 char ConstraintLetter = Constraint[0];
10868 switch (ConstraintLetter) {
10871 case 'I': case 'J': case 'K': case 'L':
10872 case 'M': case 'N': case 'O':
10873 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10877 int64_t CVal64 = C->getSExtValue();
10878 int CVal = (int) CVal64;
10879 // None of these constraints allow values larger than 32 bits. Check
10880 // that the value fits in an int.
10881 if (CVal != CVal64)
10884 switch (ConstraintLetter) {
10886 // Constant suitable for movw, must be between 0 and
10888 if (Subtarget->hasV6T2Ops())
10889 if (CVal >= 0 && CVal <= 65535)
10893 if (Subtarget->isThumb1Only()) {
10894 // This must be a constant between 0 and 255, for ADD
10896 if (CVal >= 0 && CVal <= 255)
10898 } else if (Subtarget->isThumb2()) {
10899 // A constant that can be used as an immediate value in a
10900 // data-processing instruction.
10901 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10904 // A constant that can be used as an immediate value in a
10905 // data-processing instruction.
10906 if (ARM_AM::getSOImmVal(CVal) != -1)
10912 if (Subtarget->isThumb()) { // FIXME thumb2
10913 // This must be a constant between -255 and -1, for negated ADD
10914 // immediates. This can be used in GCC with an "n" modifier that
10915 // prints the negated value, for use with SUB instructions. It is
10916 // not useful otherwise but is implemented for compatibility.
10917 if (CVal >= -255 && CVal <= -1)
10920 // This must be a constant between -4095 and 4095. It is not clear
10921 // what this constraint is intended for. Implemented for
10922 // compatibility with GCC.
10923 if (CVal >= -4095 && CVal <= 4095)
10929 if (Subtarget->isThumb1Only()) {
10930 // A 32-bit value where only one byte has a nonzero value. Exclude
10931 // zero to match GCC. This constraint is used by GCC internally for
10932 // constants that can be loaded with a move/shift combination.
10933 // It is not useful otherwise but is implemented for compatibility.
10934 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10936 } else if (Subtarget->isThumb2()) {
10937 // A constant whose bitwise inverse can be used as an immediate
10938 // value in a data-processing instruction. This can be used in GCC
10939 // with a "B" modifier that prints the inverted value, for use with
10940 // BIC and MVN instructions. It is not useful otherwise but is
10941 // implemented for compatibility.
10942 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10945 // A constant whose bitwise inverse can be used as an immediate
10946 // value in a data-processing instruction. This can be used in GCC
10947 // with a "B" modifier that prints the inverted value, for use with
10948 // BIC and MVN instructions. It is not useful otherwise but is
10949 // implemented for compatibility.
10950 if (ARM_AM::getSOImmVal(~CVal) != -1)
10956 if (Subtarget->isThumb1Only()) {
10957 // This must be a constant between -7 and 7,
10958 // for 3-operand ADD/SUB immediate instructions.
10959 if (CVal >= -7 && CVal < 7)
10961 } else if (Subtarget->isThumb2()) {
10962 // A constant whose negation can be used as an immediate value in a
10963 // data-processing instruction. This can be used in GCC with an "n"
10964 // modifier that prints the negated value, for use with SUB
10965 // instructions. It is not useful otherwise but is implemented for
10967 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10970 // A constant whose negation can be used as an immediate value in a
10971 // data-processing instruction. This can be used in GCC with an "n"
10972 // modifier that prints the negated value, for use with SUB
10973 // instructions. It is not useful otherwise but is implemented for
10975 if (ARM_AM::getSOImmVal(-CVal) != -1)
10981 if (Subtarget->isThumb()) { // FIXME thumb2
10982 // This must be a multiple of 4 between 0 and 1020, for
10983 // ADD sp + immediate.
10984 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10987 // A power of two or a constant between 0 and 32. This is used in
10988 // GCC for the shift amount on shifted register operands, but it is
10989 // useful in general for any shift amounts.
10990 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10996 if (Subtarget->isThumb()) { // FIXME thumb2
10997 // This must be a constant between 0 and 31, for shift amounts.
10998 if (CVal >= 0 && CVal <= 31)
11004 if (Subtarget->isThumb()) { // FIXME thumb2
11005 // This must be a multiple of 4 between -508 and 508, for
11006 // ADD/SUB sp = sp + immediate.
11007 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11012 Result = DAG.getTargetConstant(CVal, Op.getValueType());
11016 if (Result.getNode()) {
11017 Ops.push_back(Result);
11020 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11023 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11024 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11025 unsigned Opcode = Op->getOpcode();
11026 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11027 "Invalid opcode for Div/Rem lowering");
11028 bool isSigned = (Opcode == ISD::SDIVREM);
11029 EVT VT = Op->getValueType(0);
11030 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11033 switch (VT.getSimpleVT().SimpleTy) {
11034 default: llvm_unreachable("Unexpected request for libcall!");
11035 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11036 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11037 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11038 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11041 SDValue InChain = DAG.getEntryNode();
11043 TargetLowering::ArgListTy Args;
11044 TargetLowering::ArgListEntry Entry;
11045 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11046 EVT ArgVT = Op->getOperand(i).getValueType();
11047 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11048 Entry.Node = Op->getOperand(i);
11050 Entry.isSExt = isSigned;
11051 Entry.isZExt = !isSigned;
11052 Args.push_back(Entry);
11055 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11058 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11062 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11063 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11064 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11065 Callee, Args, DAG, dl);
11066 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11068 return CallInfo.first;
11072 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11073 // The ARM target isn't yet aware of offsets.
11077 bool ARM::isBitFieldInvertedMask(unsigned v) {
11078 if (v == 0xffffffff)
11081 // there can be 1's on either or both "outsides", all the "inside"
11082 // bits must be 0's
11083 unsigned TO = CountTrailingOnes_32(v);
11084 unsigned LO = CountLeadingOnes_32(v);
11085 v = (v >> TO) << TO;
11086 v = (v << LO) >> LO;
11090 /// isFPImmLegal - Returns true if the target can instruction select the
11091 /// specified FP immediate natively. If false, the legalizer will
11092 /// materialize the FP immediate as a load from a constant pool.
11093 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11094 if (!Subtarget->hasVFP3())
11096 if (VT == MVT::f32)
11097 return ARM_AM::getFP32Imm(Imm) != -1;
11098 if (VT == MVT::f64)
11099 return ARM_AM::getFP64Imm(Imm) != -1;
11103 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11104 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11105 /// specified in the intrinsic calls.
11106 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11108 unsigned Intrinsic) const {
11109 switch (Intrinsic) {
11110 case Intrinsic::arm_neon_vld1:
11111 case Intrinsic::arm_neon_vld2:
11112 case Intrinsic::arm_neon_vld3:
11113 case Intrinsic::arm_neon_vld4:
11114 case Intrinsic::arm_neon_vld2lane:
11115 case Intrinsic::arm_neon_vld3lane:
11116 case Intrinsic::arm_neon_vld4lane: {
11117 Info.opc = ISD::INTRINSIC_W_CHAIN;
11118 // Conservatively set memVT to the entire set of vectors loaded.
11119 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11120 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11121 Info.ptrVal = I.getArgOperand(0);
11123 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11124 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11125 Info.vol = false; // volatile loads with NEON intrinsics not supported
11126 Info.readMem = true;
11127 Info.writeMem = false;
11130 case Intrinsic::arm_neon_vst1:
11131 case Intrinsic::arm_neon_vst2:
11132 case Intrinsic::arm_neon_vst3:
11133 case Intrinsic::arm_neon_vst4:
11134 case Intrinsic::arm_neon_vst2lane:
11135 case Intrinsic::arm_neon_vst3lane:
11136 case Intrinsic::arm_neon_vst4lane: {
11137 Info.opc = ISD::INTRINSIC_VOID;
11138 // Conservatively set memVT to the entire set of vectors stored.
11139 unsigned NumElts = 0;
11140 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11141 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11142 if (!ArgTy->isVectorTy())
11144 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11146 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11147 Info.ptrVal = I.getArgOperand(0);
11149 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11150 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11151 Info.vol = false; // volatile stores with NEON intrinsics not supported
11152 Info.readMem = false;
11153 Info.writeMem = true;
11156 case Intrinsic::arm_ldrex: {
11157 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11158 Info.opc = ISD::INTRINSIC_W_CHAIN;
11159 Info.memVT = MVT::getVT(PtrTy->getElementType());
11160 Info.ptrVal = I.getArgOperand(0);
11162 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11164 Info.readMem = true;
11165 Info.writeMem = false;
11168 case Intrinsic::arm_strex: {
11169 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11170 Info.opc = ISD::INTRINSIC_W_CHAIN;
11171 Info.memVT = MVT::getVT(PtrTy->getElementType());
11172 Info.ptrVal = I.getArgOperand(1);
11174 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11176 Info.readMem = false;
11177 Info.writeMem = true;
11180 case Intrinsic::arm_strexd: {
11181 Info.opc = ISD::INTRINSIC_W_CHAIN;
11182 Info.memVT = MVT::i64;
11183 Info.ptrVal = I.getArgOperand(2);
11187 Info.readMem = false;
11188 Info.writeMem = true;
11191 case Intrinsic::arm_ldrexd: {
11192 Info.opc = ISD::INTRINSIC_W_CHAIN;
11193 Info.memVT = MVT::i64;
11194 Info.ptrVal = I.getArgOperand(0);
11198 Info.readMem = true;
11199 Info.writeMem = false;
11209 /// \brief Returns true if it is beneficial to convert a load of a constant
11210 /// to just the constant itself.
11211 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11213 assert(Ty->isIntegerTy());
11215 unsigned Bits = Ty->getPrimitiveSizeInBits();
11216 if (Bits == 0 || Bits > 32)