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"
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57 // This option should go away when tail calls fully work.
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65 cl::desc("Generate calls via indirect call instructions"),
69 ARMInterworking("arm-interworking", cl::Hidden,
70 cl::desc("Enable / disable ARM interworking (for debugging only)"),
74 class ARMCCState : public CCState {
76 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
78 LLVMContext &C, ParmContext PC)
79 : CCState(CC, isVarArg, MF, TM, locs, C) {
80 assert(((PC == Call) || (PC == Prologue)) &&
81 "ARMCCState users must specify whether their context is call"
82 "or prologue generation.");
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90 ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94 MVT PromotedBitwiseVT) {
95 if (VT != PromotedLdStVT) {
96 setOperationAction(ISD::LOAD, VT, Promote);
97 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99 setOperationAction(ISD::STORE, VT, Promote);
100 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103 MVT ElemTy = VT.getVectorElementType();
104 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105 setOperationAction(ISD::SETCC, VT, Custom);
106 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108 if (ElemTy == MVT::i32) {
109 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
120 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
121 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
122 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123 setOperationAction(ISD::SELECT, VT, Expand);
124 setOperationAction(ISD::SELECT_CC, VT, Expand);
125 setOperationAction(ISD::VSELECT, VT, Expand);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127 if (VT.isInteger()) {
128 setOperationAction(ISD::SHL, VT, Custom);
129 setOperationAction(ISD::SRA, VT, Custom);
130 setOperationAction(ISD::SRL, VT, Custom);
133 // Promote all bit-wise operations.
134 if (VT.isInteger() && VT != PromotedBitwiseVT) {
135 setOperationAction(ISD::AND, VT, Promote);
136 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137 setOperationAction(ISD::OR, VT, Promote);
138 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
139 setOperationAction(ISD::XOR, VT, Promote);
140 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
143 // Neon does not support vector divide/remainder operations.
144 setOperationAction(ISD::SDIV, VT, Expand);
145 setOperationAction(ISD::UDIV, VT, Expand);
146 setOperationAction(ISD::FDIV, VT, Expand);
147 setOperationAction(ISD::SREM, VT, Expand);
148 setOperationAction(ISD::UREM, VT, Expand);
149 setOperationAction(ISD::FREM, VT, Expand);
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPRRegClass);
154 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::QPRRegClass);
159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164 return new TargetLoweringObjectFileMachO();
166 return new ARMElfTargetObjectFile();
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170 : TargetLowering(TM, createTLOF(TM)) {
171 Subtarget = &TM.getSubtarget<ARMSubtarget>();
172 RegInfo = TM.getRegisterInfo();
173 Itins = TM.getInstrItineraryData();
175 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177 if (Subtarget->isTargetDarwin()) {
178 // Uses VFP for Thumb libfuncs if available.
179 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180 // Single-precision floating-point arithmetic.
181 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
186 // Double-precision floating-point arithmetic.
187 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
192 // Single-precision comparisons.
193 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
200 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
202 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
211 // Double-precision comparisons.
212 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
219 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
221 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
230 // Floating-point to integer conversions.
231 // i64 conversions are done via library routines even when generating VFP
232 // instructions, so use the same ones.
233 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
238 // Conversions between floating types.
239 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
242 // Integer to floating-point conversions.
243 // i64 conversions are done via library routines even when generating VFP
244 // instructions, so use the same ones.
245 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246 // e.g., __floatunsidf vs. __floatunssidfvfp.
247 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
254 // These libcalls are not available in 32-bit.
255 setLibcallName(RTLIB::SHL_I128, 0);
256 setLibcallName(RTLIB::SRL_I128, 0);
257 setLibcallName(RTLIB::SRA_I128, 0);
259 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260 // Double-precision floating-point arithmetic helper functions
261 // RTABI chapter 4.1.2, Table 2
262 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
271 // Double-precision floating-point comparison helper functions
272 // RTABI chapter 4.1.2, Table 3
273 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
286 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
287 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
288 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
289 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
298 // Single-precision floating-point arithmetic helper functions
299 // RTABI chapter 4.1.2, Table 4
300 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
309 // Single-precision floating-point comparison helper functions
310 // RTABI chapter 4.1.2, Table 5
311 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
324 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
325 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
326 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
327 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
336 // Floating-point to integer conversions.
337 // RTABI chapter 4.1.2, Table 6
338 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
355 // Conversions between floating types.
356 // RTABI chapter 4.1.2, Table 7
357 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
359 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
362 // Integer to floating-point conversions.
363 // RTABI chapter 4.1.2, Table 8
364 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381 // Long long helper functions
382 // RTABI chapter 4.2, Table 9
383 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
384 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
394 // Integer division functions
395 // RTABI chapter 4.3.1
396 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
397 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
401 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
414 // RTABI chapter 4.3.4
415 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
416 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
418 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
423 // Use divmod compiler-rt calls for iOS 5.0 and later.
424 if (Subtarget->getTargetTriple().isiOS() &&
425 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
430 if (Subtarget->isThumb1Only())
431 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
433 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435 !Subtarget->isThumb1Only()) {
436 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437 if (!Subtarget->isFPOnlySP())
438 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
440 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
443 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447 setTruncStoreAction((MVT::SimpleValueType)VT,
448 (MVT::SimpleValueType)InnerVT, Expand);
449 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
454 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
457 if (Subtarget->hasNEON()) {
458 addDRTypeForNEON(MVT::v2f32);
459 addDRTypeForNEON(MVT::v8i8);
460 addDRTypeForNEON(MVT::v4i16);
461 addDRTypeForNEON(MVT::v2i32);
462 addDRTypeForNEON(MVT::v1i64);
464 addQRTypeForNEON(MVT::v4f32);
465 addQRTypeForNEON(MVT::v2f64);
466 addQRTypeForNEON(MVT::v16i8);
467 addQRTypeForNEON(MVT::v8i16);
468 addQRTypeForNEON(MVT::v4i32);
469 addQRTypeForNEON(MVT::v2i64);
471 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
472 // neither Neon nor VFP support any arithmetic operations on it.
473 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
474 // supported for v4f32.
475 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
476 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
477 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
478 // FIXME: Code duplication: FDIV and FREM are expanded always, see
479 // ARMTargetLowering::addTypeForNEON method for details.
480 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
481 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
482 // FIXME: Create unittest.
483 // In another words, find a way when "copysign" appears in DAG with vector
485 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
486 // FIXME: Code duplication: SETCC has custom operation action, see
487 // ARMTargetLowering::addTypeForNEON method for details.
488 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
489 // FIXME: Create unittest for FNEG and for FABS.
490 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
491 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
492 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
493 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
494 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
495 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
496 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
497 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
498 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
500 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
501 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
502 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
503 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
504 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
505 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
506 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
507 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
508 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
510 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
511 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
512 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
513 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
514 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
515 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
516 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
518 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
519 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
520 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
521 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
522 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
523 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
524 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
526 // Mark v2f32 intrinsics.
527 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
528 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
529 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
530 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
531 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
532 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
533 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
534 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
535 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
536 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
537 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
538 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
539 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
540 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
541 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
543 // Neon does not support some operations on v1i64 and v2i64 types.
544 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
545 // Custom handling for some quad-vector types to detect VMULL.
546 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
547 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
548 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
549 // Custom handling for some vector types to avoid expensive expansions
550 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
551 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
552 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
553 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
554 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
555 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
556 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
557 // a destination type that is wider than the source, and nor does
558 // it have a FP_TO_[SU]INT instruction with a narrower destination than
560 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
561 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
562 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
563 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
565 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
566 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
568 // Custom expand long extensions to vectors.
569 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
570 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
571 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
572 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
573 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
574 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
575 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
576 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
578 // NEON does not have single instruction CTPOP for vectors with element
579 // types wider than 8-bits. However, custom lowering can leverage the
580 // v8i8/v16i8 vcnt instruction.
581 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
582 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
583 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
584 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
586 // NEON only has FMA instructions as of VFP4.
587 if (!Subtarget->hasVFP4()) {
588 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
589 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
592 setTargetDAGCombine(ISD::INTRINSIC_VOID);
593 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
594 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
595 setTargetDAGCombine(ISD::SHL);
596 setTargetDAGCombine(ISD::SRL);
597 setTargetDAGCombine(ISD::SRA);
598 setTargetDAGCombine(ISD::SIGN_EXTEND);
599 setTargetDAGCombine(ISD::ZERO_EXTEND);
600 setTargetDAGCombine(ISD::ANY_EXTEND);
601 setTargetDAGCombine(ISD::SELECT_CC);
602 setTargetDAGCombine(ISD::BUILD_VECTOR);
603 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
604 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
605 setTargetDAGCombine(ISD::STORE);
606 setTargetDAGCombine(ISD::FP_TO_SINT);
607 setTargetDAGCombine(ISD::FP_TO_UINT);
608 setTargetDAGCombine(ISD::FDIV);
610 // It is legal to extload from v4i8 to v4i16 or v4i32.
611 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
612 MVT::v4i16, MVT::v2i16,
614 for (unsigned i = 0; i < 6; ++i) {
615 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
616 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
617 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
621 // ARM and Thumb2 support UMLAL/SMLAL.
622 if (!Subtarget->isThumb1Only())
623 setTargetDAGCombine(ISD::ADDC);
626 computeRegisterProperties();
628 // ARM does not have f32 extending load.
629 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
631 // ARM does not have i1 sign extending load.
632 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
634 // ARM supports all 4 flavors of integer indexed load / store.
635 if (!Subtarget->isThumb1Only()) {
636 for (unsigned im = (unsigned)ISD::PRE_INC;
637 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
638 setIndexedLoadAction(im, MVT::i1, Legal);
639 setIndexedLoadAction(im, MVT::i8, Legal);
640 setIndexedLoadAction(im, MVT::i16, Legal);
641 setIndexedLoadAction(im, MVT::i32, Legal);
642 setIndexedStoreAction(im, MVT::i1, Legal);
643 setIndexedStoreAction(im, MVT::i8, Legal);
644 setIndexedStoreAction(im, MVT::i16, Legal);
645 setIndexedStoreAction(im, MVT::i32, Legal);
649 // i64 operation support.
650 setOperationAction(ISD::MUL, MVT::i64, Expand);
651 setOperationAction(ISD::MULHU, MVT::i32, Expand);
652 if (Subtarget->isThumb1Only()) {
653 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
654 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
656 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
657 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
658 setOperationAction(ISD::MULHS, MVT::i32, Expand);
660 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
661 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
662 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
663 setOperationAction(ISD::SRL, MVT::i64, Custom);
664 setOperationAction(ISD::SRA, MVT::i64, Custom);
666 if (!Subtarget->isThumb1Only()) {
667 // FIXME: We should do this for Thumb1 as well.
668 setOperationAction(ISD::ADDC, MVT::i32, Custom);
669 setOperationAction(ISD::ADDE, MVT::i32, Custom);
670 setOperationAction(ISD::SUBC, MVT::i32, Custom);
671 setOperationAction(ISD::SUBE, MVT::i32, Custom);
674 // ARM does not have ROTL.
675 setOperationAction(ISD::ROTL, MVT::i32, Expand);
676 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
677 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
678 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
679 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
681 // These just redirect to CTTZ and CTLZ on ARM.
682 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
683 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
685 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
687 // Only ARMv6 has BSWAP.
688 if (!Subtarget->hasV6Ops())
689 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
691 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
692 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
693 // These are expanded into libcalls if the cpu doesn't have HW divider.
694 setOperationAction(ISD::SDIV, MVT::i32, Expand);
695 setOperationAction(ISD::UDIV, MVT::i32, Expand);
698 // FIXME: Also set divmod for SREM on EABI
699 setOperationAction(ISD::SREM, MVT::i32, Expand);
700 setOperationAction(ISD::UREM, MVT::i32, Expand);
701 // Register based DivRem for AEABI (RTABI 4.2)
702 if (Subtarget->isTargetAEABI()) {
703 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
704 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
705 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
706 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
707 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
708 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
709 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
710 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
712 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
713 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
714 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
715 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
716 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
717 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
718 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
719 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
721 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
722 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
724 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
725 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
728 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
729 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
730 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
731 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
732 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
734 setOperationAction(ISD::TRAP, MVT::Other, Legal);
736 // Use the default implementation.
737 setOperationAction(ISD::VASTART, MVT::Other, Custom);
738 setOperationAction(ISD::VAARG, MVT::Other, Expand);
739 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
740 setOperationAction(ISD::VAEND, MVT::Other, Expand);
741 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
742 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
744 if (!Subtarget->isTargetDarwin()) {
745 // Non-Darwin platforms may return values in these registers via the
746 // personality function.
747 setExceptionPointerRegister(ARM::R0);
748 setExceptionSelectorRegister(ARM::R1);
751 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
752 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
753 // the default expansion.
754 // FIXME: This should be checking for v6k, not just v6.
755 if (Subtarget->hasDataBarrier() ||
756 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
757 // membarrier needs custom lowering; the rest are legal and handled
759 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
760 // Custom lowering for 64-bit ops
761 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
762 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
763 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
764 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
765 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
766 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
767 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
768 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
769 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
770 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
771 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
772 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
773 setInsertFencesForAtomic(true);
775 // Set them all for expansion, which will force libcalls.
776 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
777 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
778 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
779 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
780 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
781 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
782 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
783 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
784 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
785 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
786 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
787 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
788 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
789 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
790 // Unordered/Monotonic case.
791 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
792 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
795 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
797 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
798 if (!Subtarget->hasV6Ops()) {
799 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
800 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
802 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
804 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
805 !Subtarget->isThumb1Only()) {
806 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
807 // iff target supports vfp2.
808 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
809 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
812 // We want to custom lower some of our intrinsics.
813 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
814 if (Subtarget->isTargetDarwin()) {
815 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
816 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
817 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
820 setOperationAction(ISD::SETCC, MVT::i32, Expand);
821 setOperationAction(ISD::SETCC, MVT::f32, Expand);
822 setOperationAction(ISD::SETCC, MVT::f64, Expand);
823 setOperationAction(ISD::SELECT, MVT::i32, Custom);
824 setOperationAction(ISD::SELECT, MVT::f32, Custom);
825 setOperationAction(ISD::SELECT, MVT::f64, Custom);
826 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
827 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
828 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
830 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
831 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
832 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
833 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
834 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
836 // We don't support sin/cos/fmod/copysign/pow
837 setOperationAction(ISD::FSIN, MVT::f64, Expand);
838 setOperationAction(ISD::FSIN, MVT::f32, Expand);
839 setOperationAction(ISD::FCOS, MVT::f32, Expand);
840 setOperationAction(ISD::FCOS, MVT::f64, Expand);
841 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
842 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
843 setOperationAction(ISD::FREM, MVT::f64, Expand);
844 setOperationAction(ISD::FREM, MVT::f32, Expand);
845 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
846 !Subtarget->isThumb1Only()) {
847 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
848 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
850 setOperationAction(ISD::FPOW, MVT::f64, Expand);
851 setOperationAction(ISD::FPOW, MVT::f32, Expand);
853 if (!Subtarget->hasVFP4()) {
854 setOperationAction(ISD::FMA, MVT::f64, Expand);
855 setOperationAction(ISD::FMA, MVT::f32, Expand);
858 // Various VFP goodness
859 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
860 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
861 if (Subtarget->hasVFP2()) {
862 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
863 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
864 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
865 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
867 // Special handling for half-precision FP.
868 if (!Subtarget->hasFP16()) {
869 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
870 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
874 // We have target-specific dag combine patterns for the following nodes:
875 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
876 setTargetDAGCombine(ISD::ADD);
877 setTargetDAGCombine(ISD::SUB);
878 setTargetDAGCombine(ISD::MUL);
879 setTargetDAGCombine(ISD::AND);
880 setTargetDAGCombine(ISD::OR);
881 setTargetDAGCombine(ISD::XOR);
883 if (Subtarget->hasV6Ops())
884 setTargetDAGCombine(ISD::SRL);
886 setStackPointerRegisterToSaveRestore(ARM::SP);
888 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
889 !Subtarget->hasVFP2())
890 setSchedulingPreference(Sched::RegPressure);
892 setSchedulingPreference(Sched::Hybrid);
894 //// temporary - rewrite interface to use type
895 MaxStoresPerMemset = 8;
896 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
897 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
898 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
899 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
900 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
902 // On ARM arguments smaller than 4 bytes are extended, so all arguments
903 // are at least 4 bytes aligned.
904 setMinStackArgumentAlignment(4);
906 // Prefer likely predicted branches to selects on out-of-order cores.
907 PredictableSelectIsExpensive = Subtarget->isLikeA9();
909 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
912 // FIXME: It might make sense to define the representative register class as the
913 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
914 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
915 // SPR's representative would be DPR_VFP2. This should work well if register
916 // pressure tracking were modified such that a register use would increment the
917 // pressure of the register class's representative and all of it's super
918 // classes' representatives transitively. We have not implemented this because
919 // of the difficulty prior to coalescing of modeling operand register classes
920 // due to the common occurrence of cross class copies and subregister insertions
922 std::pair<const TargetRegisterClass*, uint8_t>
923 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
924 const TargetRegisterClass *RRC = 0;
926 switch (VT.SimpleTy) {
928 return TargetLowering::findRepresentativeClass(VT);
929 // Use DPR as representative register class for all floating point
930 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
931 // the cost is 1 for both f32 and f64.
932 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
933 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
934 RRC = &ARM::DPRRegClass;
935 // When NEON is used for SP, only half of the register file is available
936 // because operations that define both SP and DP results will be constrained
937 // to the VFP2 class (D0-D15). We currently model this constraint prior to
938 // coalescing by double-counting the SP regs. See the FIXME above.
939 if (Subtarget->useNEONForSinglePrecisionFP())
942 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
943 case MVT::v4f32: case MVT::v2f64:
944 RRC = &ARM::DPRRegClass;
948 RRC = &ARM::DPRRegClass;
952 RRC = &ARM::DPRRegClass;
956 return std::make_pair(RRC, Cost);
959 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
962 case ARMISD::Wrapper: return "ARMISD::Wrapper";
963 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
964 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
965 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
966 case ARMISD::CALL: return "ARMISD::CALL";
967 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
968 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
969 case ARMISD::tCALL: return "ARMISD::tCALL";
970 case ARMISD::BRCOND: return "ARMISD::BRCOND";
971 case ARMISD::BR_JT: return "ARMISD::BR_JT";
972 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
973 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
974 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
975 case ARMISD::CMP: return "ARMISD::CMP";
976 case ARMISD::CMN: return "ARMISD::CMN";
977 case ARMISD::CMPZ: return "ARMISD::CMPZ";
978 case ARMISD::CMPFP: return "ARMISD::CMPFP";
979 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
980 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
981 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
983 case ARMISD::CMOV: return "ARMISD::CMOV";
985 case ARMISD::RBIT: return "ARMISD::RBIT";
987 case ARMISD::FTOSI: return "ARMISD::FTOSI";
988 case ARMISD::FTOUI: return "ARMISD::FTOUI";
989 case ARMISD::SITOF: return "ARMISD::SITOF";
990 case ARMISD::UITOF: return "ARMISD::UITOF";
992 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
993 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
994 case ARMISD::RRX: return "ARMISD::RRX";
996 case ARMISD::ADDC: return "ARMISD::ADDC";
997 case ARMISD::ADDE: return "ARMISD::ADDE";
998 case ARMISD::SUBC: return "ARMISD::SUBC";
999 case ARMISD::SUBE: return "ARMISD::SUBE";
1001 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1002 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1004 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1005 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1007 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1009 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1011 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1013 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1015 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1017 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1018 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1019 case ARMISD::VCGE: return "ARMISD::VCGE";
1020 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1021 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1022 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1023 case ARMISD::VCGT: return "ARMISD::VCGT";
1024 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1025 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1026 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1027 case ARMISD::VTST: return "ARMISD::VTST";
1029 case ARMISD::VSHL: return "ARMISD::VSHL";
1030 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1031 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1032 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1033 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1034 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1035 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1036 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1037 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1038 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1039 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1040 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1041 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1042 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1043 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1044 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1045 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1046 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1047 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1048 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1049 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1050 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1051 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1052 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1053 case ARMISD::VDUP: return "ARMISD::VDUP";
1054 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1055 case ARMISD::VEXT: return "ARMISD::VEXT";
1056 case ARMISD::VREV64: return "ARMISD::VREV64";
1057 case ARMISD::VREV32: return "ARMISD::VREV32";
1058 case ARMISD::VREV16: return "ARMISD::VREV16";
1059 case ARMISD::VZIP: return "ARMISD::VZIP";
1060 case ARMISD::VUZP: return "ARMISD::VUZP";
1061 case ARMISD::VTRN: return "ARMISD::VTRN";
1062 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1063 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1064 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1065 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1066 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1067 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1068 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1069 case ARMISD::FMAX: return "ARMISD::FMAX";
1070 case ARMISD::FMIN: return "ARMISD::FMIN";
1071 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1072 case ARMISD::VMINNM: return "ARMISD::VMIN";
1073 case ARMISD::BFI: return "ARMISD::BFI";
1074 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1075 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1076 case ARMISD::VBSL: return "ARMISD::VBSL";
1077 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1078 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1079 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1080 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1081 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1082 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1083 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1084 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1085 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1086 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1087 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1088 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1089 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1090 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1091 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1092 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1093 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1094 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1095 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1096 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1098 case ARMISD::ATOMADD64_DAG: return "ATOMADD64_DAG";
1099 case ARMISD::ATOMSUB64_DAG: return "ATOMSUB64_DAG";
1100 case ARMISD::ATOMOR64_DAG: return "ATOMOR64_DAG";
1101 case ARMISD::ATOMXOR64_DAG: return "ATOMXOR64_DAG";
1102 case ARMISD::ATOMAND64_DAG: return "ATOMAND64_DAG";
1103 case ARMISD::ATOMNAND64_DAG: return "ATOMNAND64_DAG";
1104 case ARMISD::ATOMSWAP64_DAG: return "ATOMSWAP64_DAG";
1105 case ARMISD::ATOMCMPXCHG64_DAG: return "ATOMCMPXCHG64_DAG";
1106 case ARMISD::ATOMMIN64_DAG: return "ATOMMIN64_DAG";
1107 case ARMISD::ATOMUMIN64_DAG: return "ATOMUMIN64_DAG";
1108 case ARMISD::ATOMMAX64_DAG: return "ATOMMAX64_DAG";
1109 case ARMISD::ATOMUMAX64_DAG: return "ATOMUMAX64_DAG";
1113 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1114 if (!VT.isVector()) return getPointerTy();
1115 return VT.changeVectorElementTypeToInteger();
1118 /// getRegClassFor - Return the register class that should be used for the
1119 /// specified value type.
1120 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1121 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1122 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1123 // load / store 4 to 8 consecutive D registers.
1124 if (Subtarget->hasNEON()) {
1125 if (VT == MVT::v4i64)
1126 return &ARM::QQPRRegClass;
1127 if (VT == MVT::v8i64)
1128 return &ARM::QQQQPRRegClass;
1130 return TargetLowering::getRegClassFor(VT);
1133 // Create a fast isel object.
1135 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1136 const TargetLibraryInfo *libInfo) const {
1137 return ARM::createFastISel(funcInfo, libInfo);
1140 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1141 /// be used for loads / stores from the global.
1142 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1143 return (Subtarget->isThumb1Only() ? 127 : 4095);
1146 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1147 unsigned NumVals = N->getNumValues();
1149 return Sched::RegPressure;
1151 for (unsigned i = 0; i != NumVals; ++i) {
1152 EVT VT = N->getValueType(i);
1153 if (VT == MVT::Glue || VT == MVT::Other)
1155 if (VT.isFloatingPoint() || VT.isVector())
1159 if (!N->isMachineOpcode())
1160 return Sched::RegPressure;
1162 // Load are scheduled for latency even if there instruction itinerary
1163 // is not available.
1164 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1165 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1167 if (MCID.getNumDefs() == 0)
1168 return Sched::RegPressure;
1169 if (!Itins->isEmpty() &&
1170 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1173 return Sched::RegPressure;
1176 //===----------------------------------------------------------------------===//
1178 //===----------------------------------------------------------------------===//
1180 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1181 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1183 default: llvm_unreachable("Unknown condition code!");
1184 case ISD::SETNE: return ARMCC::NE;
1185 case ISD::SETEQ: return ARMCC::EQ;
1186 case ISD::SETGT: return ARMCC::GT;
1187 case ISD::SETGE: return ARMCC::GE;
1188 case ISD::SETLT: return ARMCC::LT;
1189 case ISD::SETLE: return ARMCC::LE;
1190 case ISD::SETUGT: return ARMCC::HI;
1191 case ISD::SETUGE: return ARMCC::HS;
1192 case ISD::SETULT: return ARMCC::LO;
1193 case ISD::SETULE: return ARMCC::LS;
1197 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1198 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1199 ARMCC::CondCodes &CondCode2) {
1200 CondCode2 = ARMCC::AL;
1202 default: llvm_unreachable("Unknown FP condition!");
1204 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1206 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1208 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1209 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1210 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1211 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1212 case ISD::SETO: CondCode = ARMCC::VC; break;
1213 case ISD::SETUO: CondCode = ARMCC::VS; break;
1214 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1215 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1216 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1218 case ISD::SETULT: CondCode = ARMCC::LT; break;
1220 case ISD::SETULE: CondCode = ARMCC::LE; break;
1222 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1226 //===----------------------------------------------------------------------===//
1227 // Calling Convention Implementation
1228 //===----------------------------------------------------------------------===//
1230 #include "ARMGenCallingConv.inc"
1232 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1233 /// given CallingConvention value.
1234 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1236 bool isVarArg) const {
1239 llvm_unreachable("Unsupported calling convention");
1240 case CallingConv::Fast:
1241 if (Subtarget->hasVFP2() && !isVarArg) {
1242 if (!Subtarget->isAAPCS_ABI())
1243 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1244 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1245 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1248 case CallingConv::C: {
1249 // Use target triple & subtarget features to do actual dispatch.
1250 if (!Subtarget->isAAPCS_ABI())
1251 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1252 else if (Subtarget->hasVFP2() &&
1253 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1255 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1256 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1258 case CallingConv::ARM_AAPCS_VFP:
1260 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1262 case CallingConv::ARM_AAPCS:
1263 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1264 case CallingConv::ARM_APCS:
1265 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1266 case CallingConv::GHC:
1267 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1271 /// LowerCallResult - Lower the result values of a call into the
1272 /// appropriate copies out of appropriate physical registers.
1274 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1275 CallingConv::ID CallConv, bool isVarArg,
1276 const SmallVectorImpl<ISD::InputArg> &Ins,
1277 SDLoc dl, SelectionDAG &DAG,
1278 SmallVectorImpl<SDValue> &InVals,
1279 bool isThisReturn, SDValue ThisVal) const {
1281 // Assign locations to each value returned by this call.
1282 SmallVector<CCValAssign, 16> RVLocs;
1283 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1284 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1285 CCInfo.AnalyzeCallResult(Ins,
1286 CCAssignFnForNode(CallConv, /* Return*/ true,
1289 // Copy all of the result registers out of their specified physreg.
1290 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1291 CCValAssign VA = RVLocs[i];
1293 // Pass 'this' value directly from the argument to return value, to avoid
1294 // reg unit interference
1295 if (i == 0 && isThisReturn) {
1296 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1297 "unexpected return calling convention register assignment");
1298 InVals.push_back(ThisVal);
1303 if (VA.needsCustom()) {
1304 // Handle f64 or half of a v2f64.
1305 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1307 Chain = Lo.getValue(1);
1308 InFlag = Lo.getValue(2);
1309 VA = RVLocs[++i]; // skip ahead to next loc
1310 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1312 Chain = Hi.getValue(1);
1313 InFlag = Hi.getValue(2);
1314 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1316 if (VA.getLocVT() == MVT::v2f64) {
1317 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1318 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1319 DAG.getConstant(0, MVT::i32));
1321 VA = RVLocs[++i]; // skip ahead to next loc
1322 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1323 Chain = Lo.getValue(1);
1324 InFlag = Lo.getValue(2);
1325 VA = RVLocs[++i]; // skip ahead to next loc
1326 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1327 Chain = Hi.getValue(1);
1328 InFlag = Hi.getValue(2);
1329 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1330 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1331 DAG.getConstant(1, MVT::i32));
1334 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1336 Chain = Val.getValue(1);
1337 InFlag = Val.getValue(2);
1340 switch (VA.getLocInfo()) {
1341 default: llvm_unreachable("Unknown loc info!");
1342 case CCValAssign::Full: break;
1343 case CCValAssign::BCvt:
1344 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1348 InVals.push_back(Val);
1354 /// LowerMemOpCallTo - Store the argument to the stack.
1356 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1357 SDValue StackPtr, SDValue Arg,
1358 SDLoc dl, SelectionDAG &DAG,
1359 const CCValAssign &VA,
1360 ISD::ArgFlagsTy Flags) const {
1361 unsigned LocMemOffset = VA.getLocMemOffset();
1362 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1363 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1364 return DAG.getStore(Chain, dl, Arg, PtrOff,
1365 MachinePointerInfo::getStack(LocMemOffset),
1369 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1370 SDValue Chain, SDValue &Arg,
1371 RegsToPassVector &RegsToPass,
1372 CCValAssign &VA, CCValAssign &NextVA,
1374 SmallVectorImpl<SDValue> &MemOpChains,
1375 ISD::ArgFlagsTy Flags) const {
1377 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1378 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1379 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1381 if (NextVA.isRegLoc())
1382 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1384 assert(NextVA.isMemLoc());
1385 if (StackPtr.getNode() == 0)
1386 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1388 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1394 /// LowerCall - Lowering a call into a callseq_start <-
1395 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1398 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1399 SmallVectorImpl<SDValue> &InVals) const {
1400 SelectionDAG &DAG = CLI.DAG;
1402 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1403 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1404 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1405 SDValue Chain = CLI.Chain;
1406 SDValue Callee = CLI.Callee;
1407 bool &isTailCall = CLI.IsTailCall;
1408 CallingConv::ID CallConv = CLI.CallConv;
1409 bool doesNotRet = CLI.DoesNotReturn;
1410 bool isVarArg = CLI.IsVarArg;
1412 MachineFunction &MF = DAG.getMachineFunction();
1413 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1414 bool isThisReturn = false;
1415 bool isSibCall = false;
1416 // Disable tail calls if they're not supported.
1417 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1420 // Check if it's really possible to do a tail call.
1421 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1422 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1423 Outs, OutVals, Ins, DAG);
1424 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1425 // detected sibcalls.
1432 // Analyze operands of the call, assigning locations to each operand.
1433 SmallVector<CCValAssign, 16> ArgLocs;
1434 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1435 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1436 CCInfo.AnalyzeCallOperands(Outs,
1437 CCAssignFnForNode(CallConv, /* Return*/ false,
1440 // Get a count of how many bytes are to be pushed on the stack.
1441 unsigned NumBytes = CCInfo.getNextStackOffset();
1443 // For tail calls, memory operands are available in our caller's stack.
1447 // Adjust the stack pointer for the new arguments...
1448 // These operations are automatically eliminated by the prolog/epilog pass
1450 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1453 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1455 RegsToPassVector RegsToPass;
1456 SmallVector<SDValue, 8> MemOpChains;
1458 // Walk the register/memloc assignments, inserting copies/loads. In the case
1459 // of tail call optimization, arguments are handled later.
1460 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1462 ++i, ++realArgIdx) {
1463 CCValAssign &VA = ArgLocs[i];
1464 SDValue Arg = OutVals[realArgIdx];
1465 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1466 bool isByVal = Flags.isByVal();
1468 // Promote the value if needed.
1469 switch (VA.getLocInfo()) {
1470 default: llvm_unreachable("Unknown loc info!");
1471 case CCValAssign::Full: break;
1472 case CCValAssign::SExt:
1473 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1475 case CCValAssign::ZExt:
1476 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1478 case CCValAssign::AExt:
1479 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1481 case CCValAssign::BCvt:
1482 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1486 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1487 if (VA.needsCustom()) {
1488 if (VA.getLocVT() == MVT::v2f64) {
1489 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1490 DAG.getConstant(0, MVT::i32));
1491 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1492 DAG.getConstant(1, MVT::i32));
1494 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1495 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1497 VA = ArgLocs[++i]; // skip ahead to next loc
1498 if (VA.isRegLoc()) {
1499 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1500 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1502 assert(VA.isMemLoc());
1504 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1505 dl, DAG, VA, Flags));
1508 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1509 StackPtr, MemOpChains, Flags);
1511 } else if (VA.isRegLoc()) {
1512 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1513 assert(VA.getLocVT() == MVT::i32 &&
1514 "unexpected calling convention register assignment");
1515 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1516 "unexpected use of 'returned'");
1517 isThisReturn = true;
1519 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1520 } else if (isByVal) {
1521 assert(VA.isMemLoc());
1522 unsigned offset = 0;
1524 // True if this byval aggregate will be split between registers
1526 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1527 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1529 if (CurByValIdx < ByValArgsCount) {
1531 unsigned RegBegin, RegEnd;
1532 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1534 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1536 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1537 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1538 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1539 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1540 MachinePointerInfo(),
1541 false, false, false, 0);
1542 MemOpChains.push_back(Load.getValue(1));
1543 RegsToPass.push_back(std::make_pair(j, Load));
1546 // If parameter size outsides register area, "offset" value
1547 // helps us to calculate stack slot for remained part properly.
1548 offset = RegEnd - RegBegin;
1550 CCInfo.nextInRegsParam();
1553 if (Flags.getByValSize() > 4*offset) {
1554 unsigned LocMemOffset = VA.getLocMemOffset();
1555 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1556 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1558 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1559 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1560 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1562 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1564 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1565 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1566 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1567 Ops, array_lengthof(Ops)));
1569 } else if (!isSibCall) {
1570 assert(VA.isMemLoc());
1572 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1573 dl, DAG, VA, Flags));
1577 if (!MemOpChains.empty())
1578 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1579 &MemOpChains[0], MemOpChains.size());
1581 // Build a sequence of copy-to-reg nodes chained together with token chain
1582 // and flag operands which copy the outgoing args into the appropriate regs.
1584 // Tail call byval lowering might overwrite argument registers so in case of
1585 // tail call optimization the copies to registers are lowered later.
1587 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1588 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1589 RegsToPass[i].second, InFlag);
1590 InFlag = Chain.getValue(1);
1593 // For tail calls lower the arguments to the 'real' stack slot.
1595 // Force all the incoming stack arguments to be loaded from the stack
1596 // before any new outgoing arguments are stored to the stack, because the
1597 // outgoing stack slots may alias the incoming argument stack slots, and
1598 // the alias isn't otherwise explicit. This is slightly more conservative
1599 // than necessary, because it means that each store effectively depends
1600 // on every argument instead of just those arguments it would clobber.
1602 // Do not flag preceding copytoreg stuff together with the following stuff.
1604 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1605 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1606 RegsToPass[i].second, InFlag);
1607 InFlag = Chain.getValue(1);
1612 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1613 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1614 // node so that legalize doesn't hack it.
1615 bool isDirect = false;
1616 bool isARMFunc = false;
1617 bool isLocalARMFunc = false;
1618 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1620 if (EnableARMLongCalls) {
1621 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1622 && "long-calls with non-static relocation model!");
1623 // Handle a global address or an external symbol. If it's not one of
1624 // those, the target's already in a register, so we don't need to do
1626 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1627 const GlobalValue *GV = G->getGlobal();
1628 // Create a constant pool entry for the callee address
1629 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1630 ARMConstantPoolValue *CPV =
1631 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1633 // Get the address of the callee into a register
1634 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1635 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1636 Callee = DAG.getLoad(getPointerTy(), dl,
1637 DAG.getEntryNode(), CPAddr,
1638 MachinePointerInfo::getConstantPool(),
1639 false, false, false, 0);
1640 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1641 const char *Sym = S->getSymbol();
1643 // Create a constant pool entry for the callee address
1644 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1645 ARMConstantPoolValue *CPV =
1646 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1647 ARMPCLabelIndex, 0);
1648 // Get the address of the callee into a register
1649 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1650 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1651 Callee = DAG.getLoad(getPointerTy(), dl,
1652 DAG.getEntryNode(), CPAddr,
1653 MachinePointerInfo::getConstantPool(),
1654 false, false, false, 0);
1656 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1657 const GlobalValue *GV = G->getGlobal();
1659 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1660 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1661 getTargetMachine().getRelocationModel() != Reloc::Static;
1662 isARMFunc = !Subtarget->isThumb() || isStub;
1663 // ARM call to a local ARM function is predicable.
1664 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1665 // tBX takes a register source operand.
1666 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1667 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1668 ARMConstantPoolValue *CPV =
1669 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1670 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1671 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1672 Callee = DAG.getLoad(getPointerTy(), dl,
1673 DAG.getEntryNode(), CPAddr,
1674 MachinePointerInfo::getConstantPool(),
1675 false, false, false, 0);
1676 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1677 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1678 getPointerTy(), Callee, PICLabel);
1680 // On ELF targets for PIC code, direct calls should go through the PLT
1681 unsigned OpFlags = 0;
1682 if (Subtarget->isTargetELF() &&
1683 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1684 OpFlags = ARMII::MO_PLT;
1685 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1687 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1689 bool isStub = Subtarget->isTargetDarwin() &&
1690 getTargetMachine().getRelocationModel() != Reloc::Static;
1691 isARMFunc = !Subtarget->isThumb() || isStub;
1692 // tBX takes a register source operand.
1693 const char *Sym = S->getSymbol();
1694 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1695 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1696 ARMConstantPoolValue *CPV =
1697 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1698 ARMPCLabelIndex, 4);
1699 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1700 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1701 Callee = DAG.getLoad(getPointerTy(), dl,
1702 DAG.getEntryNode(), CPAddr,
1703 MachinePointerInfo::getConstantPool(),
1704 false, false, false, 0);
1705 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1706 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1707 getPointerTy(), Callee, PICLabel);
1709 unsigned OpFlags = 0;
1710 // On ELF targets for PIC code, direct calls should go through the PLT
1711 if (Subtarget->isTargetELF() &&
1712 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1713 OpFlags = ARMII::MO_PLT;
1714 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1718 // FIXME: handle tail calls differently.
1720 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1721 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1722 if (Subtarget->isThumb()) {
1723 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1724 CallOpc = ARMISD::CALL_NOLINK;
1726 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1728 if (!isDirect && !Subtarget->hasV5TOps())
1729 CallOpc = ARMISD::CALL_NOLINK;
1730 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1731 // Emit regular call when code size is the priority
1733 // "mov lr, pc; b _foo" to avoid confusing the RSP
1734 CallOpc = ARMISD::CALL_NOLINK;
1736 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1739 std::vector<SDValue> Ops;
1740 Ops.push_back(Chain);
1741 Ops.push_back(Callee);
1743 // Add argument registers to the end of the list so that they are known live
1745 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1746 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1747 RegsToPass[i].second.getValueType()));
1749 // Add a register mask operand representing the call-preserved registers.
1750 const uint32_t *Mask;
1751 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1752 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1754 // For 'this' returns, use the R0-preserving mask if applicable
1755 Mask = ARI->getThisReturnPreservedMask(CallConv);
1757 // Set isThisReturn to false if the calling convention is not one that
1758 // allows 'returned' to be modeled in this way, so LowerCallResult does
1759 // not try to pass 'this' straight through
1760 isThisReturn = false;
1761 Mask = ARI->getCallPreservedMask(CallConv);
1764 Mask = ARI->getCallPreservedMask(CallConv);
1766 assert(Mask && "Missing call preserved mask for calling convention");
1767 Ops.push_back(DAG.getRegisterMask(Mask));
1769 if (InFlag.getNode())
1770 Ops.push_back(InFlag);
1772 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1774 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1776 // Returns a chain and a flag for retval copy to use.
1777 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1778 InFlag = Chain.getValue(1);
1780 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1781 DAG.getIntPtrConstant(0, true), InFlag, dl);
1783 InFlag = Chain.getValue(1);
1785 // Handle result values, copying them out of physregs into vregs that we
1787 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1788 InVals, isThisReturn,
1789 isThisReturn ? OutVals[0] : SDValue());
1792 /// HandleByVal - Every parameter *after* a byval parameter is passed
1793 /// on the stack. Remember the next parameter register to allocate,
1794 /// and then confiscate the rest of the parameter registers to insure
1797 ARMTargetLowering::HandleByVal(
1798 CCState *State, unsigned &size, unsigned Align) const {
1799 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1800 assert((State->getCallOrPrologue() == Prologue ||
1801 State->getCallOrPrologue() == Call) &&
1802 "unhandled ParmContext");
1804 // For in-prologue parameters handling, we also introduce stack offset
1805 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1806 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1807 // NSAA should be evaluted (NSAA means "next stacked argument address").
1808 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1809 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1810 unsigned NSAAOffset = State->getNextStackOffset();
1811 if (State->getCallOrPrologue() != Call) {
1812 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1814 State->getInRegsParamInfo(i, RB, RE);
1815 assert(NSAAOffset >= (RE-RB)*4 &&
1816 "Stack offset for byval regs doesn't introduced anymore?");
1817 NSAAOffset -= (RE-RB)*4;
1820 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1821 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1822 unsigned AlignInRegs = Align / 4;
1823 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1824 for (unsigned i = 0; i < Waste; ++i)
1825 reg = State->AllocateReg(GPRArgRegs, 4);
1828 unsigned excess = 4 * (ARM::R4 - reg);
1830 // Special case when NSAA != SP and parameter size greater than size of
1831 // all remained GPR regs. In that case we can't split parameter, we must
1832 // send it to stack. We also must set NCRN to R4, so waste all
1833 // remained registers.
1834 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1835 while (State->AllocateReg(GPRArgRegs, 4))
1840 // First register for byval parameter is the first register that wasn't
1841 // allocated before this method call, so it would be "reg".
1842 // If parameter is small enough to be saved in range [reg, r4), then
1843 // the end (first after last) register would be reg + param-size-in-regs,
1844 // else parameter would be splitted between registers and stack,
1845 // end register would be r4 in this case.
1846 unsigned ByValRegBegin = reg;
1847 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1848 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1849 // Note, first register is allocated in the beginning of function already,
1850 // allocate remained amount of registers we need.
1851 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1852 State->AllocateReg(GPRArgRegs, 4);
1853 // At a call site, a byval parameter that is split between
1854 // registers and memory needs its size truncated here. In a
1855 // function prologue, such byval parameters are reassembled in
1856 // memory, and are not truncated.
1857 if (State->getCallOrPrologue() == Call) {
1858 // Make remained size equal to 0 in case, when
1859 // the whole structure may be stored into registers.
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 // Also avoid sibcall optimization if either caller or callee uses struct
1939 // return semantics.
1940 if (isCalleeStructRet || isCallerStructRet)
1943 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1944 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1945 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1946 // support in the assembler and linker to be used. This would need to be
1947 // fixed to fully support tail calls in Thumb1.
1949 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1950 // LR. This means if we need to reload LR, it takes an extra instructions,
1951 // which outweighs the value of the tail call; but here we don't know yet
1952 // whether LR is going to be used. Probably the right approach is to
1953 // generate the tail call here and turn it back into CALL/RET in
1954 // emitEpilogue if LR is used.
1956 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1957 // but we need to make sure there are enough registers; the only valid
1958 // registers are the 4 used for parameters. We don't currently do this
1960 if (Subtarget->isThumb1Only())
1963 // If the calling conventions do not match, then we'd better make sure the
1964 // results are returned in the same way as what the caller expects.
1966 SmallVector<CCValAssign, 16> RVLocs1;
1967 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1968 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1969 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1971 SmallVector<CCValAssign, 16> RVLocs2;
1972 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1973 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1974 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1976 if (RVLocs1.size() != RVLocs2.size())
1978 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1979 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1981 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1983 if (RVLocs1[i].isRegLoc()) {
1984 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1987 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1993 // If Caller's vararg or byval argument has been split between registers and
1994 // stack, do not perform tail call, since part of the argument is in caller's
1996 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1997 getInfo<ARMFunctionInfo>();
1998 if (AFI_Caller->getArgRegsSaveSize())
2001 // If the callee takes no arguments then go on to check the results of the
2003 if (!Outs.empty()) {
2004 // Check if stack adjustment is needed. For now, do not do this if any
2005 // argument is passed on the stack.
2006 SmallVector<CCValAssign, 16> ArgLocs;
2007 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2008 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2009 CCInfo.AnalyzeCallOperands(Outs,
2010 CCAssignFnForNode(CalleeCC, false, isVarArg));
2011 if (CCInfo.getNextStackOffset()) {
2012 MachineFunction &MF = DAG.getMachineFunction();
2014 // Check if the arguments are already laid out in the right way as
2015 // the caller's fixed stack objects.
2016 MachineFrameInfo *MFI = MF.getFrameInfo();
2017 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2018 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2019 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2021 ++i, ++realArgIdx) {
2022 CCValAssign &VA = ArgLocs[i];
2023 EVT RegVT = VA.getLocVT();
2024 SDValue Arg = OutVals[realArgIdx];
2025 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2026 if (VA.getLocInfo() == CCValAssign::Indirect)
2028 if (VA.needsCustom()) {
2029 // f64 and vector types are split into multiple registers or
2030 // register/stack-slot combinations. The types will not match
2031 // the registers; give up on memory f64 refs until we figure
2032 // out what to do about this.
2035 if (!ArgLocs[++i].isRegLoc())
2037 if (RegVT == MVT::v2f64) {
2038 if (!ArgLocs[++i].isRegLoc())
2040 if (!ArgLocs[++i].isRegLoc())
2043 } else if (!VA.isRegLoc()) {
2044 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2056 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2057 MachineFunction &MF, bool isVarArg,
2058 const SmallVectorImpl<ISD::OutputArg> &Outs,
2059 LLVMContext &Context) const {
2060 SmallVector<CCValAssign, 16> RVLocs;
2061 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2062 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2067 ARMTargetLowering::LowerReturn(SDValue Chain,
2068 CallingConv::ID CallConv, bool isVarArg,
2069 const SmallVectorImpl<ISD::OutputArg> &Outs,
2070 const SmallVectorImpl<SDValue> &OutVals,
2071 SDLoc dl, SelectionDAG &DAG) const {
2073 // CCValAssign - represent the assignment of the return value to a location.
2074 SmallVector<CCValAssign, 16> RVLocs;
2076 // CCState - Info about the registers and stack slots.
2077 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2078 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2080 // Analyze outgoing return values.
2081 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2085 SmallVector<SDValue, 4> RetOps;
2086 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2088 // Copy the result values into the output registers.
2089 for (unsigned i = 0, realRVLocIdx = 0;
2091 ++i, ++realRVLocIdx) {
2092 CCValAssign &VA = RVLocs[i];
2093 assert(VA.isRegLoc() && "Can only return in registers!");
2095 SDValue Arg = OutVals[realRVLocIdx];
2097 switch (VA.getLocInfo()) {
2098 default: llvm_unreachable("Unknown loc info!");
2099 case CCValAssign::Full: break;
2100 case CCValAssign::BCvt:
2101 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2105 if (VA.needsCustom()) {
2106 if (VA.getLocVT() == MVT::v2f64) {
2107 // Extract the first half and return it in two registers.
2108 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2109 DAG.getConstant(0, MVT::i32));
2110 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2111 DAG.getVTList(MVT::i32, MVT::i32), Half);
2113 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2114 Flag = Chain.getValue(1);
2115 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2116 VA = RVLocs[++i]; // skip ahead to next loc
2117 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2118 HalfGPRs.getValue(1), Flag);
2119 Flag = Chain.getValue(1);
2120 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2121 VA = RVLocs[++i]; // skip ahead to next loc
2123 // Extract the 2nd half and fall through to handle it as an f64 value.
2124 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2125 DAG.getConstant(1, MVT::i32));
2127 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2129 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2130 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2131 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2132 Flag = Chain.getValue(1);
2133 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2134 VA = RVLocs[++i]; // skip ahead to next loc
2135 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2138 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2140 // Guarantee that all emitted copies are
2141 // stuck together, avoiding something bad.
2142 Flag = Chain.getValue(1);
2143 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2146 // Update chain and glue.
2149 RetOps.push_back(Flag);
2151 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2152 RetOps.data(), RetOps.size());
2155 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2156 if (N->getNumValues() != 1)
2158 if (!N->hasNUsesOfValue(1, 0))
2161 SDValue TCChain = Chain;
2162 SDNode *Copy = *N->use_begin();
2163 if (Copy->getOpcode() == ISD::CopyToReg) {
2164 // If the copy has a glue operand, we conservatively assume it isn't safe to
2165 // perform a tail call.
2166 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2168 TCChain = Copy->getOperand(0);
2169 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2170 SDNode *VMov = Copy;
2171 // f64 returned in a pair of GPRs.
2172 SmallPtrSet<SDNode*, 2> Copies;
2173 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2175 if (UI->getOpcode() != ISD::CopyToReg)
2179 if (Copies.size() > 2)
2182 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2184 SDValue UseChain = UI->getOperand(0);
2185 if (Copies.count(UseChain.getNode()))
2192 } else if (Copy->getOpcode() == ISD::BITCAST) {
2193 // f32 returned in a single GPR.
2194 if (!Copy->hasOneUse())
2196 Copy = *Copy->use_begin();
2197 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2199 TCChain = Copy->getOperand(0);
2204 bool HasRet = false;
2205 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2207 if (UI->getOpcode() != ARMISD::RET_FLAG)
2219 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2220 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2223 if (!CI->isTailCall())
2226 return !Subtarget->isThumb1Only();
2229 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2230 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2231 // one of the above mentioned nodes. It has to be wrapped because otherwise
2232 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2233 // be used to form addressing mode. These wrapped nodes will be selected
2235 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2236 EVT PtrVT = Op.getValueType();
2237 // FIXME there is no actual debug info here
2239 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2241 if (CP->isMachineConstantPoolEntry())
2242 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2243 CP->getAlignment());
2245 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2246 CP->getAlignment());
2247 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2250 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2251 return MachineJumpTableInfo::EK_Inline;
2254 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2255 SelectionDAG &DAG) const {
2256 MachineFunction &MF = DAG.getMachineFunction();
2257 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2258 unsigned ARMPCLabelIndex = 0;
2260 EVT PtrVT = getPointerTy();
2261 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2262 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2264 if (RelocM == Reloc::Static) {
2265 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2267 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2268 ARMPCLabelIndex = AFI->createPICLabelUId();
2269 ARMConstantPoolValue *CPV =
2270 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2271 ARMCP::CPBlockAddress, PCAdj);
2272 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2274 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2275 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2276 MachinePointerInfo::getConstantPool(),
2277 false, false, false, 0);
2278 if (RelocM == Reloc::Static)
2280 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2281 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2284 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2286 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2287 SelectionDAG &DAG) const {
2289 EVT PtrVT = getPointerTy();
2290 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2291 MachineFunction &MF = DAG.getMachineFunction();
2292 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2293 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2294 ARMConstantPoolValue *CPV =
2295 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2296 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2297 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2298 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2299 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2300 MachinePointerInfo::getConstantPool(),
2301 false, false, false, 0);
2302 SDValue Chain = Argument.getValue(1);
2304 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2305 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2307 // call __tls_get_addr.
2310 Entry.Node = Argument;
2311 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2312 Args.push_back(Entry);
2313 // FIXME: is there useful debug info available here?
2314 TargetLowering::CallLoweringInfo CLI(Chain,
2315 (Type *) Type::getInt32Ty(*DAG.getContext()),
2316 false, false, false, false,
2317 0, CallingConv::C, /*isTailCall=*/false,
2318 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2319 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2320 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2321 return CallResult.first;
2324 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2325 // "local exec" model.
2327 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2329 TLSModel::Model model) const {
2330 const GlobalValue *GV = GA->getGlobal();
2333 SDValue Chain = DAG.getEntryNode();
2334 EVT PtrVT = getPointerTy();
2335 // Get the Thread Pointer
2336 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2338 if (model == TLSModel::InitialExec) {
2339 MachineFunction &MF = DAG.getMachineFunction();
2340 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2341 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2342 // Initial exec model.
2343 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2344 ARMConstantPoolValue *CPV =
2345 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2346 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2348 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2349 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2350 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2351 MachinePointerInfo::getConstantPool(),
2352 false, false, false, 0);
2353 Chain = Offset.getValue(1);
2355 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2356 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2358 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2359 MachinePointerInfo::getConstantPool(),
2360 false, false, false, 0);
2363 assert(model == TLSModel::LocalExec);
2364 ARMConstantPoolValue *CPV =
2365 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2366 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2367 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2368 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2369 MachinePointerInfo::getConstantPool(),
2370 false, false, false, 0);
2373 // The address of the thread local variable is the add of the thread
2374 // pointer with the offset of the variable.
2375 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2379 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2380 // TODO: implement the "local dynamic" model
2381 assert(Subtarget->isTargetELF() &&
2382 "TLS not implemented for non-ELF targets");
2383 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2385 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2388 case TLSModel::GeneralDynamic:
2389 case TLSModel::LocalDynamic:
2390 return LowerToTLSGeneralDynamicModel(GA, DAG);
2391 case TLSModel::InitialExec:
2392 case TLSModel::LocalExec:
2393 return LowerToTLSExecModels(GA, DAG, model);
2395 llvm_unreachable("bogus TLS model");
2398 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2399 SelectionDAG &DAG) const {
2400 EVT PtrVT = getPointerTy();
2402 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2403 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2404 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2405 ARMConstantPoolValue *CPV =
2406 ARMConstantPoolConstant::Create(GV,
2407 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2408 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2409 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2410 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2412 MachinePointerInfo::getConstantPool(),
2413 false, false, false, 0);
2414 SDValue Chain = Result.getValue(1);
2415 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2416 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2418 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2419 MachinePointerInfo::getGOT(),
2420 false, false, false, 0);
2424 // If we have T2 ops, we can materialize the address directly via movt/movw
2425 // pair. This is always cheaper.
2426 if (Subtarget->useMovt()) {
2428 // FIXME: Once remat is capable of dealing with instructions with register
2429 // operands, expand this into two nodes.
2430 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2431 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2433 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2434 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2435 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2436 MachinePointerInfo::getConstantPool(),
2437 false, false, false, 0);
2441 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2442 SelectionDAG &DAG) const {
2443 EVT PtrVT = getPointerTy();
2445 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2446 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2448 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2449 // update ARMFastISel::ARMMaterializeGV.
2450 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2452 // FIXME: Once remat is capable of dealing with instructions with register
2453 // operands, expand this into two nodes.
2454 if (RelocM == Reloc::Static)
2455 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2456 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2458 unsigned Wrapper = (RelocM == Reloc::PIC_)
2459 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2460 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2461 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2462 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2463 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2464 MachinePointerInfo::getGOT(),
2465 false, false, false, 0);
2469 unsigned ARMPCLabelIndex = 0;
2471 if (RelocM == Reloc::Static) {
2472 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2474 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2475 ARMPCLabelIndex = AFI->createPICLabelUId();
2476 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2477 ARMConstantPoolValue *CPV =
2478 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2480 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2482 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2484 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2485 MachinePointerInfo::getConstantPool(),
2486 false, false, false, 0);
2487 SDValue Chain = Result.getValue(1);
2489 if (RelocM == Reloc::PIC_) {
2490 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2491 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2494 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2495 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2496 false, false, false, 0);
2501 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2502 SelectionDAG &DAG) const {
2503 assert(Subtarget->isTargetELF() &&
2504 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2505 MachineFunction &MF = DAG.getMachineFunction();
2506 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2507 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2508 EVT PtrVT = getPointerTy();
2510 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2511 ARMConstantPoolValue *CPV =
2512 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2513 ARMPCLabelIndex, PCAdj);
2514 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2515 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2516 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2517 MachinePointerInfo::getConstantPool(),
2518 false, false, false, 0);
2519 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2520 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2524 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2526 SDValue Val = DAG.getConstant(0, MVT::i32);
2527 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2528 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2529 Op.getOperand(1), Val);
2533 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2535 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2536 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2540 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2541 const ARMSubtarget *Subtarget) const {
2542 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2545 default: return SDValue(); // Don't custom lower most intrinsics.
2546 case Intrinsic::arm_thread_pointer: {
2547 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2548 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2550 case Intrinsic::eh_sjlj_lsda: {
2551 MachineFunction &MF = DAG.getMachineFunction();
2552 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2553 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2554 EVT PtrVT = getPointerTy();
2555 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2557 unsigned PCAdj = (RelocM != Reloc::PIC_)
2558 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2559 ARMConstantPoolValue *CPV =
2560 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2561 ARMCP::CPLSDA, PCAdj);
2562 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2563 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2565 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2566 MachinePointerInfo::getConstantPool(),
2567 false, false, false, 0);
2569 if (RelocM == Reloc::PIC_) {
2570 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2571 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2575 case Intrinsic::arm_neon_vmulls:
2576 case Intrinsic::arm_neon_vmullu: {
2577 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2578 ? ARMISD::VMULLs : ARMISD::VMULLu;
2579 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2580 Op.getOperand(1), Op.getOperand(2));
2585 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2586 const ARMSubtarget *Subtarget) {
2587 // FIXME: handle "fence singlethread" more efficiently.
2589 if (!Subtarget->hasDataBarrier()) {
2590 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2591 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2593 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2594 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2595 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2596 DAG.getConstant(0, MVT::i32));
2599 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2600 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2601 unsigned Domain = ARM_MB::ISH;
2602 if (Subtarget->isMClass()) {
2603 // Only a full system barrier exists in the M-class architectures.
2604 Domain = ARM_MB::SY;
2605 } else if (Subtarget->isSwift() && Ord == Release) {
2606 // Swift happens to implement ISHST barriers in a way that's compatible with
2607 // Release semantics but weaker than ISH so we'd be fools not to use
2608 // it. Beware: other processors probably don't!
2609 Domain = ARM_MB::ISHST;
2612 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2613 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2614 DAG.getConstant(Domain, MVT::i32));
2617 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2618 const ARMSubtarget *Subtarget) {
2619 // ARM pre v5TE and Thumb1 does not have preload instructions.
2620 if (!(Subtarget->isThumb2() ||
2621 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2622 // Just preserve the chain.
2623 return Op.getOperand(0);
2626 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2628 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2629 // ARMv7 with MP extension has PLDW.
2630 return Op.getOperand(0);
2632 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2633 if (Subtarget->isThumb()) {
2635 isRead = ~isRead & 1;
2636 isData = ~isData & 1;
2639 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2640 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2641 DAG.getConstant(isData, MVT::i32));
2644 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2645 MachineFunction &MF = DAG.getMachineFunction();
2646 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2648 // vastart just stores the address of the VarArgsFrameIndex slot into the
2649 // memory location argument.
2651 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2652 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2653 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2654 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2655 MachinePointerInfo(SV), false, false, 0);
2659 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2660 SDValue &Root, SelectionDAG &DAG,
2662 MachineFunction &MF = DAG.getMachineFunction();
2663 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2665 const TargetRegisterClass *RC;
2666 if (AFI->isThumb1OnlyFunction())
2667 RC = &ARM::tGPRRegClass;
2669 RC = &ARM::GPRRegClass;
2671 // Transform the arguments stored in physical registers into virtual ones.
2672 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2673 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2676 if (NextVA.isMemLoc()) {
2677 MachineFrameInfo *MFI = MF.getFrameInfo();
2678 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2680 // Create load node to retrieve arguments from the stack.
2681 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2682 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2683 MachinePointerInfo::getFixedStack(FI),
2684 false, false, false, 0);
2686 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2687 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2690 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2694 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2695 unsigned InRegsParamRecordIdx,
2697 unsigned &ArgRegsSize,
2698 unsigned &ArgRegsSaveSize)
2701 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2702 unsigned RBegin, REnd;
2703 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2704 NumGPRs = REnd - RBegin;
2706 unsigned int firstUnalloced;
2707 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2708 sizeof(GPRArgRegs) /
2709 sizeof(GPRArgRegs[0]));
2710 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2713 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2714 ArgRegsSize = NumGPRs * 4;
2716 // If parameter is split between stack and GPRs...
2717 if (NumGPRs && Align == 8 &&
2718 (ArgRegsSize < ArgSize ||
2719 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2720 // Add padding for part of param recovered from GPRs, so
2721 // its last byte must be at address K*8 - 1.
2722 // We need to do it, since remained (stack) part of parameter has
2723 // stack alignment, and we need to "attach" "GPRs head" without gaps
2726 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2727 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2729 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2731 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2732 (ArgRegsSize + AFI->getArgRegsSaveSize());
2733 ArgRegsSaveSize = ArgRegsSize + Padding;
2735 // We don't need to extend regs save size for byval parameters if they
2736 // are passed via GPRs only.
2737 ArgRegsSaveSize = ArgRegsSize;
2740 // The remaining GPRs hold either the beginning of variable-argument
2741 // data, or the beginning of an aggregate passed by value (usually
2742 // byval). Either way, we allocate stack slots adjacent to the data
2743 // provided by our caller, and store the unallocated registers there.
2744 // If this is a variadic function, the va_list pointer will begin with
2745 // these values; otherwise, this reassembles a (byval) structure that
2746 // was split between registers and memory.
2747 // Return: The frame index registers were stored into.
2749 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2750 SDLoc dl, SDValue &Chain,
2751 const Value *OrigArg,
2752 unsigned InRegsParamRecordIdx,
2753 unsigned OffsetFromOrigArg,
2756 bool ForceMutable) const {
2758 // Currently, two use-cases possible:
2759 // Case #1. Non var-args function, and we meet first byval parameter.
2760 // Setup first unallocated register as first byval register;
2761 // eat all remained registers
2762 // (these two actions are performed by HandleByVal method).
2763 // Then, here, we initialize stack frame with
2764 // "store-reg" instructions.
2765 // Case #2. Var-args function, that doesn't contain byval parameters.
2766 // The same: eat all remained unallocated registers,
2767 // initialize stack frame.
2769 MachineFunction &MF = DAG.getMachineFunction();
2770 MachineFrameInfo *MFI = MF.getFrameInfo();
2771 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2772 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2773 unsigned RBegin, REnd;
2774 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2775 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2776 firstRegToSaveIndex = RBegin - ARM::R0;
2777 lastRegToSaveIndex = REnd - ARM::R0;
2779 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2780 (GPRArgRegs, array_lengthof(GPRArgRegs));
2781 lastRegToSaveIndex = 4;
2784 unsigned ArgRegsSize, ArgRegsSaveSize;
2785 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2786 ArgRegsSize, ArgRegsSaveSize);
2788 // Store any by-val regs to their spots on the stack so that they may be
2789 // loaded by deferencing the result of formal parameter pointer or va_next.
2790 // Note: once stack area for byval/varargs registers
2791 // was initialized, it can't be initialized again.
2792 if (ArgRegsSaveSize) {
2794 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2797 assert(AFI->getStoredByValParamsPadding() == 0 &&
2798 "The only parameter may be padded.");
2799 AFI->setStoredByValParamsPadding(Padding);
2802 int FrameIndex = MFI->CreateFixedObject(
2804 Padding + ArgOffset,
2806 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2808 SmallVector<SDValue, 4> MemOps;
2809 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2810 ++firstRegToSaveIndex, ++i) {
2811 const TargetRegisterClass *RC;
2812 if (AFI->isThumb1OnlyFunction())
2813 RC = &ARM::tGPRRegClass;
2815 RC = &ARM::GPRRegClass;
2817 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2818 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2820 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2821 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2823 MemOps.push_back(Store);
2824 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2825 DAG.getConstant(4, getPointerTy()));
2828 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2830 if (!MemOps.empty())
2831 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2832 &MemOps[0], MemOps.size());
2835 // This will point to the next argument passed via stack.
2836 return MFI->CreateFixedObject(
2837 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2840 // Setup stack frame, the va_list pointer will start from.
2842 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2843 SDLoc dl, SDValue &Chain,
2845 bool ForceMutable) const {
2846 MachineFunction &MF = DAG.getMachineFunction();
2847 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2849 // Try to store any remaining integer argument regs
2850 // to their spots on the stack so that they may be loaded by deferencing
2851 // the result of va_next.
2852 // If there is no regs to be stored, just point address after last
2853 // argument passed via stack.
2855 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2856 0, ArgOffset, 0, ForceMutable);
2858 AFI->setVarArgsFrameIndex(FrameIndex);
2862 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2863 CallingConv::ID CallConv, bool isVarArg,
2864 const SmallVectorImpl<ISD::InputArg>
2866 SDLoc dl, SelectionDAG &DAG,
2867 SmallVectorImpl<SDValue> &InVals)
2869 MachineFunction &MF = DAG.getMachineFunction();
2870 MachineFrameInfo *MFI = MF.getFrameInfo();
2872 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2874 // Assign locations to all of the incoming arguments.
2875 SmallVector<CCValAssign, 16> ArgLocs;
2876 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2877 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2878 CCInfo.AnalyzeFormalArguments(Ins,
2879 CCAssignFnForNode(CallConv, /* Return*/ false,
2882 SmallVector<SDValue, 16> ArgValues;
2883 int lastInsIndex = -1;
2885 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2886 unsigned CurArgIdx = 0;
2888 // Initially ArgRegsSaveSize is zero.
2889 // Then we increase this value each time we meet byval parameter.
2890 // We also increase this value in case of varargs function.
2891 AFI->setArgRegsSaveSize(0);
2893 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2894 CCValAssign &VA = ArgLocs[i];
2895 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2896 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2897 // Arguments stored in registers.
2898 if (VA.isRegLoc()) {
2899 EVT RegVT = VA.getLocVT();
2901 if (VA.needsCustom()) {
2902 // f64 and vector types are split up into multiple registers or
2903 // combinations of registers and stack slots.
2904 if (VA.getLocVT() == MVT::v2f64) {
2905 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2907 VA = ArgLocs[++i]; // skip ahead to next loc
2909 if (VA.isMemLoc()) {
2910 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2911 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2912 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2913 MachinePointerInfo::getFixedStack(FI),
2914 false, false, false, 0);
2916 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2919 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2920 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2921 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2922 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2923 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2925 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2928 const TargetRegisterClass *RC;
2930 if (RegVT == MVT::f32)
2931 RC = &ARM::SPRRegClass;
2932 else if (RegVT == MVT::f64)
2933 RC = &ARM::DPRRegClass;
2934 else if (RegVT == MVT::v2f64)
2935 RC = &ARM::QPRRegClass;
2936 else if (RegVT == MVT::i32)
2937 RC = AFI->isThumb1OnlyFunction() ?
2938 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2939 (const TargetRegisterClass*)&ARM::GPRRegClass;
2941 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2943 // Transform the arguments in physical registers into virtual ones.
2944 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2945 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2948 // If this is an 8 or 16-bit value, it is really passed promoted
2949 // to 32 bits. Insert an assert[sz]ext to capture this, then
2950 // truncate to the right size.
2951 switch (VA.getLocInfo()) {
2952 default: llvm_unreachable("Unknown loc info!");
2953 case CCValAssign::Full: break;
2954 case CCValAssign::BCvt:
2955 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2957 case CCValAssign::SExt:
2958 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2959 DAG.getValueType(VA.getValVT()));
2960 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2962 case CCValAssign::ZExt:
2963 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2964 DAG.getValueType(VA.getValVT()));
2965 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2969 InVals.push_back(ArgValue);
2971 } else { // VA.isRegLoc()
2974 assert(VA.isMemLoc());
2975 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2977 int index = ArgLocs[i].getValNo();
2979 // Some Ins[] entries become multiple ArgLoc[] entries.
2980 // Process them only once.
2981 if (index != lastInsIndex)
2983 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2984 // FIXME: For now, all byval parameter objects are marked mutable.
2985 // This can be changed with more analysis.
2986 // In case of tail call optimization mark all arguments mutable.
2987 // Since they could be overwritten by lowering of arguments in case of
2989 if (Flags.isByVal()) {
2990 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2991 int FrameIndex = StoreByValRegs(
2992 CCInfo, DAG, dl, Chain, CurOrigArg,
2994 Ins[VA.getValNo()].PartOffset,
2995 VA.getLocMemOffset(),
2996 Flags.getByValSize(),
2997 true /*force mutable frames*/);
2998 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2999 CCInfo.nextInRegsParam();
3001 unsigned FIOffset = VA.getLocMemOffset() +
3002 AFI->getStoredByValParamsPadding();
3003 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3006 // Create load nodes to retrieve arguments from the stack.
3007 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3008 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3009 MachinePointerInfo::getFixedStack(FI),
3010 false, false, false, 0));
3012 lastInsIndex = index;
3019 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3020 CCInfo.getNextStackOffset());
3025 /// isFloatingPointZero - Return true if this is +0.0.
3026 static bool isFloatingPointZero(SDValue Op) {
3027 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3028 return CFP->getValueAPF().isPosZero();
3029 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3030 // Maybe this has already been legalized into the constant pool?
3031 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3032 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3033 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3034 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3035 return CFP->getValueAPF().isPosZero();
3041 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3042 /// the given operands.
3044 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3045 SDValue &ARMcc, SelectionDAG &DAG,
3047 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3048 unsigned C = RHSC->getZExtValue();
3049 if (!isLegalICmpImmediate(C)) {
3050 // Constant does not fit, try adjusting it by one?
3055 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3056 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3057 RHS = DAG.getConstant(C-1, MVT::i32);
3062 if (C != 0 && isLegalICmpImmediate(C-1)) {
3063 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3064 RHS = DAG.getConstant(C-1, MVT::i32);
3069 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3070 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3071 RHS = DAG.getConstant(C+1, MVT::i32);
3076 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3077 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3078 RHS = DAG.getConstant(C+1, MVT::i32);
3085 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3086 ARMISD::NodeType CompareType;
3089 CompareType = ARMISD::CMP;
3094 CompareType = ARMISD::CMPZ;
3097 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3098 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3101 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3103 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3106 if (!isFloatingPointZero(RHS))
3107 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3109 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3110 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3113 /// duplicateCmp - Glue values can have only one use, so this function
3114 /// duplicates a comparison node.
3116 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3117 unsigned Opc = Cmp.getOpcode();
3119 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3120 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3122 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3123 Cmp = Cmp.getOperand(0);
3124 Opc = Cmp.getOpcode();
3125 if (Opc == ARMISD::CMPFP)
3126 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3128 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3129 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3131 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3134 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3135 SDValue Cond = Op.getOperand(0);
3136 SDValue SelectTrue = Op.getOperand(1);
3137 SDValue SelectFalse = Op.getOperand(2);
3142 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3143 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3145 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3146 const ConstantSDNode *CMOVTrue =
3147 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3148 const ConstantSDNode *CMOVFalse =
3149 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3151 if (CMOVTrue && CMOVFalse) {
3152 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3153 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3157 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3159 False = SelectFalse;
3160 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3165 if (True.getNode() && False.getNode()) {
3166 EVT VT = Op.getValueType();
3167 SDValue ARMcc = Cond.getOperand(2);
3168 SDValue CCR = Cond.getOperand(3);
3169 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3170 assert(True.getValueType() == VT);
3171 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3176 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3177 // undefined bits before doing a full-word comparison with zero.
3178 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3179 DAG.getConstant(1, Cond.getValueType()));
3181 return DAG.getSelectCC(dl, Cond,
3182 DAG.getConstant(0, Cond.getValueType()),
3183 SelectTrue, SelectFalse, ISD::SETNE);
3186 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3187 if (CC == ISD::SETNE)
3189 return ISD::getSetCCSwappedOperands(CC);
3192 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3193 bool &swpCmpOps, bool &swpVselOps) {
3194 // Start by selecting the GE condition code for opcodes that return true for
3196 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3198 CondCode = ARMCC::GE;
3200 // and GT for opcodes that return false for 'equality'.
3201 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3203 CondCode = ARMCC::GT;
3205 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3206 // to swap the compare operands.
3207 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3211 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3212 // If we have an unordered opcode, we need to swap the operands to the VSEL
3213 // instruction (effectively negating the condition).
3215 // This also has the effect of swapping which one of 'less' or 'greater'
3216 // returns true, so we also swap the compare operands. It also switches
3217 // whether we return true for 'equality', so we compensate by picking the
3218 // opposite condition code to our original choice.
3219 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3220 CC == ISD::SETUGT) {
3221 swpCmpOps = !swpCmpOps;
3222 swpVselOps = !swpVselOps;
3223 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3226 // 'ordered' is 'anything but unordered', so use the VS condition code and
3227 // swap the VSEL operands.
3228 if (CC == ISD::SETO) {
3229 CondCode = ARMCC::VS;
3233 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3234 // code and swap the VSEL operands.
3235 if (CC == ISD::SETUNE) {
3236 CondCode = ARMCC::EQ;
3241 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3242 EVT VT = Op.getValueType();
3243 SDValue LHS = Op.getOperand(0);
3244 SDValue RHS = Op.getOperand(1);
3245 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3246 SDValue TrueVal = Op.getOperand(2);
3247 SDValue FalseVal = Op.getOperand(3);
3250 if (LHS.getValueType() == MVT::i32) {
3251 // Try to generate VSEL on ARMv8.
3252 // The VSEL instruction can't use all the usual ARM condition
3253 // codes: it only has two bits to select the condition code, so it's
3254 // constrained to use only GE, GT, VS and EQ.
3256 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3257 // swap the operands of the previous compare instruction (effectively
3258 // inverting the compare condition, swapping 'less' and 'greater') and
3259 // sometimes need to swap the operands to the VSEL (which inverts the
3260 // condition in the sense of firing whenever the previous condition didn't)
3261 if (getSubtarget()->hasV8FP() && (TrueVal.getValueType() == MVT::f32 ||
3262 TrueVal.getValueType() == MVT::f64)) {
3263 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3264 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3265 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3266 CC = getInverseCCForVSEL(CC);
3267 std::swap(TrueVal, FalseVal);
3272 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3273 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3274 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3278 ARMCC::CondCodes CondCode, CondCode2;
3279 FPCCToARMCC(CC, CondCode, CondCode2);
3281 // Try to generate VSEL on ARMv8.
3282 if (getSubtarget()->hasV8FP() && (TrueVal.getValueType() == MVT::f32 ||
3283 TrueVal.getValueType() == MVT::f64)) {
3284 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3285 // same operands, as follows:
3286 // c = fcmp [ogt, olt, ugt, ult] a, b
3288 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3289 // handled differently than the original code sequence.
3290 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3292 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3293 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3294 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3295 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3298 bool swpCmpOps = false;
3299 bool swpVselOps = false;
3300 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3302 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3303 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3305 std::swap(LHS, RHS);
3307 std::swap(TrueVal, FalseVal);
3311 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3312 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3313 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3314 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3316 if (CondCode2 != ARMCC::AL) {
3317 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3318 // FIXME: Needs another CMP because flag can have but one use.
3319 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3320 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3321 Result, TrueVal, ARMcc2, CCR, Cmp2);
3326 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3327 /// to morph to an integer compare sequence.
3328 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3329 const ARMSubtarget *Subtarget) {
3330 SDNode *N = Op.getNode();
3331 if (!N->hasOneUse())
3332 // Otherwise it requires moving the value from fp to integer registers.
3334 if (!N->getNumValues())
3336 EVT VT = Op.getValueType();
3337 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3338 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3339 // vmrs are very slow, e.g. cortex-a8.
3342 if (isFloatingPointZero(Op)) {
3346 return ISD::isNormalLoad(N);
3349 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3350 if (isFloatingPointZero(Op))
3351 return DAG.getConstant(0, MVT::i32);
3353 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3354 return DAG.getLoad(MVT::i32, SDLoc(Op),
3355 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3356 Ld->isVolatile(), Ld->isNonTemporal(),
3357 Ld->isInvariant(), Ld->getAlignment());
3359 llvm_unreachable("Unknown VFP cmp argument!");
3362 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3363 SDValue &RetVal1, SDValue &RetVal2) {
3364 if (isFloatingPointZero(Op)) {
3365 RetVal1 = DAG.getConstant(0, MVT::i32);
3366 RetVal2 = DAG.getConstant(0, MVT::i32);
3370 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3371 SDValue Ptr = Ld->getBasePtr();
3372 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3373 Ld->getChain(), Ptr,
3374 Ld->getPointerInfo(),
3375 Ld->isVolatile(), Ld->isNonTemporal(),
3376 Ld->isInvariant(), Ld->getAlignment());
3378 EVT PtrType = Ptr.getValueType();
3379 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3380 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3381 PtrType, Ptr, DAG.getConstant(4, PtrType));
3382 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3383 Ld->getChain(), NewPtr,
3384 Ld->getPointerInfo().getWithOffset(4),
3385 Ld->isVolatile(), Ld->isNonTemporal(),
3386 Ld->isInvariant(), NewAlign);
3390 llvm_unreachable("Unknown VFP cmp argument!");
3393 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3394 /// f32 and even f64 comparisons to integer ones.
3396 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3397 SDValue Chain = Op.getOperand(0);
3398 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3399 SDValue LHS = Op.getOperand(2);
3400 SDValue RHS = Op.getOperand(3);
3401 SDValue Dest = Op.getOperand(4);
3404 bool LHSSeenZero = false;
3405 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3406 bool RHSSeenZero = false;
3407 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3408 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3409 // If unsafe fp math optimization is enabled and there are no other uses of
3410 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3411 // to an integer comparison.
3412 if (CC == ISD::SETOEQ)
3414 else if (CC == ISD::SETUNE)
3417 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3419 if (LHS.getValueType() == MVT::f32) {
3420 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3421 bitcastf32Toi32(LHS, DAG), Mask);
3422 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3423 bitcastf32Toi32(RHS, DAG), Mask);
3424 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3425 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3426 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3427 Chain, Dest, ARMcc, CCR, Cmp);
3432 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3433 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3434 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3435 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3436 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3437 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3438 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3439 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3440 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3446 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3447 SDValue Chain = Op.getOperand(0);
3448 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3449 SDValue LHS = Op.getOperand(2);
3450 SDValue RHS = Op.getOperand(3);
3451 SDValue Dest = Op.getOperand(4);
3454 if (LHS.getValueType() == MVT::i32) {
3456 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3457 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3458 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3459 Chain, Dest, ARMcc, CCR, Cmp);
3462 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3464 if (getTargetMachine().Options.UnsafeFPMath &&
3465 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3466 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3467 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3468 if (Result.getNode())
3472 ARMCC::CondCodes CondCode, CondCode2;
3473 FPCCToARMCC(CC, CondCode, CondCode2);
3475 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3476 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3477 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3478 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3479 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3480 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3481 if (CondCode2 != ARMCC::AL) {
3482 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3483 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3484 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3489 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3490 SDValue Chain = Op.getOperand(0);
3491 SDValue Table = Op.getOperand(1);
3492 SDValue Index = Op.getOperand(2);
3495 EVT PTy = getPointerTy();
3496 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3497 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3498 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3499 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3500 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3501 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3502 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3503 if (Subtarget->isThumb2()) {
3504 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3505 // which does another jump to the destination. This also makes it easier
3506 // to translate it to TBB / TBH later.
3507 // FIXME: This might not work if the function is extremely large.
3508 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3509 Addr, Op.getOperand(2), JTI, UId);
3511 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3512 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3513 MachinePointerInfo::getJumpTable(),
3514 false, false, false, 0);
3515 Chain = Addr.getValue(1);
3516 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3517 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3519 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3520 MachinePointerInfo::getJumpTable(),
3521 false, false, false, 0);
3522 Chain = Addr.getValue(1);
3523 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3527 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3528 EVT VT = Op.getValueType();
3531 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3532 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3534 return DAG.UnrollVectorOp(Op.getNode());
3537 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3538 "Invalid type for custom lowering!");
3539 if (VT != MVT::v4i16)
3540 return DAG.UnrollVectorOp(Op.getNode());
3542 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3543 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3546 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3547 EVT VT = Op.getValueType();
3549 return LowerVectorFP_TO_INT(Op, DAG);
3554 switch (Op.getOpcode()) {
3555 default: llvm_unreachable("Invalid opcode!");
3556 case ISD::FP_TO_SINT:
3557 Opc = ARMISD::FTOSI;
3559 case ISD::FP_TO_UINT:
3560 Opc = ARMISD::FTOUI;
3563 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3564 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3567 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3568 EVT VT = Op.getValueType();
3571 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3572 if (VT.getVectorElementType() == MVT::f32)
3574 return DAG.UnrollVectorOp(Op.getNode());
3577 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3578 "Invalid type for custom lowering!");
3579 if (VT != MVT::v4f32)
3580 return DAG.UnrollVectorOp(Op.getNode());
3584 switch (Op.getOpcode()) {
3585 default: llvm_unreachable("Invalid opcode!");
3586 case ISD::SINT_TO_FP:
3587 CastOpc = ISD::SIGN_EXTEND;
3588 Opc = ISD::SINT_TO_FP;
3590 case ISD::UINT_TO_FP:
3591 CastOpc = ISD::ZERO_EXTEND;
3592 Opc = ISD::UINT_TO_FP;
3596 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3597 return DAG.getNode(Opc, dl, VT, Op);
3600 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3601 EVT VT = Op.getValueType();
3603 return LowerVectorINT_TO_FP(Op, DAG);
3608 switch (Op.getOpcode()) {
3609 default: llvm_unreachable("Invalid opcode!");
3610 case ISD::SINT_TO_FP:
3611 Opc = ARMISD::SITOF;
3613 case ISD::UINT_TO_FP:
3614 Opc = ARMISD::UITOF;
3618 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3619 return DAG.getNode(Opc, dl, VT, Op);
3622 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3623 // Implement fcopysign with a fabs and a conditional fneg.
3624 SDValue Tmp0 = Op.getOperand(0);
3625 SDValue Tmp1 = Op.getOperand(1);
3627 EVT VT = Op.getValueType();
3628 EVT SrcVT = Tmp1.getValueType();
3629 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3630 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3631 bool UseNEON = !InGPR && Subtarget->hasNEON();
3634 // Use VBSL to copy the sign bit.
3635 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3636 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3637 DAG.getTargetConstant(EncodedVal, MVT::i32));
3638 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3640 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3641 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3642 DAG.getConstant(32, MVT::i32));
3643 else /*if (VT == MVT::f32)*/
3644 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3645 if (SrcVT == MVT::f32) {
3646 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3648 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3649 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3650 DAG.getConstant(32, MVT::i32));
3651 } else if (VT == MVT::f32)
3652 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3653 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3654 DAG.getConstant(32, MVT::i32));
3655 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3656 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3658 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3660 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3661 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3662 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3664 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3665 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3666 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3667 if (VT == MVT::f32) {
3668 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3669 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3670 DAG.getConstant(0, MVT::i32));
3672 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3678 // Bitcast operand 1 to i32.
3679 if (SrcVT == MVT::f64)
3680 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3681 &Tmp1, 1).getValue(1);
3682 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3684 // Or in the signbit with integer operations.
3685 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3686 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3687 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3688 if (VT == MVT::f32) {
3689 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3690 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3691 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3692 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3695 // f64: Or the high part with signbit and then combine two parts.
3696 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3698 SDValue Lo = Tmp0.getValue(0);
3699 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3700 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3701 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3704 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3705 MachineFunction &MF = DAG.getMachineFunction();
3706 MachineFrameInfo *MFI = MF.getFrameInfo();
3707 MFI->setReturnAddressIsTaken(true);
3709 EVT VT = Op.getValueType();
3711 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3713 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3714 SDValue Offset = DAG.getConstant(4, MVT::i32);
3715 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3716 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3717 MachinePointerInfo(), false, false, false, 0);
3720 // Return LR, which contains the return address. Mark it an implicit live-in.
3721 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3722 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3725 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3726 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3727 MFI->setFrameAddressIsTaken(true);
3729 EVT VT = Op.getValueType();
3730 SDLoc dl(Op); // FIXME probably not meaningful
3731 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3732 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3733 ? ARM::R7 : ARM::R11;
3734 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3736 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3737 MachinePointerInfo(),
3738 false, false, false, 0);
3742 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3743 /// and size(DestVec) > 128-bits.
3744 /// This is achieved by doing the one extension from the SrcVec, splitting the
3745 /// result, extending these parts, and then concatenating these into the
3747 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3748 SDValue Op = N->getOperand(0);
3749 EVT SrcVT = Op.getValueType();
3750 EVT DestVT = N->getValueType(0);
3752 assert(DestVT.getSizeInBits() > 128 &&
3753 "Custom sext/zext expansion needs >128-bit vector.");
3754 // If this is a normal length extension, use the default expansion.
3755 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3756 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3760 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3761 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3762 unsigned NumElts = SrcVT.getVectorNumElements();
3763 LLVMContext &Ctx = *DAG.getContext();
3764 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3766 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3768 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3770 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3773 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3774 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3775 DAG.getIntPtrConstant(0));
3776 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3777 DAG.getIntPtrConstant(NumElts/2));
3778 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3779 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3780 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3783 /// ExpandBITCAST - If the target supports VFP, this function is called to
3784 /// expand a bit convert where either the source or destination type is i64 to
3785 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3786 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3787 /// vectors), since the legalizer won't know what to do with that.
3788 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3789 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3791 SDValue Op = N->getOperand(0);
3793 // This function is only supposed to be called for i64 types, either as the
3794 // source or destination of the bit convert.
3795 EVT SrcVT = Op.getValueType();
3796 EVT DstVT = N->getValueType(0);
3797 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3798 "ExpandBITCAST called for non-i64 type");
3800 // Turn i64->f64 into VMOVDRR.
3801 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3802 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3803 DAG.getConstant(0, MVT::i32));
3804 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3805 DAG.getConstant(1, MVT::i32));
3806 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3807 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3810 // Turn f64->i64 into VMOVRRD.
3811 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3812 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3813 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3814 // Merge the pieces into a single i64 value.
3815 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3821 /// getZeroVector - Returns a vector of specified type with all zero elements.
3822 /// Zero vectors are used to represent vector negation and in those cases
3823 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3824 /// not support i64 elements, so sometimes the zero vectors will need to be
3825 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3827 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3828 assert(VT.isVector() && "Expected a vector type");
3829 // The canonical modified immediate encoding of a zero vector is....0!
3830 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3831 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3832 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3833 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3836 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3837 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3838 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3839 SelectionDAG &DAG) const {
3840 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3841 EVT VT = Op.getValueType();
3842 unsigned VTBits = VT.getSizeInBits();
3844 SDValue ShOpLo = Op.getOperand(0);
3845 SDValue ShOpHi = Op.getOperand(1);
3846 SDValue ShAmt = Op.getOperand(2);
3848 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3850 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3852 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3853 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3854 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3855 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3856 DAG.getConstant(VTBits, MVT::i32));
3857 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3858 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3859 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3861 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3862 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3864 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3865 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3868 SDValue Ops[2] = { Lo, Hi };
3869 return DAG.getMergeValues(Ops, 2, dl);
3872 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3873 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3874 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3875 SelectionDAG &DAG) const {
3876 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3877 EVT VT = Op.getValueType();
3878 unsigned VTBits = VT.getSizeInBits();
3880 SDValue ShOpLo = Op.getOperand(0);
3881 SDValue ShOpHi = Op.getOperand(1);
3882 SDValue ShAmt = Op.getOperand(2);
3885 assert(Op.getOpcode() == ISD::SHL_PARTS);
3886 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3887 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3888 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3889 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3890 DAG.getConstant(VTBits, MVT::i32));
3891 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3892 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3894 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3895 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3896 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3898 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3899 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3902 SDValue Ops[2] = { Lo, Hi };
3903 return DAG.getMergeValues(Ops, 2, dl);
3906 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3907 SelectionDAG &DAG) const {
3908 // The rounding mode is in bits 23:22 of the FPSCR.
3909 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3910 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3911 // so that the shift + and get folded into a bitfield extract.
3913 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3914 DAG.getConstant(Intrinsic::arm_get_fpscr,
3916 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3917 DAG.getConstant(1U << 22, MVT::i32));
3918 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3919 DAG.getConstant(22, MVT::i32));
3920 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3921 DAG.getConstant(3, MVT::i32));
3924 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3925 const ARMSubtarget *ST) {
3926 EVT VT = N->getValueType(0);
3929 if (!ST->hasV6T2Ops())
3932 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3933 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3936 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3937 /// for each 16-bit element from operand, repeated. The basic idea is to
3938 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3940 /// Trace for v4i16:
3941 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3942 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3943 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3944 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3945 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3946 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3947 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3948 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3949 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3950 EVT VT = N->getValueType(0);
3953 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3954 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3955 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3956 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3957 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3958 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3961 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3962 /// bit-count for each 16-bit element from the operand. We need slightly
3963 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3964 /// 64/128-bit registers.
3966 /// Trace for v4i16:
3967 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3968 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3969 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3970 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3971 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3972 EVT VT = N->getValueType(0);
3975 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3976 if (VT.is64BitVector()) {
3977 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3978 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3979 DAG.getIntPtrConstant(0));
3981 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3982 BitCounts, DAG.getIntPtrConstant(0));
3983 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3987 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3988 /// bit-count for each 32-bit element from the operand. The idea here is
3989 /// to split the vector into 16-bit elements, leverage the 16-bit count
3990 /// routine, and then combine the results.
3992 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3993 /// input = [v0 v1 ] (vi: 32-bit elements)
3994 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3995 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3996 /// vrev: N0 = [k1 k0 k3 k2 ]
3998 /// N1 =+[k1 k0 k3 k2 ]
4000 /// N2 =+[k1 k3 k0 k2 ]
4002 /// Extended =+[k1 k3 k0 k2 ]
4004 /// Extracted=+[k1 k3 ]
4006 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4007 EVT VT = N->getValueType(0);
4010 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4012 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4013 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4014 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4015 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4016 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4018 if (VT.is64BitVector()) {
4019 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4020 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4021 DAG.getIntPtrConstant(0));
4023 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4024 DAG.getIntPtrConstant(0));
4025 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4029 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4030 const ARMSubtarget *ST) {
4031 EVT VT = N->getValueType(0);
4033 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4034 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4035 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4036 "Unexpected type for custom ctpop lowering");
4038 if (VT.getVectorElementType() == MVT::i32)
4039 return lowerCTPOP32BitElements(N, DAG);
4041 return lowerCTPOP16BitElements(N, DAG);
4044 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4045 const ARMSubtarget *ST) {
4046 EVT VT = N->getValueType(0);
4052 // Lower vector shifts on NEON to use VSHL.
4053 assert(ST->hasNEON() && "unexpected vector shift");
4055 // Left shifts translate directly to the vshiftu intrinsic.
4056 if (N->getOpcode() == ISD::SHL)
4057 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4058 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4059 N->getOperand(0), N->getOperand(1));
4061 assert((N->getOpcode() == ISD::SRA ||
4062 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4064 // NEON uses the same intrinsics for both left and right shifts. For
4065 // right shifts, the shift amounts are negative, so negate the vector of
4067 EVT ShiftVT = N->getOperand(1).getValueType();
4068 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4069 getZeroVector(ShiftVT, DAG, dl),
4071 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4072 Intrinsic::arm_neon_vshifts :
4073 Intrinsic::arm_neon_vshiftu);
4074 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4075 DAG.getConstant(vshiftInt, MVT::i32),
4076 N->getOperand(0), NegatedCount);
4079 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4080 const ARMSubtarget *ST) {
4081 EVT VT = N->getValueType(0);
4084 // We can get here for a node like i32 = ISD::SHL i32, i64
4088 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4089 "Unknown shift to lower!");
4091 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4092 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4093 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4096 // If we are in thumb mode, we don't have RRX.
4097 if (ST->isThumb1Only()) return SDValue();
4099 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4100 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4101 DAG.getConstant(0, MVT::i32));
4102 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4103 DAG.getConstant(1, MVT::i32));
4105 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4106 // captures the result into a carry flag.
4107 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4108 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4110 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4111 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4113 // Merge the pieces into a single i64 value.
4114 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4117 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4118 SDValue TmpOp0, TmpOp1;
4119 bool Invert = false;
4123 SDValue Op0 = Op.getOperand(0);
4124 SDValue Op1 = Op.getOperand(1);
4125 SDValue CC = Op.getOperand(2);
4126 EVT VT = Op.getValueType();
4127 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4130 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4131 switch (SetCCOpcode) {
4132 default: llvm_unreachable("Illegal FP comparison");
4134 case ISD::SETNE: Invert = true; // Fallthrough
4136 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4138 case ISD::SETLT: Swap = true; // Fallthrough
4140 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4142 case ISD::SETLE: Swap = true; // Fallthrough
4144 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4145 case ISD::SETUGE: Swap = true; // Fallthrough
4146 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4147 case ISD::SETUGT: Swap = true; // Fallthrough
4148 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4149 case ISD::SETUEQ: Invert = true; // Fallthrough
4151 // Expand this to (OLT | OGT).
4155 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4156 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4158 case ISD::SETUO: Invert = true; // Fallthrough
4160 // Expand this to (OLT | OGE).
4164 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4165 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4169 // Integer comparisons.
4170 switch (SetCCOpcode) {
4171 default: llvm_unreachable("Illegal integer comparison");
4172 case ISD::SETNE: Invert = true;
4173 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4174 case ISD::SETLT: Swap = true;
4175 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4176 case ISD::SETLE: Swap = true;
4177 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4178 case ISD::SETULT: Swap = true;
4179 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4180 case ISD::SETULE: Swap = true;
4181 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4184 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4185 if (Opc == ARMISD::VCEQ) {
4188 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4190 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4193 // Ignore bitconvert.
4194 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4195 AndOp = AndOp.getOperand(0);
4197 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4199 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4200 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4207 std::swap(Op0, Op1);
4209 // If one of the operands is a constant vector zero, attempt to fold the
4210 // comparison to a specialized compare-against-zero form.
4212 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4214 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4215 if (Opc == ARMISD::VCGE)
4216 Opc = ARMISD::VCLEZ;
4217 else if (Opc == ARMISD::VCGT)
4218 Opc = ARMISD::VCLTZ;
4223 if (SingleOp.getNode()) {
4226 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4228 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4230 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4232 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4234 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4236 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4239 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4243 Result = DAG.getNOT(dl, Result, VT);
4248 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4249 /// valid vector constant for a NEON instruction with a "modified immediate"
4250 /// operand (e.g., VMOV). If so, return the encoded value.
4251 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4252 unsigned SplatBitSize, SelectionDAG &DAG,
4253 EVT &VT, bool is128Bits, NEONModImmType type) {
4254 unsigned OpCmode, Imm;
4256 // SplatBitSize is set to the smallest size that splats the vector, so a
4257 // zero vector will always have SplatBitSize == 8. However, NEON modified
4258 // immediate instructions others than VMOV do not support the 8-bit encoding
4259 // of a zero vector, and the default encoding of zero is supposed to be the
4264 switch (SplatBitSize) {
4266 if (type != VMOVModImm)
4268 // Any 1-byte value is OK. Op=0, Cmode=1110.
4269 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4272 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4276 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4277 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4278 if ((SplatBits & ~0xff) == 0) {
4279 // Value = 0x00nn: Op=x, Cmode=100x.
4284 if ((SplatBits & ~0xff00) == 0) {
4285 // Value = 0xnn00: Op=x, Cmode=101x.
4287 Imm = SplatBits >> 8;
4293 // NEON's 32-bit VMOV supports splat values where:
4294 // * only one byte is nonzero, or
4295 // * the least significant byte is 0xff and the second byte is nonzero, or
4296 // * the least significant 2 bytes are 0xff and the third is nonzero.
4297 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4298 if ((SplatBits & ~0xff) == 0) {
4299 // Value = 0x000000nn: Op=x, Cmode=000x.
4304 if ((SplatBits & ~0xff00) == 0) {
4305 // Value = 0x0000nn00: Op=x, Cmode=001x.
4307 Imm = SplatBits >> 8;
4310 if ((SplatBits & ~0xff0000) == 0) {
4311 // Value = 0x00nn0000: Op=x, Cmode=010x.
4313 Imm = SplatBits >> 16;
4316 if ((SplatBits & ~0xff000000) == 0) {
4317 // Value = 0xnn000000: Op=x, Cmode=011x.
4319 Imm = SplatBits >> 24;
4323 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4324 if (type == OtherModImm) return SDValue();
4326 if ((SplatBits & ~0xffff) == 0 &&
4327 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4328 // Value = 0x0000nnff: Op=x, Cmode=1100.
4330 Imm = SplatBits >> 8;
4335 if ((SplatBits & ~0xffffff) == 0 &&
4336 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4337 // Value = 0x00nnffff: Op=x, Cmode=1101.
4339 Imm = SplatBits >> 16;
4340 SplatBits |= 0xffff;
4344 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4345 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4346 // VMOV.I32. A (very) minor optimization would be to replicate the value
4347 // and fall through here to test for a valid 64-bit splat. But, then the
4348 // caller would also need to check and handle the change in size.
4352 if (type != VMOVModImm)
4354 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4355 uint64_t BitMask = 0xff;
4357 unsigned ImmMask = 1;
4359 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4360 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4363 } else if ((SplatBits & BitMask) != 0) {
4369 // Op=1, Cmode=1110.
4372 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4377 llvm_unreachable("unexpected size for isNEONModifiedImm");
4380 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4381 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4384 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4385 const ARMSubtarget *ST) const {
4389 bool IsDouble = Op.getValueType() == MVT::f64;
4390 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4392 // Try splatting with a VMOV.f32...
4393 APFloat FPVal = CFP->getValueAPF();
4394 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4397 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4398 // We have code in place to select a valid ConstantFP already, no need to
4403 // It's a float and we are trying to use NEON operations where
4404 // possible. Lower it to a splat followed by an extract.
4406 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4407 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4409 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4410 DAG.getConstant(0, MVT::i32));
4413 // The rest of our options are NEON only, make sure that's allowed before
4415 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4419 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4421 // It wouldn't really be worth bothering for doubles except for one very
4422 // important value, which does happen to match: 0.0. So make sure we don't do
4424 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4427 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4428 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4430 if (NewVal != SDValue()) {
4432 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4435 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4437 // It's a float: cast and extract a vector element.
4438 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4440 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4441 DAG.getConstant(0, MVT::i32));
4444 // Finally, try a VMVN.i32
4445 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4447 if (NewVal != SDValue()) {
4449 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4452 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4454 // It's a float: cast and extract a vector element.
4455 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4457 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4458 DAG.getConstant(0, MVT::i32));
4464 // check if an VEXT instruction can handle the shuffle mask when the
4465 // vector sources of the shuffle are the same.
4466 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4467 unsigned NumElts = VT.getVectorNumElements();
4469 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4475 // If this is a VEXT shuffle, the immediate value is the index of the first
4476 // element. The other shuffle indices must be the successive elements after
4478 unsigned ExpectedElt = Imm;
4479 for (unsigned i = 1; i < NumElts; ++i) {
4480 // Increment the expected index. If it wraps around, just follow it
4481 // back to index zero and keep going.
4483 if (ExpectedElt == NumElts)
4486 if (M[i] < 0) continue; // ignore UNDEF indices
4487 if (ExpectedElt != static_cast<unsigned>(M[i]))
4495 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4496 bool &ReverseVEXT, unsigned &Imm) {
4497 unsigned NumElts = VT.getVectorNumElements();
4498 ReverseVEXT = false;
4500 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4506 // If this is a VEXT shuffle, the immediate value is the index of the first
4507 // element. The other shuffle indices must be the successive elements after
4509 unsigned ExpectedElt = Imm;
4510 for (unsigned i = 1; i < NumElts; ++i) {
4511 // Increment the expected index. If it wraps around, it may still be
4512 // a VEXT but the source vectors must be swapped.
4514 if (ExpectedElt == NumElts * 2) {
4519 if (M[i] < 0) continue; // ignore UNDEF indices
4520 if (ExpectedElt != static_cast<unsigned>(M[i]))
4524 // Adjust the index value if the source operands will be swapped.
4531 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4532 /// instruction with the specified blocksize. (The order of the elements
4533 /// within each block of the vector is reversed.)
4534 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4535 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4536 "Only possible block sizes for VREV are: 16, 32, 64");
4538 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4542 unsigned NumElts = VT.getVectorNumElements();
4543 unsigned BlockElts = M[0] + 1;
4544 // If the first shuffle index is UNDEF, be optimistic.
4546 BlockElts = BlockSize / EltSz;
4548 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4551 for (unsigned i = 0; i < NumElts; ++i) {
4552 if (M[i] < 0) continue; // ignore UNDEF indices
4553 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4560 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4561 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4562 // range, then 0 is placed into the resulting vector. So pretty much any mask
4563 // of 8 elements can work here.
4564 return VT == MVT::v8i8 && M.size() == 8;
4567 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4568 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4572 unsigned NumElts = VT.getVectorNumElements();
4573 WhichResult = (M[0] == 0 ? 0 : 1);
4574 for (unsigned i = 0; i < NumElts; i += 2) {
4575 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4576 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4582 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4583 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4584 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4585 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4586 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4590 unsigned NumElts = VT.getVectorNumElements();
4591 WhichResult = (M[0] == 0 ? 0 : 1);
4592 for (unsigned i = 0; i < NumElts; i += 2) {
4593 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4594 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4600 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4601 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4605 unsigned NumElts = VT.getVectorNumElements();
4606 WhichResult = (M[0] == 0 ? 0 : 1);
4607 for (unsigned i = 0; i != NumElts; ++i) {
4608 if (M[i] < 0) continue; // ignore UNDEF indices
4609 if ((unsigned) M[i] != 2 * i + WhichResult)
4613 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4614 if (VT.is64BitVector() && EltSz == 32)
4620 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4621 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4622 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4623 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4624 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4628 unsigned Half = VT.getVectorNumElements() / 2;
4629 WhichResult = (M[0] == 0 ? 0 : 1);
4630 for (unsigned j = 0; j != 2; ++j) {
4631 unsigned Idx = WhichResult;
4632 for (unsigned i = 0; i != Half; ++i) {
4633 int MIdx = M[i + j * Half];
4634 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4640 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4641 if (VT.is64BitVector() && EltSz == 32)
4647 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4648 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4652 unsigned NumElts = VT.getVectorNumElements();
4653 WhichResult = (M[0] == 0 ? 0 : 1);
4654 unsigned Idx = WhichResult * NumElts / 2;
4655 for (unsigned i = 0; i != NumElts; i += 2) {
4656 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4657 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4662 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4663 if (VT.is64BitVector() && EltSz == 32)
4669 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4670 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4671 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4672 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4673 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4677 unsigned NumElts = VT.getVectorNumElements();
4678 WhichResult = (M[0] == 0 ? 0 : 1);
4679 unsigned Idx = WhichResult * NumElts / 2;
4680 for (unsigned i = 0; i != NumElts; i += 2) {
4681 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4682 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4687 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4688 if (VT.is64BitVector() && EltSz == 32)
4694 /// \return true if this is a reverse operation on an vector.
4695 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4696 unsigned NumElts = VT.getVectorNumElements();
4697 // Make sure the mask has the right size.
4698 if (NumElts != M.size())
4701 // Look for <15, ..., 3, -1, 1, 0>.
4702 for (unsigned i = 0; i != NumElts; ++i)
4703 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4709 // If N is an integer constant that can be moved into a register in one
4710 // instruction, return an SDValue of such a constant (will become a MOV
4711 // instruction). Otherwise return null.
4712 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4713 const ARMSubtarget *ST, SDLoc dl) {
4715 if (!isa<ConstantSDNode>(N))
4717 Val = cast<ConstantSDNode>(N)->getZExtValue();
4719 if (ST->isThumb1Only()) {
4720 if (Val <= 255 || ~Val <= 255)
4721 return DAG.getConstant(Val, MVT::i32);
4723 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4724 return DAG.getConstant(Val, MVT::i32);
4729 // If this is a case we can't handle, return null and let the default
4730 // expansion code take care of it.
4731 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4732 const ARMSubtarget *ST) const {
4733 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4735 EVT VT = Op.getValueType();
4737 APInt SplatBits, SplatUndef;
4738 unsigned SplatBitSize;
4740 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4741 if (SplatBitSize <= 64) {
4742 // Check if an immediate VMOV works.
4744 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4745 SplatUndef.getZExtValue(), SplatBitSize,
4746 DAG, VmovVT, VT.is128BitVector(),
4748 if (Val.getNode()) {
4749 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4750 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4753 // Try an immediate VMVN.
4754 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4755 Val = isNEONModifiedImm(NegatedImm,
4756 SplatUndef.getZExtValue(), SplatBitSize,
4757 DAG, VmovVT, VT.is128BitVector(),
4759 if (Val.getNode()) {
4760 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4761 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4764 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4765 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4766 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4768 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4769 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4775 // Scan through the operands to see if only one value is used.
4777 // As an optimisation, even if more than one value is used it may be more
4778 // profitable to splat with one value then change some lanes.
4780 // Heuristically we decide to do this if the vector has a "dominant" value,
4781 // defined as splatted to more than half of the lanes.
4782 unsigned NumElts = VT.getVectorNumElements();
4783 bool isOnlyLowElement = true;
4784 bool usesOnlyOneValue = true;
4785 bool hasDominantValue = false;
4786 bool isConstant = true;
4788 // Map of the number of times a particular SDValue appears in the
4790 DenseMap<SDValue, unsigned> ValueCounts;
4792 for (unsigned i = 0; i < NumElts; ++i) {
4793 SDValue V = Op.getOperand(i);
4794 if (V.getOpcode() == ISD::UNDEF)
4797 isOnlyLowElement = false;
4798 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4801 ValueCounts.insert(std::make_pair(V, 0));
4802 unsigned &Count = ValueCounts[V];
4804 // Is this value dominant? (takes up more than half of the lanes)
4805 if (++Count > (NumElts / 2)) {
4806 hasDominantValue = true;
4810 if (ValueCounts.size() != 1)
4811 usesOnlyOneValue = false;
4812 if (!Value.getNode() && ValueCounts.size() > 0)
4813 Value = ValueCounts.begin()->first;
4815 if (ValueCounts.size() == 0)
4816 return DAG.getUNDEF(VT);
4818 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4819 // Keep going if we are hitting this case.
4820 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4821 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4823 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4825 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4826 // i32 and try again.
4827 if (hasDominantValue && EltSize <= 32) {
4831 // If we are VDUPing a value that comes directly from a vector, that will
4832 // cause an unnecessary move to and from a GPR, where instead we could
4833 // just use VDUPLANE. We can only do this if the lane being extracted
4834 // is at a constant index, as the VDUP from lane instructions only have
4835 // constant-index forms.
4836 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4837 isa<ConstantSDNode>(Value->getOperand(1))) {
4838 // We need to create a new undef vector to use for the VDUPLANE if the
4839 // size of the vector from which we get the value is different than the
4840 // size of the vector that we need to create. We will insert the element
4841 // such that the register coalescer will remove unnecessary copies.
4842 if (VT != Value->getOperand(0).getValueType()) {
4843 ConstantSDNode *constIndex;
4844 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4845 assert(constIndex && "The index is not a constant!");
4846 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4847 VT.getVectorNumElements();
4848 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4849 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4850 Value, DAG.getConstant(index, MVT::i32)),
4851 DAG.getConstant(index, MVT::i32));
4853 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4854 Value->getOperand(0), Value->getOperand(1));
4856 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4858 if (!usesOnlyOneValue) {
4859 // The dominant value was splatted as 'N', but we now have to insert
4860 // all differing elements.
4861 for (unsigned I = 0; I < NumElts; ++I) {
4862 if (Op.getOperand(I) == Value)
4864 SmallVector<SDValue, 3> Ops;
4866 Ops.push_back(Op.getOperand(I));
4867 Ops.push_back(DAG.getConstant(I, MVT::i32));
4868 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4873 if (VT.getVectorElementType().isFloatingPoint()) {
4874 SmallVector<SDValue, 8> Ops;
4875 for (unsigned i = 0; i < NumElts; ++i)
4876 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4878 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4879 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4880 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4882 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4884 if (usesOnlyOneValue) {
4885 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4886 if (isConstant && Val.getNode())
4887 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4891 // If all elements are constants and the case above didn't get hit, fall back
4892 // to the default expansion, which will generate a load from the constant
4897 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4899 SDValue shuffle = ReconstructShuffle(Op, DAG);
4900 if (shuffle != SDValue())
4904 // Vectors with 32- or 64-bit elements can be built by directly assigning
4905 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4906 // will be legalized.
4907 if (EltSize >= 32) {
4908 // Do the expansion with floating-point types, since that is what the VFP
4909 // registers are defined to use, and since i64 is not legal.
4910 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4911 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4912 SmallVector<SDValue, 8> Ops;
4913 for (unsigned i = 0; i < NumElts; ++i)
4914 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4915 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4916 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4919 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4920 // know the default expansion would otherwise fall back on something even
4921 // worse. For a vector with one or two non-undef values, that's
4922 // scalar_to_vector for the elements followed by a shuffle (provided the
4923 // shuffle is valid for the target) and materialization element by element
4924 // on the stack followed by a load for everything else.
4925 if (!isConstant && !usesOnlyOneValue) {
4926 SDValue Vec = DAG.getUNDEF(VT);
4927 for (unsigned i = 0 ; i < NumElts; ++i) {
4928 SDValue V = Op.getOperand(i);
4929 if (V.getOpcode() == ISD::UNDEF)
4931 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4932 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4940 // Gather data to see if the operation can be modelled as a
4941 // shuffle in combination with VEXTs.
4942 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4943 SelectionDAG &DAG) const {
4945 EVT VT = Op.getValueType();
4946 unsigned NumElts = VT.getVectorNumElements();
4948 SmallVector<SDValue, 2> SourceVecs;
4949 SmallVector<unsigned, 2> MinElts;
4950 SmallVector<unsigned, 2> MaxElts;
4952 for (unsigned i = 0; i < NumElts; ++i) {
4953 SDValue V = Op.getOperand(i);
4954 if (V.getOpcode() == ISD::UNDEF)
4956 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4957 // A shuffle can only come from building a vector from various
4958 // elements of other vectors.
4960 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4961 VT.getVectorElementType()) {
4962 // This code doesn't know how to handle shuffles where the vector
4963 // element types do not match (this happens because type legalization
4964 // promotes the return type of EXTRACT_VECTOR_ELT).
4965 // FIXME: It might be appropriate to extend this code to handle
4966 // mismatched types.
4970 // Record this extraction against the appropriate vector if possible...
4971 SDValue SourceVec = V.getOperand(0);
4972 // If the element number isn't a constant, we can't effectively
4973 // analyze what's going on.
4974 if (!isa<ConstantSDNode>(V.getOperand(1)))
4976 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4977 bool FoundSource = false;
4978 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4979 if (SourceVecs[j] == SourceVec) {
4980 if (MinElts[j] > EltNo)
4982 if (MaxElts[j] < EltNo)
4989 // Or record a new source if not...
4991 SourceVecs.push_back(SourceVec);
4992 MinElts.push_back(EltNo);
4993 MaxElts.push_back(EltNo);
4997 // Currently only do something sane when at most two source vectors
4999 if (SourceVecs.size() > 2)
5002 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5003 int VEXTOffsets[2] = {0, 0};
5005 // This loop extracts the usage patterns of the source vectors
5006 // and prepares appropriate SDValues for a shuffle if possible.
5007 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5008 if (SourceVecs[i].getValueType() == VT) {
5009 // No VEXT necessary
5010 ShuffleSrcs[i] = SourceVecs[i];
5013 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5014 // It probably isn't worth padding out a smaller vector just to
5015 // break it down again in a shuffle.
5019 // Since only 64-bit and 128-bit vectors are legal on ARM and
5020 // we've eliminated the other cases...
5021 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5022 "unexpected vector sizes in ReconstructShuffle");
5024 if (MaxElts[i] - MinElts[i] >= NumElts) {
5025 // Span too large for a VEXT to cope
5029 if (MinElts[i] >= NumElts) {
5030 // The extraction can just take the second half
5031 VEXTOffsets[i] = NumElts;
5032 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5034 DAG.getIntPtrConstant(NumElts));
5035 } else if (MaxElts[i] < NumElts) {
5036 // The extraction can just take the first half
5038 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5040 DAG.getIntPtrConstant(0));
5042 // An actual VEXT is needed
5043 VEXTOffsets[i] = MinElts[i];
5044 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5046 DAG.getIntPtrConstant(0));
5047 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5049 DAG.getIntPtrConstant(NumElts));
5050 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5051 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5055 SmallVector<int, 8> Mask;
5057 for (unsigned i = 0; i < NumElts; ++i) {
5058 SDValue Entry = Op.getOperand(i);
5059 if (Entry.getOpcode() == ISD::UNDEF) {
5064 SDValue ExtractVec = Entry.getOperand(0);
5065 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5066 .getOperand(1))->getSExtValue();
5067 if (ExtractVec == SourceVecs[0]) {
5068 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5070 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5074 // Final check before we try to produce nonsense...
5075 if (isShuffleMaskLegal(Mask, VT))
5076 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5082 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5083 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5084 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5085 /// are assumed to be legal.
5087 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5089 if (VT.getVectorNumElements() == 4 &&
5090 (VT.is128BitVector() || VT.is64BitVector())) {
5091 unsigned PFIndexes[4];
5092 for (unsigned i = 0; i != 4; ++i) {
5096 PFIndexes[i] = M[i];
5099 // Compute the index in the perfect shuffle table.
5100 unsigned PFTableIndex =
5101 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5102 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5103 unsigned Cost = (PFEntry >> 30);
5110 unsigned Imm, WhichResult;
5112 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5113 return (EltSize >= 32 ||
5114 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5115 isVREVMask(M, VT, 64) ||
5116 isVREVMask(M, VT, 32) ||
5117 isVREVMask(M, VT, 16) ||
5118 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5119 isVTBLMask(M, VT) ||
5120 isVTRNMask(M, VT, WhichResult) ||
5121 isVUZPMask(M, VT, WhichResult) ||
5122 isVZIPMask(M, VT, WhichResult) ||
5123 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5124 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5125 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5126 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5129 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5130 /// the specified operations to build the shuffle.
5131 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5132 SDValue RHS, SelectionDAG &DAG,
5134 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5135 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5136 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5139 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5148 OP_VUZPL, // VUZP, left result
5149 OP_VUZPR, // VUZP, right result
5150 OP_VZIPL, // VZIP, left result
5151 OP_VZIPR, // VZIP, right result
5152 OP_VTRNL, // VTRN, left result
5153 OP_VTRNR // VTRN, right result
5156 if (OpNum == OP_COPY) {
5157 if (LHSID == (1*9+2)*9+3) return LHS;
5158 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5162 SDValue OpLHS, OpRHS;
5163 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5164 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5165 EVT VT = OpLHS.getValueType();
5168 default: llvm_unreachable("Unknown shuffle opcode!");
5170 // VREV divides the vector in half and swaps within the half.
5171 if (VT.getVectorElementType() == MVT::i32 ||
5172 VT.getVectorElementType() == MVT::f32)
5173 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5174 // vrev <4 x i16> -> VREV32
5175 if (VT.getVectorElementType() == MVT::i16)
5176 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5177 // vrev <4 x i8> -> VREV16
5178 assert(VT.getVectorElementType() == MVT::i8);
5179 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5184 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5185 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5189 return DAG.getNode(ARMISD::VEXT, dl, VT,
5191 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5194 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5195 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5198 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5199 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5202 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5203 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5207 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5208 ArrayRef<int> ShuffleMask,
5209 SelectionDAG &DAG) {
5210 // Check to see if we can use the VTBL instruction.
5211 SDValue V1 = Op.getOperand(0);
5212 SDValue V2 = Op.getOperand(1);
5215 SmallVector<SDValue, 8> VTBLMask;
5216 for (ArrayRef<int>::iterator
5217 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5218 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5220 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5221 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5222 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5225 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5226 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5230 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5231 SelectionDAG &DAG) {
5233 SDValue OpLHS = Op.getOperand(0);
5234 EVT VT = OpLHS.getValueType();
5236 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5237 "Expect an v8i16/v16i8 type");
5238 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5239 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5240 // extract the first 8 bytes into the top double word and the last 8 bytes
5241 // into the bottom double word. The v8i16 case is similar.
5242 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5243 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5244 DAG.getConstant(ExtractNum, MVT::i32));
5247 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5248 SDValue V1 = Op.getOperand(0);
5249 SDValue V2 = Op.getOperand(1);
5251 EVT VT = Op.getValueType();
5252 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5254 // Convert shuffles that are directly supported on NEON to target-specific
5255 // DAG nodes, instead of keeping them as shuffles and matching them again
5256 // during code selection. This is more efficient and avoids the possibility
5257 // of inconsistencies between legalization and selection.
5258 // FIXME: floating-point vectors should be canonicalized to integer vectors
5259 // of the same time so that they get CSEd properly.
5260 ArrayRef<int> ShuffleMask = SVN->getMask();
5262 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5263 if (EltSize <= 32) {
5264 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5265 int Lane = SVN->getSplatIndex();
5266 // If this is undef splat, generate it via "just" vdup, if possible.
5267 if (Lane == -1) Lane = 0;
5269 // Test if V1 is a SCALAR_TO_VECTOR.
5270 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5271 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5273 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5274 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5276 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5277 !isa<ConstantSDNode>(V1.getOperand(0))) {
5278 bool IsScalarToVector = true;
5279 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5280 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5281 IsScalarToVector = false;
5284 if (IsScalarToVector)
5285 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5287 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5288 DAG.getConstant(Lane, MVT::i32));
5293 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5296 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5297 DAG.getConstant(Imm, MVT::i32));
5300 if (isVREVMask(ShuffleMask, VT, 64))
5301 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5302 if (isVREVMask(ShuffleMask, VT, 32))
5303 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5304 if (isVREVMask(ShuffleMask, VT, 16))
5305 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5307 if (V2->getOpcode() == ISD::UNDEF &&
5308 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5309 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5310 DAG.getConstant(Imm, MVT::i32));
5313 // Check for Neon shuffles that modify both input vectors in place.
5314 // If both results are used, i.e., if there are two shuffles with the same
5315 // source operands and with masks corresponding to both results of one of
5316 // these operations, DAG memoization will ensure that a single node is
5317 // used for both shuffles.
5318 unsigned WhichResult;
5319 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5320 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5321 V1, V2).getValue(WhichResult);
5322 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5323 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5324 V1, V2).getValue(WhichResult);
5325 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5326 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5327 V1, V2).getValue(WhichResult);
5329 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5330 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5331 V1, V1).getValue(WhichResult);
5332 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5333 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5334 V1, V1).getValue(WhichResult);
5335 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5336 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5337 V1, V1).getValue(WhichResult);
5340 // If the shuffle is not directly supported and it has 4 elements, use
5341 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5342 unsigned NumElts = VT.getVectorNumElements();
5344 unsigned PFIndexes[4];
5345 for (unsigned i = 0; i != 4; ++i) {
5346 if (ShuffleMask[i] < 0)
5349 PFIndexes[i] = ShuffleMask[i];
5352 // Compute the index in the perfect shuffle table.
5353 unsigned PFTableIndex =
5354 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5355 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5356 unsigned Cost = (PFEntry >> 30);
5359 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5362 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5363 if (EltSize >= 32) {
5364 // Do the expansion with floating-point types, since that is what the VFP
5365 // registers are defined to use, and since i64 is not legal.
5366 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5367 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5368 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5369 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5370 SmallVector<SDValue, 8> Ops;
5371 for (unsigned i = 0; i < NumElts; ++i) {
5372 if (ShuffleMask[i] < 0)
5373 Ops.push_back(DAG.getUNDEF(EltVT));
5375 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5376 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5377 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5380 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5381 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5384 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5385 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5387 if (VT == MVT::v8i8) {
5388 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5389 if (NewOp.getNode())
5396 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5397 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5398 SDValue Lane = Op.getOperand(2);
5399 if (!isa<ConstantSDNode>(Lane))
5405 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5406 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5407 SDValue Lane = Op.getOperand(1);
5408 if (!isa<ConstantSDNode>(Lane))
5411 SDValue Vec = Op.getOperand(0);
5412 if (Op.getValueType() == MVT::i32 &&
5413 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5415 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5421 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5422 // The only time a CONCAT_VECTORS operation can have legal types is when
5423 // two 64-bit vectors are concatenated to a 128-bit vector.
5424 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5425 "unexpected CONCAT_VECTORS");
5427 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5428 SDValue Op0 = Op.getOperand(0);
5429 SDValue Op1 = Op.getOperand(1);
5430 if (Op0.getOpcode() != ISD::UNDEF)
5431 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5432 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5433 DAG.getIntPtrConstant(0));
5434 if (Op1.getOpcode() != ISD::UNDEF)
5435 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5436 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5437 DAG.getIntPtrConstant(1));
5438 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5441 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5442 /// element has been zero/sign-extended, depending on the isSigned parameter,
5443 /// from an integer type half its size.
5444 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5446 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5447 EVT VT = N->getValueType(0);
5448 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5449 SDNode *BVN = N->getOperand(0).getNode();
5450 if (BVN->getValueType(0) != MVT::v4i32 ||
5451 BVN->getOpcode() != ISD::BUILD_VECTOR)
5453 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5454 unsigned HiElt = 1 - LoElt;
5455 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5456 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5457 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5458 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5459 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5462 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5463 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5466 if (Hi0->isNullValue() && Hi1->isNullValue())
5472 if (N->getOpcode() != ISD::BUILD_VECTOR)
5475 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5476 SDNode *Elt = N->getOperand(i).getNode();
5477 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5478 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5479 unsigned HalfSize = EltSize / 2;
5481 if (!isIntN(HalfSize, C->getSExtValue()))
5484 if (!isUIntN(HalfSize, C->getZExtValue()))
5495 /// isSignExtended - Check if a node is a vector value that is sign-extended
5496 /// or a constant BUILD_VECTOR with sign-extended elements.
5497 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5498 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5500 if (isExtendedBUILD_VECTOR(N, DAG, true))
5505 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5506 /// or a constant BUILD_VECTOR with zero-extended elements.
5507 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5508 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5510 if (isExtendedBUILD_VECTOR(N, DAG, false))
5515 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5516 if (OrigVT.getSizeInBits() >= 64)
5519 assert(OrigVT.isSimple() && "Expecting a simple value type");
5521 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5522 switch (OrigSimpleTy) {
5523 default: llvm_unreachable("Unexpected Vector Type");
5532 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5533 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5534 /// We insert the required extension here to get the vector to fill a D register.
5535 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5538 unsigned ExtOpcode) {
5539 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5540 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5541 // 64-bits we need to insert a new extension so that it will be 64-bits.
5542 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5543 if (OrigTy.getSizeInBits() >= 64)
5546 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5547 EVT NewVT = getExtensionTo64Bits(OrigTy);
5549 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5552 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5553 /// does not do any sign/zero extension. If the original vector is less
5554 /// than 64 bits, an appropriate extension will be added after the load to
5555 /// reach a total size of 64 bits. We have to add the extension separately
5556 /// because ARM does not have a sign/zero extending load for vectors.
5557 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5558 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5560 // The load already has the right type.
5561 if (ExtendedTy == LD->getMemoryVT())
5562 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5563 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5564 LD->isNonTemporal(), LD->isInvariant(),
5565 LD->getAlignment());
5567 // We need to create a zextload/sextload. We cannot just create a load
5568 // followed by a zext/zext node because LowerMUL is also run during normal
5569 // operation legalization where we can't create illegal types.
5570 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5571 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5572 LD->getMemoryVT(), LD->isVolatile(),
5573 LD->isNonTemporal(), LD->getAlignment());
5576 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5577 /// extending load, or BUILD_VECTOR with extended elements, return the
5578 /// unextended value. The unextended vector should be 64 bits so that it can
5579 /// be used as an operand to a VMULL instruction. If the original vector size
5580 /// before extension is less than 64 bits we add a an extension to resize
5581 /// the vector to 64 bits.
5582 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5583 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5584 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5585 N->getOperand(0)->getValueType(0),
5589 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5590 return SkipLoadExtensionForVMULL(LD, DAG);
5592 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5593 // have been legalized as a BITCAST from v4i32.
5594 if (N->getOpcode() == ISD::BITCAST) {
5595 SDNode *BVN = N->getOperand(0).getNode();
5596 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5597 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5598 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5599 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5600 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5602 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5603 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5604 EVT VT = N->getValueType(0);
5605 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5606 unsigned NumElts = VT.getVectorNumElements();
5607 MVT TruncVT = MVT::getIntegerVT(EltSize);
5608 SmallVector<SDValue, 8> Ops;
5609 for (unsigned i = 0; i != NumElts; ++i) {
5610 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5611 const APInt &CInt = C->getAPIntValue();
5612 // Element types smaller than 32 bits are not legal, so use i32 elements.
5613 // The values are implicitly truncated so sext vs. zext doesn't matter.
5614 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5616 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5617 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5620 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5621 unsigned Opcode = N->getOpcode();
5622 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5623 SDNode *N0 = N->getOperand(0).getNode();
5624 SDNode *N1 = N->getOperand(1).getNode();
5625 return N0->hasOneUse() && N1->hasOneUse() &&
5626 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5631 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5632 unsigned Opcode = N->getOpcode();
5633 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5634 SDNode *N0 = N->getOperand(0).getNode();
5635 SDNode *N1 = N->getOperand(1).getNode();
5636 return N0->hasOneUse() && N1->hasOneUse() &&
5637 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5642 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5643 // Multiplications are only custom-lowered for 128-bit vectors so that
5644 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5645 EVT VT = Op.getValueType();
5646 assert(VT.is128BitVector() && VT.isInteger() &&
5647 "unexpected type for custom-lowering ISD::MUL");
5648 SDNode *N0 = Op.getOperand(0).getNode();
5649 SDNode *N1 = Op.getOperand(1).getNode();
5650 unsigned NewOpc = 0;
5652 bool isN0SExt = isSignExtended(N0, DAG);
5653 bool isN1SExt = isSignExtended(N1, DAG);
5654 if (isN0SExt && isN1SExt)
5655 NewOpc = ARMISD::VMULLs;
5657 bool isN0ZExt = isZeroExtended(N0, DAG);
5658 bool isN1ZExt = isZeroExtended(N1, DAG);
5659 if (isN0ZExt && isN1ZExt)
5660 NewOpc = ARMISD::VMULLu;
5661 else if (isN1SExt || isN1ZExt) {
5662 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5663 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5664 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5665 NewOpc = ARMISD::VMULLs;
5667 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5668 NewOpc = ARMISD::VMULLu;
5670 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5672 NewOpc = ARMISD::VMULLu;
5678 if (VT == MVT::v2i64)
5679 // Fall through to expand this. It is not legal.
5682 // Other vector multiplications are legal.
5687 // Legalize to a VMULL instruction.
5690 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5692 Op0 = SkipExtensionForVMULL(N0, DAG);
5693 assert(Op0.getValueType().is64BitVector() &&
5694 Op1.getValueType().is64BitVector() &&
5695 "unexpected types for extended operands to VMULL");
5696 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5699 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5700 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5707 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5708 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5709 EVT Op1VT = Op1.getValueType();
5710 return DAG.getNode(N0->getOpcode(), DL, VT,
5711 DAG.getNode(NewOpc, DL, VT,
5712 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5713 DAG.getNode(NewOpc, DL, VT,
5714 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5718 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5720 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5721 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5722 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5723 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5724 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5725 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5726 // Get reciprocal estimate.
5727 // float4 recip = vrecpeq_f32(yf);
5728 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5729 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5730 // Because char has a smaller range than uchar, we can actually get away
5731 // without any newton steps. This requires that we use a weird bias
5732 // of 0xb000, however (again, this has been exhaustively tested).
5733 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5734 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5735 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5736 Y = DAG.getConstant(0xb000, MVT::i32);
5737 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5738 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5739 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5740 // Convert back to short.
5741 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5742 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5747 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5749 // Convert to float.
5750 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5751 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5752 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5753 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5754 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5755 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5757 // Use reciprocal estimate and one refinement step.
5758 // float4 recip = vrecpeq_f32(yf);
5759 // recip *= vrecpsq_f32(yf, recip);
5760 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5761 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5762 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5763 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5765 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5766 // Because short has a smaller range than ushort, we can actually get away
5767 // with only a single newton step. This requires that we use a weird bias
5768 // of 89, however (again, this has been exhaustively tested).
5769 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5770 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5771 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5772 N1 = DAG.getConstant(0x89, MVT::i32);
5773 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5774 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5775 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5776 // Convert back to integer and return.
5777 // return vmovn_s32(vcvt_s32_f32(result));
5778 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5779 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5783 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5784 EVT VT = Op.getValueType();
5785 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5786 "unexpected type for custom-lowering ISD::SDIV");
5789 SDValue N0 = Op.getOperand(0);
5790 SDValue N1 = Op.getOperand(1);
5793 if (VT == MVT::v8i8) {
5794 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5795 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5797 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5798 DAG.getIntPtrConstant(4));
5799 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5800 DAG.getIntPtrConstant(4));
5801 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5802 DAG.getIntPtrConstant(0));
5803 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5804 DAG.getIntPtrConstant(0));
5806 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5807 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5809 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5810 N0 = LowerCONCAT_VECTORS(N0, DAG);
5812 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5815 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5818 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5819 EVT VT = Op.getValueType();
5820 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5821 "unexpected type for custom-lowering ISD::UDIV");
5824 SDValue N0 = Op.getOperand(0);
5825 SDValue N1 = Op.getOperand(1);
5828 if (VT == MVT::v8i8) {
5829 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5830 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5832 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5833 DAG.getIntPtrConstant(4));
5834 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5835 DAG.getIntPtrConstant(4));
5836 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5837 DAG.getIntPtrConstant(0));
5838 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5839 DAG.getIntPtrConstant(0));
5841 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5842 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5844 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5845 N0 = LowerCONCAT_VECTORS(N0, DAG);
5847 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5848 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5853 // v4i16 sdiv ... Convert to float.
5854 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5855 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5856 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5857 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5858 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5859 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5861 // Use reciprocal estimate and two refinement steps.
5862 // float4 recip = vrecpeq_f32(yf);
5863 // recip *= vrecpsq_f32(yf, recip);
5864 // recip *= vrecpsq_f32(yf, recip);
5865 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5866 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5867 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5868 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5870 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5871 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5872 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5874 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5875 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5876 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5877 // and that it will never cause us to return an answer too large).
5878 // float4 result = as_float4(as_int4(xf*recip) + 2);
5879 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5880 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5881 N1 = DAG.getConstant(2, MVT::i32);
5882 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5883 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5884 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5885 // Convert back to integer and return.
5886 // return vmovn_u32(vcvt_s32_f32(result));
5887 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5888 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5892 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5893 EVT VT = Op.getNode()->getValueType(0);
5894 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5897 bool ExtraOp = false;
5898 switch (Op.getOpcode()) {
5899 default: llvm_unreachable("Invalid code");
5900 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5901 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5902 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5903 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5907 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5909 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5910 Op.getOperand(1), Op.getOperand(2));
5913 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5914 // Monotonic load/store is legal for all targets
5915 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5918 // Aquire/Release load/store is not legal for targets without a
5919 // dmb or equivalent available.
5924 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5925 SelectionDAG &DAG, unsigned NewOp) {
5927 assert (Node->getValueType(0) == MVT::i64 &&
5928 "Only know how to expand i64 atomics");
5930 SmallVector<SDValue, 6> Ops;
5931 Ops.push_back(Node->getOperand(0)); // Chain
5932 Ops.push_back(Node->getOperand(1)); // Ptr
5934 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5935 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5936 // High part of Val1
5937 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5938 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5939 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5940 // High part of Val1
5941 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5942 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5943 // High part of Val2
5944 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5945 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5947 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5949 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5950 cast<MemSDNode>(Node)->getMemOperand());
5951 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5952 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5953 Results.push_back(Result.getValue(2));
5956 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5957 SmallVectorImpl<SDValue> &Results,
5959 const ARMSubtarget *Subtarget) {
5961 SDValue Cycles32, OutChain;
5963 if (Subtarget->hasPerfMon()) {
5964 // Under Power Management extensions, the cycle-count is:
5965 // mrc p15, #0, <Rt>, c9, c13, #0
5966 SDValue Ops[] = { N->getOperand(0), // Chain
5967 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5968 DAG.getConstant(15, MVT::i32),
5969 DAG.getConstant(0, MVT::i32),
5970 DAG.getConstant(9, MVT::i32),
5971 DAG.getConstant(13, MVT::i32),
5972 DAG.getConstant(0, MVT::i32)
5975 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
5976 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
5977 array_lengthof(Ops));
5978 OutChain = Cycles32.getValue(1);
5980 // Intrinsic is defined to return 0 on unsupported platforms. Technically
5981 // there are older ARM CPUs that have implementation-specific ways of
5982 // obtaining this information (FIXME!).
5983 Cycles32 = DAG.getConstant(0, MVT::i32);
5984 OutChain = DAG.getEntryNode();
5988 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
5989 Cycles32, DAG.getConstant(0, MVT::i32));
5990 Results.push_back(Cycles64);
5991 Results.push_back(OutChain);
5994 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5995 switch (Op.getOpcode()) {
5996 default: llvm_unreachable("Don't know how to custom lower this!");
5997 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5998 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5999 case ISD::GlobalAddress:
6000 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6001 LowerGlobalAddressELF(Op, DAG);
6002 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6003 case ISD::SELECT: return LowerSELECT(Op, DAG);
6004 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6005 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6006 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6007 case ISD::VASTART: return LowerVASTART(Op, DAG);
6008 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6009 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6010 case ISD::SINT_TO_FP:
6011 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6012 case ISD::FP_TO_SINT:
6013 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6014 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6015 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6016 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6017 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6018 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6019 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6020 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6022 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6025 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6026 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6027 case ISD::SRL_PARTS:
6028 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6029 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6030 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6031 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6032 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6033 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6034 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6035 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6036 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6037 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6038 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6039 case ISD::MUL: return LowerMUL(Op, DAG);
6040 case ISD::SDIV: return LowerSDIV(Op, DAG);
6041 case ISD::UDIV: return LowerUDIV(Op, DAG);
6045 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6046 case ISD::ATOMIC_LOAD:
6047 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6049 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6053 /// ReplaceNodeResults - Replace the results of node with an illegal result
6054 /// type with new values built out of custom code.
6055 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6056 SmallVectorImpl<SDValue>&Results,
6057 SelectionDAG &DAG) const {
6059 switch (N->getOpcode()) {
6061 llvm_unreachable("Don't know how to custom expand this!");
6063 Res = ExpandBITCAST(N, DAG);
6065 case ISD::SIGN_EXTEND:
6066 case ISD::ZERO_EXTEND:
6067 Res = ExpandVectorExtension(N, DAG);
6071 Res = Expand64BitShift(N, DAG, Subtarget);
6073 case ISD::READCYCLECOUNTER:
6074 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6076 case ISD::ATOMIC_LOAD_ADD:
6077 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
6079 case ISD::ATOMIC_LOAD_AND:
6080 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
6082 case ISD::ATOMIC_LOAD_NAND:
6083 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
6085 case ISD::ATOMIC_LOAD_OR:
6086 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
6088 case ISD::ATOMIC_LOAD_SUB:
6089 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
6091 case ISD::ATOMIC_LOAD_XOR:
6092 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
6094 case ISD::ATOMIC_SWAP:
6095 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
6097 case ISD::ATOMIC_CMP_SWAP:
6098 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
6100 case ISD::ATOMIC_LOAD_MIN:
6101 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
6103 case ISD::ATOMIC_LOAD_UMIN:
6104 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
6106 case ISD::ATOMIC_LOAD_MAX:
6107 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
6109 case ISD::ATOMIC_LOAD_UMAX:
6110 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
6114 Results.push_back(Res);
6117 //===----------------------------------------------------------------------===//
6118 // ARM Scheduler Hooks
6119 //===----------------------------------------------------------------------===//
6122 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6123 MachineBasicBlock *BB,
6124 unsigned Size) const {
6125 unsigned dest = MI->getOperand(0).getReg();
6126 unsigned ptr = MI->getOperand(1).getReg();
6127 unsigned oldval = MI->getOperand(2).getReg();
6128 unsigned newval = MI->getOperand(3).getReg();
6129 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6130 DebugLoc dl = MI->getDebugLoc();
6131 bool isThumb2 = Subtarget->isThumb2();
6133 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6134 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6135 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6136 (const TargetRegisterClass*)&ARM::GPRRegClass);
6139 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6140 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6141 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6144 unsigned ldrOpc, strOpc;
6146 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6148 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6149 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6152 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6153 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6156 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6157 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6161 MachineFunction *MF = BB->getParent();
6162 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6163 MachineFunction::iterator It = BB;
6164 ++It; // insert the new blocks after the current block
6166 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6167 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6168 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6169 MF->insert(It, loop1MBB);
6170 MF->insert(It, loop2MBB);
6171 MF->insert(It, exitMBB);
6173 // Transfer the remainder of BB and its successor edges to exitMBB.
6174 exitMBB->splice(exitMBB->begin(), BB,
6175 llvm::next(MachineBasicBlock::iterator(MI)),
6177 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6181 // fallthrough --> loop1MBB
6182 BB->addSuccessor(loop1MBB);
6185 // ldrex dest, [ptr]
6189 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6190 if (ldrOpc == ARM::t2LDREX)
6192 AddDefaultPred(MIB);
6193 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6194 .addReg(dest).addReg(oldval));
6195 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6196 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6197 BB->addSuccessor(loop2MBB);
6198 BB->addSuccessor(exitMBB);
6201 // strex scratch, newval, [ptr]
6205 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6206 if (strOpc == ARM::t2STREX)
6208 AddDefaultPred(MIB);
6209 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6210 .addReg(scratch).addImm(0));
6211 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6212 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6213 BB->addSuccessor(loop1MBB);
6214 BB->addSuccessor(exitMBB);
6220 MI->eraseFromParent(); // The instruction is gone now.
6226 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6227 unsigned Size, unsigned BinOpcode) const {
6228 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6229 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6231 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6232 MachineFunction *MF = BB->getParent();
6233 MachineFunction::iterator It = BB;
6236 unsigned dest = MI->getOperand(0).getReg();
6237 unsigned ptr = MI->getOperand(1).getReg();
6238 unsigned incr = MI->getOperand(2).getReg();
6239 DebugLoc dl = MI->getDebugLoc();
6240 bool isThumb2 = Subtarget->isThumb2();
6242 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6244 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6245 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6248 unsigned ldrOpc, strOpc;
6250 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6252 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6253 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6256 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6257 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6260 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6261 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6265 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6266 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6267 MF->insert(It, loopMBB);
6268 MF->insert(It, exitMBB);
6270 // Transfer the remainder of BB and its successor edges to exitMBB.
6271 exitMBB->splice(exitMBB->begin(), BB,
6272 llvm::next(MachineBasicBlock::iterator(MI)),
6274 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6276 const TargetRegisterClass *TRC = isThumb2 ?
6277 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6278 (const TargetRegisterClass*)&ARM::GPRRegClass;
6279 unsigned scratch = MRI.createVirtualRegister(TRC);
6280 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6284 // fallthrough --> loopMBB
6285 BB->addSuccessor(loopMBB);
6289 // <binop> scratch2, dest, incr
6290 // strex scratch, scratch2, ptr
6293 // fallthrough --> exitMBB
6295 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6296 if (ldrOpc == ARM::t2LDREX)
6298 AddDefaultPred(MIB);
6300 // operand order needs to go the other way for NAND
6301 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6302 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6303 addReg(incr).addReg(dest)).addReg(0);
6305 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6306 addReg(dest).addReg(incr)).addReg(0);
6309 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6310 if (strOpc == ARM::t2STREX)
6312 AddDefaultPred(MIB);
6313 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6314 .addReg(scratch).addImm(0));
6315 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6316 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6318 BB->addSuccessor(loopMBB);
6319 BB->addSuccessor(exitMBB);
6325 MI->eraseFromParent(); // The instruction is gone now.
6331 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6332 MachineBasicBlock *BB,
6335 ARMCC::CondCodes Cond) const {
6336 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6338 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6339 MachineFunction *MF = BB->getParent();
6340 MachineFunction::iterator It = BB;
6343 unsigned dest = MI->getOperand(0).getReg();
6344 unsigned ptr = MI->getOperand(1).getReg();
6345 unsigned incr = MI->getOperand(2).getReg();
6346 unsigned oldval = dest;
6347 DebugLoc dl = MI->getDebugLoc();
6348 bool isThumb2 = Subtarget->isThumb2();
6350 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6352 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6353 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6356 unsigned ldrOpc, strOpc, extendOpc;
6358 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6360 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6361 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6362 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6365 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6366 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6367 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6370 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6371 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6376 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6377 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6378 MF->insert(It, loopMBB);
6379 MF->insert(It, exitMBB);
6381 // Transfer the remainder of BB and its successor edges to exitMBB.
6382 exitMBB->splice(exitMBB->begin(), BB,
6383 llvm::next(MachineBasicBlock::iterator(MI)),
6385 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6387 const TargetRegisterClass *TRC = isThumb2 ?
6388 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6389 (const TargetRegisterClass*)&ARM::GPRRegClass;
6390 unsigned scratch = MRI.createVirtualRegister(TRC);
6391 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6395 // fallthrough --> loopMBB
6396 BB->addSuccessor(loopMBB);
6400 // (sign extend dest, if required)
6402 // cmov.cond scratch2, incr, dest
6403 // strex scratch, scratch2, ptr
6406 // fallthrough --> exitMBB
6408 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6409 if (ldrOpc == ARM::t2LDREX)
6411 AddDefaultPred(MIB);
6413 // Sign extend the value, if necessary.
6414 if (signExtend && extendOpc) {
6415 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6416 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6421 // Build compare and cmov instructions.
6422 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6423 .addReg(oldval).addReg(incr));
6424 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6425 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6427 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6428 if (strOpc == ARM::t2STREX)
6430 AddDefaultPred(MIB);
6431 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6432 .addReg(scratch).addImm(0));
6433 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6434 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6436 BB->addSuccessor(loopMBB);
6437 BB->addSuccessor(exitMBB);
6443 MI->eraseFromParent(); // The instruction is gone now.
6449 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6450 unsigned Op1, unsigned Op2,
6451 bool NeedsCarry, bool IsCmpxchg,
6452 bool IsMinMax, ARMCC::CondCodes CC) const {
6453 // This also handles ATOMIC_SWAP, indicated by Op1==0.
6454 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6456 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6457 MachineFunction *MF = BB->getParent();
6458 MachineFunction::iterator It = BB;
6461 unsigned destlo = MI->getOperand(0).getReg();
6462 unsigned desthi = MI->getOperand(1).getReg();
6463 unsigned ptr = MI->getOperand(2).getReg();
6464 unsigned vallo = MI->getOperand(3).getReg();
6465 unsigned valhi = MI->getOperand(4).getReg();
6466 DebugLoc dl = MI->getDebugLoc();
6467 bool isThumb2 = Subtarget->isThumb2();
6469 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6471 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6472 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6473 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6474 MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6475 MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6478 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6479 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6480 if (IsCmpxchg || IsMinMax)
6481 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6483 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6484 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6486 MF->insert(It, loopMBB);
6487 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6488 if (IsCmpxchg) MF->insert(It, cont2BB);
6489 MF->insert(It, exitMBB);
6491 // Transfer the remainder of BB and its successor edges to exitMBB.
6492 exitMBB->splice(exitMBB->begin(), BB,
6493 llvm::next(MachineBasicBlock::iterator(MI)),
6495 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6497 const TargetRegisterClass *TRC = isThumb2 ?
6498 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6499 (const TargetRegisterClass*)&ARM::GPRRegClass;
6500 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6504 // fallthrough --> loopMBB
6505 BB->addSuccessor(loopMBB);
6508 // ldrexd r2, r3, ptr
6509 // <binopa> r0, r2, incr
6510 // <binopb> r1, r3, incr
6511 // strexd storesuccess, r0, r1, ptr
6512 // cmp storesuccess, #0
6514 // fallthrough --> exitMBB
6519 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6520 .addReg(destlo, RegState::Define)
6521 .addReg(desthi, RegState::Define)
6524 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6525 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6526 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6527 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6528 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6529 .addReg(GPRPair0, 0, ARM::gsub_0);
6530 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6531 .addReg(GPRPair0, 0, ARM::gsub_1);
6534 unsigned StoreLo, StoreHi;
6537 for (unsigned i = 0; i < 2; i++) {
6538 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6540 .addReg(i == 0 ? destlo : desthi)
6541 .addReg(i == 0 ? vallo : valhi));
6542 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6543 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6544 BB->addSuccessor(exitMBB);
6545 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6546 BB = (i == 0 ? contBB : cont2BB);
6549 // Copy to physregs for strexd
6550 StoreLo = MI->getOperand(5).getReg();
6551 StoreHi = MI->getOperand(6).getReg();
6553 // Perform binary operation
6554 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6555 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6556 .addReg(destlo).addReg(vallo))
6557 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6558 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6559 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6560 .addReg(desthi).addReg(valhi))
6561 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6566 // Copy to physregs for strexd
6571 // Compare and branch to exit block.
6572 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6573 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6574 BB->addSuccessor(exitMBB);
6575 BB->addSuccessor(contBB);
6583 MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6584 MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6585 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6586 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6588 // Marshal a pair...
6589 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6590 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6591 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6592 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6593 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6596 .addImm(ARM::gsub_0);
6597 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6600 .addImm(ARM::gsub_1);
6603 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6604 .addReg(StorePair).addReg(ptr));
6607 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6608 .addReg(storesuccess).addImm(0));
6609 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6610 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6612 BB->addSuccessor(loopMBB);
6613 BB->addSuccessor(exitMBB);
6619 MI->eraseFromParent(); // The instruction is gone now.
6624 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6625 /// registers the function context.
6626 void ARMTargetLowering::
6627 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6628 MachineBasicBlock *DispatchBB, int FI) const {
6629 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6630 DebugLoc dl = MI->getDebugLoc();
6631 MachineFunction *MF = MBB->getParent();
6632 MachineRegisterInfo *MRI = &MF->getRegInfo();
6633 MachineConstantPool *MCP = MF->getConstantPool();
6634 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6635 const Function *F = MF->getFunction();
6637 bool isThumb = Subtarget->isThumb();
6638 bool isThumb2 = Subtarget->isThumb2();
6640 unsigned PCLabelId = AFI->createPICLabelUId();
6641 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6642 ARMConstantPoolValue *CPV =
6643 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6644 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6646 const TargetRegisterClass *TRC = isThumb ?
6647 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6648 (const TargetRegisterClass*)&ARM::GPRRegClass;
6650 // Grab constant pool and fixed stack memory operands.
6651 MachineMemOperand *CPMMO =
6652 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6653 MachineMemOperand::MOLoad, 4, 4);
6655 MachineMemOperand *FIMMOSt =
6656 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6657 MachineMemOperand::MOStore, 4, 4);
6659 // Load the address of the dispatch MBB into the jump buffer.
6661 // Incoming value: jbuf
6662 // ldr.n r5, LCPI1_1
6665 // str r5, [$jbuf, #+4] ; &jbuf[1]
6666 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6667 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6668 .addConstantPoolIndex(CPI)
6669 .addMemOperand(CPMMO));
6670 // Set the low bit because of thumb mode.
6671 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6673 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6674 .addReg(NewVReg1, RegState::Kill)
6676 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6677 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6678 .addReg(NewVReg2, RegState::Kill)
6680 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6681 .addReg(NewVReg3, RegState::Kill)
6683 .addImm(36) // &jbuf[1] :: pc
6684 .addMemOperand(FIMMOSt));
6685 } else if (isThumb) {
6686 // Incoming value: jbuf
6687 // ldr.n r1, LCPI1_4
6691 // add r2, $jbuf, #+4 ; &jbuf[1]
6693 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6694 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6695 .addConstantPoolIndex(CPI)
6696 .addMemOperand(CPMMO));
6697 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6698 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6699 .addReg(NewVReg1, RegState::Kill)
6701 // Set the low bit because of thumb mode.
6702 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6703 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6704 .addReg(ARM::CPSR, RegState::Define)
6706 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6707 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6708 .addReg(ARM::CPSR, RegState::Define)
6709 .addReg(NewVReg2, RegState::Kill)
6710 .addReg(NewVReg3, RegState::Kill));
6711 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6712 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6714 .addImm(36)); // &jbuf[1] :: pc
6715 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6716 .addReg(NewVReg4, RegState::Kill)
6717 .addReg(NewVReg5, RegState::Kill)
6719 .addMemOperand(FIMMOSt));
6721 // Incoming value: jbuf
6724 // str r1, [$jbuf, #+4] ; &jbuf[1]
6725 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6726 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6727 .addConstantPoolIndex(CPI)
6729 .addMemOperand(CPMMO));
6730 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6731 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6732 .addReg(NewVReg1, RegState::Kill)
6733 .addImm(PCLabelId));
6734 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6735 .addReg(NewVReg2, RegState::Kill)
6737 .addImm(36) // &jbuf[1] :: pc
6738 .addMemOperand(FIMMOSt));
6742 MachineBasicBlock *ARMTargetLowering::
6743 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6744 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6745 DebugLoc dl = MI->getDebugLoc();
6746 MachineFunction *MF = MBB->getParent();
6747 MachineRegisterInfo *MRI = &MF->getRegInfo();
6748 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6749 MachineFrameInfo *MFI = MF->getFrameInfo();
6750 int FI = MFI->getFunctionContextIndex();
6752 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6753 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6754 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6756 // Get a mapping of the call site numbers to all of the landing pads they're
6758 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6759 unsigned MaxCSNum = 0;
6760 MachineModuleInfo &MMI = MF->getMMI();
6761 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6763 if (!BB->isLandingPad()) continue;
6765 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6767 for (MachineBasicBlock::iterator
6768 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6769 if (!II->isEHLabel()) continue;
6771 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6772 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6774 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6775 for (SmallVectorImpl<unsigned>::iterator
6776 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6777 CSI != CSE; ++CSI) {
6778 CallSiteNumToLPad[*CSI].push_back(BB);
6779 MaxCSNum = std::max(MaxCSNum, *CSI);
6785 // Get an ordered list of the machine basic blocks for the jump table.
6786 std::vector<MachineBasicBlock*> LPadList;
6787 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6788 LPadList.reserve(CallSiteNumToLPad.size());
6789 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6790 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6791 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6792 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6793 LPadList.push_back(*II);
6794 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6798 assert(!LPadList.empty() &&
6799 "No landing pad destinations for the dispatch jump table!");
6801 // Create the jump table and associated information.
6802 MachineJumpTableInfo *JTI =
6803 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6804 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6805 unsigned UId = AFI->createJumpTableUId();
6806 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6808 // Create the MBBs for the dispatch code.
6810 // Shove the dispatch's address into the return slot in the function context.
6811 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6812 DispatchBB->setIsLandingPad();
6814 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6815 unsigned trap_opcode;
6816 if (Subtarget->isThumb())
6817 trap_opcode = ARM::tTRAP;
6819 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6821 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6822 DispatchBB->addSuccessor(TrapBB);
6824 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6825 DispatchBB->addSuccessor(DispContBB);
6828 MF->insert(MF->end(), DispatchBB);
6829 MF->insert(MF->end(), DispContBB);
6830 MF->insert(MF->end(), TrapBB);
6832 // Insert code into the entry block that creates and registers the function
6834 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6836 MachineMemOperand *FIMMOLd =
6837 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6838 MachineMemOperand::MOLoad |
6839 MachineMemOperand::MOVolatile, 4, 4);
6841 MachineInstrBuilder MIB;
6842 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6844 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6845 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6847 // Add a register mask with no preserved registers. This results in all
6848 // registers being marked as clobbered.
6849 MIB.addRegMask(RI.getNoPreservedMask());
6851 unsigned NumLPads = LPadList.size();
6852 if (Subtarget->isThumb2()) {
6853 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6854 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6857 .addMemOperand(FIMMOLd));
6859 if (NumLPads < 256) {
6860 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6862 .addImm(LPadList.size()));
6864 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6865 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6866 .addImm(NumLPads & 0xFFFF));
6868 unsigned VReg2 = VReg1;
6869 if ((NumLPads & 0xFFFF0000) != 0) {
6870 VReg2 = MRI->createVirtualRegister(TRC);
6871 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6873 .addImm(NumLPads >> 16));
6876 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6881 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6886 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6887 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6888 .addJumpTableIndex(MJTI)
6891 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6894 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6895 .addReg(NewVReg3, RegState::Kill)
6897 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6899 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6900 .addReg(NewVReg4, RegState::Kill)
6902 .addJumpTableIndex(MJTI)
6904 } else if (Subtarget->isThumb()) {
6905 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6906 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6909 .addMemOperand(FIMMOLd));
6911 if (NumLPads < 256) {
6912 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6916 MachineConstantPool *ConstantPool = MF->getConstantPool();
6917 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6918 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6920 // MachineConstantPool wants an explicit alignment.
6921 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6923 Align = getDataLayout()->getTypeAllocSize(C->getType());
6924 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6926 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6927 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6928 .addReg(VReg1, RegState::Define)
6929 .addConstantPoolIndex(Idx));
6930 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6935 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6940 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6941 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6942 .addReg(ARM::CPSR, RegState::Define)
6946 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6947 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6948 .addJumpTableIndex(MJTI)
6951 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6952 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6953 .addReg(ARM::CPSR, RegState::Define)
6954 .addReg(NewVReg2, RegState::Kill)
6957 MachineMemOperand *JTMMOLd =
6958 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6959 MachineMemOperand::MOLoad, 4, 4);
6961 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6962 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6963 .addReg(NewVReg4, RegState::Kill)
6965 .addMemOperand(JTMMOLd));
6967 unsigned NewVReg6 = NewVReg5;
6968 if (RelocM == Reloc::PIC_) {
6969 NewVReg6 = MRI->createVirtualRegister(TRC);
6970 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6971 .addReg(ARM::CPSR, RegState::Define)
6972 .addReg(NewVReg5, RegState::Kill)
6976 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6977 .addReg(NewVReg6, RegState::Kill)
6978 .addJumpTableIndex(MJTI)
6981 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6982 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6985 .addMemOperand(FIMMOLd));
6987 if (NumLPads < 256) {
6988 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6991 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6992 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6993 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6994 .addImm(NumLPads & 0xFFFF));
6996 unsigned VReg2 = VReg1;
6997 if ((NumLPads & 0xFFFF0000) != 0) {
6998 VReg2 = MRI->createVirtualRegister(TRC);
6999 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7001 .addImm(NumLPads >> 16));
7004 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7008 MachineConstantPool *ConstantPool = MF->getConstantPool();
7009 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7010 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7012 // MachineConstantPool wants an explicit alignment.
7013 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7015 Align = getDataLayout()->getTypeAllocSize(C->getType());
7016 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7018 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7019 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7020 .addReg(VReg1, RegState::Define)
7021 .addConstantPoolIndex(Idx)
7023 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7025 .addReg(VReg1, RegState::Kill));
7028 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7033 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7035 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7037 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7038 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7039 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7040 .addJumpTableIndex(MJTI)
7043 MachineMemOperand *JTMMOLd =
7044 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7045 MachineMemOperand::MOLoad, 4, 4);
7046 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7048 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7049 .addReg(NewVReg3, RegState::Kill)
7052 .addMemOperand(JTMMOLd));
7054 if (RelocM == Reloc::PIC_) {
7055 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7056 .addReg(NewVReg5, RegState::Kill)
7058 .addJumpTableIndex(MJTI)
7061 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7062 .addReg(NewVReg5, RegState::Kill)
7063 .addJumpTableIndex(MJTI)
7068 // Add the jump table entries as successors to the MBB.
7069 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7070 for (std::vector<MachineBasicBlock*>::iterator
7071 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7072 MachineBasicBlock *CurMBB = *I;
7073 if (SeenMBBs.insert(CurMBB))
7074 DispContBB->addSuccessor(CurMBB);
7077 // N.B. the order the invoke BBs are processed in doesn't matter here.
7078 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7079 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7080 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7081 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7082 MachineBasicBlock *BB = *I;
7084 // Remove the landing pad successor from the invoke block and replace it
7085 // with the new dispatch block.
7086 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7088 while (!Successors.empty()) {
7089 MachineBasicBlock *SMBB = Successors.pop_back_val();
7090 if (SMBB->isLandingPad()) {
7091 BB->removeSuccessor(SMBB);
7092 MBBLPads.push_back(SMBB);
7096 BB->addSuccessor(DispatchBB);
7098 // Find the invoke call and mark all of the callee-saved registers as
7099 // 'implicit defined' so that they're spilled. This prevents code from
7100 // moving instructions to before the EH block, where they will never be
7102 for (MachineBasicBlock::reverse_iterator
7103 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7104 if (!II->isCall()) continue;
7106 DenseMap<unsigned, bool> DefRegs;
7107 for (MachineInstr::mop_iterator
7108 OI = II->operands_begin(), OE = II->operands_end();
7110 if (!OI->isReg()) continue;
7111 DefRegs[OI->getReg()] = true;
7114 MachineInstrBuilder MIB(*MF, &*II);
7116 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7117 unsigned Reg = SavedRegs[i];
7118 if (Subtarget->isThumb2() &&
7119 !ARM::tGPRRegClass.contains(Reg) &&
7120 !ARM::hGPRRegClass.contains(Reg))
7122 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7124 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7127 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7134 // Mark all former landing pads as non-landing pads. The dispatch is the only
7136 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7137 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7138 (*I)->setIsLandingPad(false);
7140 // The instruction is gone now.
7141 MI->eraseFromParent();
7147 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7148 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7149 E = MBB->succ_end(); I != E; ++I)
7152 llvm_unreachable("Expecting a BB with two successors!");
7155 MachineBasicBlock *ARMTargetLowering::
7156 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
7157 // This pseudo instruction has 3 operands: dst, src, size
7158 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7159 // Otherwise, we will generate unrolled scalar copies.
7160 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7161 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7162 MachineFunction::iterator It = BB;
7165 unsigned dest = MI->getOperand(0).getReg();
7166 unsigned src = MI->getOperand(1).getReg();
7167 unsigned SizeVal = MI->getOperand(2).getImm();
7168 unsigned Align = MI->getOperand(3).getImm();
7169 DebugLoc dl = MI->getDebugLoc();
7171 bool isThumb2 = Subtarget->isThumb2();
7172 MachineFunction *MF = BB->getParent();
7173 MachineRegisterInfo &MRI = MF->getRegInfo();
7174 unsigned ldrOpc, strOpc, UnitSize = 0;
7176 const TargetRegisterClass *TRC = isThumb2 ?
7177 (const TargetRegisterClass*)&ARM::tGPRRegClass :
7178 (const TargetRegisterClass*)&ARM::GPRRegClass;
7179 const TargetRegisterClass *TRC_Vec = 0;
7182 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7183 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7185 } else if (Align & 2) {
7186 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
7187 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
7190 // Check whether we can use NEON instructions.
7191 if (!MF->getFunction()->getAttributes().
7192 hasAttribute(AttributeSet::FunctionIndex,
7193 Attribute::NoImplicitFloat) &&
7194 Subtarget->hasNEON()) {
7195 if ((Align % 16 == 0) && SizeVal >= 16) {
7196 ldrOpc = ARM::VLD1q32wb_fixed;
7197 strOpc = ARM::VST1q32wb_fixed;
7199 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
7201 else if ((Align % 8 == 0) && SizeVal >= 8) {
7202 ldrOpc = ARM::VLD1d32wb_fixed;
7203 strOpc = ARM::VST1d32wb_fixed;
7205 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
7208 // Can't use NEON instructions.
7209 if (UnitSize == 0) {
7210 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
7211 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
7216 unsigned BytesLeft = SizeVal % UnitSize;
7217 unsigned LoopSize = SizeVal - BytesLeft;
7219 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7220 // Use LDR and STR to copy.
7221 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7222 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7223 unsigned srcIn = src;
7224 unsigned destIn = dest;
7225 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7226 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7227 unsigned srcOut = MRI.createVirtualRegister(TRC);
7228 unsigned destOut = MRI.createVirtualRegister(TRC);
7229 if (UnitSize >= 8) {
7230 AddDefaultPred(BuildMI(*BB, MI, dl,
7231 TII->get(ldrOpc), scratch)
7232 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7234 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7235 .addReg(destIn).addImm(0).addReg(scratch));
7236 } else if (isThumb2) {
7237 AddDefaultPred(BuildMI(*BB, MI, dl,
7238 TII->get(ldrOpc), scratch)
7239 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7241 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7242 .addReg(scratch).addReg(destIn)
7245 AddDefaultPred(BuildMI(*BB, MI, dl,
7246 TII->get(ldrOpc), scratch)
7247 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7250 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7251 .addReg(scratch).addReg(destIn)
7252 .addReg(0).addImm(UnitSize));
7258 // Handle the leftover bytes with LDRB and STRB.
7259 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7260 // [destOut] = STRB_POST(scratch, destIn, 1)
7261 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7262 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7263 for (unsigned i = 0; i < BytesLeft; i++) {
7264 unsigned scratch = MRI.createVirtualRegister(TRC);
7265 unsigned srcOut = MRI.createVirtualRegister(TRC);
7266 unsigned destOut = MRI.createVirtualRegister(TRC);
7268 AddDefaultPred(BuildMI(*BB, MI, dl,
7269 TII->get(ldrOpc),scratch)
7270 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7272 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7273 .addReg(scratch).addReg(destIn)
7274 .addReg(0).addImm(1));
7276 AddDefaultPred(BuildMI(*BB, MI, dl,
7277 TII->get(ldrOpc),scratch)
7278 .addReg(srcOut, RegState::Define).addReg(srcIn)
7279 .addReg(0).addImm(1));
7281 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7282 .addReg(scratch).addReg(destIn)
7283 .addReg(0).addImm(1));
7288 MI->eraseFromParent(); // The instruction is gone now.
7292 // Expand the pseudo op to a loop.
7295 // movw varEnd, # --> with thumb2
7297 // ldrcp varEnd, idx --> without thumb2
7298 // fallthrough --> loopMBB
7300 // PHI varPhi, varEnd, varLoop
7301 // PHI srcPhi, src, srcLoop
7302 // PHI destPhi, dst, destLoop
7303 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7304 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7305 // subs varLoop, varPhi, #UnitSize
7307 // fallthrough --> exitMBB
7309 // epilogue to handle left-over bytes
7310 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7311 // [destOut] = STRB_POST(scratch, destLoop, 1)
7312 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7313 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7314 MF->insert(It, loopMBB);
7315 MF->insert(It, exitMBB);
7317 // Transfer the remainder of BB and its successor edges to exitMBB.
7318 exitMBB->splice(exitMBB->begin(), BB,
7319 llvm::next(MachineBasicBlock::iterator(MI)),
7321 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7323 // Load an immediate to varEnd.
7324 unsigned varEnd = MRI.createVirtualRegister(TRC);
7326 unsigned VReg1 = varEnd;
7327 if ((LoopSize & 0xFFFF0000) != 0)
7328 VReg1 = MRI.createVirtualRegister(TRC);
7329 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7330 .addImm(LoopSize & 0xFFFF));
7332 if ((LoopSize & 0xFFFF0000) != 0)
7333 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7335 .addImm(LoopSize >> 16));
7337 MachineConstantPool *ConstantPool = MF->getConstantPool();
7338 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7339 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7341 // MachineConstantPool wants an explicit alignment.
7342 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7344 Align = getDataLayout()->getTypeAllocSize(C->getType());
7345 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7347 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7348 .addReg(varEnd, RegState::Define)
7349 .addConstantPoolIndex(Idx)
7352 BB->addSuccessor(loopMBB);
7354 // Generate the loop body:
7355 // varPhi = PHI(varLoop, varEnd)
7356 // srcPhi = PHI(srcLoop, src)
7357 // destPhi = PHI(destLoop, dst)
7358 MachineBasicBlock *entryBB = BB;
7360 unsigned varLoop = MRI.createVirtualRegister(TRC);
7361 unsigned varPhi = MRI.createVirtualRegister(TRC);
7362 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7363 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7364 unsigned destLoop = MRI.createVirtualRegister(TRC);
7365 unsigned destPhi = MRI.createVirtualRegister(TRC);
7367 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7368 .addReg(varLoop).addMBB(loopMBB)
7369 .addReg(varEnd).addMBB(entryBB);
7370 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7371 .addReg(srcLoop).addMBB(loopMBB)
7372 .addReg(src).addMBB(entryBB);
7373 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7374 .addReg(destLoop).addMBB(loopMBB)
7375 .addReg(dest).addMBB(entryBB);
7377 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7378 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7379 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7380 if (UnitSize >= 8) {
7381 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7382 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7384 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7385 .addReg(destPhi).addImm(0).addReg(scratch));
7386 } else if (isThumb2) {
7387 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7388 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7390 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7391 .addReg(scratch).addReg(destPhi)
7394 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7395 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7398 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7399 .addReg(scratch).addReg(destPhi)
7400 .addReg(0).addImm(UnitSize));
7403 // Decrement loop variable by UnitSize.
7404 MachineInstrBuilder MIB = BuildMI(BB, dl,
7405 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7406 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7407 MIB->getOperand(5).setReg(ARM::CPSR);
7408 MIB->getOperand(5).setIsDef(true);
7410 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7411 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7413 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7414 BB->addSuccessor(loopMBB);
7415 BB->addSuccessor(exitMBB);
7417 // Add epilogue to handle BytesLeft.
7419 MachineInstr *StartOfExit = exitMBB->begin();
7420 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7421 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7423 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7424 // [destOut] = STRB_POST(scratch, destLoop, 1)
7425 unsigned srcIn = srcLoop;
7426 unsigned destIn = destLoop;
7427 for (unsigned i = 0; i < BytesLeft; i++) {
7428 unsigned scratch = MRI.createVirtualRegister(TRC);
7429 unsigned srcOut = MRI.createVirtualRegister(TRC);
7430 unsigned destOut = MRI.createVirtualRegister(TRC);
7432 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7433 TII->get(ldrOpc),scratch)
7434 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7436 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7437 .addReg(scratch).addReg(destIn)
7440 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7441 TII->get(ldrOpc),scratch)
7442 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7444 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7445 .addReg(scratch).addReg(destIn)
7446 .addReg(0).addImm(1));
7452 MI->eraseFromParent(); // The instruction is gone now.
7457 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7458 MachineBasicBlock *BB) const {
7459 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7460 DebugLoc dl = MI->getDebugLoc();
7461 bool isThumb2 = Subtarget->isThumb2();
7462 switch (MI->getOpcode()) {
7465 llvm_unreachable("Unexpected instr type to insert");
7467 // The Thumb2 pre-indexed stores have the same MI operands, they just
7468 // define them differently in the .td files from the isel patterns, so
7469 // they need pseudos.
7470 case ARM::t2STR_preidx:
7471 MI->setDesc(TII->get(ARM::t2STR_PRE));
7473 case ARM::t2STRB_preidx:
7474 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7476 case ARM::t2STRH_preidx:
7477 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7480 case ARM::STRi_preidx:
7481 case ARM::STRBi_preidx: {
7482 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7483 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7484 // Decode the offset.
7485 unsigned Offset = MI->getOperand(4).getImm();
7486 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7487 Offset = ARM_AM::getAM2Offset(Offset);
7491 MachineMemOperand *MMO = *MI->memoperands_begin();
7492 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7493 .addOperand(MI->getOperand(0)) // Rn_wb
7494 .addOperand(MI->getOperand(1)) // Rt
7495 .addOperand(MI->getOperand(2)) // Rn
7496 .addImm(Offset) // offset (skip GPR==zero_reg)
7497 .addOperand(MI->getOperand(5)) // pred
7498 .addOperand(MI->getOperand(6))
7499 .addMemOperand(MMO);
7500 MI->eraseFromParent();
7503 case ARM::STRr_preidx:
7504 case ARM::STRBr_preidx:
7505 case ARM::STRH_preidx: {
7507 switch (MI->getOpcode()) {
7508 default: llvm_unreachable("unexpected opcode!");
7509 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7510 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7511 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7513 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7514 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7515 MIB.addOperand(MI->getOperand(i));
7516 MI->eraseFromParent();
7519 case ARM::ATOMIC_LOAD_ADD_I8:
7520 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7521 case ARM::ATOMIC_LOAD_ADD_I16:
7522 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7523 case ARM::ATOMIC_LOAD_ADD_I32:
7524 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7526 case ARM::ATOMIC_LOAD_AND_I8:
7527 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7528 case ARM::ATOMIC_LOAD_AND_I16:
7529 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7530 case ARM::ATOMIC_LOAD_AND_I32:
7531 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7533 case ARM::ATOMIC_LOAD_OR_I8:
7534 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7535 case ARM::ATOMIC_LOAD_OR_I16:
7536 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7537 case ARM::ATOMIC_LOAD_OR_I32:
7538 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7540 case ARM::ATOMIC_LOAD_XOR_I8:
7541 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7542 case ARM::ATOMIC_LOAD_XOR_I16:
7543 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7544 case ARM::ATOMIC_LOAD_XOR_I32:
7545 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7547 case ARM::ATOMIC_LOAD_NAND_I8:
7548 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7549 case ARM::ATOMIC_LOAD_NAND_I16:
7550 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7551 case ARM::ATOMIC_LOAD_NAND_I32:
7552 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7554 case ARM::ATOMIC_LOAD_SUB_I8:
7555 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7556 case ARM::ATOMIC_LOAD_SUB_I16:
7557 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7558 case ARM::ATOMIC_LOAD_SUB_I32:
7559 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7561 case ARM::ATOMIC_LOAD_MIN_I8:
7562 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7563 case ARM::ATOMIC_LOAD_MIN_I16:
7564 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7565 case ARM::ATOMIC_LOAD_MIN_I32:
7566 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7568 case ARM::ATOMIC_LOAD_MAX_I8:
7569 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7570 case ARM::ATOMIC_LOAD_MAX_I16:
7571 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7572 case ARM::ATOMIC_LOAD_MAX_I32:
7573 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7575 case ARM::ATOMIC_LOAD_UMIN_I8:
7576 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7577 case ARM::ATOMIC_LOAD_UMIN_I16:
7578 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7579 case ARM::ATOMIC_LOAD_UMIN_I32:
7580 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7582 case ARM::ATOMIC_LOAD_UMAX_I8:
7583 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7584 case ARM::ATOMIC_LOAD_UMAX_I16:
7585 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7586 case ARM::ATOMIC_LOAD_UMAX_I32:
7587 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7589 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7590 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7591 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7593 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7594 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7595 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7598 case ARM::ATOMADD6432:
7599 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7600 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7601 /*NeedsCarry*/ true);
7602 case ARM::ATOMSUB6432:
7603 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7604 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7605 /*NeedsCarry*/ true);
7606 case ARM::ATOMOR6432:
7607 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7608 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7609 case ARM::ATOMXOR6432:
7610 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7611 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7612 case ARM::ATOMAND6432:
7613 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7614 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7615 case ARM::ATOMSWAP6432:
7616 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7617 case ARM::ATOMCMPXCHG6432:
7618 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7619 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7620 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7621 case ARM::ATOMMIN6432:
7622 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7623 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7624 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7625 /*IsMinMax*/ true, ARMCC::LT);
7626 case ARM::ATOMMAX6432:
7627 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7628 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7629 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7630 /*IsMinMax*/ true, ARMCC::GE);
7631 case ARM::ATOMUMIN6432:
7632 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7633 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7634 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7635 /*IsMinMax*/ true, ARMCC::LO);
7636 case ARM::ATOMUMAX6432:
7637 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7638 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7639 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7640 /*IsMinMax*/ true, ARMCC::HS);
7642 case ARM::tMOVCCr_pseudo: {
7643 // To "insert" a SELECT_CC instruction, we actually have to insert the
7644 // diamond control-flow pattern. The incoming instruction knows the
7645 // destination vreg to set, the condition code register to branch on, the
7646 // true/false values to select between, and a branch opcode to use.
7647 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7648 MachineFunction::iterator It = BB;
7654 // cmpTY ccX, r1, r2
7656 // fallthrough --> copy0MBB
7657 MachineBasicBlock *thisMBB = BB;
7658 MachineFunction *F = BB->getParent();
7659 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7660 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7661 F->insert(It, copy0MBB);
7662 F->insert(It, sinkMBB);
7664 // Transfer the remainder of BB and its successor edges to sinkMBB.
7665 sinkMBB->splice(sinkMBB->begin(), BB,
7666 llvm::next(MachineBasicBlock::iterator(MI)),
7668 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7670 BB->addSuccessor(copy0MBB);
7671 BB->addSuccessor(sinkMBB);
7673 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7674 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7677 // %FalseValue = ...
7678 // # fallthrough to sinkMBB
7681 // Update machine-CFG edges
7682 BB->addSuccessor(sinkMBB);
7685 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7688 BuildMI(*BB, BB->begin(), dl,
7689 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7690 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7691 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7693 MI->eraseFromParent(); // The pseudo instruction is gone now.
7698 case ARM::BCCZi64: {
7699 // If there is an unconditional branch to the other successor, remove it.
7700 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7702 // Compare both parts that make up the double comparison separately for
7704 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7706 unsigned LHS1 = MI->getOperand(1).getReg();
7707 unsigned LHS2 = MI->getOperand(2).getReg();
7709 AddDefaultPred(BuildMI(BB, dl,
7710 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7711 .addReg(LHS1).addImm(0));
7712 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7713 .addReg(LHS2).addImm(0)
7714 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7716 unsigned RHS1 = MI->getOperand(3).getReg();
7717 unsigned RHS2 = MI->getOperand(4).getReg();
7718 AddDefaultPred(BuildMI(BB, dl,
7719 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7720 .addReg(LHS1).addReg(RHS1));
7721 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7722 .addReg(LHS2).addReg(RHS2)
7723 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7726 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7727 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7728 if (MI->getOperand(0).getImm() == ARMCC::NE)
7729 std::swap(destMBB, exitMBB);
7731 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7732 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7734 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7736 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7738 MI->eraseFromParent(); // The pseudo instruction is gone now.
7742 case ARM::Int_eh_sjlj_setjmp:
7743 case ARM::Int_eh_sjlj_setjmp_nofp:
7744 case ARM::tInt_eh_sjlj_setjmp:
7745 case ARM::t2Int_eh_sjlj_setjmp:
7746 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7747 EmitSjLjDispatchBlock(MI, BB);
7752 // To insert an ABS instruction, we have to insert the
7753 // diamond control-flow pattern. The incoming instruction knows the
7754 // source vreg to test against 0, the destination vreg to set,
7755 // the condition code register to branch on, the
7756 // true/false values to select between, and a branch opcode to use.
7761 // BCC (branch to SinkBB if V0 >= 0)
7762 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7763 // SinkBB: V1 = PHI(V2, V3)
7764 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7765 MachineFunction::iterator BBI = BB;
7767 MachineFunction *Fn = BB->getParent();
7768 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7769 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7770 Fn->insert(BBI, RSBBB);
7771 Fn->insert(BBI, SinkBB);
7773 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7774 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7775 bool isThumb2 = Subtarget->isThumb2();
7776 MachineRegisterInfo &MRI = Fn->getRegInfo();
7777 // In Thumb mode S must not be specified if source register is the SP or
7778 // PC and if destination register is the SP, so restrict register class
7779 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7780 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7781 (const TargetRegisterClass*)&ARM::GPRRegClass);
7783 // Transfer the remainder of BB and its successor edges to sinkMBB.
7784 SinkBB->splice(SinkBB->begin(), BB,
7785 llvm::next(MachineBasicBlock::iterator(MI)),
7787 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7789 BB->addSuccessor(RSBBB);
7790 BB->addSuccessor(SinkBB);
7792 // fall through to SinkMBB
7793 RSBBB->addSuccessor(SinkBB);
7795 // insert a cmp at the end of BB
7796 AddDefaultPred(BuildMI(BB, dl,
7797 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7798 .addReg(ABSSrcReg).addImm(0));
7800 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7802 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7803 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7805 // insert rsbri in RSBBB
7806 // Note: BCC and rsbri will be converted into predicated rsbmi
7807 // by if-conversion pass
7808 BuildMI(*RSBBB, RSBBB->begin(), dl,
7809 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7810 .addReg(ABSSrcReg, RegState::Kill)
7811 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7813 // insert PHI in SinkBB,
7814 // reuse ABSDstReg to not change uses of ABS instruction
7815 BuildMI(*SinkBB, SinkBB->begin(), dl,
7816 TII->get(ARM::PHI), ABSDstReg)
7817 .addReg(NewRsbDstReg).addMBB(RSBBB)
7818 .addReg(ABSSrcReg).addMBB(BB);
7820 // remove ABS instruction
7821 MI->eraseFromParent();
7823 // return last added BB
7826 case ARM::COPY_STRUCT_BYVAL_I32:
7828 return EmitStructByval(MI, BB);
7832 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7833 SDNode *Node) const {
7834 if (!MI->hasPostISelHook()) {
7835 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7836 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7840 const MCInstrDesc *MCID = &MI->getDesc();
7841 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7842 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7843 // operand is still set to noreg. If needed, set the optional operand's
7844 // register to CPSR, and remove the redundant implicit def.
7846 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7848 // Rename pseudo opcodes.
7849 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7851 const ARMBaseInstrInfo *TII =
7852 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7853 MCID = &TII->get(NewOpc);
7855 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7856 "converted opcode should be the same except for cc_out");
7860 // Add the optional cc_out operand
7861 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7863 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7865 // Any ARM instruction that sets the 's' bit should specify an optional
7866 // "cc_out" operand in the last operand position.
7867 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7868 assert(!NewOpc && "Optional cc_out operand required");
7871 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7872 // since we already have an optional CPSR def.
7873 bool definesCPSR = false;
7874 bool deadCPSR = false;
7875 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7877 const MachineOperand &MO = MI->getOperand(i);
7878 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7882 MI->RemoveOperand(i);
7887 assert(!NewOpc && "Optional cc_out operand required");
7890 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7892 assert(!MI->getOperand(ccOutIdx).getReg() &&
7893 "expect uninitialized optional cc_out operand");
7897 // If this instruction was defined with an optional CPSR def and its dag node
7898 // had a live implicit CPSR def, then activate the optional CPSR def.
7899 MachineOperand &MO = MI->getOperand(ccOutIdx);
7900 MO.setReg(ARM::CPSR);
7904 //===----------------------------------------------------------------------===//
7905 // ARM Optimization Hooks
7906 //===----------------------------------------------------------------------===//
7908 // Helper function that checks if N is a null or all ones constant.
7909 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7910 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7913 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7916 // Return true if N is conditionally 0 or all ones.
7917 // Detects these expressions where cc is an i1 value:
7919 // (select cc 0, y) [AllOnes=0]
7920 // (select cc y, 0) [AllOnes=0]
7921 // (zext cc) [AllOnes=0]
7922 // (sext cc) [AllOnes=0/1]
7923 // (select cc -1, y) [AllOnes=1]
7924 // (select cc y, -1) [AllOnes=1]
7926 // Invert is set when N is the null/all ones constant when CC is false.
7927 // OtherOp is set to the alternative value of N.
7928 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7929 SDValue &CC, bool &Invert,
7931 SelectionDAG &DAG) {
7932 switch (N->getOpcode()) {
7933 default: return false;
7935 CC = N->getOperand(0);
7936 SDValue N1 = N->getOperand(1);
7937 SDValue N2 = N->getOperand(2);
7938 if (isZeroOrAllOnes(N1, AllOnes)) {
7943 if (isZeroOrAllOnes(N2, AllOnes)) {
7950 case ISD::ZERO_EXTEND:
7951 // (zext cc) can never be the all ones value.
7955 case ISD::SIGN_EXTEND: {
7956 EVT VT = N->getValueType(0);
7957 CC = N->getOperand(0);
7958 if (CC.getValueType() != MVT::i1)
7962 // When looking for an AllOnes constant, N is an sext, and the 'other'
7964 OtherOp = DAG.getConstant(0, VT);
7965 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7966 // When looking for a 0 constant, N can be zext or sext.
7967 OtherOp = DAG.getConstant(1, VT);
7969 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7975 // Combine a constant select operand into its use:
7977 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7978 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7979 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7980 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7981 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7983 // The transform is rejected if the select doesn't have a constant operand that
7984 // is null, or all ones when AllOnes is set.
7986 // Also recognize sext/zext from i1:
7988 // (add (zext cc), x) -> (select cc (add x, 1), x)
7989 // (add (sext cc), x) -> (select cc (add x, -1), x)
7991 // These transformations eventually create predicated instructions.
7993 // @param N The node to transform.
7994 // @param Slct The N operand that is a select.
7995 // @param OtherOp The other N operand (x above).
7996 // @param DCI Context.
7997 // @param AllOnes Require the select constant to be all ones instead of null.
7998 // @returns The new node, or SDValue() on failure.
8000 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8001 TargetLowering::DAGCombinerInfo &DCI,
8002 bool AllOnes = false) {
8003 SelectionDAG &DAG = DCI.DAG;
8004 EVT VT = N->getValueType(0);
8005 SDValue NonConstantVal;
8008 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8009 NonConstantVal, DAG))
8012 // Slct is now know to be the desired identity constant when CC is true.
8013 SDValue TrueVal = OtherOp;
8014 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8015 OtherOp, NonConstantVal);
8016 // Unless SwapSelectOps says CC should be false.
8018 std::swap(TrueVal, FalseVal);
8020 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8021 CCOp, TrueVal, FalseVal);
8024 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8026 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8027 TargetLowering::DAGCombinerInfo &DCI) {
8028 SDValue N0 = N->getOperand(0);
8029 SDValue N1 = N->getOperand(1);
8030 if (N0.getNode()->hasOneUse()) {
8031 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8032 if (Result.getNode())
8035 if (N1.getNode()->hasOneUse()) {
8036 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8037 if (Result.getNode())
8043 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8044 // (only after legalization).
8045 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8046 TargetLowering::DAGCombinerInfo &DCI,
8047 const ARMSubtarget *Subtarget) {
8049 // Only perform optimization if after legalize, and if NEON is available. We
8050 // also expected both operands to be BUILD_VECTORs.
8051 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8052 || N0.getOpcode() != ISD::BUILD_VECTOR
8053 || N1.getOpcode() != ISD::BUILD_VECTOR)
8056 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8057 EVT VT = N->getValueType(0);
8058 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8061 // Check that the vector operands are of the right form.
8062 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8063 // operands, where N is the size of the formed vector.
8064 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8065 // index such that we have a pair wise add pattern.
8067 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8068 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8070 SDValue Vec = N0->getOperand(0)->getOperand(0);
8071 SDNode *V = Vec.getNode();
8072 unsigned nextIndex = 0;
8074 // For each operands to the ADD which are BUILD_VECTORs,
8075 // check to see if each of their operands are an EXTRACT_VECTOR with
8076 // the same vector and appropriate index.
8077 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8078 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8079 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8081 SDValue ExtVec0 = N0->getOperand(i);
8082 SDValue ExtVec1 = N1->getOperand(i);
8084 // First operand is the vector, verify its the same.
8085 if (V != ExtVec0->getOperand(0).getNode() ||
8086 V != ExtVec1->getOperand(0).getNode())
8089 // Second is the constant, verify its correct.
8090 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8091 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8093 // For the constant, we want to see all the even or all the odd.
8094 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8095 || C1->getZExtValue() != nextIndex+1)
8104 // Create VPADDL node.
8105 SelectionDAG &DAG = DCI.DAG;
8106 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8108 // Build operand list.
8109 SmallVector<SDValue, 8> Ops;
8110 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8111 TLI.getPointerTy()));
8113 // Input is the vector.
8116 // Get widened type and narrowed type.
8118 unsigned numElem = VT.getVectorNumElements();
8119 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8120 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8121 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8122 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8124 llvm_unreachable("Invalid vector element type for padd optimization.");
8127 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8128 widenType, &Ops[0], Ops.size());
8129 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8132 static SDValue findMUL_LOHI(SDValue V) {
8133 if (V->getOpcode() == ISD::UMUL_LOHI ||
8134 V->getOpcode() == ISD::SMUL_LOHI)
8139 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8140 TargetLowering::DAGCombinerInfo &DCI,
8141 const ARMSubtarget *Subtarget) {
8143 if (Subtarget->isThumb1Only()) return SDValue();
8145 // Only perform the checks after legalize when the pattern is available.
8146 if (DCI.isBeforeLegalize()) return SDValue();
8148 // Look for multiply add opportunities.
8149 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8150 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8151 // a glue link from the first add to the second add.
8152 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8153 // a S/UMLAL instruction.
8156 // \ / \ [no multiline comment]
8162 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8163 SDValue AddcOp0 = AddcNode->getOperand(0);
8164 SDValue AddcOp1 = AddcNode->getOperand(1);
8166 // Check if the two operands are from the same mul_lohi node.
8167 if (AddcOp0.getNode() == AddcOp1.getNode())
8170 assert(AddcNode->getNumValues() == 2 &&
8171 AddcNode->getValueType(0) == MVT::i32 &&
8172 "Expect ADDC with two result values. First: i32");
8174 // Check that we have a glued ADDC node.
8175 if (AddcNode->getValueType(1) != MVT::Glue)
8178 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8179 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8180 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8181 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8182 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8185 // Look for the glued ADDE.
8186 SDNode* AddeNode = AddcNode->getGluedUser();
8187 if (AddeNode == NULL)
8190 // Make sure it is really an ADDE.
8191 if (AddeNode->getOpcode() != ISD::ADDE)
8194 assert(AddeNode->getNumOperands() == 3 &&
8195 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8196 "ADDE node has the wrong inputs");
8198 // Check for the triangle shape.
8199 SDValue AddeOp0 = AddeNode->getOperand(0);
8200 SDValue AddeOp1 = AddeNode->getOperand(1);
8202 // Make sure that the ADDE operands are not coming from the same node.
8203 if (AddeOp0.getNode() == AddeOp1.getNode())
8206 // Find the MUL_LOHI node walking up ADDE's operands.
8207 bool IsLeftOperandMUL = false;
8208 SDValue MULOp = findMUL_LOHI(AddeOp0);
8209 if (MULOp == SDValue())
8210 MULOp = findMUL_LOHI(AddeOp1);
8212 IsLeftOperandMUL = true;
8213 if (MULOp == SDValue())
8216 // Figure out the right opcode.
8217 unsigned Opc = MULOp->getOpcode();
8218 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8220 // Figure out the high and low input values to the MLAL node.
8221 SDValue* HiMul = &MULOp;
8222 SDValue* HiAdd = NULL;
8223 SDValue* LoMul = NULL;
8224 SDValue* LowAdd = NULL;
8226 if (IsLeftOperandMUL)
8232 if (AddcOp0->getOpcode() == Opc) {
8236 if (AddcOp1->getOpcode() == Opc) {
8244 if (LoMul->getNode() != HiMul->getNode())
8247 // Create the merged node.
8248 SelectionDAG &DAG = DCI.DAG;
8250 // Build operand list.
8251 SmallVector<SDValue, 8> Ops;
8252 Ops.push_back(LoMul->getOperand(0));
8253 Ops.push_back(LoMul->getOperand(1));
8254 Ops.push_back(*LowAdd);
8255 Ops.push_back(*HiAdd);
8257 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8258 DAG.getVTList(MVT::i32, MVT::i32),
8259 &Ops[0], Ops.size());
8261 // Replace the ADDs' nodes uses by the MLA node's values.
8262 SDValue HiMLALResult(MLALNode.getNode(), 1);
8263 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8265 SDValue LoMLALResult(MLALNode.getNode(), 0);
8266 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8268 // Return original node to notify the driver to stop replacing.
8269 SDValue resNode(AddcNode, 0);
8273 /// PerformADDCCombine - Target-specific dag combine transform from
8274 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8275 static SDValue PerformADDCCombine(SDNode *N,
8276 TargetLowering::DAGCombinerInfo &DCI,
8277 const ARMSubtarget *Subtarget) {
8279 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8283 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8284 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8285 /// called with the default operands, and if that fails, with commuted
8287 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8288 TargetLowering::DAGCombinerInfo &DCI,
8289 const ARMSubtarget *Subtarget){
8291 // Attempt to create vpaddl for this add.
8292 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8293 if (Result.getNode())
8296 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8297 if (N0.getNode()->hasOneUse()) {
8298 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8299 if (Result.getNode()) return Result;
8304 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8306 static SDValue PerformADDCombine(SDNode *N,
8307 TargetLowering::DAGCombinerInfo &DCI,
8308 const ARMSubtarget *Subtarget) {
8309 SDValue N0 = N->getOperand(0);
8310 SDValue N1 = N->getOperand(1);
8312 // First try with the default operand order.
8313 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8314 if (Result.getNode())
8317 // If that didn't work, try again with the operands commuted.
8318 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8321 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8323 static SDValue PerformSUBCombine(SDNode *N,
8324 TargetLowering::DAGCombinerInfo &DCI) {
8325 SDValue N0 = N->getOperand(0);
8326 SDValue N1 = N->getOperand(1);
8328 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8329 if (N1.getNode()->hasOneUse()) {
8330 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8331 if (Result.getNode()) return Result;
8337 /// PerformVMULCombine
8338 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8339 /// special multiplier accumulator forwarding.
8345 static SDValue PerformVMULCombine(SDNode *N,
8346 TargetLowering::DAGCombinerInfo &DCI,
8347 const ARMSubtarget *Subtarget) {
8348 if (!Subtarget->hasVMLxForwarding())
8351 SelectionDAG &DAG = DCI.DAG;
8352 SDValue N0 = N->getOperand(0);
8353 SDValue N1 = N->getOperand(1);
8354 unsigned Opcode = N0.getOpcode();
8355 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8356 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8357 Opcode = N1.getOpcode();
8358 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8359 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8364 EVT VT = N->getValueType(0);
8366 SDValue N00 = N0->getOperand(0);
8367 SDValue N01 = N0->getOperand(1);
8368 return DAG.getNode(Opcode, DL, VT,
8369 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8370 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8373 static SDValue PerformMULCombine(SDNode *N,
8374 TargetLowering::DAGCombinerInfo &DCI,
8375 const ARMSubtarget *Subtarget) {
8376 SelectionDAG &DAG = DCI.DAG;
8378 if (Subtarget->isThumb1Only())
8381 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8384 EVT VT = N->getValueType(0);
8385 if (VT.is64BitVector() || VT.is128BitVector())
8386 return PerformVMULCombine(N, DCI, Subtarget);
8390 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8394 int64_t MulAmt = C->getSExtValue();
8395 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8397 ShiftAmt = ShiftAmt & (32 - 1);
8398 SDValue V = N->getOperand(0);
8402 MulAmt >>= ShiftAmt;
8405 if (isPowerOf2_32(MulAmt - 1)) {
8406 // (mul x, 2^N + 1) => (add (shl x, N), x)
8407 Res = DAG.getNode(ISD::ADD, DL, VT,
8409 DAG.getNode(ISD::SHL, DL, VT,
8411 DAG.getConstant(Log2_32(MulAmt - 1),
8413 } else if (isPowerOf2_32(MulAmt + 1)) {
8414 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8415 Res = DAG.getNode(ISD::SUB, DL, VT,
8416 DAG.getNode(ISD::SHL, DL, VT,
8418 DAG.getConstant(Log2_32(MulAmt + 1),
8424 uint64_t MulAmtAbs = -MulAmt;
8425 if (isPowerOf2_32(MulAmtAbs + 1)) {
8426 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8427 Res = DAG.getNode(ISD::SUB, DL, VT,
8429 DAG.getNode(ISD::SHL, DL, VT,
8431 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8433 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8434 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8435 Res = DAG.getNode(ISD::ADD, DL, VT,
8437 DAG.getNode(ISD::SHL, DL, VT,
8439 DAG.getConstant(Log2_32(MulAmtAbs-1),
8441 Res = DAG.getNode(ISD::SUB, DL, VT,
8442 DAG.getConstant(0, MVT::i32),Res);
8449 Res = DAG.getNode(ISD::SHL, DL, VT,
8450 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8452 // Do not add new nodes to DAG combiner worklist.
8453 DCI.CombineTo(N, Res, false);
8457 static SDValue PerformANDCombine(SDNode *N,
8458 TargetLowering::DAGCombinerInfo &DCI,
8459 const ARMSubtarget *Subtarget) {
8461 // Attempt to use immediate-form VBIC
8462 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8464 EVT VT = N->getValueType(0);
8465 SelectionDAG &DAG = DCI.DAG;
8467 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8470 APInt SplatBits, SplatUndef;
8471 unsigned SplatBitSize;
8474 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8475 if (SplatBitSize <= 64) {
8477 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8478 SplatUndef.getZExtValue(), SplatBitSize,
8479 DAG, VbicVT, VT.is128BitVector(),
8481 if (Val.getNode()) {
8483 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8484 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8485 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8490 if (!Subtarget->isThumb1Only()) {
8491 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8492 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8493 if (Result.getNode())
8500 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8501 static SDValue PerformORCombine(SDNode *N,
8502 TargetLowering::DAGCombinerInfo &DCI,
8503 const ARMSubtarget *Subtarget) {
8504 // Attempt to use immediate-form VORR
8505 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8507 EVT VT = N->getValueType(0);
8508 SelectionDAG &DAG = DCI.DAG;
8510 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8513 APInt SplatBits, SplatUndef;
8514 unsigned SplatBitSize;
8516 if (BVN && Subtarget->hasNEON() &&
8517 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8518 if (SplatBitSize <= 64) {
8520 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8521 SplatUndef.getZExtValue(), SplatBitSize,
8522 DAG, VorrVT, VT.is128BitVector(),
8524 if (Val.getNode()) {
8526 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8527 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8528 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8533 if (!Subtarget->isThumb1Only()) {
8534 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8535 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8536 if (Result.getNode())
8540 // The code below optimizes (or (and X, Y), Z).
8541 // The AND operand needs to have a single user to make these optimizations
8543 SDValue N0 = N->getOperand(0);
8544 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8546 SDValue N1 = N->getOperand(1);
8548 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8549 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8550 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8552 unsigned SplatBitSize;
8555 APInt SplatBits0, SplatBits1;
8556 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8557 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8558 // Ensure that the second operand of both ands are constants
8559 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8560 HasAnyUndefs) && !HasAnyUndefs) {
8561 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8562 HasAnyUndefs) && !HasAnyUndefs) {
8563 // Ensure that the bit width of the constants are the same and that
8564 // the splat arguments are logical inverses as per the pattern we
8565 // are trying to simplify.
8566 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8567 SplatBits0 == ~SplatBits1) {
8568 // Canonicalize the vector type to make instruction selection
8570 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8571 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8575 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8581 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8584 // BFI is only available on V6T2+
8585 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8589 // 1) or (and A, mask), val => ARMbfi A, val, mask
8590 // iff (val & mask) == val
8592 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8593 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8594 // && mask == ~mask2
8595 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8596 // && ~mask == mask2
8597 // (i.e., copy a bitfield value into another bitfield of the same width)
8602 SDValue N00 = N0.getOperand(0);
8604 // The value and the mask need to be constants so we can verify this is
8605 // actually a bitfield set. If the mask is 0xffff, we can do better
8606 // via a movt instruction, so don't use BFI in that case.
8607 SDValue MaskOp = N0.getOperand(1);
8608 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8611 unsigned Mask = MaskC->getZExtValue();
8615 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8616 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8618 unsigned Val = N1C->getZExtValue();
8619 if ((Val & ~Mask) != Val)
8622 if (ARM::isBitFieldInvertedMask(Mask)) {
8623 Val >>= countTrailingZeros(~Mask);
8625 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8626 DAG.getConstant(Val, MVT::i32),
8627 DAG.getConstant(Mask, MVT::i32));
8629 // Do not add new nodes to DAG combiner worklist.
8630 DCI.CombineTo(N, Res, false);
8633 } else if (N1.getOpcode() == ISD::AND) {
8634 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8635 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8638 unsigned Mask2 = N11C->getZExtValue();
8640 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8642 if (ARM::isBitFieldInvertedMask(Mask) &&
8644 // The pack halfword instruction works better for masks that fit it,
8645 // so use that when it's available.
8646 if (Subtarget->hasT2ExtractPack() &&
8647 (Mask == 0xffff || Mask == 0xffff0000))
8650 unsigned amt = countTrailingZeros(Mask2);
8651 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8652 DAG.getConstant(amt, MVT::i32));
8653 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8654 DAG.getConstant(Mask, MVT::i32));
8655 // Do not add new nodes to DAG combiner worklist.
8656 DCI.CombineTo(N, Res, false);
8658 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8660 // The pack halfword instruction works better for masks that fit it,
8661 // so use that when it's available.
8662 if (Subtarget->hasT2ExtractPack() &&
8663 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8666 unsigned lsb = countTrailingZeros(Mask);
8667 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8668 DAG.getConstant(lsb, MVT::i32));
8669 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8670 DAG.getConstant(Mask2, MVT::i32));
8671 // Do not add new nodes to DAG combiner worklist.
8672 DCI.CombineTo(N, Res, false);
8677 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8678 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8679 ARM::isBitFieldInvertedMask(~Mask)) {
8680 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8681 // where lsb(mask) == #shamt and masked bits of B are known zero.
8682 SDValue ShAmt = N00.getOperand(1);
8683 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8684 unsigned LSB = countTrailingZeros(Mask);
8688 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8689 DAG.getConstant(~Mask, MVT::i32));
8691 // Do not add new nodes to DAG combiner worklist.
8692 DCI.CombineTo(N, Res, false);
8698 static SDValue PerformXORCombine(SDNode *N,
8699 TargetLowering::DAGCombinerInfo &DCI,
8700 const ARMSubtarget *Subtarget) {
8701 EVT VT = N->getValueType(0);
8702 SelectionDAG &DAG = DCI.DAG;
8704 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8707 if (!Subtarget->isThumb1Only()) {
8708 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8709 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8710 if (Result.getNode())
8717 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8718 /// the bits being cleared by the AND are not demanded by the BFI.
8719 static SDValue PerformBFICombine(SDNode *N,
8720 TargetLowering::DAGCombinerInfo &DCI) {
8721 SDValue N1 = N->getOperand(1);
8722 if (N1.getOpcode() == ISD::AND) {
8723 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8726 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8727 unsigned LSB = countTrailingZeros(~InvMask);
8728 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8729 unsigned Mask = (1 << Width)-1;
8730 unsigned Mask2 = N11C->getZExtValue();
8731 if ((Mask & (~Mask2)) == 0)
8732 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8733 N->getOperand(0), N1.getOperand(0),
8739 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8740 /// ARMISD::VMOVRRD.
8741 static SDValue PerformVMOVRRDCombine(SDNode *N,
8742 TargetLowering::DAGCombinerInfo &DCI) {
8743 // vmovrrd(vmovdrr x, y) -> x,y
8744 SDValue InDouble = N->getOperand(0);
8745 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8746 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8748 // vmovrrd(load f64) -> (load i32), (load i32)
8749 SDNode *InNode = InDouble.getNode();
8750 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8751 InNode->getValueType(0) == MVT::f64 &&
8752 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8753 !cast<LoadSDNode>(InNode)->isVolatile()) {
8754 // TODO: Should this be done for non-FrameIndex operands?
8755 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8757 SelectionDAG &DAG = DCI.DAG;
8759 SDValue BasePtr = LD->getBasePtr();
8760 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8761 LD->getPointerInfo(), LD->isVolatile(),
8762 LD->isNonTemporal(), LD->isInvariant(),
8763 LD->getAlignment());
8765 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8766 DAG.getConstant(4, MVT::i32));
8767 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8768 LD->getPointerInfo(), LD->isVolatile(),
8769 LD->isNonTemporal(), LD->isInvariant(),
8770 std::min(4U, LD->getAlignment() / 2));
8772 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8773 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8774 DCI.RemoveFromWorklist(LD);
8782 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8783 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8784 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8785 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8786 SDValue Op0 = N->getOperand(0);
8787 SDValue Op1 = N->getOperand(1);
8788 if (Op0.getOpcode() == ISD::BITCAST)
8789 Op0 = Op0.getOperand(0);
8790 if (Op1.getOpcode() == ISD::BITCAST)
8791 Op1 = Op1.getOperand(0);
8792 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8793 Op0.getNode() == Op1.getNode() &&
8794 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8795 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8796 N->getValueType(0), Op0.getOperand(0));
8800 /// PerformSTORECombine - Target-specific dag combine xforms for
8802 static SDValue PerformSTORECombine(SDNode *N,
8803 TargetLowering::DAGCombinerInfo &DCI) {
8804 StoreSDNode *St = cast<StoreSDNode>(N);
8805 if (St->isVolatile())
8808 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8809 // pack all of the elements in one place. Next, store to memory in fewer
8811 SDValue StVal = St->getValue();
8812 EVT VT = StVal.getValueType();
8813 if (St->isTruncatingStore() && VT.isVector()) {
8814 SelectionDAG &DAG = DCI.DAG;
8815 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8816 EVT StVT = St->getMemoryVT();
8817 unsigned NumElems = VT.getVectorNumElements();
8818 assert(StVT != VT && "Cannot truncate to the same type");
8819 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8820 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8822 // From, To sizes and ElemCount must be pow of two
8823 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8825 // We are going to use the original vector elt for storing.
8826 // Accumulated smaller vector elements must be a multiple of the store size.
8827 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8829 unsigned SizeRatio = FromEltSz / ToEltSz;
8830 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8832 // Create a type on which we perform the shuffle.
8833 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8834 NumElems*SizeRatio);
8835 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8838 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8839 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8840 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8842 // Can't shuffle using an illegal type.
8843 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8845 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8846 DAG.getUNDEF(WideVec.getValueType()),
8848 // At this point all of the data is stored at the bottom of the
8849 // register. We now need to save it to mem.
8851 // Find the largest store unit
8852 MVT StoreType = MVT::i8;
8853 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8854 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8855 MVT Tp = (MVT::SimpleValueType)tp;
8856 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8859 // Didn't find a legal store type.
8860 if (!TLI.isTypeLegal(StoreType))
8863 // Bitcast the original vector into a vector of store-size units
8864 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8865 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8866 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8867 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8868 SmallVector<SDValue, 8> Chains;
8869 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8870 TLI.getPointerTy());
8871 SDValue BasePtr = St->getBasePtr();
8873 // Perform one or more big stores into memory.
8874 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8875 for (unsigned I = 0; I < E; I++) {
8876 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8877 StoreType, ShuffWide,
8878 DAG.getIntPtrConstant(I));
8879 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8880 St->getPointerInfo(), St->isVolatile(),
8881 St->isNonTemporal(), St->getAlignment());
8882 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8884 Chains.push_back(Ch);
8886 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8890 if (!ISD::isNormalStore(St))
8893 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8894 // ARM stores of arguments in the same cache line.
8895 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8896 StVal.getNode()->hasOneUse()) {
8897 SelectionDAG &DAG = DCI.DAG;
8899 SDValue BasePtr = St->getBasePtr();
8900 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8901 StVal.getNode()->getOperand(0), BasePtr,
8902 St->getPointerInfo(), St->isVolatile(),
8903 St->isNonTemporal(), St->getAlignment());
8905 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8906 DAG.getConstant(4, MVT::i32));
8907 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8908 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8909 St->isNonTemporal(),
8910 std::min(4U, St->getAlignment() / 2));
8913 if (StVal.getValueType() != MVT::i64 ||
8914 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8917 // Bitcast an i64 store extracted from a vector to f64.
8918 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8919 SelectionDAG &DAG = DCI.DAG;
8921 SDValue IntVec = StVal.getOperand(0);
8922 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8923 IntVec.getValueType().getVectorNumElements());
8924 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8925 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8926 Vec, StVal.getOperand(1));
8928 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8929 // Make the DAGCombiner fold the bitcasts.
8930 DCI.AddToWorklist(Vec.getNode());
8931 DCI.AddToWorklist(ExtElt.getNode());
8932 DCI.AddToWorklist(V.getNode());
8933 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8934 St->getPointerInfo(), St->isVolatile(),
8935 St->isNonTemporal(), St->getAlignment(),
8939 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8940 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8941 /// i64 vector to have f64 elements, since the value can then be loaded
8942 /// directly into a VFP register.
8943 static bool hasNormalLoadOperand(SDNode *N) {
8944 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8945 for (unsigned i = 0; i < NumElts; ++i) {
8946 SDNode *Elt = N->getOperand(i).getNode();
8947 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8953 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8954 /// ISD::BUILD_VECTOR.
8955 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8956 TargetLowering::DAGCombinerInfo &DCI){
8957 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8958 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8959 // into a pair of GPRs, which is fine when the value is used as a scalar,
8960 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8961 SelectionDAG &DAG = DCI.DAG;
8962 if (N->getNumOperands() == 2) {
8963 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8968 // Load i64 elements as f64 values so that type legalization does not split
8969 // them up into i32 values.
8970 EVT VT = N->getValueType(0);
8971 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8974 SmallVector<SDValue, 8> Ops;
8975 unsigned NumElts = VT.getVectorNumElements();
8976 for (unsigned i = 0; i < NumElts; ++i) {
8977 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8979 // Make the DAGCombiner fold the bitcast.
8980 DCI.AddToWorklist(V.getNode());
8982 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8983 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8984 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8987 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8989 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8990 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8991 // At that time, we may have inserted bitcasts from integer to float.
8992 // If these bitcasts have survived DAGCombine, change the lowering of this
8993 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8994 // force to use floating point types.
8996 // Make sure we can change the type of the vector.
8997 // This is possible iff:
8998 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8999 // 1.1. Vector is used only once.
9000 // 1.2. Use is a bit convert to an integer type.
9001 // 2. The size of its operands are 32-bits (64-bits are not legal).
9002 EVT VT = N->getValueType(0);
9003 EVT EltVT = VT.getVectorElementType();
9005 // Check 1.1. and 2.
9006 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9009 // By construction, the input type must be float.
9010 assert(EltVT == MVT::f32 && "Unexpected type!");
9013 SDNode *Use = *N->use_begin();
9014 if (Use->getOpcode() != ISD::BITCAST ||
9015 Use->getValueType(0).isFloatingPoint())
9018 // Check profitability.
9019 // Model is, if more than half of the relevant operands are bitcast from
9020 // i32, turn the build_vector into a sequence of insert_vector_elt.
9021 // Relevant operands are everything that is not statically
9022 // (i.e., at compile time) bitcasted.
9023 unsigned NumOfBitCastedElts = 0;
9024 unsigned NumElts = VT.getVectorNumElements();
9025 unsigned NumOfRelevantElts = NumElts;
9026 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9027 SDValue Elt = N->getOperand(Idx);
9028 if (Elt->getOpcode() == ISD::BITCAST) {
9029 // Assume only bit cast to i32 will go away.
9030 if (Elt->getOperand(0).getValueType() == MVT::i32)
9031 ++NumOfBitCastedElts;
9032 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9033 // Constants are statically casted, thus do not count them as
9034 // relevant operands.
9035 --NumOfRelevantElts;
9038 // Check if more than half of the elements require a non-free bitcast.
9039 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9042 SelectionDAG &DAG = DCI.DAG;
9043 // Create the new vector type.
9044 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9045 // Check if the type is legal.
9046 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9047 if (!TLI.isTypeLegal(VecVT))
9051 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9052 // => BITCAST INSERT_VECTOR_ELT
9053 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9055 SDValue Vec = DAG.getUNDEF(VecVT);
9057 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9058 SDValue V = N->getOperand(Idx);
9059 if (V.getOpcode() == ISD::UNDEF)
9061 if (V.getOpcode() == ISD::BITCAST &&
9062 V->getOperand(0).getValueType() == MVT::i32)
9063 // Fold obvious case.
9064 V = V.getOperand(0);
9066 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9067 // Make the DAGCombiner fold the bitcasts.
9068 DCI.AddToWorklist(V.getNode());
9070 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9071 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9073 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9074 // Make the DAGCombiner fold the bitcasts.
9075 DCI.AddToWorklist(Vec.getNode());
9079 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9080 /// ISD::INSERT_VECTOR_ELT.
9081 static SDValue PerformInsertEltCombine(SDNode *N,
9082 TargetLowering::DAGCombinerInfo &DCI) {
9083 // Bitcast an i64 load inserted into a vector to f64.
9084 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9085 EVT VT = N->getValueType(0);
9086 SDNode *Elt = N->getOperand(1).getNode();
9087 if (VT.getVectorElementType() != MVT::i64 ||
9088 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9091 SelectionDAG &DAG = DCI.DAG;
9093 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9094 VT.getVectorNumElements());
9095 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9096 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9097 // Make the DAGCombiner fold the bitcasts.
9098 DCI.AddToWorklist(Vec.getNode());
9099 DCI.AddToWorklist(V.getNode());
9100 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9101 Vec, V, N->getOperand(2));
9102 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9105 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9106 /// ISD::VECTOR_SHUFFLE.
9107 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9108 // The LLVM shufflevector instruction does not require the shuffle mask
9109 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9110 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9111 // operands do not match the mask length, they are extended by concatenating
9112 // them with undef vectors. That is probably the right thing for other
9113 // targets, but for NEON it is better to concatenate two double-register
9114 // size vector operands into a single quad-register size vector. Do that
9115 // transformation here:
9116 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9117 // shuffle(concat(v1, v2), undef)
9118 SDValue Op0 = N->getOperand(0);
9119 SDValue Op1 = N->getOperand(1);
9120 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9121 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9122 Op0.getNumOperands() != 2 ||
9123 Op1.getNumOperands() != 2)
9125 SDValue Concat0Op1 = Op0.getOperand(1);
9126 SDValue Concat1Op1 = Op1.getOperand(1);
9127 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9128 Concat1Op1.getOpcode() != ISD::UNDEF)
9130 // Skip the transformation if any of the types are illegal.
9131 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9132 EVT VT = N->getValueType(0);
9133 if (!TLI.isTypeLegal(VT) ||
9134 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9135 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9138 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9139 Op0.getOperand(0), Op1.getOperand(0));
9140 // Translate the shuffle mask.
9141 SmallVector<int, 16> NewMask;
9142 unsigned NumElts = VT.getVectorNumElements();
9143 unsigned HalfElts = NumElts/2;
9144 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9145 for (unsigned n = 0; n < NumElts; ++n) {
9146 int MaskElt = SVN->getMaskElt(n);
9148 if (MaskElt < (int)HalfElts)
9150 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9151 NewElt = HalfElts + MaskElt - NumElts;
9152 NewMask.push_back(NewElt);
9154 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9155 DAG.getUNDEF(VT), NewMask.data());
9158 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9159 /// NEON load/store intrinsics to merge base address updates.
9160 static SDValue CombineBaseUpdate(SDNode *N,
9161 TargetLowering::DAGCombinerInfo &DCI) {
9162 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9165 SelectionDAG &DAG = DCI.DAG;
9166 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9167 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9168 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9169 SDValue Addr = N->getOperand(AddrOpIdx);
9171 // Search for a use of the address operand that is an increment.
9172 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9173 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9175 if (User->getOpcode() != ISD::ADD ||
9176 UI.getUse().getResNo() != Addr.getResNo())
9179 // Check that the add is independent of the load/store. Otherwise, folding
9180 // it would create a cycle.
9181 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9184 // Find the new opcode for the updating load/store.
9186 bool isLaneOp = false;
9187 unsigned NewOpc = 0;
9188 unsigned NumVecs = 0;
9190 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9192 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9193 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9195 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9197 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9199 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9201 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9202 NumVecs = 2; isLaneOp = true; break;
9203 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9204 NumVecs = 3; isLaneOp = true; break;
9205 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9206 NumVecs = 4; isLaneOp = true; break;
9207 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9208 NumVecs = 1; isLoad = false; break;
9209 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9210 NumVecs = 2; isLoad = false; break;
9211 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9212 NumVecs = 3; isLoad = false; break;
9213 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9214 NumVecs = 4; isLoad = false; break;
9215 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9216 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9217 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9218 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9219 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9220 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9224 switch (N->getOpcode()) {
9225 default: llvm_unreachable("unexpected opcode for Neon base update");
9226 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9227 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9228 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9232 // Find the size of memory referenced by the load/store.
9235 VecTy = N->getValueType(0);
9237 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9238 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9240 NumBytes /= VecTy.getVectorNumElements();
9242 // If the increment is a constant, it must match the memory ref size.
9243 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9244 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9245 uint64_t IncVal = CInc->getZExtValue();
9246 if (IncVal != NumBytes)
9248 } else if (NumBytes >= 3 * 16) {
9249 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9250 // separate instructions that make it harder to use a non-constant update.
9254 // Create the new updating load/store node.
9256 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9258 for (n = 0; n < NumResultVecs; ++n)
9260 Tys[n++] = MVT::i32;
9261 Tys[n] = MVT::Other;
9262 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9263 SmallVector<SDValue, 8> Ops;
9264 Ops.push_back(N->getOperand(0)); // incoming chain
9265 Ops.push_back(N->getOperand(AddrOpIdx));
9267 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9268 Ops.push_back(N->getOperand(i));
9270 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9271 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9272 Ops.data(), Ops.size(),
9273 MemInt->getMemoryVT(),
9274 MemInt->getMemOperand());
9277 std::vector<SDValue> NewResults;
9278 for (unsigned i = 0; i < NumResultVecs; ++i) {
9279 NewResults.push_back(SDValue(UpdN.getNode(), i));
9281 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9282 DCI.CombineTo(N, NewResults);
9283 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9290 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9291 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9292 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9294 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9295 SelectionDAG &DAG = DCI.DAG;
9296 EVT VT = N->getValueType(0);
9297 // vldN-dup instructions only support 64-bit vectors for N > 1.
9298 if (!VT.is64BitVector())
9301 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9302 SDNode *VLD = N->getOperand(0).getNode();
9303 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9305 unsigned NumVecs = 0;
9306 unsigned NewOpc = 0;
9307 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9308 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9310 NewOpc = ARMISD::VLD2DUP;
9311 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9313 NewOpc = ARMISD::VLD3DUP;
9314 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9316 NewOpc = ARMISD::VLD4DUP;
9321 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9322 // numbers match the load.
9323 unsigned VLDLaneNo =
9324 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9325 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9327 // Ignore uses of the chain result.
9328 if (UI.getUse().getResNo() == NumVecs)
9331 if (User->getOpcode() != ARMISD::VDUPLANE ||
9332 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9336 // Create the vldN-dup node.
9339 for (n = 0; n < NumVecs; ++n)
9341 Tys[n] = MVT::Other;
9342 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9343 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9344 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9345 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9346 Ops, 2, VLDMemInt->getMemoryVT(),
9347 VLDMemInt->getMemOperand());
9350 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9352 unsigned ResNo = UI.getUse().getResNo();
9353 // Ignore uses of the chain result.
9354 if (ResNo == NumVecs)
9357 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9360 // Now the vldN-lane intrinsic is dead except for its chain result.
9361 // Update uses of the chain.
9362 std::vector<SDValue> VLDDupResults;
9363 for (unsigned n = 0; n < NumVecs; ++n)
9364 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9365 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9366 DCI.CombineTo(VLD, VLDDupResults);
9371 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9372 /// ARMISD::VDUPLANE.
9373 static SDValue PerformVDUPLANECombine(SDNode *N,
9374 TargetLowering::DAGCombinerInfo &DCI) {
9375 SDValue Op = N->getOperand(0);
9377 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9378 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9379 if (CombineVLDDUP(N, DCI))
9380 return SDValue(N, 0);
9382 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9383 // redundant. Ignore bit_converts for now; element sizes are checked below.
9384 while (Op.getOpcode() == ISD::BITCAST)
9385 Op = Op.getOperand(0);
9386 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9389 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9390 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9391 // The canonical VMOV for a zero vector uses a 32-bit element size.
9392 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9394 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9396 EVT VT = N->getValueType(0);
9397 if (EltSize > VT.getVectorElementType().getSizeInBits())
9400 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9403 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9404 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9405 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9409 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9411 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9416 APFloat APF = C->getValueAPF();
9417 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9418 != APFloat::opOK || !isExact)
9421 c0 = (I == 0) ? cN : c0;
9422 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9429 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9430 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9431 /// when the VMUL has a constant operand that is a power of 2.
9433 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9434 /// vmul.f32 d16, d17, d16
9435 /// vcvt.s32.f32 d16, d16
9437 /// vcvt.s32.f32 d16, d16, #3
9438 static SDValue PerformVCVTCombine(SDNode *N,
9439 TargetLowering::DAGCombinerInfo &DCI,
9440 const ARMSubtarget *Subtarget) {
9441 SelectionDAG &DAG = DCI.DAG;
9442 SDValue Op = N->getOperand(0);
9444 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9445 Op.getOpcode() != ISD::FMUL)
9449 SDValue N0 = Op->getOperand(0);
9450 SDValue ConstVec = Op->getOperand(1);
9451 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9453 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9454 !isConstVecPow2(ConstVec, isSigned, C))
9457 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9458 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9459 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9460 // These instructions only exist converting from f32 to i32. We can handle
9461 // smaller integers by generating an extra truncate, but larger ones would
9466 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9467 Intrinsic::arm_neon_vcvtfp2fxu;
9468 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9469 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9470 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9471 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9472 DAG.getConstant(Log2_64(C), MVT::i32));
9474 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9475 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9480 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9481 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9482 /// when the VDIV has a constant operand that is a power of 2.
9484 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9485 /// vcvt.f32.s32 d16, d16
9486 /// vdiv.f32 d16, d17, d16
9488 /// vcvt.f32.s32 d16, d16, #3
9489 static SDValue PerformVDIVCombine(SDNode *N,
9490 TargetLowering::DAGCombinerInfo &DCI,
9491 const ARMSubtarget *Subtarget) {
9492 SelectionDAG &DAG = DCI.DAG;
9493 SDValue Op = N->getOperand(0);
9494 unsigned OpOpcode = Op.getNode()->getOpcode();
9496 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9497 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9501 SDValue ConstVec = N->getOperand(1);
9502 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9504 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9505 !isConstVecPow2(ConstVec, isSigned, C))
9508 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9509 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9510 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9511 // These instructions only exist converting from i32 to f32. We can handle
9512 // smaller integers by generating an extra extend, but larger ones would
9517 SDValue ConvInput = Op.getOperand(0);
9518 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9519 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9520 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9521 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9524 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9525 Intrinsic::arm_neon_vcvtfxu2fp;
9526 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9528 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9529 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9532 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9533 /// operand of a vector shift operation, where all the elements of the
9534 /// build_vector must have the same constant integer value.
9535 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9536 // Ignore bit_converts.
9537 while (Op.getOpcode() == ISD::BITCAST)
9538 Op = Op.getOperand(0);
9539 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9540 APInt SplatBits, SplatUndef;
9541 unsigned SplatBitSize;
9543 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9544 HasAnyUndefs, ElementBits) ||
9545 SplatBitSize > ElementBits)
9547 Cnt = SplatBits.getSExtValue();
9551 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9552 /// operand of a vector shift left operation. That value must be in the range:
9553 /// 0 <= Value < ElementBits for a left shift; or
9554 /// 0 <= Value <= ElementBits for a long left shift.
9555 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9556 assert(VT.isVector() && "vector shift count is not a vector type");
9557 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9558 if (! getVShiftImm(Op, ElementBits, Cnt))
9560 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9563 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9564 /// operand of a vector shift right operation. For a shift opcode, the value
9565 /// is positive, but for an intrinsic the value count must be negative. The
9566 /// absolute value must be in the range:
9567 /// 1 <= |Value| <= ElementBits for a right shift; or
9568 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9569 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9571 assert(VT.isVector() && "vector shift count is not a vector type");
9572 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9573 if (! getVShiftImm(Op, ElementBits, Cnt))
9577 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9580 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9581 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9582 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9585 // Don't do anything for most intrinsics.
9588 // Vector shifts: check for immediate versions and lower them.
9589 // Note: This is done during DAG combining instead of DAG legalizing because
9590 // the build_vectors for 64-bit vector element shift counts are generally
9591 // not legal, and it is hard to see their values after they get legalized to
9592 // loads from a constant pool.
9593 case Intrinsic::arm_neon_vshifts:
9594 case Intrinsic::arm_neon_vshiftu:
9595 case Intrinsic::arm_neon_vshiftls:
9596 case Intrinsic::arm_neon_vshiftlu:
9597 case Intrinsic::arm_neon_vshiftn:
9598 case Intrinsic::arm_neon_vrshifts:
9599 case Intrinsic::arm_neon_vrshiftu:
9600 case Intrinsic::arm_neon_vrshiftn:
9601 case Intrinsic::arm_neon_vqshifts:
9602 case Intrinsic::arm_neon_vqshiftu:
9603 case Intrinsic::arm_neon_vqshiftsu:
9604 case Intrinsic::arm_neon_vqshiftns:
9605 case Intrinsic::arm_neon_vqshiftnu:
9606 case Intrinsic::arm_neon_vqshiftnsu:
9607 case Intrinsic::arm_neon_vqrshiftns:
9608 case Intrinsic::arm_neon_vqrshiftnu:
9609 case Intrinsic::arm_neon_vqrshiftnsu: {
9610 EVT VT = N->getOperand(1).getValueType();
9612 unsigned VShiftOpc = 0;
9615 case Intrinsic::arm_neon_vshifts:
9616 case Intrinsic::arm_neon_vshiftu:
9617 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9618 VShiftOpc = ARMISD::VSHL;
9621 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9622 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9623 ARMISD::VSHRs : ARMISD::VSHRu);
9628 case Intrinsic::arm_neon_vshiftls:
9629 case Intrinsic::arm_neon_vshiftlu:
9630 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9632 llvm_unreachable("invalid shift count for vshll intrinsic");
9634 case Intrinsic::arm_neon_vrshifts:
9635 case Intrinsic::arm_neon_vrshiftu:
9636 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9640 case Intrinsic::arm_neon_vqshifts:
9641 case Intrinsic::arm_neon_vqshiftu:
9642 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9646 case Intrinsic::arm_neon_vqshiftsu:
9647 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9649 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9651 case Intrinsic::arm_neon_vshiftn:
9652 case Intrinsic::arm_neon_vrshiftn:
9653 case Intrinsic::arm_neon_vqshiftns:
9654 case Intrinsic::arm_neon_vqshiftnu:
9655 case Intrinsic::arm_neon_vqshiftnsu:
9656 case Intrinsic::arm_neon_vqrshiftns:
9657 case Intrinsic::arm_neon_vqrshiftnu:
9658 case Intrinsic::arm_neon_vqrshiftnsu:
9659 // Narrowing shifts require an immediate right shift.
9660 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9662 llvm_unreachable("invalid shift count for narrowing vector shift "
9666 llvm_unreachable("unhandled vector shift");
9670 case Intrinsic::arm_neon_vshifts:
9671 case Intrinsic::arm_neon_vshiftu:
9672 // Opcode already set above.
9674 case Intrinsic::arm_neon_vshiftls:
9675 case Intrinsic::arm_neon_vshiftlu:
9676 if (Cnt == VT.getVectorElementType().getSizeInBits())
9677 VShiftOpc = ARMISD::VSHLLi;
9679 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9680 ARMISD::VSHLLs : ARMISD::VSHLLu);
9682 case Intrinsic::arm_neon_vshiftn:
9683 VShiftOpc = ARMISD::VSHRN; break;
9684 case Intrinsic::arm_neon_vrshifts:
9685 VShiftOpc = ARMISD::VRSHRs; break;
9686 case Intrinsic::arm_neon_vrshiftu:
9687 VShiftOpc = ARMISD::VRSHRu; break;
9688 case Intrinsic::arm_neon_vrshiftn:
9689 VShiftOpc = ARMISD::VRSHRN; break;
9690 case Intrinsic::arm_neon_vqshifts:
9691 VShiftOpc = ARMISD::VQSHLs; break;
9692 case Intrinsic::arm_neon_vqshiftu:
9693 VShiftOpc = ARMISD::VQSHLu; break;
9694 case Intrinsic::arm_neon_vqshiftsu:
9695 VShiftOpc = ARMISD::VQSHLsu; break;
9696 case Intrinsic::arm_neon_vqshiftns:
9697 VShiftOpc = ARMISD::VQSHRNs; break;
9698 case Intrinsic::arm_neon_vqshiftnu:
9699 VShiftOpc = ARMISD::VQSHRNu; break;
9700 case Intrinsic::arm_neon_vqshiftnsu:
9701 VShiftOpc = ARMISD::VQSHRNsu; break;
9702 case Intrinsic::arm_neon_vqrshiftns:
9703 VShiftOpc = ARMISD::VQRSHRNs; break;
9704 case Intrinsic::arm_neon_vqrshiftnu:
9705 VShiftOpc = ARMISD::VQRSHRNu; break;
9706 case Intrinsic::arm_neon_vqrshiftnsu:
9707 VShiftOpc = ARMISD::VQRSHRNsu; break;
9710 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9711 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9714 case Intrinsic::arm_neon_vshiftins: {
9715 EVT VT = N->getOperand(1).getValueType();
9717 unsigned VShiftOpc = 0;
9719 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9720 VShiftOpc = ARMISD::VSLI;
9721 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9722 VShiftOpc = ARMISD::VSRI;
9724 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9727 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9728 N->getOperand(1), N->getOperand(2),
9729 DAG.getConstant(Cnt, MVT::i32));
9732 case Intrinsic::arm_neon_vqrshifts:
9733 case Intrinsic::arm_neon_vqrshiftu:
9734 // No immediate versions of these to check for.
9741 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9742 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9743 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9744 /// vector element shift counts are generally not legal, and it is hard to see
9745 /// their values after they get legalized to loads from a constant pool.
9746 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9747 const ARMSubtarget *ST) {
9748 EVT VT = N->getValueType(0);
9749 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9750 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9751 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9752 SDValue N1 = N->getOperand(1);
9753 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9754 SDValue N0 = N->getOperand(0);
9755 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9756 DAG.MaskedValueIsZero(N0.getOperand(0),
9757 APInt::getHighBitsSet(32, 16)))
9758 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9762 // Nothing to be done for scalar shifts.
9763 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9764 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9767 assert(ST->hasNEON() && "unexpected vector shift");
9770 switch (N->getOpcode()) {
9771 default: llvm_unreachable("unexpected shift opcode");
9774 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9775 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9776 DAG.getConstant(Cnt, MVT::i32));
9781 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9782 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9783 ARMISD::VSHRs : ARMISD::VSHRu);
9784 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9785 DAG.getConstant(Cnt, MVT::i32));
9791 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9792 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9793 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9794 const ARMSubtarget *ST) {
9795 SDValue N0 = N->getOperand(0);
9797 // Check for sign- and zero-extensions of vector extract operations of 8-
9798 // and 16-bit vector elements. NEON supports these directly. They are
9799 // handled during DAG combining because type legalization will promote them
9800 // to 32-bit types and it is messy to recognize the operations after that.
9801 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9802 SDValue Vec = N0.getOperand(0);
9803 SDValue Lane = N0.getOperand(1);
9804 EVT VT = N->getValueType(0);
9805 EVT EltVT = N0.getValueType();
9806 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9808 if (VT == MVT::i32 &&
9809 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9810 TLI.isTypeLegal(Vec.getValueType()) &&
9811 isa<ConstantSDNode>(Lane)) {
9814 switch (N->getOpcode()) {
9815 default: llvm_unreachable("unexpected opcode");
9816 case ISD::SIGN_EXTEND:
9817 Opc = ARMISD::VGETLANEs;
9819 case ISD::ZERO_EXTEND:
9820 case ISD::ANY_EXTEND:
9821 Opc = ARMISD::VGETLANEu;
9824 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9831 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9832 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9833 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9834 const ARMSubtarget *ST) {
9835 // If the target supports NEON, try to use vmax/vmin instructions for f32
9836 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9837 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9838 // a NaN; only do the transformation when it matches that behavior.
9840 // For now only do this when using NEON for FP operations; if using VFP, it
9841 // is not obvious that the benefit outweighs the cost of switching to the
9843 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9844 N->getValueType(0) != MVT::f32)
9847 SDValue CondLHS = N->getOperand(0);
9848 SDValue CondRHS = N->getOperand(1);
9849 SDValue LHS = N->getOperand(2);
9850 SDValue RHS = N->getOperand(3);
9851 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9853 unsigned Opcode = 0;
9855 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9856 IsReversed = false; // x CC y ? x : y
9857 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9858 IsReversed = true ; // x CC y ? y : x
9872 // If LHS is NaN, an ordered comparison will be false and the result will
9873 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9874 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9875 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9876 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9878 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9879 // will return -0, so vmin can only be used for unsafe math or if one of
9880 // the operands is known to be nonzero.
9881 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9882 !DAG.getTarget().Options.UnsafeFPMath &&
9883 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9885 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9894 // If LHS is NaN, an ordered comparison will be false and the result will
9895 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9896 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9897 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9898 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9900 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9901 // will return +0, so vmax can only be used for unsafe math or if one of
9902 // the operands is known to be nonzero.
9903 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9904 !DAG.getTarget().Options.UnsafeFPMath &&
9905 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9907 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9913 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9916 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9918 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9919 SDValue Cmp = N->getOperand(4);
9920 if (Cmp.getOpcode() != ARMISD::CMPZ)
9921 // Only looking at EQ and NE cases.
9924 EVT VT = N->getValueType(0);
9926 SDValue LHS = Cmp.getOperand(0);
9927 SDValue RHS = Cmp.getOperand(1);
9928 SDValue FalseVal = N->getOperand(0);
9929 SDValue TrueVal = N->getOperand(1);
9930 SDValue ARMcc = N->getOperand(2);
9931 ARMCC::CondCodes CC =
9932 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9950 /// FIXME: Turn this into a target neutral optimization?
9952 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9953 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9954 N->getOperand(3), Cmp);
9955 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9957 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9958 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9959 N->getOperand(3), NewCmp);
9962 if (Res.getNode()) {
9963 APInt KnownZero, KnownOne;
9964 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9965 // Capture demanded bits information that would be otherwise lost.
9966 if (KnownZero == 0xfffffffe)
9967 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9968 DAG.getValueType(MVT::i1));
9969 else if (KnownZero == 0xffffff00)
9970 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9971 DAG.getValueType(MVT::i8));
9972 else if (KnownZero == 0xffff0000)
9973 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9974 DAG.getValueType(MVT::i16));
9980 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9981 DAGCombinerInfo &DCI) const {
9982 switch (N->getOpcode()) {
9984 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9985 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9986 case ISD::SUB: return PerformSUBCombine(N, DCI);
9987 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9988 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9989 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9990 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9991 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9992 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9993 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9994 case ISD::STORE: return PerformSTORECombine(N, DCI);
9995 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9996 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9997 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9998 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9999 case ISD::FP_TO_SINT:
10000 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10001 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10002 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10005 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10006 case ISD::SIGN_EXTEND:
10007 case ISD::ZERO_EXTEND:
10008 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10009 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10010 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10011 case ARMISD::VLD2DUP:
10012 case ARMISD::VLD3DUP:
10013 case ARMISD::VLD4DUP:
10014 return CombineBaseUpdate(N, DCI);
10015 case ARMISD::BUILD_VECTOR:
10016 return PerformARMBUILD_VECTORCombine(N, DCI);
10017 case ISD::INTRINSIC_VOID:
10018 case ISD::INTRINSIC_W_CHAIN:
10019 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10020 case Intrinsic::arm_neon_vld1:
10021 case Intrinsic::arm_neon_vld2:
10022 case Intrinsic::arm_neon_vld3:
10023 case Intrinsic::arm_neon_vld4:
10024 case Intrinsic::arm_neon_vld2lane:
10025 case Intrinsic::arm_neon_vld3lane:
10026 case Intrinsic::arm_neon_vld4lane:
10027 case Intrinsic::arm_neon_vst1:
10028 case Intrinsic::arm_neon_vst2:
10029 case Intrinsic::arm_neon_vst3:
10030 case Intrinsic::arm_neon_vst4:
10031 case Intrinsic::arm_neon_vst2lane:
10032 case Intrinsic::arm_neon_vst3lane:
10033 case Intrinsic::arm_neon_vst4lane:
10034 return CombineBaseUpdate(N, DCI);
10042 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10044 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10047 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10048 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10049 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10051 switch (VT.getSimpleVT().SimpleTy) {
10057 // Unaligned access can use (for example) LRDB, LRDH, LDR
10058 if (AllowsUnaligned) {
10060 *Fast = Subtarget->hasV7Ops();
10067 // For any little-endian targets with neon, we can support unaligned ld/st
10068 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10069 // A big-endian target may also explictly support unaligned accesses
10070 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10080 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10081 unsigned AlignCheck) {
10082 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10083 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10086 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10087 unsigned DstAlign, unsigned SrcAlign,
10088 bool IsMemset, bool ZeroMemset,
10090 MachineFunction &MF) const {
10091 const Function *F = MF.getFunction();
10093 // See if we can use NEON instructions for this...
10094 if ((!IsMemset || ZeroMemset) &&
10095 Subtarget->hasNEON() &&
10096 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10097 Attribute::NoImplicitFloat)) {
10100 (memOpAlign(SrcAlign, DstAlign, 16) ||
10101 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10103 } else if (Size >= 8 &&
10104 (memOpAlign(SrcAlign, DstAlign, 8) ||
10105 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10110 // Lowering to i32/i16 if the size permits.
10113 else if (Size >= 2)
10116 // Let the target-independent logic figure it out.
10120 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10121 if (Val.getOpcode() != ISD::LOAD)
10124 EVT VT1 = Val.getValueType();
10125 if (!VT1.isSimple() || !VT1.isInteger() ||
10126 !VT2.isSimple() || !VT2.isInteger())
10129 switch (VT1.getSimpleVT().SimpleTy) {
10134 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10141 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10142 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10145 if (!isTypeLegal(EVT::getEVT(Ty1)))
10148 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10150 // Assuming the caller doesn't have a zeroext or signext return parameter,
10151 // truncation all the way down to i1 is valid.
10156 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10160 unsigned Scale = 1;
10161 switch (VT.getSimpleVT().SimpleTy) {
10162 default: return false;
10177 if ((V & (Scale - 1)) != 0)
10180 return V == (V & ((1LL << 5) - 1));
10183 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10184 const ARMSubtarget *Subtarget) {
10185 bool isNeg = false;
10191 switch (VT.getSimpleVT().SimpleTy) {
10192 default: return false;
10197 // + imm12 or - imm8
10199 return V == (V & ((1LL << 8) - 1));
10200 return V == (V & ((1LL << 12) - 1));
10203 // Same as ARM mode. FIXME: NEON?
10204 if (!Subtarget->hasVFP2())
10209 return V == (V & ((1LL << 8) - 1));
10213 /// isLegalAddressImmediate - Return true if the integer value can be used
10214 /// as the offset of the target addressing mode for load / store of the
10216 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10217 const ARMSubtarget *Subtarget) {
10221 if (!VT.isSimple())
10224 if (Subtarget->isThumb1Only())
10225 return isLegalT1AddressImmediate(V, VT);
10226 else if (Subtarget->isThumb2())
10227 return isLegalT2AddressImmediate(V, VT, Subtarget);
10232 switch (VT.getSimpleVT().SimpleTy) {
10233 default: return false;
10238 return V == (V & ((1LL << 12) - 1));
10241 return V == (V & ((1LL << 8) - 1));
10244 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10249 return V == (V & ((1LL << 8) - 1));
10253 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10255 int Scale = AM.Scale;
10259 switch (VT.getSimpleVT().SimpleTy) {
10260 default: return false;
10268 Scale = Scale & ~1;
10269 return Scale == 2 || Scale == 4 || Scale == 8;
10272 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10276 // Note, we allow "void" uses (basically, uses that aren't loads or
10277 // stores), because arm allows folding a scale into many arithmetic
10278 // operations. This should be made more precise and revisited later.
10280 // Allow r << imm, but the imm has to be a multiple of two.
10281 if (Scale & 1) return false;
10282 return isPowerOf2_32(Scale);
10286 /// isLegalAddressingMode - Return true if the addressing mode represented
10287 /// by AM is legal for this target, for a load/store of the specified type.
10288 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10290 EVT VT = getValueType(Ty, true);
10291 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10294 // Can never fold addr of global into load/store.
10298 switch (AM.Scale) {
10299 case 0: // no scale reg, must be "r+i" or "r", or "i".
10302 if (Subtarget->isThumb1Only())
10306 // ARM doesn't support any R+R*scale+imm addr modes.
10310 if (!VT.isSimple())
10313 if (Subtarget->isThumb2())
10314 return isLegalT2ScaledAddressingMode(AM, VT);
10316 int Scale = AM.Scale;
10317 switch (VT.getSimpleVT().SimpleTy) {
10318 default: return false;
10322 if (Scale < 0) Scale = -Scale;
10326 return isPowerOf2_32(Scale & ~1);
10330 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10335 // Note, we allow "void" uses (basically, uses that aren't loads or
10336 // stores), because arm allows folding a scale into many arithmetic
10337 // operations. This should be made more precise and revisited later.
10339 // Allow r << imm, but the imm has to be a multiple of two.
10340 if (Scale & 1) return false;
10341 return isPowerOf2_32(Scale);
10347 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10348 /// icmp immediate, that is the target has icmp instructions which can compare
10349 /// a register against the immediate without having to materialize the
10350 /// immediate into a register.
10351 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10352 // Thumb2 and ARM modes can use cmn for negative immediates.
10353 if (!Subtarget->isThumb())
10354 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10355 if (Subtarget->isThumb2())
10356 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10357 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10358 return Imm >= 0 && Imm <= 255;
10361 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10362 /// *or sub* immediate, that is the target has add or sub instructions which can
10363 /// add a register with the immediate without having to materialize the
10364 /// immediate into a register.
10365 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10366 // Same encoding for add/sub, just flip the sign.
10367 int64_t AbsImm = llvm::abs64(Imm);
10368 if (!Subtarget->isThumb())
10369 return ARM_AM::getSOImmVal(AbsImm) != -1;
10370 if (Subtarget->isThumb2())
10371 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10372 // Thumb1 only has 8-bit unsigned immediate.
10373 return AbsImm >= 0 && AbsImm <= 255;
10376 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10377 bool isSEXTLoad, SDValue &Base,
10378 SDValue &Offset, bool &isInc,
10379 SelectionDAG &DAG) {
10380 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10383 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10384 // AddressingMode 3
10385 Base = Ptr->getOperand(0);
10386 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10387 int RHSC = (int)RHS->getZExtValue();
10388 if (RHSC < 0 && RHSC > -256) {
10389 assert(Ptr->getOpcode() == ISD::ADD);
10391 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10395 isInc = (Ptr->getOpcode() == ISD::ADD);
10396 Offset = Ptr->getOperand(1);
10398 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10399 // AddressingMode 2
10400 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10401 int RHSC = (int)RHS->getZExtValue();
10402 if (RHSC < 0 && RHSC > -0x1000) {
10403 assert(Ptr->getOpcode() == ISD::ADD);
10405 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10406 Base = Ptr->getOperand(0);
10411 if (Ptr->getOpcode() == ISD::ADD) {
10413 ARM_AM::ShiftOpc ShOpcVal=
10414 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10415 if (ShOpcVal != ARM_AM::no_shift) {
10416 Base = Ptr->getOperand(1);
10417 Offset = Ptr->getOperand(0);
10419 Base = Ptr->getOperand(0);
10420 Offset = Ptr->getOperand(1);
10425 isInc = (Ptr->getOpcode() == ISD::ADD);
10426 Base = Ptr->getOperand(0);
10427 Offset = Ptr->getOperand(1);
10431 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10435 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10436 bool isSEXTLoad, SDValue &Base,
10437 SDValue &Offset, bool &isInc,
10438 SelectionDAG &DAG) {
10439 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10442 Base = Ptr->getOperand(0);
10443 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10444 int RHSC = (int)RHS->getZExtValue();
10445 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10446 assert(Ptr->getOpcode() == ISD::ADD);
10448 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10450 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10451 isInc = Ptr->getOpcode() == ISD::ADD;
10452 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10460 /// getPreIndexedAddressParts - returns true by value, base pointer and
10461 /// offset pointer and addressing mode by reference if the node's address
10462 /// can be legally represented as pre-indexed load / store address.
10464 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10466 ISD::MemIndexedMode &AM,
10467 SelectionDAG &DAG) const {
10468 if (Subtarget->isThumb1Only())
10473 bool isSEXTLoad = false;
10474 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10475 Ptr = LD->getBasePtr();
10476 VT = LD->getMemoryVT();
10477 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10478 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10479 Ptr = ST->getBasePtr();
10480 VT = ST->getMemoryVT();
10485 bool isLegal = false;
10486 if (Subtarget->isThumb2())
10487 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10488 Offset, isInc, DAG);
10490 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10491 Offset, isInc, DAG);
10495 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10499 /// getPostIndexedAddressParts - returns true by value, base pointer and
10500 /// offset pointer and addressing mode by reference if this node can be
10501 /// combined with a load / store to form a post-indexed load / store.
10502 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10505 ISD::MemIndexedMode &AM,
10506 SelectionDAG &DAG) const {
10507 if (Subtarget->isThumb1Only())
10512 bool isSEXTLoad = false;
10513 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10514 VT = LD->getMemoryVT();
10515 Ptr = LD->getBasePtr();
10516 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10517 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10518 VT = ST->getMemoryVT();
10519 Ptr = ST->getBasePtr();
10524 bool isLegal = false;
10525 if (Subtarget->isThumb2())
10526 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10529 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10535 // Swap base ptr and offset to catch more post-index load / store when
10536 // it's legal. In Thumb2 mode, offset must be an immediate.
10537 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10538 !Subtarget->isThumb2())
10539 std::swap(Base, Offset);
10541 // Post-indexed load / store update the base pointer.
10546 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10550 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10553 const SelectionDAG &DAG,
10554 unsigned Depth) const {
10555 unsigned BitWidth = KnownOne.getBitWidth();
10556 KnownZero = KnownOne = APInt(BitWidth, 0);
10557 switch (Op.getOpcode()) {
10563 // These nodes' second result is a boolean
10564 if (Op.getResNo() == 0)
10566 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10568 case ARMISD::CMOV: {
10569 // Bits are known zero/one if known on the LHS and RHS.
10570 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10571 if (KnownZero == 0 && KnownOne == 0) return;
10573 APInt KnownZeroRHS, KnownOneRHS;
10574 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10575 KnownZero &= KnownZeroRHS;
10576 KnownOne &= KnownOneRHS;
10582 //===----------------------------------------------------------------------===//
10583 // ARM Inline Assembly Support
10584 //===----------------------------------------------------------------------===//
10586 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10587 // Looking for "rev" which is V6+.
10588 if (!Subtarget->hasV6Ops())
10591 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10592 std::string AsmStr = IA->getAsmString();
10593 SmallVector<StringRef, 4> AsmPieces;
10594 SplitString(AsmStr, AsmPieces, ";\n");
10596 switch (AsmPieces.size()) {
10597 default: return false;
10599 AsmStr = AsmPieces[0];
10601 SplitString(AsmStr, AsmPieces, " \t,");
10604 if (AsmPieces.size() == 3 &&
10605 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10606 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10607 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10608 if (Ty && Ty->getBitWidth() == 32)
10609 return IntrinsicLowering::LowerToByteSwap(CI);
10617 /// getConstraintType - Given a constraint letter, return the type of
10618 /// constraint it is for this target.
10619 ARMTargetLowering::ConstraintType
10620 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10621 if (Constraint.size() == 1) {
10622 switch (Constraint[0]) {
10624 case 'l': return C_RegisterClass;
10625 case 'w': return C_RegisterClass;
10626 case 'h': return C_RegisterClass;
10627 case 'x': return C_RegisterClass;
10628 case 't': return C_RegisterClass;
10629 case 'j': return C_Other; // Constant for movw.
10630 // An address with a single base register. Due to the way we
10631 // currently handle addresses it is the same as an 'r' memory constraint.
10632 case 'Q': return C_Memory;
10634 } else if (Constraint.size() == 2) {
10635 switch (Constraint[0]) {
10637 // All 'U+' constraints are addresses.
10638 case 'U': return C_Memory;
10641 return TargetLowering::getConstraintType(Constraint);
10644 /// Examine constraint type and operand type and determine a weight value.
10645 /// This object must already have been set up with the operand type
10646 /// and the current alternative constraint selected.
10647 TargetLowering::ConstraintWeight
10648 ARMTargetLowering::getSingleConstraintMatchWeight(
10649 AsmOperandInfo &info, const char *constraint) const {
10650 ConstraintWeight weight = CW_Invalid;
10651 Value *CallOperandVal = info.CallOperandVal;
10652 // If we don't have a value, we can't do a match,
10653 // but allow it at the lowest weight.
10654 if (CallOperandVal == NULL)
10656 Type *type = CallOperandVal->getType();
10657 // Look at the constraint type.
10658 switch (*constraint) {
10660 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10663 if (type->isIntegerTy()) {
10664 if (Subtarget->isThumb())
10665 weight = CW_SpecificReg;
10667 weight = CW_Register;
10671 if (type->isFloatingPointTy())
10672 weight = CW_Register;
10678 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10680 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10682 if (Constraint.size() == 1) {
10683 // GCC ARM Constraint Letters
10684 switch (Constraint[0]) {
10685 case 'l': // Low regs or general regs.
10686 if (Subtarget->isThumb())
10687 return RCPair(0U, &ARM::tGPRRegClass);
10688 return RCPair(0U, &ARM::GPRRegClass);
10689 case 'h': // High regs or no regs.
10690 if (Subtarget->isThumb())
10691 return RCPair(0U, &ARM::hGPRRegClass);
10694 return RCPair(0U, &ARM::GPRRegClass);
10696 if (VT == MVT::f32)
10697 return RCPair(0U, &ARM::SPRRegClass);
10698 if (VT.getSizeInBits() == 64)
10699 return RCPair(0U, &ARM::DPRRegClass);
10700 if (VT.getSizeInBits() == 128)
10701 return RCPair(0U, &ARM::QPRRegClass);
10704 if (VT == MVT::f32)
10705 return RCPair(0U, &ARM::SPR_8RegClass);
10706 if (VT.getSizeInBits() == 64)
10707 return RCPair(0U, &ARM::DPR_8RegClass);
10708 if (VT.getSizeInBits() == 128)
10709 return RCPair(0U, &ARM::QPR_8RegClass);
10712 if (VT == MVT::f32)
10713 return RCPair(0U, &ARM::SPRRegClass);
10717 if (StringRef("{cc}").equals_lower(Constraint))
10718 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10720 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10723 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10724 /// vector. If it is invalid, don't add anything to Ops.
10725 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10726 std::string &Constraint,
10727 std::vector<SDValue>&Ops,
10728 SelectionDAG &DAG) const {
10729 SDValue Result(0, 0);
10731 // Currently only support length 1 constraints.
10732 if (Constraint.length() != 1) return;
10734 char ConstraintLetter = Constraint[0];
10735 switch (ConstraintLetter) {
10738 case 'I': case 'J': case 'K': case 'L':
10739 case 'M': case 'N': case 'O':
10740 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10744 int64_t CVal64 = C->getSExtValue();
10745 int CVal = (int) CVal64;
10746 // None of these constraints allow values larger than 32 bits. Check
10747 // that the value fits in an int.
10748 if (CVal != CVal64)
10751 switch (ConstraintLetter) {
10753 // Constant suitable for movw, must be between 0 and
10755 if (Subtarget->hasV6T2Ops())
10756 if (CVal >= 0 && CVal <= 65535)
10760 if (Subtarget->isThumb1Only()) {
10761 // This must be a constant between 0 and 255, for ADD
10763 if (CVal >= 0 && CVal <= 255)
10765 } else if (Subtarget->isThumb2()) {
10766 // A constant that can be used as an immediate value in a
10767 // data-processing instruction.
10768 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10771 // A constant that can be used as an immediate value in a
10772 // data-processing instruction.
10773 if (ARM_AM::getSOImmVal(CVal) != -1)
10779 if (Subtarget->isThumb()) { // FIXME thumb2
10780 // This must be a constant between -255 and -1, for negated ADD
10781 // immediates. This can be used in GCC with an "n" modifier that
10782 // prints the negated value, for use with SUB instructions. It is
10783 // not useful otherwise but is implemented for compatibility.
10784 if (CVal >= -255 && CVal <= -1)
10787 // This must be a constant between -4095 and 4095. It is not clear
10788 // what this constraint is intended for. Implemented for
10789 // compatibility with GCC.
10790 if (CVal >= -4095 && CVal <= 4095)
10796 if (Subtarget->isThumb1Only()) {
10797 // A 32-bit value where only one byte has a nonzero value. Exclude
10798 // zero to match GCC. This constraint is used by GCC internally for
10799 // constants that can be loaded with a move/shift combination.
10800 // It is not useful otherwise but is implemented for compatibility.
10801 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10803 } else if (Subtarget->isThumb2()) {
10804 // A constant whose bitwise inverse can be used as an immediate
10805 // value in a data-processing instruction. This can be used in GCC
10806 // with a "B" modifier that prints the inverted value, for use with
10807 // BIC and MVN instructions. It is not useful otherwise but is
10808 // implemented for compatibility.
10809 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10812 // A constant whose bitwise inverse can be used as an immediate
10813 // value in a data-processing instruction. This can be used in GCC
10814 // with a "B" modifier that prints the inverted value, for use with
10815 // BIC and MVN instructions. It is not useful otherwise but is
10816 // implemented for compatibility.
10817 if (ARM_AM::getSOImmVal(~CVal) != -1)
10823 if (Subtarget->isThumb1Only()) {
10824 // This must be a constant between -7 and 7,
10825 // for 3-operand ADD/SUB immediate instructions.
10826 if (CVal >= -7 && CVal < 7)
10828 } else if (Subtarget->isThumb2()) {
10829 // A constant whose negation can be used as an immediate value in a
10830 // data-processing instruction. This can be used in GCC with an "n"
10831 // modifier that prints the negated value, for use with SUB
10832 // instructions. It is not useful otherwise but is implemented for
10834 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10837 // A constant whose negation can be used as an immediate value in a
10838 // data-processing instruction. This can be used in GCC with an "n"
10839 // modifier that prints the negated value, for use with SUB
10840 // instructions. It is not useful otherwise but is implemented for
10842 if (ARM_AM::getSOImmVal(-CVal) != -1)
10848 if (Subtarget->isThumb()) { // FIXME thumb2
10849 // This must be a multiple of 4 between 0 and 1020, for
10850 // ADD sp + immediate.
10851 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10854 // A power of two or a constant between 0 and 32. This is used in
10855 // GCC for the shift amount on shifted register operands, but it is
10856 // useful in general for any shift amounts.
10857 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10863 if (Subtarget->isThumb()) { // FIXME thumb2
10864 // This must be a constant between 0 and 31, for shift amounts.
10865 if (CVal >= 0 && CVal <= 31)
10871 if (Subtarget->isThumb()) { // FIXME thumb2
10872 // This must be a multiple of 4 between -508 and 508, for
10873 // ADD/SUB sp = sp + immediate.
10874 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10879 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10883 if (Result.getNode()) {
10884 Ops.push_back(Result);
10887 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10890 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10891 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10892 unsigned Opcode = Op->getOpcode();
10893 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10894 "Invalid opcode for Div/Rem lowering");
10895 bool isSigned = (Opcode == ISD::SDIVREM);
10896 EVT VT = Op->getValueType(0);
10897 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10900 switch (VT.getSimpleVT().SimpleTy) {
10901 default: llvm_unreachable("Unexpected request for libcall!");
10902 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10903 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10904 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10905 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10908 SDValue InChain = DAG.getEntryNode();
10910 TargetLowering::ArgListTy Args;
10911 TargetLowering::ArgListEntry Entry;
10912 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10913 EVT ArgVT = Op->getOperand(i).getValueType();
10914 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10915 Entry.Node = Op->getOperand(i);
10917 Entry.isSExt = isSigned;
10918 Entry.isZExt = !isSigned;
10919 Args.push_back(Entry);
10922 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10925 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10929 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10930 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10931 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10932 Callee, Args, DAG, dl);
10933 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10935 return CallInfo.first;
10939 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10940 // The ARM target isn't yet aware of offsets.
10944 bool ARM::isBitFieldInvertedMask(unsigned v) {
10945 if (v == 0xffffffff)
10948 // there can be 1's on either or both "outsides", all the "inside"
10949 // bits must be 0's
10950 unsigned TO = CountTrailingOnes_32(v);
10951 unsigned LO = CountLeadingOnes_32(v);
10952 v = (v >> TO) << TO;
10953 v = (v << LO) >> LO;
10957 /// isFPImmLegal - Returns true if the target can instruction select the
10958 /// specified FP immediate natively. If false, the legalizer will
10959 /// materialize the FP immediate as a load from a constant pool.
10960 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10961 if (!Subtarget->hasVFP3())
10963 if (VT == MVT::f32)
10964 return ARM_AM::getFP32Imm(Imm) != -1;
10965 if (VT == MVT::f64)
10966 return ARM_AM::getFP64Imm(Imm) != -1;
10970 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10971 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10972 /// specified in the intrinsic calls.
10973 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10975 unsigned Intrinsic) const {
10976 switch (Intrinsic) {
10977 case Intrinsic::arm_neon_vld1:
10978 case Intrinsic::arm_neon_vld2:
10979 case Intrinsic::arm_neon_vld3:
10980 case Intrinsic::arm_neon_vld4:
10981 case Intrinsic::arm_neon_vld2lane:
10982 case Intrinsic::arm_neon_vld3lane:
10983 case Intrinsic::arm_neon_vld4lane: {
10984 Info.opc = ISD::INTRINSIC_W_CHAIN;
10985 // Conservatively set memVT to the entire set of vectors loaded.
10986 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10987 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10988 Info.ptrVal = I.getArgOperand(0);
10990 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10991 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10992 Info.vol = false; // volatile loads with NEON intrinsics not supported
10993 Info.readMem = true;
10994 Info.writeMem = false;
10997 case Intrinsic::arm_neon_vst1:
10998 case Intrinsic::arm_neon_vst2:
10999 case Intrinsic::arm_neon_vst3:
11000 case Intrinsic::arm_neon_vst4:
11001 case Intrinsic::arm_neon_vst2lane:
11002 case Intrinsic::arm_neon_vst3lane:
11003 case Intrinsic::arm_neon_vst4lane: {
11004 Info.opc = ISD::INTRINSIC_VOID;
11005 // Conservatively set memVT to the entire set of vectors stored.
11006 unsigned NumElts = 0;
11007 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11008 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11009 if (!ArgTy->isVectorTy())
11011 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11013 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11014 Info.ptrVal = I.getArgOperand(0);
11016 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11017 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11018 Info.vol = false; // volatile stores with NEON intrinsics not supported
11019 Info.readMem = false;
11020 Info.writeMem = true;
11023 case Intrinsic::arm_ldrex: {
11024 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11025 Info.opc = ISD::INTRINSIC_W_CHAIN;
11026 Info.memVT = MVT::getVT(PtrTy->getElementType());
11027 Info.ptrVal = I.getArgOperand(0);
11029 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11031 Info.readMem = true;
11032 Info.writeMem = false;
11035 case Intrinsic::arm_strex: {
11036 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11037 Info.opc = ISD::INTRINSIC_W_CHAIN;
11038 Info.memVT = MVT::getVT(PtrTy->getElementType());
11039 Info.ptrVal = I.getArgOperand(1);
11041 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11043 Info.readMem = false;
11044 Info.writeMem = true;
11047 case Intrinsic::arm_strexd: {
11048 Info.opc = ISD::INTRINSIC_W_CHAIN;
11049 Info.memVT = MVT::i64;
11050 Info.ptrVal = I.getArgOperand(2);
11054 Info.readMem = false;
11055 Info.writeMem = true;
11058 case Intrinsic::arm_ldrexd: {
11059 Info.opc = ISD::INTRINSIC_W_CHAIN;
11060 Info.memVT = MVT::i64;
11061 Info.ptrVal = I.getArgOperand(0);
11065 Info.readMem = true;
11066 Info.writeMem = false;