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, SmallVector<CCValAssign, 16> &locs,
78 LLVMContext &C, ParmContext PC)
79 : CCState(CC, isVarArg, MF, TM, locs, C) {
80 assert(((PC == Call) || (PC == Prologue)) &&
81 "ARMCCState users must specify whether their context is call"
82 "or prologue generation.");
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90 ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94 MVT PromotedBitwiseVT) {
95 if (VT != PromotedLdStVT) {
96 setOperationAction(ISD::LOAD, VT, Promote);
97 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99 setOperationAction(ISD::STORE, VT, Promote);
100 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103 MVT ElemTy = VT.getVectorElementType();
104 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105 setOperationAction(ISD::SETCC, VT, Custom);
106 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108 if (ElemTy == MVT::i32) {
109 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
120 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
121 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
122 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123 setOperationAction(ISD::SELECT, VT, Expand);
124 setOperationAction(ISD::SELECT_CC, VT, Expand);
125 setOperationAction(ISD::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().getOS() == Triple::IOS &&
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);
456 if (Subtarget->hasNEON()) {
457 addDRTypeForNEON(MVT::v2f32);
458 addDRTypeForNEON(MVT::v8i8);
459 addDRTypeForNEON(MVT::v4i16);
460 addDRTypeForNEON(MVT::v2i32);
461 addDRTypeForNEON(MVT::v1i64);
463 addQRTypeForNEON(MVT::v4f32);
464 addQRTypeForNEON(MVT::v2f64);
465 addQRTypeForNEON(MVT::v16i8);
466 addQRTypeForNEON(MVT::v8i16);
467 addQRTypeForNEON(MVT::v4i32);
468 addQRTypeForNEON(MVT::v2i64);
470 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471 // neither Neon nor VFP support any arithmetic operations on it.
472 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473 // supported for v4f32.
474 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477 // FIXME: Code duplication: FDIV and FREM are expanded always, see
478 // ARMTargetLowering::addTypeForNEON method for details.
479 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481 // FIXME: Create unittest.
482 // In another words, find a way when "copysign" appears in DAG with vector
484 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485 // FIXME: Code duplication: SETCC has custom operation action, see
486 // ARMTargetLowering::addTypeForNEON method for details.
487 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488 // FIXME: Create unittest for FNEG and for FABS.
489 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
509 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
525 // Mark v2f32 intrinsics.
526 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
527 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
528 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
529 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
530 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
531 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
532 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
533 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
534 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
535 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
536 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
537 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
538 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
539 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
540 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
542 // Neon does not support some operations on v1i64 and v2i64 types.
543 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
544 // Custom handling for some quad-vector types to detect VMULL.
545 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
546 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
547 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
548 // Custom handling for some vector types to avoid expensive expansions
549 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
550 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
551 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
552 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
553 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
554 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
555 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
556 // a destination type that is wider than the source, and nor does
557 // it have a FP_TO_[SU]INT instruction with a narrower destination than
559 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
560 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
561 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
562 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
564 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
565 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
567 // Custom expand long extensions to vectors.
568 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
569 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
570 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
571 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
572 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
573 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
574 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
575 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
577 // NEON does not have single instruction CTPOP for vectors with element
578 // types wider than 8-bits. However, custom lowering can leverage the
579 // v8i8/v16i8 vcnt instruction.
580 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
581 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
582 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
583 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
585 // NEON only has FMA instructions as of VFP4.
586 if (!Subtarget->hasVFP4()) {
587 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
588 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
591 setTargetDAGCombine(ISD::INTRINSIC_VOID);
592 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
594 setTargetDAGCombine(ISD::SHL);
595 setTargetDAGCombine(ISD::SRL);
596 setTargetDAGCombine(ISD::SRA);
597 setTargetDAGCombine(ISD::SIGN_EXTEND);
598 setTargetDAGCombine(ISD::ZERO_EXTEND);
599 setTargetDAGCombine(ISD::ANY_EXTEND);
600 setTargetDAGCombine(ISD::SELECT_CC);
601 setTargetDAGCombine(ISD::BUILD_VECTOR);
602 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
603 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
604 setTargetDAGCombine(ISD::STORE);
605 setTargetDAGCombine(ISD::FP_TO_SINT);
606 setTargetDAGCombine(ISD::FP_TO_UINT);
607 setTargetDAGCombine(ISD::FDIV);
609 // It is legal to extload from v4i8 to v4i16 or v4i32.
610 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
611 MVT::v4i16, MVT::v2i16,
613 for (unsigned i = 0; i < 6; ++i) {
614 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
615 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
616 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
620 // ARM and Thumb2 support UMLAL/SMLAL.
621 if (!Subtarget->isThumb1Only())
622 setTargetDAGCombine(ISD::ADDC);
625 computeRegisterProperties();
627 // ARM does not have f32 extending load.
628 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
630 // ARM does not have i1 sign extending load.
631 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
633 // ARM supports all 4 flavors of integer indexed load / store.
634 if (!Subtarget->isThumb1Only()) {
635 for (unsigned im = (unsigned)ISD::PRE_INC;
636 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
637 setIndexedLoadAction(im, MVT::i1, Legal);
638 setIndexedLoadAction(im, MVT::i8, Legal);
639 setIndexedLoadAction(im, MVT::i16, Legal);
640 setIndexedLoadAction(im, MVT::i32, Legal);
641 setIndexedStoreAction(im, MVT::i1, Legal);
642 setIndexedStoreAction(im, MVT::i8, Legal);
643 setIndexedStoreAction(im, MVT::i16, Legal);
644 setIndexedStoreAction(im, MVT::i32, Legal);
648 // i64 operation support.
649 setOperationAction(ISD::MUL, MVT::i64, Expand);
650 setOperationAction(ISD::MULHU, MVT::i32, Expand);
651 if (Subtarget->isThumb1Only()) {
652 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
653 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
655 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
656 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
657 setOperationAction(ISD::MULHS, MVT::i32, Expand);
659 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662 setOperationAction(ISD::SRL, MVT::i64, Custom);
663 setOperationAction(ISD::SRA, MVT::i64, Custom);
665 if (!Subtarget->isThumb1Only()) {
666 // FIXME: We should do this for Thumb1 as well.
667 setOperationAction(ISD::ADDC, MVT::i32, Custom);
668 setOperationAction(ISD::ADDE, MVT::i32, Custom);
669 setOperationAction(ISD::SUBC, MVT::i32, Custom);
670 setOperationAction(ISD::SUBE, MVT::i32, Custom);
673 // ARM does not have ROTL.
674 setOperationAction(ISD::ROTL, MVT::i32, Expand);
675 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
676 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
677 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
678 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
680 // These just redirect to CTTZ and CTLZ on ARM.
681 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
682 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
684 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
686 // Only ARMv6 has BSWAP.
687 if (!Subtarget->hasV6Ops())
688 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
690 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
691 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
692 // These are expanded into libcalls if the cpu doesn't have HW divider.
693 setOperationAction(ISD::SDIV, MVT::i32, Expand);
694 setOperationAction(ISD::UDIV, MVT::i32, Expand);
696 setOperationAction(ISD::SREM, MVT::i32, Expand);
697 setOperationAction(ISD::UREM, MVT::i32, Expand);
698 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
699 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
701 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
702 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
703 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
704 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
705 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
707 setOperationAction(ISD::TRAP, MVT::Other, Legal);
709 // Use the default implementation.
710 setOperationAction(ISD::VASTART, MVT::Other, Custom);
711 setOperationAction(ISD::VAARG, MVT::Other, Expand);
712 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
713 setOperationAction(ISD::VAEND, MVT::Other, Expand);
714 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
715 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
717 if (!Subtarget->isTargetDarwin()) {
718 // Non-Darwin platforms may return values in these registers via the
719 // personality function.
720 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
721 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
722 setExceptionPointerRegister(ARM::R0);
723 setExceptionSelectorRegister(ARM::R1);
726 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
727 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
728 // the default expansion.
729 // FIXME: This should be checking for v6k, not just v6.
730 if (Subtarget->hasDataBarrier() ||
731 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
732 // membarrier needs custom lowering; the rest are legal and handled
734 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
735 // Custom lowering for 64-bit ops
736 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
737 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
738 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
739 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
740 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
741 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
742 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
743 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
744 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
745 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
746 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
747 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
748 setInsertFencesForAtomic(true);
750 // Set them all for expansion, which will force libcalls.
751 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
752 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
753 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
754 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
755 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
756 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
757 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
758 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
759 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
760 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
761 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
762 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
763 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
764 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
765 // Unordered/Monotonic case.
766 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
767 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
770 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
772 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
773 if (!Subtarget->hasV6Ops()) {
774 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
775 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
777 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
779 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
780 !Subtarget->isThumb1Only()) {
781 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
782 // iff target supports vfp2.
783 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
784 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
787 // We want to custom lower some of our intrinsics.
788 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
789 if (Subtarget->isTargetDarwin()) {
790 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
791 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
792 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
795 setOperationAction(ISD::SETCC, MVT::i32, Expand);
796 setOperationAction(ISD::SETCC, MVT::f32, Expand);
797 setOperationAction(ISD::SETCC, MVT::f64, Expand);
798 setOperationAction(ISD::SELECT, MVT::i32, Custom);
799 setOperationAction(ISD::SELECT, MVT::f32, Custom);
800 setOperationAction(ISD::SELECT, MVT::f64, Custom);
801 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
802 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
803 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
805 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
806 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
807 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
808 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
809 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
811 // We don't support sin/cos/fmod/copysign/pow
812 setOperationAction(ISD::FSIN, MVT::f64, Expand);
813 setOperationAction(ISD::FSIN, MVT::f32, Expand);
814 setOperationAction(ISD::FCOS, MVT::f32, Expand);
815 setOperationAction(ISD::FCOS, MVT::f64, Expand);
816 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
817 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
818 setOperationAction(ISD::FREM, MVT::f64, Expand);
819 setOperationAction(ISD::FREM, MVT::f32, Expand);
820 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821 !Subtarget->isThumb1Only()) {
822 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
823 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
825 setOperationAction(ISD::FPOW, MVT::f64, Expand);
826 setOperationAction(ISD::FPOW, MVT::f32, Expand);
828 if (!Subtarget->hasVFP4()) {
829 setOperationAction(ISD::FMA, MVT::f64, Expand);
830 setOperationAction(ISD::FMA, MVT::f32, Expand);
833 // Various VFP goodness
834 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
835 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
836 if (Subtarget->hasVFP2()) {
837 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
838 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
839 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
840 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
842 // Special handling for half-precision FP.
843 if (!Subtarget->hasFP16()) {
844 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
845 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
849 // We have target-specific dag combine patterns for the following nodes:
850 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
851 setTargetDAGCombine(ISD::ADD);
852 setTargetDAGCombine(ISD::SUB);
853 setTargetDAGCombine(ISD::MUL);
854 setTargetDAGCombine(ISD::AND);
855 setTargetDAGCombine(ISD::OR);
856 setTargetDAGCombine(ISD::XOR);
858 if (Subtarget->hasV6Ops())
859 setTargetDAGCombine(ISD::SRL);
861 setStackPointerRegisterToSaveRestore(ARM::SP);
863 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
864 !Subtarget->hasVFP2())
865 setSchedulingPreference(Sched::RegPressure);
867 setSchedulingPreference(Sched::Hybrid);
869 //// temporary - rewrite interface to use type
870 MaxStoresPerMemset = 8;
871 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
872 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
873 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
875 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
877 // On ARM arguments smaller than 4 bytes are extended, so all arguments
878 // are at least 4 bytes aligned.
879 setMinStackArgumentAlignment(4);
881 // Prefer likely predicted branches to selects on out-of-order cores.
882 PredictableSelectIsExpensive = Subtarget->isLikeA9();
884 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
887 // FIXME: It might make sense to define the representative register class as the
888 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
889 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
890 // SPR's representative would be DPR_VFP2. This should work well if register
891 // pressure tracking were modified such that a register use would increment the
892 // pressure of the register class's representative and all of it's super
893 // classes' representatives transitively. We have not implemented this because
894 // of the difficulty prior to coalescing of modeling operand register classes
895 // due to the common occurrence of cross class copies and subregister insertions
897 std::pair<const TargetRegisterClass*, uint8_t>
898 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
899 const TargetRegisterClass *RRC = 0;
901 switch (VT.SimpleTy) {
903 return TargetLowering::findRepresentativeClass(VT);
904 // Use DPR as representative register class for all floating point
905 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
906 // the cost is 1 for both f32 and f64.
907 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
908 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
909 RRC = &ARM::DPRRegClass;
910 // When NEON is used for SP, only half of the register file is available
911 // because operations that define both SP and DP results will be constrained
912 // to the VFP2 class (D0-D15). We currently model this constraint prior to
913 // coalescing by double-counting the SP regs. See the FIXME above.
914 if (Subtarget->useNEONForSinglePrecisionFP())
917 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
918 case MVT::v4f32: case MVT::v2f64:
919 RRC = &ARM::DPRRegClass;
923 RRC = &ARM::DPRRegClass;
927 RRC = &ARM::DPRRegClass;
931 return std::make_pair(RRC, Cost);
934 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
937 case ARMISD::Wrapper: return "ARMISD::Wrapper";
938 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
939 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
940 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
941 case ARMISD::CALL: return "ARMISD::CALL";
942 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
943 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
944 case ARMISD::tCALL: return "ARMISD::tCALL";
945 case ARMISD::BRCOND: return "ARMISD::BRCOND";
946 case ARMISD::BR_JT: return "ARMISD::BR_JT";
947 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
948 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
949 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
950 case ARMISD::CMP: return "ARMISD::CMP";
951 case ARMISD::CMN: return "ARMISD::CMN";
952 case ARMISD::CMPZ: return "ARMISD::CMPZ";
953 case ARMISD::CMPFP: return "ARMISD::CMPFP";
954 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
955 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
956 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
958 case ARMISD::CMOV: return "ARMISD::CMOV";
960 case ARMISD::RBIT: return "ARMISD::RBIT";
962 case ARMISD::FTOSI: return "ARMISD::FTOSI";
963 case ARMISD::FTOUI: return "ARMISD::FTOUI";
964 case ARMISD::SITOF: return "ARMISD::SITOF";
965 case ARMISD::UITOF: return "ARMISD::UITOF";
967 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
968 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
969 case ARMISD::RRX: return "ARMISD::RRX";
971 case ARMISD::ADDC: return "ARMISD::ADDC";
972 case ARMISD::ADDE: return "ARMISD::ADDE";
973 case ARMISD::SUBC: return "ARMISD::SUBC";
974 case ARMISD::SUBE: return "ARMISD::SUBE";
976 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
977 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
979 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
980 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
982 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
984 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
986 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
988 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
989 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
991 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
993 case ARMISD::VCEQ: return "ARMISD::VCEQ";
994 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
995 case ARMISD::VCGE: return "ARMISD::VCGE";
996 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
997 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
998 case ARMISD::VCGEU: return "ARMISD::VCGEU";
999 case ARMISD::VCGT: return "ARMISD::VCGT";
1000 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1001 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1002 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1003 case ARMISD::VTST: return "ARMISD::VTST";
1005 case ARMISD::VSHL: return "ARMISD::VSHL";
1006 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1007 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1008 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1009 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1010 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1011 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1012 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1013 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1014 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1015 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1016 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1017 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1018 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1019 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1020 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1021 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1022 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1023 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1024 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1025 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1026 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1027 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1028 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1029 case ARMISD::VDUP: return "ARMISD::VDUP";
1030 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1031 case ARMISD::VEXT: return "ARMISD::VEXT";
1032 case ARMISD::VREV64: return "ARMISD::VREV64";
1033 case ARMISD::VREV32: return "ARMISD::VREV32";
1034 case ARMISD::VREV16: return "ARMISD::VREV16";
1035 case ARMISD::VZIP: return "ARMISD::VZIP";
1036 case ARMISD::VUZP: return "ARMISD::VUZP";
1037 case ARMISD::VTRN: return "ARMISD::VTRN";
1038 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1039 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1040 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1041 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1042 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1043 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1044 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1045 case ARMISD::FMAX: return "ARMISD::FMAX";
1046 case ARMISD::FMIN: return "ARMISD::FMIN";
1047 case ARMISD::BFI: return "ARMISD::BFI";
1048 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1049 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1050 case ARMISD::VBSL: return "ARMISD::VBSL";
1051 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1052 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1053 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1054 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1055 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1056 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1057 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1058 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1059 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1060 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1061 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1062 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1063 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1064 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1065 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1066 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1067 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1068 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1069 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1070 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1074 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1075 if (!VT.isVector()) return getPointerTy();
1076 return VT.changeVectorElementTypeToInteger();
1079 /// getRegClassFor - Return the register class that should be used for the
1080 /// specified value type.
1081 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1082 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1083 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1084 // load / store 4 to 8 consecutive D registers.
1085 if (Subtarget->hasNEON()) {
1086 if (VT == MVT::v4i64)
1087 return &ARM::QQPRRegClass;
1088 if (VT == MVT::v8i64)
1089 return &ARM::QQQQPRRegClass;
1091 return TargetLowering::getRegClassFor(VT);
1094 // Create a fast isel object.
1096 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1097 const TargetLibraryInfo *libInfo) const {
1098 return ARM::createFastISel(funcInfo, libInfo);
1101 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1102 /// be used for loads / stores from the global.
1103 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1104 return (Subtarget->isThumb1Only() ? 127 : 4095);
1107 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1108 unsigned NumVals = N->getNumValues();
1110 return Sched::RegPressure;
1112 for (unsigned i = 0; i != NumVals; ++i) {
1113 EVT VT = N->getValueType(i);
1114 if (VT == MVT::Glue || VT == MVT::Other)
1116 if (VT.isFloatingPoint() || VT.isVector())
1120 if (!N->isMachineOpcode())
1121 return Sched::RegPressure;
1123 // Load are scheduled for latency even if there instruction itinerary
1124 // is not available.
1125 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1126 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1128 if (MCID.getNumDefs() == 0)
1129 return Sched::RegPressure;
1130 if (!Itins->isEmpty() &&
1131 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1134 return Sched::RegPressure;
1137 //===----------------------------------------------------------------------===//
1139 //===----------------------------------------------------------------------===//
1141 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1142 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1144 default: llvm_unreachable("Unknown condition code!");
1145 case ISD::SETNE: return ARMCC::NE;
1146 case ISD::SETEQ: return ARMCC::EQ;
1147 case ISD::SETGT: return ARMCC::GT;
1148 case ISD::SETGE: return ARMCC::GE;
1149 case ISD::SETLT: return ARMCC::LT;
1150 case ISD::SETLE: return ARMCC::LE;
1151 case ISD::SETUGT: return ARMCC::HI;
1152 case ISD::SETUGE: return ARMCC::HS;
1153 case ISD::SETULT: return ARMCC::LO;
1154 case ISD::SETULE: return ARMCC::LS;
1158 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1159 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1160 ARMCC::CondCodes &CondCode2) {
1161 CondCode2 = ARMCC::AL;
1163 default: llvm_unreachable("Unknown FP condition!");
1165 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1167 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1169 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1170 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1171 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1172 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1173 case ISD::SETO: CondCode = ARMCC::VC; break;
1174 case ISD::SETUO: CondCode = ARMCC::VS; break;
1175 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1176 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1177 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1179 case ISD::SETULT: CondCode = ARMCC::LT; break;
1181 case ISD::SETULE: CondCode = ARMCC::LE; break;
1183 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1187 //===----------------------------------------------------------------------===//
1188 // Calling Convention Implementation
1189 //===----------------------------------------------------------------------===//
1191 #include "ARMGenCallingConv.inc"
1193 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1194 /// given CallingConvention value.
1195 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1197 bool isVarArg) const {
1200 llvm_unreachable("Unsupported calling convention");
1201 case CallingConv::Fast:
1202 if (Subtarget->hasVFP2() && !isVarArg) {
1203 if (!Subtarget->isAAPCS_ABI())
1204 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1205 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1206 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1209 case CallingConv::C: {
1210 // Use target triple & subtarget features to do actual dispatch.
1211 if (!Subtarget->isAAPCS_ABI())
1212 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1213 else if (Subtarget->hasVFP2() &&
1214 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1216 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1217 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1219 case CallingConv::ARM_AAPCS_VFP:
1221 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1223 case CallingConv::ARM_AAPCS:
1224 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1225 case CallingConv::ARM_APCS:
1226 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1227 case CallingConv::GHC:
1228 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1232 /// LowerCallResult - Lower the result values of a call into the
1233 /// appropriate copies out of appropriate physical registers.
1235 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1236 CallingConv::ID CallConv, bool isVarArg,
1237 const SmallVectorImpl<ISD::InputArg> &Ins,
1238 SDLoc dl, SelectionDAG &DAG,
1239 SmallVectorImpl<SDValue> &InVals,
1240 bool isThisReturn, SDValue ThisVal) const {
1242 // Assign locations to each value returned by this call.
1243 SmallVector<CCValAssign, 16> RVLocs;
1244 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1245 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1246 CCInfo.AnalyzeCallResult(Ins,
1247 CCAssignFnForNode(CallConv, /* Return*/ true,
1250 // Copy all of the result registers out of their specified physreg.
1251 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1252 CCValAssign VA = RVLocs[i];
1254 // Pass 'this' value directly from the argument to return value, to avoid
1255 // reg unit interference
1256 if (i == 0 && isThisReturn) {
1257 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1258 "unexpected return calling convention register assignment");
1259 InVals.push_back(ThisVal);
1264 if (VA.needsCustom()) {
1265 // Handle f64 or half of a v2f64.
1266 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1268 Chain = Lo.getValue(1);
1269 InFlag = Lo.getValue(2);
1270 VA = RVLocs[++i]; // skip ahead to next loc
1271 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1273 Chain = Hi.getValue(1);
1274 InFlag = Hi.getValue(2);
1275 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1277 if (VA.getLocVT() == MVT::v2f64) {
1278 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1279 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1280 DAG.getConstant(0, MVT::i32));
1282 VA = RVLocs[++i]; // skip ahead to next loc
1283 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1284 Chain = Lo.getValue(1);
1285 InFlag = Lo.getValue(2);
1286 VA = RVLocs[++i]; // skip ahead to next loc
1287 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1288 Chain = Hi.getValue(1);
1289 InFlag = Hi.getValue(2);
1290 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1291 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1292 DAG.getConstant(1, MVT::i32));
1295 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1297 Chain = Val.getValue(1);
1298 InFlag = Val.getValue(2);
1301 switch (VA.getLocInfo()) {
1302 default: llvm_unreachable("Unknown loc info!");
1303 case CCValAssign::Full: break;
1304 case CCValAssign::BCvt:
1305 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1309 InVals.push_back(Val);
1315 /// LowerMemOpCallTo - Store the argument to the stack.
1317 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1318 SDValue StackPtr, SDValue Arg,
1319 SDLoc dl, SelectionDAG &DAG,
1320 const CCValAssign &VA,
1321 ISD::ArgFlagsTy Flags) const {
1322 unsigned LocMemOffset = VA.getLocMemOffset();
1323 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1324 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1325 return DAG.getStore(Chain, dl, Arg, PtrOff,
1326 MachinePointerInfo::getStack(LocMemOffset),
1330 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1331 SDValue Chain, SDValue &Arg,
1332 RegsToPassVector &RegsToPass,
1333 CCValAssign &VA, CCValAssign &NextVA,
1335 SmallVector<SDValue, 8> &MemOpChains,
1336 ISD::ArgFlagsTy Flags) const {
1338 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1339 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1340 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1342 if (NextVA.isRegLoc())
1343 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1345 assert(NextVA.isMemLoc());
1346 if (StackPtr.getNode() == 0)
1347 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1349 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1355 /// LowerCall - Lowering a call into a callseq_start <-
1356 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1359 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1360 SmallVectorImpl<SDValue> &InVals) const {
1361 SelectionDAG &DAG = CLI.DAG;
1363 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1364 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1365 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1366 SDValue Chain = CLI.Chain;
1367 SDValue Callee = CLI.Callee;
1368 bool &isTailCall = CLI.IsTailCall;
1369 CallingConv::ID CallConv = CLI.CallConv;
1370 bool doesNotRet = CLI.DoesNotReturn;
1371 bool isVarArg = CLI.IsVarArg;
1373 MachineFunction &MF = DAG.getMachineFunction();
1374 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1375 bool isThisReturn = false;
1376 bool isSibCall = false;
1377 // Disable tail calls if they're not supported.
1378 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1381 // Check if it's really possible to do a tail call.
1382 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1383 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1384 Outs, OutVals, Ins, DAG);
1385 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1386 // detected sibcalls.
1393 // Analyze operands of the call, assigning locations to each operand.
1394 SmallVector<CCValAssign, 16> ArgLocs;
1395 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1396 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1397 CCInfo.AnalyzeCallOperands(Outs,
1398 CCAssignFnForNode(CallConv, /* Return*/ false,
1401 // Get a count of how many bytes are to be pushed on the stack.
1402 unsigned NumBytes = CCInfo.getNextStackOffset();
1404 // For tail calls, memory operands are available in our caller's stack.
1408 // Adjust the stack pointer for the new arguments...
1409 // These operations are automatically eliminated by the prolog/epilog pass
1411 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1414 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1416 RegsToPassVector RegsToPass;
1417 SmallVector<SDValue, 8> MemOpChains;
1419 // Walk the register/memloc assignments, inserting copies/loads. In the case
1420 // of tail call optimization, arguments are handled later.
1421 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1423 ++i, ++realArgIdx) {
1424 CCValAssign &VA = ArgLocs[i];
1425 SDValue Arg = OutVals[realArgIdx];
1426 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1427 bool isByVal = Flags.isByVal();
1429 // Promote the value if needed.
1430 switch (VA.getLocInfo()) {
1431 default: llvm_unreachable("Unknown loc info!");
1432 case CCValAssign::Full: break;
1433 case CCValAssign::SExt:
1434 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1436 case CCValAssign::ZExt:
1437 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1439 case CCValAssign::AExt:
1440 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1442 case CCValAssign::BCvt:
1443 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1447 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1448 if (VA.needsCustom()) {
1449 if (VA.getLocVT() == MVT::v2f64) {
1450 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1451 DAG.getConstant(0, MVT::i32));
1452 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1453 DAG.getConstant(1, MVT::i32));
1455 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1456 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1458 VA = ArgLocs[++i]; // skip ahead to next loc
1459 if (VA.isRegLoc()) {
1460 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1461 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1463 assert(VA.isMemLoc());
1465 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1466 dl, DAG, VA, Flags));
1469 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1470 StackPtr, MemOpChains, Flags);
1472 } else if (VA.isRegLoc()) {
1473 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1474 assert(VA.getLocVT() == MVT::i32 &&
1475 "unexpected calling convention register assignment");
1476 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1477 "unexpected use of 'returned'");
1478 isThisReturn = true;
1480 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1481 } else if (isByVal) {
1482 assert(VA.isMemLoc());
1483 unsigned offset = 0;
1485 // True if this byval aggregate will be split between registers
1487 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1488 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1490 if (CurByValIdx < ByValArgsCount) {
1492 unsigned RegBegin, RegEnd;
1493 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1495 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1497 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1498 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1499 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1500 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1501 MachinePointerInfo(),
1502 false, false, false, 0);
1503 MemOpChains.push_back(Load.getValue(1));
1504 RegsToPass.push_back(std::make_pair(j, Load));
1507 // If parameter size outsides register area, "offset" value
1508 // helps us to calculate stack slot for remained part properly.
1509 offset = RegEnd - RegBegin;
1511 CCInfo.nextInRegsParam();
1514 if (Flags.getByValSize() > 4*offset) {
1515 unsigned LocMemOffset = VA.getLocMemOffset();
1516 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1517 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1519 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1520 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1521 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1523 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1525 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1526 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1527 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1528 Ops, array_lengthof(Ops)));
1530 } else if (!isSibCall) {
1531 assert(VA.isMemLoc());
1533 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1534 dl, DAG, VA, Flags));
1538 if (!MemOpChains.empty())
1539 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1540 &MemOpChains[0], MemOpChains.size());
1542 // Build a sequence of copy-to-reg nodes chained together with token chain
1543 // and flag operands which copy the outgoing args into the appropriate regs.
1545 // Tail call byval lowering might overwrite argument registers so in case of
1546 // tail call optimization the copies to registers are lowered later.
1548 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1549 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1550 RegsToPass[i].second, InFlag);
1551 InFlag = Chain.getValue(1);
1554 // For tail calls lower the arguments to the 'real' stack slot.
1556 // Force all the incoming stack arguments to be loaded from the stack
1557 // before any new outgoing arguments are stored to the stack, because the
1558 // outgoing stack slots may alias the incoming argument stack slots, and
1559 // the alias isn't otherwise explicit. This is slightly more conservative
1560 // than necessary, because it means that each store effectively depends
1561 // on every argument instead of just those arguments it would clobber.
1563 // Do not flag preceding copytoreg stuff together with the following stuff.
1565 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1566 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1567 RegsToPass[i].second, InFlag);
1568 InFlag = Chain.getValue(1);
1573 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1574 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1575 // node so that legalize doesn't hack it.
1576 bool isDirect = false;
1577 bool isARMFunc = false;
1578 bool isLocalARMFunc = false;
1579 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1581 if (EnableARMLongCalls) {
1582 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1583 && "long-calls with non-static relocation model!");
1584 // Handle a global address or an external symbol. If it's not one of
1585 // those, the target's already in a register, so we don't need to do
1587 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1588 const GlobalValue *GV = G->getGlobal();
1589 // Create a constant pool entry for the callee address
1590 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1591 ARMConstantPoolValue *CPV =
1592 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1594 // Get the address of the callee into a register
1595 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1596 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1597 Callee = DAG.getLoad(getPointerTy(), dl,
1598 DAG.getEntryNode(), CPAddr,
1599 MachinePointerInfo::getConstantPool(),
1600 false, false, false, 0);
1601 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1602 const char *Sym = S->getSymbol();
1604 // Create a constant pool entry for the callee address
1605 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1606 ARMConstantPoolValue *CPV =
1607 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1608 ARMPCLabelIndex, 0);
1609 // Get the address of the callee into a register
1610 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1611 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1612 Callee = DAG.getLoad(getPointerTy(), dl,
1613 DAG.getEntryNode(), CPAddr,
1614 MachinePointerInfo::getConstantPool(),
1615 false, false, false, 0);
1617 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1618 const GlobalValue *GV = G->getGlobal();
1620 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1621 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1622 getTargetMachine().getRelocationModel() != Reloc::Static;
1623 isARMFunc = !Subtarget->isThumb() || isStub;
1624 // ARM call to a local ARM function is predicable.
1625 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1626 // tBX takes a register source operand.
1627 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1628 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1629 ARMConstantPoolValue *CPV =
1630 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1631 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1632 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1633 Callee = DAG.getLoad(getPointerTy(), dl,
1634 DAG.getEntryNode(), CPAddr,
1635 MachinePointerInfo::getConstantPool(),
1636 false, false, false, 0);
1637 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1638 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1639 getPointerTy(), Callee, PICLabel);
1641 // On ELF targets for PIC code, direct calls should go through the PLT
1642 unsigned OpFlags = 0;
1643 if (Subtarget->isTargetELF() &&
1644 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1645 OpFlags = ARMII::MO_PLT;
1646 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1648 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1650 bool isStub = Subtarget->isTargetDarwin() &&
1651 getTargetMachine().getRelocationModel() != Reloc::Static;
1652 isARMFunc = !Subtarget->isThumb() || isStub;
1653 // tBX takes a register source operand.
1654 const char *Sym = S->getSymbol();
1655 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1656 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1657 ARMConstantPoolValue *CPV =
1658 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1659 ARMPCLabelIndex, 4);
1660 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1661 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1662 Callee = DAG.getLoad(getPointerTy(), dl,
1663 DAG.getEntryNode(), CPAddr,
1664 MachinePointerInfo::getConstantPool(),
1665 false, false, false, 0);
1666 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1667 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1668 getPointerTy(), Callee, PICLabel);
1670 unsigned OpFlags = 0;
1671 // On ELF targets for PIC code, direct calls should go through the PLT
1672 if (Subtarget->isTargetELF() &&
1673 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1674 OpFlags = ARMII::MO_PLT;
1675 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1679 // FIXME: handle tail calls differently.
1681 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1682 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1683 if (Subtarget->isThumb()) {
1684 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1685 CallOpc = ARMISD::CALL_NOLINK;
1687 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1689 if (!isDirect && !Subtarget->hasV5TOps())
1690 CallOpc = ARMISD::CALL_NOLINK;
1691 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1692 // Emit regular call when code size is the priority
1694 // "mov lr, pc; b _foo" to avoid confusing the RSP
1695 CallOpc = ARMISD::CALL_NOLINK;
1697 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1700 std::vector<SDValue> Ops;
1701 Ops.push_back(Chain);
1702 Ops.push_back(Callee);
1704 // Add argument registers to the end of the list so that they are known live
1706 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1707 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1708 RegsToPass[i].second.getValueType()));
1710 // Add a register mask operand representing the call-preserved registers.
1711 const uint32_t *Mask;
1712 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1713 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1715 // For 'this' returns, use the R0-preserving mask if applicable
1716 Mask = ARI->getThisReturnPreservedMask(CallConv);
1718 // Set isThisReturn to false if the calling convention is not one that
1719 // allows 'returned' to be modeled in this way, so LowerCallResult does
1720 // not try to pass 'this' straight through
1721 isThisReturn = false;
1722 Mask = ARI->getCallPreservedMask(CallConv);
1725 Mask = ARI->getCallPreservedMask(CallConv);
1727 assert(Mask && "Missing call preserved mask for calling convention");
1728 Ops.push_back(DAG.getRegisterMask(Mask));
1730 if (InFlag.getNode())
1731 Ops.push_back(InFlag);
1733 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1735 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1737 // Returns a chain and a flag for retval copy to use.
1738 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1739 InFlag = Chain.getValue(1);
1741 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1742 DAG.getIntPtrConstant(0, true), InFlag, dl);
1744 InFlag = Chain.getValue(1);
1746 // Handle result values, copying them out of physregs into vregs that we
1748 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1749 InVals, isThisReturn,
1750 isThisReturn ? OutVals[0] : SDValue());
1753 /// HandleByVal - Every parameter *after* a byval parameter is passed
1754 /// on the stack. Remember the next parameter register to allocate,
1755 /// and then confiscate the rest of the parameter registers to insure
1758 ARMTargetLowering::HandleByVal(
1759 CCState *State, unsigned &size, unsigned Align) const {
1760 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1761 assert((State->getCallOrPrologue() == Prologue ||
1762 State->getCallOrPrologue() == Call) &&
1763 "unhandled ParmContext");
1765 // For in-prologue parameters handling, we also introduce stack offset
1766 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1767 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1768 // NSAA should be evaluted (NSAA means "next stacked argument address").
1769 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1770 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1771 unsigned NSAAOffset = State->getNextStackOffset();
1772 if (State->getCallOrPrologue() != Call) {
1773 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1775 State->getInRegsParamInfo(i, RB, RE);
1776 assert(NSAAOffset >= (RE-RB)*4 &&
1777 "Stack offset for byval regs doesn't introduced anymore?");
1778 NSAAOffset -= (RE-RB)*4;
1781 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1782 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1783 unsigned AlignInRegs = Align / 4;
1784 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1785 for (unsigned i = 0; i < Waste; ++i)
1786 reg = State->AllocateReg(GPRArgRegs, 4);
1789 unsigned excess = 4 * (ARM::R4 - reg);
1791 // Special case when NSAA != SP and parameter size greater than size of
1792 // all remained GPR regs. In that case we can't split parameter, we must
1793 // send it to stack. We also must set NCRN to R4, so waste all
1794 // remained registers.
1795 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1796 while (State->AllocateReg(GPRArgRegs, 4))
1801 // First register for byval parameter is the first register that wasn't
1802 // allocated before this method call, so it would be "reg".
1803 // If parameter is small enough to be saved in range [reg, r4), then
1804 // the end (first after last) register would be reg + param-size-in-regs,
1805 // else parameter would be splitted between registers and stack,
1806 // end register would be r4 in this case.
1807 unsigned ByValRegBegin = reg;
1808 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1809 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1810 // Note, first register is allocated in the beginning of function already,
1811 // allocate remained amount of registers we need.
1812 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1813 State->AllocateReg(GPRArgRegs, 4);
1814 // At a call site, a byval parameter that is split between
1815 // registers and memory needs its size truncated here. In a
1816 // function prologue, such byval parameters are reassembled in
1817 // memory, and are not truncated.
1818 if (State->getCallOrPrologue() == Call) {
1819 // Make remained size equal to 0 in case, when
1820 // the whole structure may be stored into registers.
1830 /// MatchingStackOffset - Return true if the given stack call argument is
1831 /// already available in the same position (relatively) of the caller's
1832 /// incoming argument stack.
1834 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1835 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1836 const TargetInstrInfo *TII) {
1837 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1839 if (Arg.getOpcode() == ISD::CopyFromReg) {
1840 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1841 if (!TargetRegisterInfo::isVirtualRegister(VR))
1843 MachineInstr *Def = MRI->getVRegDef(VR);
1846 if (!Flags.isByVal()) {
1847 if (!TII->isLoadFromStackSlot(Def, FI))
1852 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1853 if (Flags.isByVal())
1854 // ByVal argument is passed in as a pointer but it's now being
1855 // dereferenced. e.g.
1856 // define @foo(%struct.X* %A) {
1857 // tail call @bar(%struct.X* byval %A)
1860 SDValue Ptr = Ld->getBasePtr();
1861 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1864 FI = FINode->getIndex();
1868 assert(FI != INT_MAX);
1869 if (!MFI->isFixedObjectIndex(FI))
1871 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1874 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1875 /// for tail call optimization. Targets which want to do tail call
1876 /// optimization should implement this function.
1878 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1879 CallingConv::ID CalleeCC,
1881 bool isCalleeStructRet,
1882 bool isCallerStructRet,
1883 const SmallVectorImpl<ISD::OutputArg> &Outs,
1884 const SmallVectorImpl<SDValue> &OutVals,
1885 const SmallVectorImpl<ISD::InputArg> &Ins,
1886 SelectionDAG& DAG) const {
1887 const Function *CallerF = DAG.getMachineFunction().getFunction();
1888 CallingConv::ID CallerCC = CallerF->getCallingConv();
1889 bool CCMatch = CallerCC == CalleeCC;
1891 // Look for obvious safe cases to perform tail call optimization that do not
1892 // require ABI changes. This is what gcc calls sibcall.
1894 // Do not sibcall optimize vararg calls unless the call site is not passing
1896 if (isVarArg && !Outs.empty())
1899 // Also avoid sibcall optimization if either caller or callee uses struct
1900 // return semantics.
1901 if (isCalleeStructRet || isCallerStructRet)
1904 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1905 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1906 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1907 // support in the assembler and linker to be used. This would need to be
1908 // fixed to fully support tail calls in Thumb1.
1910 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1911 // LR. This means if we need to reload LR, it takes an extra instructions,
1912 // which outweighs the value of the tail call; but here we don't know yet
1913 // whether LR is going to be used. Probably the right approach is to
1914 // generate the tail call here and turn it back into CALL/RET in
1915 // emitEpilogue if LR is used.
1917 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1918 // but we need to make sure there are enough registers; the only valid
1919 // registers are the 4 used for parameters. We don't currently do this
1921 if (Subtarget->isThumb1Only())
1924 // If the calling conventions do not match, then we'd better make sure the
1925 // results are returned in the same way as what the caller expects.
1927 SmallVector<CCValAssign, 16> RVLocs1;
1928 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1929 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1930 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1932 SmallVector<CCValAssign, 16> RVLocs2;
1933 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1934 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1935 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1937 if (RVLocs1.size() != RVLocs2.size())
1939 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1940 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1942 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1944 if (RVLocs1[i].isRegLoc()) {
1945 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1948 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1954 // If Caller's vararg or byval argument has been split between registers and
1955 // stack, do not perform tail call, since part of the argument is in caller's
1957 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1958 getInfo<ARMFunctionInfo>();
1959 if (AFI_Caller->getArgRegsSaveSize())
1962 // If the callee takes no arguments then go on to check the results of the
1964 if (!Outs.empty()) {
1965 // Check if stack adjustment is needed. For now, do not do this if any
1966 // argument is passed on the stack.
1967 SmallVector<CCValAssign, 16> ArgLocs;
1968 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1969 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1970 CCInfo.AnalyzeCallOperands(Outs,
1971 CCAssignFnForNode(CalleeCC, false, isVarArg));
1972 if (CCInfo.getNextStackOffset()) {
1973 MachineFunction &MF = DAG.getMachineFunction();
1975 // Check if the arguments are already laid out in the right way as
1976 // the caller's fixed stack objects.
1977 MachineFrameInfo *MFI = MF.getFrameInfo();
1978 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1979 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1980 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1982 ++i, ++realArgIdx) {
1983 CCValAssign &VA = ArgLocs[i];
1984 EVT RegVT = VA.getLocVT();
1985 SDValue Arg = OutVals[realArgIdx];
1986 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1987 if (VA.getLocInfo() == CCValAssign::Indirect)
1989 if (VA.needsCustom()) {
1990 // f64 and vector types are split into multiple registers or
1991 // register/stack-slot combinations. The types will not match
1992 // the registers; give up on memory f64 refs until we figure
1993 // out what to do about this.
1996 if (!ArgLocs[++i].isRegLoc())
1998 if (RegVT == MVT::v2f64) {
1999 if (!ArgLocs[++i].isRegLoc())
2001 if (!ArgLocs[++i].isRegLoc())
2004 } else if (!VA.isRegLoc()) {
2005 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2017 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2018 MachineFunction &MF, bool isVarArg,
2019 const SmallVectorImpl<ISD::OutputArg> &Outs,
2020 LLVMContext &Context) const {
2021 SmallVector<CCValAssign, 16> RVLocs;
2022 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2023 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2028 ARMTargetLowering::LowerReturn(SDValue Chain,
2029 CallingConv::ID CallConv, bool isVarArg,
2030 const SmallVectorImpl<ISD::OutputArg> &Outs,
2031 const SmallVectorImpl<SDValue> &OutVals,
2032 SDLoc dl, SelectionDAG &DAG) const {
2034 // CCValAssign - represent the assignment of the return value to a location.
2035 SmallVector<CCValAssign, 16> RVLocs;
2037 // CCState - Info about the registers and stack slots.
2038 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2039 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2041 // Analyze outgoing return values.
2042 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2046 SmallVector<SDValue, 4> RetOps;
2047 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2049 // Copy the result values into the output registers.
2050 for (unsigned i = 0, realRVLocIdx = 0;
2052 ++i, ++realRVLocIdx) {
2053 CCValAssign &VA = RVLocs[i];
2054 assert(VA.isRegLoc() && "Can only return in registers!");
2056 SDValue Arg = OutVals[realRVLocIdx];
2058 switch (VA.getLocInfo()) {
2059 default: llvm_unreachable("Unknown loc info!");
2060 case CCValAssign::Full: break;
2061 case CCValAssign::BCvt:
2062 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2066 if (VA.needsCustom()) {
2067 if (VA.getLocVT() == MVT::v2f64) {
2068 // Extract the first half and return it in two registers.
2069 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2070 DAG.getConstant(0, MVT::i32));
2071 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2072 DAG.getVTList(MVT::i32, MVT::i32), Half);
2074 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2075 Flag = Chain.getValue(1);
2076 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2077 VA = RVLocs[++i]; // skip ahead to next loc
2078 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2079 HalfGPRs.getValue(1), Flag);
2080 Flag = Chain.getValue(1);
2081 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2082 VA = RVLocs[++i]; // skip ahead to next loc
2084 // Extract the 2nd half and fall through to handle it as an f64 value.
2085 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2086 DAG.getConstant(1, MVT::i32));
2088 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2090 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2091 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2092 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2093 Flag = Chain.getValue(1);
2094 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2095 VA = RVLocs[++i]; // skip ahead to next loc
2096 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2099 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2101 // Guarantee that all emitted copies are
2102 // stuck together, avoiding something bad.
2103 Flag = Chain.getValue(1);
2104 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2107 // Update chain and glue.
2110 RetOps.push_back(Flag);
2112 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2113 RetOps.data(), RetOps.size());
2116 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2117 if (N->getNumValues() != 1)
2119 if (!N->hasNUsesOfValue(1, 0))
2122 SDValue TCChain = Chain;
2123 SDNode *Copy = *N->use_begin();
2124 if (Copy->getOpcode() == ISD::CopyToReg) {
2125 // If the copy has a glue operand, we conservatively assume it isn't safe to
2126 // perform a tail call.
2127 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2129 TCChain = Copy->getOperand(0);
2130 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2131 SDNode *VMov = Copy;
2132 // f64 returned in a pair of GPRs.
2133 SmallPtrSet<SDNode*, 2> Copies;
2134 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2136 if (UI->getOpcode() != ISD::CopyToReg)
2140 if (Copies.size() > 2)
2143 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2145 SDValue UseChain = UI->getOperand(0);
2146 if (Copies.count(UseChain.getNode()))
2153 } else if (Copy->getOpcode() == ISD::BITCAST) {
2154 // f32 returned in a single GPR.
2155 if (!Copy->hasOneUse())
2157 Copy = *Copy->use_begin();
2158 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2160 TCChain = Copy->getOperand(0);
2165 bool HasRet = false;
2166 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2168 if (UI->getOpcode() != ARMISD::RET_FLAG)
2180 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2181 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2184 if (!CI->isTailCall())
2187 return !Subtarget->isThumb1Only();
2190 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2191 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2192 // one of the above mentioned nodes. It has to be wrapped because otherwise
2193 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2194 // be used to form addressing mode. These wrapped nodes will be selected
2196 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2197 EVT PtrVT = Op.getValueType();
2198 // FIXME there is no actual debug info here
2200 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2202 if (CP->isMachineConstantPoolEntry())
2203 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2204 CP->getAlignment());
2206 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2207 CP->getAlignment());
2208 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2211 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2212 return MachineJumpTableInfo::EK_Inline;
2215 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2216 SelectionDAG &DAG) const {
2217 MachineFunction &MF = DAG.getMachineFunction();
2218 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2219 unsigned ARMPCLabelIndex = 0;
2221 EVT PtrVT = getPointerTy();
2222 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2223 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2225 if (RelocM == Reloc::Static) {
2226 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2228 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2229 ARMPCLabelIndex = AFI->createPICLabelUId();
2230 ARMConstantPoolValue *CPV =
2231 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2232 ARMCP::CPBlockAddress, PCAdj);
2233 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2235 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2236 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2237 MachinePointerInfo::getConstantPool(),
2238 false, false, false, 0);
2239 if (RelocM == Reloc::Static)
2241 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2242 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2245 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2247 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2248 SelectionDAG &DAG) const {
2250 EVT PtrVT = getPointerTy();
2251 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2252 MachineFunction &MF = DAG.getMachineFunction();
2253 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2254 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2255 ARMConstantPoolValue *CPV =
2256 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2257 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2258 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2259 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2260 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2261 MachinePointerInfo::getConstantPool(),
2262 false, false, false, 0);
2263 SDValue Chain = Argument.getValue(1);
2265 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2266 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2268 // call __tls_get_addr.
2271 Entry.Node = Argument;
2272 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2273 Args.push_back(Entry);
2274 // FIXME: is there useful debug info available here?
2275 TargetLowering::CallLoweringInfo CLI(Chain,
2276 (Type *) Type::getInt32Ty(*DAG.getContext()),
2277 false, false, false, false,
2278 0, CallingConv::C, /*isTailCall=*/false,
2279 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2280 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2281 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2282 return CallResult.first;
2285 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2286 // "local exec" model.
2288 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2290 TLSModel::Model model) const {
2291 const GlobalValue *GV = GA->getGlobal();
2294 SDValue Chain = DAG.getEntryNode();
2295 EVT PtrVT = getPointerTy();
2296 // Get the Thread Pointer
2297 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2299 if (model == TLSModel::InitialExec) {
2300 MachineFunction &MF = DAG.getMachineFunction();
2301 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2302 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2303 // Initial exec model.
2304 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2305 ARMConstantPoolValue *CPV =
2306 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2307 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2309 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2310 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2311 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2312 MachinePointerInfo::getConstantPool(),
2313 false, false, false, 0);
2314 Chain = Offset.getValue(1);
2316 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2317 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2319 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2320 MachinePointerInfo::getConstantPool(),
2321 false, false, false, 0);
2324 assert(model == TLSModel::LocalExec);
2325 ARMConstantPoolValue *CPV =
2326 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2327 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2328 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2329 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2330 MachinePointerInfo::getConstantPool(),
2331 false, false, false, 0);
2334 // The address of the thread local variable is the add of the thread
2335 // pointer with the offset of the variable.
2336 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2340 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2341 // TODO: implement the "local dynamic" model
2342 assert(Subtarget->isTargetELF() &&
2343 "TLS not implemented for non-ELF targets");
2344 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2346 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2349 case TLSModel::GeneralDynamic:
2350 case TLSModel::LocalDynamic:
2351 return LowerToTLSGeneralDynamicModel(GA, DAG);
2352 case TLSModel::InitialExec:
2353 case TLSModel::LocalExec:
2354 return LowerToTLSExecModels(GA, DAG, model);
2356 llvm_unreachable("bogus TLS model");
2359 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2360 SelectionDAG &DAG) const {
2361 EVT PtrVT = getPointerTy();
2363 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2364 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2365 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2366 ARMConstantPoolValue *CPV =
2367 ARMConstantPoolConstant::Create(GV,
2368 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2369 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2370 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2371 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2373 MachinePointerInfo::getConstantPool(),
2374 false, false, false, 0);
2375 SDValue Chain = Result.getValue(1);
2376 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2377 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2379 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2380 MachinePointerInfo::getGOT(),
2381 false, false, false, 0);
2385 // If we have T2 ops, we can materialize the address directly via movt/movw
2386 // pair. This is always cheaper.
2387 if (Subtarget->useMovt()) {
2389 // FIXME: Once remat is capable of dealing with instructions with register
2390 // operands, expand this into two nodes.
2391 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2392 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2394 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2395 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2396 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2397 MachinePointerInfo::getConstantPool(),
2398 false, false, false, 0);
2402 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2403 SelectionDAG &DAG) const {
2404 EVT PtrVT = getPointerTy();
2406 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2407 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2409 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2410 // update ARMFastISel::ARMMaterializeGV.
2411 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2413 // FIXME: Once remat is capable of dealing with instructions with register
2414 // operands, expand this into two nodes.
2415 if (RelocM == Reloc::Static)
2416 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2417 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2419 unsigned Wrapper = (RelocM == Reloc::PIC_)
2420 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2421 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2422 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2423 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2424 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2425 MachinePointerInfo::getGOT(),
2426 false, false, false, 0);
2430 unsigned ARMPCLabelIndex = 0;
2432 if (RelocM == Reloc::Static) {
2433 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2435 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2436 ARMPCLabelIndex = AFI->createPICLabelUId();
2437 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2438 ARMConstantPoolValue *CPV =
2439 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2441 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2443 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2445 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2446 MachinePointerInfo::getConstantPool(),
2447 false, false, false, 0);
2448 SDValue Chain = Result.getValue(1);
2450 if (RelocM == Reloc::PIC_) {
2451 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2452 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2455 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2456 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2457 false, false, false, 0);
2462 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2463 SelectionDAG &DAG) const {
2464 assert(Subtarget->isTargetELF() &&
2465 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2466 MachineFunction &MF = DAG.getMachineFunction();
2467 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2468 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2469 EVT PtrVT = getPointerTy();
2471 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2472 ARMConstantPoolValue *CPV =
2473 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2474 ARMPCLabelIndex, PCAdj);
2475 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2476 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2477 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2478 MachinePointerInfo::getConstantPool(),
2479 false, false, false, 0);
2480 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2481 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2485 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2487 SDValue Val = DAG.getConstant(0, MVT::i32);
2488 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2489 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2490 Op.getOperand(1), Val);
2494 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2496 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2497 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2501 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2502 const ARMSubtarget *Subtarget) const {
2503 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2506 default: return SDValue(); // Don't custom lower most intrinsics.
2507 case Intrinsic::arm_thread_pointer: {
2508 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2509 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2511 case Intrinsic::eh_sjlj_lsda: {
2512 MachineFunction &MF = DAG.getMachineFunction();
2513 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2514 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2515 EVT PtrVT = getPointerTy();
2516 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2518 unsigned PCAdj = (RelocM != Reloc::PIC_)
2519 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2520 ARMConstantPoolValue *CPV =
2521 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2522 ARMCP::CPLSDA, PCAdj);
2523 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2524 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2526 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2527 MachinePointerInfo::getConstantPool(),
2528 false, false, false, 0);
2530 if (RelocM == Reloc::PIC_) {
2531 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2532 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2536 case Intrinsic::arm_neon_vmulls:
2537 case Intrinsic::arm_neon_vmullu: {
2538 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2539 ? ARMISD::VMULLs : ARMISD::VMULLu;
2540 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2541 Op.getOperand(1), Op.getOperand(2));
2546 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2547 const ARMSubtarget *Subtarget) {
2548 // FIXME: handle "fence singlethread" more efficiently.
2550 if (!Subtarget->hasDataBarrier()) {
2551 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2552 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2554 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2555 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2556 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2557 DAG.getConstant(0, MVT::i32));
2560 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2561 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2562 unsigned Domain = ARM_MB::ISH;
2563 if (Subtarget->isSwift() && Ord == Release) {
2564 // Swift happens to implement ISHST barriers in a way that's compatible with
2565 // Release semantics but weaker than ISH so we'd be fools not to use
2566 // it. Beware: other processors probably don't!
2567 Domain = ARM_MB::ISHST;
2570 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2571 DAG.getConstant(Domain, MVT::i32));
2574 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2575 const ARMSubtarget *Subtarget) {
2576 // ARM pre v5TE and Thumb1 does not have preload instructions.
2577 if (!(Subtarget->isThumb2() ||
2578 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2579 // Just preserve the chain.
2580 return Op.getOperand(0);
2583 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2585 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2586 // ARMv7 with MP extension has PLDW.
2587 return Op.getOperand(0);
2589 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2590 if (Subtarget->isThumb()) {
2592 isRead = ~isRead & 1;
2593 isData = ~isData & 1;
2596 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2597 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2598 DAG.getConstant(isData, MVT::i32));
2601 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2602 MachineFunction &MF = DAG.getMachineFunction();
2603 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2605 // vastart just stores the address of the VarArgsFrameIndex slot into the
2606 // memory location argument.
2608 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2609 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2610 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2611 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2612 MachinePointerInfo(SV), false, false, 0);
2616 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2617 SDValue &Root, SelectionDAG &DAG,
2619 MachineFunction &MF = DAG.getMachineFunction();
2620 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2622 const TargetRegisterClass *RC;
2623 if (AFI->isThumb1OnlyFunction())
2624 RC = &ARM::tGPRRegClass;
2626 RC = &ARM::GPRRegClass;
2628 // Transform the arguments stored in physical registers into virtual ones.
2629 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2630 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2633 if (NextVA.isMemLoc()) {
2634 MachineFrameInfo *MFI = MF.getFrameInfo();
2635 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2637 // Create load node to retrieve arguments from the stack.
2638 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2639 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2640 MachinePointerInfo::getFixedStack(FI),
2641 false, false, false, 0);
2643 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2644 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2647 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2651 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2652 unsigned InRegsParamRecordIdx,
2654 unsigned &ArgRegsSize,
2655 unsigned &ArgRegsSaveSize)
2658 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2659 unsigned RBegin, REnd;
2660 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2661 NumGPRs = REnd - RBegin;
2663 unsigned int firstUnalloced;
2664 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2665 sizeof(GPRArgRegs) /
2666 sizeof(GPRArgRegs[0]));
2667 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2670 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2671 ArgRegsSize = NumGPRs * 4;
2673 // If parameter is split between stack and GPRs...
2674 if (NumGPRs && Align == 8 &&
2675 (ArgRegsSize < ArgSize ||
2676 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2677 // Add padding for part of param recovered from GPRs, so
2678 // its last byte must be at address K*8 - 1.
2679 // We need to do it, since remained (stack) part of parameter has
2680 // stack alignment, and we need to "attach" "GPRs head" without gaps
2683 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2684 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2686 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2688 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2689 (ArgRegsSize + AFI->getArgRegsSaveSize());
2690 ArgRegsSaveSize = ArgRegsSize + Padding;
2692 // We don't need to extend regs save size for byval parameters if they
2693 // are passed via GPRs only.
2694 ArgRegsSaveSize = ArgRegsSize;
2697 // The remaining GPRs hold either the beginning of variable-argument
2698 // data, or the beginning of an aggregate passed by value (usually
2699 // byval). Either way, we allocate stack slots adjacent to the data
2700 // provided by our caller, and store the unallocated registers there.
2701 // If this is a variadic function, the va_list pointer will begin with
2702 // these values; otherwise, this reassembles a (byval) structure that
2703 // was split between registers and memory.
2704 // Return: The frame index registers were stored into.
2706 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2707 SDLoc dl, SDValue &Chain,
2708 const Value *OrigArg,
2709 unsigned InRegsParamRecordIdx,
2710 unsigned OffsetFromOrigArg,
2713 bool ForceMutable) const {
2715 // Currently, two use-cases possible:
2716 // Case #1. Non var-args function, and we meet first byval parameter.
2717 // Setup first unallocated register as first byval register;
2718 // eat all remained registers
2719 // (these two actions are performed by HandleByVal method).
2720 // Then, here, we initialize stack frame with
2721 // "store-reg" instructions.
2722 // Case #2. Var-args function, that doesn't contain byval parameters.
2723 // The same: eat all remained unallocated registers,
2724 // initialize stack frame.
2726 MachineFunction &MF = DAG.getMachineFunction();
2727 MachineFrameInfo *MFI = MF.getFrameInfo();
2728 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2729 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2730 unsigned RBegin, REnd;
2731 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2732 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2733 firstRegToSaveIndex = RBegin - ARM::R0;
2734 lastRegToSaveIndex = REnd - ARM::R0;
2736 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2737 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2738 lastRegToSaveIndex = 4;
2741 unsigned ArgRegsSize, ArgRegsSaveSize;
2742 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2743 ArgRegsSize, ArgRegsSaveSize);
2745 // Store any by-val regs to their spots on the stack so that they may be
2746 // loaded by deferencing the result of formal parameter pointer or va_next.
2747 // Note: once stack area for byval/varargs registers
2748 // was initialized, it can't be initialized again.
2749 if (ArgRegsSaveSize) {
2751 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2754 assert(AFI->getStoredByValParamsPadding() == 0 &&
2755 "The only parameter may be padded.");
2756 AFI->setStoredByValParamsPadding(Padding);
2759 int FrameIndex = MFI->CreateFixedObject(
2761 Padding + ArgOffset,
2763 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2765 SmallVector<SDValue, 4> MemOps;
2766 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2767 ++firstRegToSaveIndex, ++i) {
2768 const TargetRegisterClass *RC;
2769 if (AFI->isThumb1OnlyFunction())
2770 RC = &ARM::tGPRRegClass;
2772 RC = &ARM::GPRRegClass;
2774 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2775 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2777 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2778 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2780 MemOps.push_back(Store);
2781 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2782 DAG.getConstant(4, getPointerTy()));
2785 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2787 if (!MemOps.empty())
2788 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2789 &MemOps[0], MemOps.size());
2792 // This will point to the next argument passed via stack.
2793 return MFI->CreateFixedObject(
2794 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2797 // Setup stack frame, the va_list pointer will start from.
2799 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2800 SDLoc dl, SDValue &Chain,
2802 bool ForceMutable) const {
2803 MachineFunction &MF = DAG.getMachineFunction();
2804 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2806 // Try to store any remaining integer argument regs
2807 // to their spots on the stack so that they may be loaded by deferencing
2808 // the result of va_next.
2809 // If there is no regs to be stored, just point address after last
2810 // argument passed via stack.
2812 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2813 0, ArgOffset, 0, ForceMutable);
2815 AFI->setVarArgsFrameIndex(FrameIndex);
2819 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2820 CallingConv::ID CallConv, bool isVarArg,
2821 const SmallVectorImpl<ISD::InputArg>
2823 SDLoc dl, SelectionDAG &DAG,
2824 SmallVectorImpl<SDValue> &InVals)
2826 MachineFunction &MF = DAG.getMachineFunction();
2827 MachineFrameInfo *MFI = MF.getFrameInfo();
2829 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2831 // Assign locations to all of the incoming arguments.
2832 SmallVector<CCValAssign, 16> ArgLocs;
2833 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2834 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2835 CCInfo.AnalyzeFormalArguments(Ins,
2836 CCAssignFnForNode(CallConv, /* Return*/ false,
2839 SmallVector<SDValue, 16> ArgValues;
2840 int lastInsIndex = -1;
2842 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2843 unsigned CurArgIdx = 0;
2845 // Initially ArgRegsSaveSize is zero.
2846 // Then we increase this value each time we meet byval parameter.
2847 // We also increase this value in case of varargs function.
2848 AFI->setArgRegsSaveSize(0);
2850 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2851 CCValAssign &VA = ArgLocs[i];
2852 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2853 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2854 // Arguments stored in registers.
2855 if (VA.isRegLoc()) {
2856 EVT RegVT = VA.getLocVT();
2858 if (VA.needsCustom()) {
2859 // f64 and vector types are split up into multiple registers or
2860 // combinations of registers and stack slots.
2861 if (VA.getLocVT() == MVT::v2f64) {
2862 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2864 VA = ArgLocs[++i]; // skip ahead to next loc
2866 if (VA.isMemLoc()) {
2867 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2868 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2869 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2870 MachinePointerInfo::getFixedStack(FI),
2871 false, false, false, 0);
2873 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2876 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2877 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2878 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2879 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2880 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2882 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2885 const TargetRegisterClass *RC;
2887 if (RegVT == MVT::f32)
2888 RC = &ARM::SPRRegClass;
2889 else if (RegVT == MVT::f64)
2890 RC = &ARM::DPRRegClass;
2891 else if (RegVT == MVT::v2f64)
2892 RC = &ARM::QPRRegClass;
2893 else if (RegVT == MVT::i32)
2894 RC = AFI->isThumb1OnlyFunction() ?
2895 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2896 (const TargetRegisterClass*)&ARM::GPRRegClass;
2898 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2900 // Transform the arguments in physical registers into virtual ones.
2901 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2902 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2905 // If this is an 8 or 16-bit value, it is really passed promoted
2906 // to 32 bits. Insert an assert[sz]ext to capture this, then
2907 // truncate to the right size.
2908 switch (VA.getLocInfo()) {
2909 default: llvm_unreachable("Unknown loc info!");
2910 case CCValAssign::Full: break;
2911 case CCValAssign::BCvt:
2912 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2914 case CCValAssign::SExt:
2915 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2916 DAG.getValueType(VA.getValVT()));
2917 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2919 case CCValAssign::ZExt:
2920 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2921 DAG.getValueType(VA.getValVT()));
2922 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2926 InVals.push_back(ArgValue);
2928 } else { // VA.isRegLoc()
2931 assert(VA.isMemLoc());
2932 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2934 int index = ArgLocs[i].getValNo();
2936 // Some Ins[] entries become multiple ArgLoc[] entries.
2937 // Process them only once.
2938 if (index != lastInsIndex)
2940 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2941 // FIXME: For now, all byval parameter objects are marked mutable.
2942 // This can be changed with more analysis.
2943 // In case of tail call optimization mark all arguments mutable.
2944 // Since they could be overwritten by lowering of arguments in case of
2946 if (Flags.isByVal()) {
2947 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2948 int FrameIndex = StoreByValRegs(
2949 CCInfo, DAG, dl, Chain, CurOrigArg,
2951 Ins[VA.getValNo()].PartOffset,
2952 VA.getLocMemOffset(),
2953 Flags.getByValSize(),
2954 true /*force mutable frames*/);
2955 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2956 CCInfo.nextInRegsParam();
2958 unsigned FIOffset = VA.getLocMemOffset() +
2959 AFI->getStoredByValParamsPadding();
2960 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2963 // Create load nodes to retrieve arguments from the stack.
2964 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2965 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2966 MachinePointerInfo::getFixedStack(FI),
2967 false, false, false, 0));
2969 lastInsIndex = index;
2976 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2977 CCInfo.getNextStackOffset());
2982 /// isFloatingPointZero - Return true if this is +0.0.
2983 static bool isFloatingPointZero(SDValue Op) {
2984 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2985 return CFP->getValueAPF().isPosZero();
2986 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2987 // Maybe this has already been legalized into the constant pool?
2988 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2989 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2990 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2991 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2992 return CFP->getValueAPF().isPosZero();
2998 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2999 /// the given operands.
3001 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3002 SDValue &ARMcc, SelectionDAG &DAG,
3004 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3005 unsigned C = RHSC->getZExtValue();
3006 if (!isLegalICmpImmediate(C)) {
3007 // Constant does not fit, try adjusting it by one?
3012 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3013 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3014 RHS = DAG.getConstant(C-1, MVT::i32);
3019 if (C != 0 && isLegalICmpImmediate(C-1)) {
3020 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3021 RHS = DAG.getConstant(C-1, MVT::i32);
3026 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3027 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3028 RHS = DAG.getConstant(C+1, MVT::i32);
3033 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3034 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3035 RHS = DAG.getConstant(C+1, MVT::i32);
3042 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3043 ARMISD::NodeType CompareType;
3046 CompareType = ARMISD::CMP;
3051 CompareType = ARMISD::CMPZ;
3054 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3055 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3058 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3060 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3063 if (!isFloatingPointZero(RHS))
3064 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3066 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3067 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3070 /// duplicateCmp - Glue values can have only one use, so this function
3071 /// duplicates a comparison node.
3073 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3074 unsigned Opc = Cmp.getOpcode();
3076 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3077 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3079 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3080 Cmp = Cmp.getOperand(0);
3081 Opc = Cmp.getOpcode();
3082 if (Opc == ARMISD::CMPFP)
3083 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3085 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3086 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3088 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3091 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3092 SDValue Cond = Op.getOperand(0);
3093 SDValue SelectTrue = Op.getOperand(1);
3094 SDValue SelectFalse = Op.getOperand(2);
3099 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3100 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3102 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3103 const ConstantSDNode *CMOVTrue =
3104 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3105 const ConstantSDNode *CMOVFalse =
3106 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3108 if (CMOVTrue && CMOVFalse) {
3109 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3110 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3114 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3116 False = SelectFalse;
3117 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3122 if (True.getNode() && False.getNode()) {
3123 EVT VT = Op.getValueType();
3124 SDValue ARMcc = Cond.getOperand(2);
3125 SDValue CCR = Cond.getOperand(3);
3126 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3127 assert(True.getValueType() == VT);
3128 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3133 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3134 // undefined bits before doing a full-word comparison with zero.
3135 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3136 DAG.getConstant(1, Cond.getValueType()));
3138 return DAG.getSelectCC(dl, Cond,
3139 DAG.getConstant(0, Cond.getValueType()),
3140 SelectTrue, SelectFalse, ISD::SETNE);
3143 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3144 EVT VT = Op.getValueType();
3145 SDValue LHS = Op.getOperand(0);
3146 SDValue RHS = Op.getOperand(1);
3147 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3148 SDValue TrueVal = Op.getOperand(2);
3149 SDValue FalseVal = Op.getOperand(3);
3152 if (LHS.getValueType() == MVT::i32) {
3154 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3155 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3156 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3159 ARMCC::CondCodes CondCode, CondCode2;
3160 FPCCToARMCC(CC, CondCode, CondCode2);
3162 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3163 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3164 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3165 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3167 if (CondCode2 != ARMCC::AL) {
3168 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3169 // FIXME: Needs another CMP because flag can have but one use.
3170 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3171 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3172 Result, TrueVal, ARMcc2, CCR, Cmp2);
3177 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3178 /// to morph to an integer compare sequence.
3179 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3180 const ARMSubtarget *Subtarget) {
3181 SDNode *N = Op.getNode();
3182 if (!N->hasOneUse())
3183 // Otherwise it requires moving the value from fp to integer registers.
3185 if (!N->getNumValues())
3187 EVT VT = Op.getValueType();
3188 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3189 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3190 // vmrs are very slow, e.g. cortex-a8.
3193 if (isFloatingPointZero(Op)) {
3197 return ISD::isNormalLoad(N);
3200 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3201 if (isFloatingPointZero(Op))
3202 return DAG.getConstant(0, MVT::i32);
3204 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3205 return DAG.getLoad(MVT::i32, SDLoc(Op),
3206 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3207 Ld->isVolatile(), Ld->isNonTemporal(),
3208 Ld->isInvariant(), Ld->getAlignment());
3210 llvm_unreachable("Unknown VFP cmp argument!");
3213 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3214 SDValue &RetVal1, SDValue &RetVal2) {
3215 if (isFloatingPointZero(Op)) {
3216 RetVal1 = DAG.getConstant(0, MVT::i32);
3217 RetVal2 = DAG.getConstant(0, MVT::i32);
3221 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3222 SDValue Ptr = Ld->getBasePtr();
3223 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3224 Ld->getChain(), Ptr,
3225 Ld->getPointerInfo(),
3226 Ld->isVolatile(), Ld->isNonTemporal(),
3227 Ld->isInvariant(), Ld->getAlignment());
3229 EVT PtrType = Ptr.getValueType();
3230 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3231 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3232 PtrType, Ptr, DAG.getConstant(4, PtrType));
3233 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3234 Ld->getChain(), NewPtr,
3235 Ld->getPointerInfo().getWithOffset(4),
3236 Ld->isVolatile(), Ld->isNonTemporal(),
3237 Ld->isInvariant(), NewAlign);
3241 llvm_unreachable("Unknown VFP cmp argument!");
3244 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3245 /// f32 and even f64 comparisons to integer ones.
3247 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3248 SDValue Chain = Op.getOperand(0);
3249 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3250 SDValue LHS = Op.getOperand(2);
3251 SDValue RHS = Op.getOperand(3);
3252 SDValue Dest = Op.getOperand(4);
3255 bool LHSSeenZero = false;
3256 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3257 bool RHSSeenZero = false;
3258 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3259 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3260 // If unsafe fp math optimization is enabled and there are no other uses of
3261 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3262 // to an integer comparison.
3263 if (CC == ISD::SETOEQ)
3265 else if (CC == ISD::SETUNE)
3268 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3270 if (LHS.getValueType() == MVT::f32) {
3271 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3272 bitcastf32Toi32(LHS, DAG), Mask);
3273 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3274 bitcastf32Toi32(RHS, DAG), Mask);
3275 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3276 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3277 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3278 Chain, Dest, ARMcc, CCR, Cmp);
3283 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3284 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3285 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3286 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3287 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3288 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3289 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3290 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3291 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3297 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3298 SDValue Chain = Op.getOperand(0);
3299 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3300 SDValue LHS = Op.getOperand(2);
3301 SDValue RHS = Op.getOperand(3);
3302 SDValue Dest = Op.getOperand(4);
3305 if (LHS.getValueType() == MVT::i32) {
3307 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3308 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3309 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3310 Chain, Dest, ARMcc, CCR, Cmp);
3313 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3315 if (getTargetMachine().Options.UnsafeFPMath &&
3316 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3317 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3318 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3319 if (Result.getNode())
3323 ARMCC::CondCodes CondCode, CondCode2;
3324 FPCCToARMCC(CC, CondCode, CondCode2);
3326 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3327 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3328 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3329 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3330 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3331 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3332 if (CondCode2 != ARMCC::AL) {
3333 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3334 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3335 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3340 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3341 SDValue Chain = Op.getOperand(0);
3342 SDValue Table = Op.getOperand(1);
3343 SDValue Index = Op.getOperand(2);
3346 EVT PTy = getPointerTy();
3347 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3348 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3349 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3350 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3351 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3352 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3353 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3354 if (Subtarget->isThumb2()) {
3355 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3356 // which does another jump to the destination. This also makes it easier
3357 // to translate it to TBB / TBH later.
3358 // FIXME: This might not work if the function is extremely large.
3359 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3360 Addr, Op.getOperand(2), JTI, UId);
3362 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3363 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3364 MachinePointerInfo::getJumpTable(),
3365 false, false, false, 0);
3366 Chain = Addr.getValue(1);
3367 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3368 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3370 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3371 MachinePointerInfo::getJumpTable(),
3372 false, false, false, 0);
3373 Chain = Addr.getValue(1);
3374 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3378 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3379 EVT VT = Op.getValueType();
3382 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3383 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3385 return DAG.UnrollVectorOp(Op.getNode());
3388 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3389 "Invalid type for custom lowering!");
3390 if (VT != MVT::v4i16)
3391 return DAG.UnrollVectorOp(Op.getNode());
3393 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3394 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3397 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3398 EVT VT = Op.getValueType();
3400 return LowerVectorFP_TO_INT(Op, DAG);
3405 switch (Op.getOpcode()) {
3406 default: llvm_unreachable("Invalid opcode!");
3407 case ISD::FP_TO_SINT:
3408 Opc = ARMISD::FTOSI;
3410 case ISD::FP_TO_UINT:
3411 Opc = ARMISD::FTOUI;
3414 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3415 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3418 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3419 EVT VT = Op.getValueType();
3422 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3423 if (VT.getVectorElementType() == MVT::f32)
3425 return DAG.UnrollVectorOp(Op.getNode());
3428 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3429 "Invalid type for custom lowering!");
3430 if (VT != MVT::v4f32)
3431 return DAG.UnrollVectorOp(Op.getNode());
3435 switch (Op.getOpcode()) {
3436 default: llvm_unreachable("Invalid opcode!");
3437 case ISD::SINT_TO_FP:
3438 CastOpc = ISD::SIGN_EXTEND;
3439 Opc = ISD::SINT_TO_FP;
3441 case ISD::UINT_TO_FP:
3442 CastOpc = ISD::ZERO_EXTEND;
3443 Opc = ISD::UINT_TO_FP;
3447 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3448 return DAG.getNode(Opc, dl, VT, Op);
3451 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3452 EVT VT = Op.getValueType();
3454 return LowerVectorINT_TO_FP(Op, DAG);
3459 switch (Op.getOpcode()) {
3460 default: llvm_unreachable("Invalid opcode!");
3461 case ISD::SINT_TO_FP:
3462 Opc = ARMISD::SITOF;
3464 case ISD::UINT_TO_FP:
3465 Opc = ARMISD::UITOF;
3469 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3470 return DAG.getNode(Opc, dl, VT, Op);
3473 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3474 // Implement fcopysign with a fabs and a conditional fneg.
3475 SDValue Tmp0 = Op.getOperand(0);
3476 SDValue Tmp1 = Op.getOperand(1);
3478 EVT VT = Op.getValueType();
3479 EVT SrcVT = Tmp1.getValueType();
3480 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3481 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3482 bool UseNEON = !InGPR && Subtarget->hasNEON();
3485 // Use VBSL to copy the sign bit.
3486 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3487 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3488 DAG.getTargetConstant(EncodedVal, MVT::i32));
3489 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3491 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3492 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3493 DAG.getConstant(32, MVT::i32));
3494 else /*if (VT == MVT::f32)*/
3495 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3496 if (SrcVT == MVT::f32) {
3497 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3499 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3500 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3501 DAG.getConstant(32, MVT::i32));
3502 } else if (VT == MVT::f32)
3503 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3504 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3505 DAG.getConstant(32, MVT::i32));
3506 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3507 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3509 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3511 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3512 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3513 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3515 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3516 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3517 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3518 if (VT == MVT::f32) {
3519 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3520 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3521 DAG.getConstant(0, MVT::i32));
3523 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3529 // Bitcast operand 1 to i32.
3530 if (SrcVT == MVT::f64)
3531 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3532 &Tmp1, 1).getValue(1);
3533 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3535 // Or in the signbit with integer operations.
3536 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3537 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3538 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3539 if (VT == MVT::f32) {
3540 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3541 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3542 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3543 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3546 // f64: Or the high part with signbit and then combine two parts.
3547 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3549 SDValue Lo = Tmp0.getValue(0);
3550 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3551 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3552 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3555 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3556 MachineFunction &MF = DAG.getMachineFunction();
3557 MachineFrameInfo *MFI = MF.getFrameInfo();
3558 MFI->setReturnAddressIsTaken(true);
3560 EVT VT = Op.getValueType();
3562 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3564 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3565 SDValue Offset = DAG.getConstant(4, MVT::i32);
3566 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3567 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3568 MachinePointerInfo(), false, false, false, 0);
3571 // Return LR, which contains the return address. Mark it an implicit live-in.
3572 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3573 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3576 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3577 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3578 MFI->setFrameAddressIsTaken(true);
3580 EVT VT = Op.getValueType();
3581 SDLoc dl(Op); // FIXME probably not meaningful
3582 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3583 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3584 ? ARM::R7 : ARM::R11;
3585 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3587 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3588 MachinePointerInfo(),
3589 false, false, false, 0);
3593 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3594 /// and size(DestVec) > 128-bits.
3595 /// This is achieved by doing the one extension from the SrcVec, splitting the
3596 /// result, extending these parts, and then concatenating these into the
3598 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3599 SDValue Op = N->getOperand(0);
3600 EVT SrcVT = Op.getValueType();
3601 EVT DestVT = N->getValueType(0);
3603 assert(DestVT.getSizeInBits() > 128 &&
3604 "Custom sext/zext expansion needs >128-bit vector.");
3605 // If this is a normal length extension, use the default expansion.
3606 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3607 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3611 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3612 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3613 unsigned NumElts = SrcVT.getVectorNumElements();
3614 LLVMContext &Ctx = *DAG.getContext();
3615 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3617 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3619 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3621 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3624 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3625 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3626 DAG.getIntPtrConstant(0));
3627 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3628 DAG.getIntPtrConstant(NumElts/2));
3629 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3630 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3631 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3634 /// ExpandBITCAST - If the target supports VFP, this function is called to
3635 /// expand a bit convert where either the source or destination type is i64 to
3636 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3637 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3638 /// vectors), since the legalizer won't know what to do with that.
3639 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3640 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3642 SDValue Op = N->getOperand(0);
3644 // This function is only supposed to be called for i64 types, either as the
3645 // source or destination of the bit convert.
3646 EVT SrcVT = Op.getValueType();
3647 EVT DstVT = N->getValueType(0);
3648 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3649 "ExpandBITCAST called for non-i64 type");
3651 // Turn i64->f64 into VMOVDRR.
3652 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3653 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3654 DAG.getConstant(0, MVT::i32));
3655 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3656 DAG.getConstant(1, MVT::i32));
3657 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3658 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3661 // Turn f64->i64 into VMOVRRD.
3662 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3663 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3664 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3665 // Merge the pieces into a single i64 value.
3666 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3672 /// getZeroVector - Returns a vector of specified type with all zero elements.
3673 /// Zero vectors are used to represent vector negation and in those cases
3674 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3675 /// not support i64 elements, so sometimes the zero vectors will need to be
3676 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3678 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3679 assert(VT.isVector() && "Expected a vector type");
3680 // The canonical modified immediate encoding of a zero vector is....0!
3681 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3682 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3683 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3684 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3687 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3688 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3689 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3690 SelectionDAG &DAG) const {
3691 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3692 EVT VT = Op.getValueType();
3693 unsigned VTBits = VT.getSizeInBits();
3695 SDValue ShOpLo = Op.getOperand(0);
3696 SDValue ShOpHi = Op.getOperand(1);
3697 SDValue ShAmt = Op.getOperand(2);
3699 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3701 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3703 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3704 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3705 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3706 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3707 DAG.getConstant(VTBits, MVT::i32));
3708 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3709 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3710 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3712 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3713 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3715 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3716 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3719 SDValue Ops[2] = { Lo, Hi };
3720 return DAG.getMergeValues(Ops, 2, dl);
3723 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3724 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3725 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3726 SelectionDAG &DAG) const {
3727 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3728 EVT VT = Op.getValueType();
3729 unsigned VTBits = VT.getSizeInBits();
3731 SDValue ShOpLo = Op.getOperand(0);
3732 SDValue ShOpHi = Op.getOperand(1);
3733 SDValue ShAmt = Op.getOperand(2);
3736 assert(Op.getOpcode() == ISD::SHL_PARTS);
3737 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3738 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3739 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3740 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3741 DAG.getConstant(VTBits, MVT::i32));
3742 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3743 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3745 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3746 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3747 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3749 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3750 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3753 SDValue Ops[2] = { Lo, Hi };
3754 return DAG.getMergeValues(Ops, 2, dl);
3757 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3758 SelectionDAG &DAG) const {
3759 // The rounding mode is in bits 23:22 of the FPSCR.
3760 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3761 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3762 // so that the shift + and get folded into a bitfield extract.
3764 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3765 DAG.getConstant(Intrinsic::arm_get_fpscr,
3767 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3768 DAG.getConstant(1U << 22, MVT::i32));
3769 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3770 DAG.getConstant(22, MVT::i32));
3771 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3772 DAG.getConstant(3, MVT::i32));
3775 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3776 const ARMSubtarget *ST) {
3777 EVT VT = N->getValueType(0);
3780 if (!ST->hasV6T2Ops())
3783 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3784 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3787 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3788 /// for each 16-bit element from operand, repeated. The basic idea is to
3789 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3791 /// Trace for v4i16:
3792 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3793 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3794 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3795 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3796 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3797 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3798 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3799 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3800 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3801 EVT VT = N->getValueType(0);
3804 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3805 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3806 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3807 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3808 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3809 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3812 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3813 /// bit-count for each 16-bit element from the operand. We need slightly
3814 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3815 /// 64/128-bit registers.
3817 /// Trace for v4i16:
3818 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3819 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3820 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3821 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3822 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3823 EVT VT = N->getValueType(0);
3826 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3827 if (VT.is64BitVector()) {
3828 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3829 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3830 DAG.getIntPtrConstant(0));
3832 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3833 BitCounts, DAG.getIntPtrConstant(0));
3834 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3838 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3839 /// bit-count for each 32-bit element from the operand. The idea here is
3840 /// to split the vector into 16-bit elements, leverage the 16-bit count
3841 /// routine, and then combine the results.
3843 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3844 /// input = [v0 v1 ] (vi: 32-bit elements)
3845 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3846 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3847 /// vrev: N0 = [k1 k0 k3 k2 ]
3849 /// N1 =+[k1 k0 k3 k2 ]
3851 /// N2 =+[k1 k3 k0 k2 ]
3853 /// Extended =+[k1 k3 k0 k2 ]
3855 /// Extracted=+[k1 k3 ]
3857 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3858 EVT VT = N->getValueType(0);
3861 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3863 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3864 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3865 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3866 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3867 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3869 if (VT.is64BitVector()) {
3870 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3871 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3872 DAG.getIntPtrConstant(0));
3874 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3875 DAG.getIntPtrConstant(0));
3876 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3880 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3881 const ARMSubtarget *ST) {
3882 EVT VT = N->getValueType(0);
3884 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3885 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3886 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3887 "Unexpected type for custom ctpop lowering");
3889 if (VT.getVectorElementType() == MVT::i32)
3890 return lowerCTPOP32BitElements(N, DAG);
3892 return lowerCTPOP16BitElements(N, DAG);
3895 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3896 const ARMSubtarget *ST) {
3897 EVT VT = N->getValueType(0);
3903 // Lower vector shifts on NEON to use VSHL.
3904 assert(ST->hasNEON() && "unexpected vector shift");
3906 // Left shifts translate directly to the vshiftu intrinsic.
3907 if (N->getOpcode() == ISD::SHL)
3908 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3909 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3910 N->getOperand(0), N->getOperand(1));
3912 assert((N->getOpcode() == ISD::SRA ||
3913 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3915 // NEON uses the same intrinsics for both left and right shifts. For
3916 // right shifts, the shift amounts are negative, so negate the vector of
3918 EVT ShiftVT = N->getOperand(1).getValueType();
3919 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3920 getZeroVector(ShiftVT, DAG, dl),
3922 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3923 Intrinsic::arm_neon_vshifts :
3924 Intrinsic::arm_neon_vshiftu);
3925 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3926 DAG.getConstant(vshiftInt, MVT::i32),
3927 N->getOperand(0), NegatedCount);
3930 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3931 const ARMSubtarget *ST) {
3932 EVT VT = N->getValueType(0);
3935 // We can get here for a node like i32 = ISD::SHL i32, i64
3939 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3940 "Unknown shift to lower!");
3942 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3943 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3944 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3947 // If we are in thumb mode, we don't have RRX.
3948 if (ST->isThumb1Only()) return SDValue();
3950 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3951 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3952 DAG.getConstant(0, MVT::i32));
3953 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3954 DAG.getConstant(1, MVT::i32));
3956 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3957 // captures the result into a carry flag.
3958 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3959 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3961 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3962 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3964 // Merge the pieces into a single i64 value.
3965 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3968 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3969 SDValue TmpOp0, TmpOp1;
3970 bool Invert = false;
3974 SDValue Op0 = Op.getOperand(0);
3975 SDValue Op1 = Op.getOperand(1);
3976 SDValue CC = Op.getOperand(2);
3977 EVT VT = Op.getValueType();
3978 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3981 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3982 switch (SetCCOpcode) {
3983 default: llvm_unreachable("Illegal FP comparison");
3985 case ISD::SETNE: Invert = true; // Fallthrough
3987 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3989 case ISD::SETLT: Swap = true; // Fallthrough
3991 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3993 case ISD::SETLE: Swap = true; // Fallthrough
3995 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3996 case ISD::SETUGE: Swap = true; // Fallthrough
3997 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3998 case ISD::SETUGT: Swap = true; // Fallthrough
3999 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4000 case ISD::SETUEQ: Invert = true; // Fallthrough
4002 // Expand this to (OLT | OGT).
4006 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4007 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4009 case ISD::SETUO: Invert = true; // Fallthrough
4011 // Expand this to (OLT | OGE).
4015 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4016 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4020 // Integer comparisons.
4021 switch (SetCCOpcode) {
4022 default: llvm_unreachable("Illegal integer comparison");
4023 case ISD::SETNE: Invert = true;
4024 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4025 case ISD::SETLT: Swap = true;
4026 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4027 case ISD::SETLE: Swap = true;
4028 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4029 case ISD::SETULT: Swap = true;
4030 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4031 case ISD::SETULE: Swap = true;
4032 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4035 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4036 if (Opc == ARMISD::VCEQ) {
4039 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4041 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4044 // Ignore bitconvert.
4045 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4046 AndOp = AndOp.getOperand(0);
4048 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4050 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4051 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4058 std::swap(Op0, Op1);
4060 // If one of the operands is a constant vector zero, attempt to fold the
4061 // comparison to a specialized compare-against-zero form.
4063 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4065 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4066 if (Opc == ARMISD::VCGE)
4067 Opc = ARMISD::VCLEZ;
4068 else if (Opc == ARMISD::VCGT)
4069 Opc = ARMISD::VCLTZ;
4074 if (SingleOp.getNode()) {
4077 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4079 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4081 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4083 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4085 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4087 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4090 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4094 Result = DAG.getNOT(dl, Result, VT);
4099 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4100 /// valid vector constant for a NEON instruction with a "modified immediate"
4101 /// operand (e.g., VMOV). If so, return the encoded value.
4102 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4103 unsigned SplatBitSize, SelectionDAG &DAG,
4104 EVT &VT, bool is128Bits, NEONModImmType type) {
4105 unsigned OpCmode, Imm;
4107 // SplatBitSize is set to the smallest size that splats the vector, so a
4108 // zero vector will always have SplatBitSize == 8. However, NEON modified
4109 // immediate instructions others than VMOV do not support the 8-bit encoding
4110 // of a zero vector, and the default encoding of zero is supposed to be the
4115 switch (SplatBitSize) {
4117 if (type != VMOVModImm)
4119 // Any 1-byte value is OK. Op=0, Cmode=1110.
4120 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4123 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4127 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4128 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4129 if ((SplatBits & ~0xff) == 0) {
4130 // Value = 0x00nn: Op=x, Cmode=100x.
4135 if ((SplatBits & ~0xff00) == 0) {
4136 // Value = 0xnn00: Op=x, Cmode=101x.
4138 Imm = SplatBits >> 8;
4144 // NEON's 32-bit VMOV supports splat values where:
4145 // * only one byte is nonzero, or
4146 // * the least significant byte is 0xff and the second byte is nonzero, or
4147 // * the least significant 2 bytes are 0xff and the third is nonzero.
4148 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4149 if ((SplatBits & ~0xff) == 0) {
4150 // Value = 0x000000nn: Op=x, Cmode=000x.
4155 if ((SplatBits & ~0xff00) == 0) {
4156 // Value = 0x0000nn00: Op=x, Cmode=001x.
4158 Imm = SplatBits >> 8;
4161 if ((SplatBits & ~0xff0000) == 0) {
4162 // Value = 0x00nn0000: Op=x, Cmode=010x.
4164 Imm = SplatBits >> 16;
4167 if ((SplatBits & ~0xff000000) == 0) {
4168 // Value = 0xnn000000: Op=x, Cmode=011x.
4170 Imm = SplatBits >> 24;
4174 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4175 if (type == OtherModImm) return SDValue();
4177 if ((SplatBits & ~0xffff) == 0 &&
4178 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4179 // Value = 0x0000nnff: Op=x, Cmode=1100.
4181 Imm = SplatBits >> 8;
4186 if ((SplatBits & ~0xffffff) == 0 &&
4187 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4188 // Value = 0x00nnffff: Op=x, Cmode=1101.
4190 Imm = SplatBits >> 16;
4191 SplatBits |= 0xffff;
4195 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4196 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4197 // VMOV.I32. A (very) minor optimization would be to replicate the value
4198 // and fall through here to test for a valid 64-bit splat. But, then the
4199 // caller would also need to check and handle the change in size.
4203 if (type != VMOVModImm)
4205 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4206 uint64_t BitMask = 0xff;
4208 unsigned ImmMask = 1;
4210 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4211 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4214 } else if ((SplatBits & BitMask) != 0) {
4220 // Op=1, Cmode=1110.
4223 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4228 llvm_unreachable("unexpected size for isNEONModifiedImm");
4231 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4232 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4235 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4236 const ARMSubtarget *ST) const {
4237 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4240 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4241 assert(Op.getValueType() == MVT::f32 &&
4242 "ConstantFP custom lowering should only occur for f32.");
4244 // Try splatting with a VMOV.f32...
4245 APFloat FPVal = CFP->getValueAPF();
4246 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4249 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4250 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4252 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4253 DAG.getConstant(0, MVT::i32));
4256 // If that fails, try a VMOV.i32
4258 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4259 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4261 if (NewVal != SDValue()) {
4263 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4265 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4267 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4268 DAG.getConstant(0, MVT::i32));
4271 // Finally, try a VMVN.i32
4272 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4274 if (NewVal != SDValue()) {
4276 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4277 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4279 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4280 DAG.getConstant(0, MVT::i32));
4286 // check if an VEXT instruction can handle the shuffle mask when the
4287 // vector sources of the shuffle are the same.
4288 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4289 unsigned NumElts = VT.getVectorNumElements();
4291 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4297 // If this is a VEXT shuffle, the immediate value is the index of the first
4298 // element. The other shuffle indices must be the successive elements after
4300 unsigned ExpectedElt = Imm;
4301 for (unsigned i = 1; i < NumElts; ++i) {
4302 // Increment the expected index. If it wraps around, just follow it
4303 // back to index zero and keep going.
4305 if (ExpectedElt == NumElts)
4308 if (M[i] < 0) continue; // ignore UNDEF indices
4309 if (ExpectedElt != static_cast<unsigned>(M[i]))
4317 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4318 bool &ReverseVEXT, unsigned &Imm) {
4319 unsigned NumElts = VT.getVectorNumElements();
4320 ReverseVEXT = false;
4322 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4328 // If this is a VEXT shuffle, the immediate value is the index of the first
4329 // element. The other shuffle indices must be the successive elements after
4331 unsigned ExpectedElt = Imm;
4332 for (unsigned i = 1; i < NumElts; ++i) {
4333 // Increment the expected index. If it wraps around, it may still be
4334 // a VEXT but the source vectors must be swapped.
4336 if (ExpectedElt == NumElts * 2) {
4341 if (M[i] < 0) continue; // ignore UNDEF indices
4342 if (ExpectedElt != static_cast<unsigned>(M[i]))
4346 // Adjust the index value if the source operands will be swapped.
4353 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4354 /// instruction with the specified blocksize. (The order of the elements
4355 /// within each block of the vector is reversed.)
4356 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4357 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4358 "Only possible block sizes for VREV are: 16, 32, 64");
4360 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4364 unsigned NumElts = VT.getVectorNumElements();
4365 unsigned BlockElts = M[0] + 1;
4366 // If the first shuffle index is UNDEF, be optimistic.
4368 BlockElts = BlockSize / EltSz;
4370 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4373 for (unsigned i = 0; i < NumElts; ++i) {
4374 if (M[i] < 0) continue; // ignore UNDEF indices
4375 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4382 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4383 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4384 // range, then 0 is placed into the resulting vector. So pretty much any mask
4385 // of 8 elements can work here.
4386 return VT == MVT::v8i8 && M.size() == 8;
4389 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4390 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4394 unsigned NumElts = VT.getVectorNumElements();
4395 WhichResult = (M[0] == 0 ? 0 : 1);
4396 for (unsigned i = 0; i < NumElts; i += 2) {
4397 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4398 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4404 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4405 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4406 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4407 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4408 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4412 unsigned NumElts = VT.getVectorNumElements();
4413 WhichResult = (M[0] == 0 ? 0 : 1);
4414 for (unsigned i = 0; i < NumElts; i += 2) {
4415 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4416 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4422 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4423 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4427 unsigned NumElts = VT.getVectorNumElements();
4428 WhichResult = (M[0] == 0 ? 0 : 1);
4429 for (unsigned i = 0; i != NumElts; ++i) {
4430 if (M[i] < 0) continue; // ignore UNDEF indices
4431 if ((unsigned) M[i] != 2 * i + WhichResult)
4435 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4436 if (VT.is64BitVector() && EltSz == 32)
4442 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4443 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4444 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4445 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4446 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4450 unsigned Half = VT.getVectorNumElements() / 2;
4451 WhichResult = (M[0] == 0 ? 0 : 1);
4452 for (unsigned j = 0; j != 2; ++j) {
4453 unsigned Idx = WhichResult;
4454 for (unsigned i = 0; i != Half; ++i) {
4455 int MIdx = M[i + j * Half];
4456 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4462 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4463 if (VT.is64BitVector() && EltSz == 32)
4469 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4470 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4474 unsigned NumElts = VT.getVectorNumElements();
4475 WhichResult = (M[0] == 0 ? 0 : 1);
4476 unsigned Idx = WhichResult * NumElts / 2;
4477 for (unsigned i = 0; i != NumElts; i += 2) {
4478 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4479 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4484 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4485 if (VT.is64BitVector() && EltSz == 32)
4491 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4492 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4493 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4494 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4495 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4499 unsigned NumElts = VT.getVectorNumElements();
4500 WhichResult = (M[0] == 0 ? 0 : 1);
4501 unsigned Idx = WhichResult * NumElts / 2;
4502 for (unsigned i = 0; i != NumElts; i += 2) {
4503 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4504 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4509 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4510 if (VT.is64BitVector() && EltSz == 32)
4516 /// \return true if this is a reverse operation on an vector.
4517 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4518 unsigned NumElts = VT.getVectorNumElements();
4519 // Make sure the mask has the right size.
4520 if (NumElts != M.size())
4523 // Look for <15, ..., 3, -1, 1, 0>.
4524 for (unsigned i = 0; i != NumElts; ++i)
4525 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4531 // If N is an integer constant that can be moved into a register in one
4532 // instruction, return an SDValue of such a constant (will become a MOV
4533 // instruction). Otherwise return null.
4534 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4535 const ARMSubtarget *ST, SDLoc dl) {
4537 if (!isa<ConstantSDNode>(N))
4539 Val = cast<ConstantSDNode>(N)->getZExtValue();
4541 if (ST->isThumb1Only()) {
4542 if (Val <= 255 || ~Val <= 255)
4543 return DAG.getConstant(Val, MVT::i32);
4545 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4546 return DAG.getConstant(Val, MVT::i32);
4551 // If this is a case we can't handle, return null and let the default
4552 // expansion code take care of it.
4553 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4554 const ARMSubtarget *ST) const {
4555 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4557 EVT VT = Op.getValueType();
4559 APInt SplatBits, SplatUndef;
4560 unsigned SplatBitSize;
4562 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4563 if (SplatBitSize <= 64) {
4564 // Check if an immediate VMOV works.
4566 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4567 SplatUndef.getZExtValue(), SplatBitSize,
4568 DAG, VmovVT, VT.is128BitVector(),
4570 if (Val.getNode()) {
4571 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4572 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4575 // Try an immediate VMVN.
4576 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4577 Val = isNEONModifiedImm(NegatedImm,
4578 SplatUndef.getZExtValue(), SplatBitSize,
4579 DAG, VmovVT, VT.is128BitVector(),
4581 if (Val.getNode()) {
4582 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4583 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4586 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4587 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4588 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4590 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4591 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4597 // Scan through the operands to see if only one value is used.
4599 // As an optimisation, even if more than one value is used it may be more
4600 // profitable to splat with one value then change some lanes.
4602 // Heuristically we decide to do this if the vector has a "dominant" value,
4603 // defined as splatted to more than half of the lanes.
4604 unsigned NumElts = VT.getVectorNumElements();
4605 bool isOnlyLowElement = true;
4606 bool usesOnlyOneValue = true;
4607 bool hasDominantValue = false;
4608 bool isConstant = true;
4610 // Map of the number of times a particular SDValue appears in the
4612 DenseMap<SDValue, unsigned> ValueCounts;
4614 for (unsigned i = 0; i < NumElts; ++i) {
4615 SDValue V = Op.getOperand(i);
4616 if (V.getOpcode() == ISD::UNDEF)
4619 isOnlyLowElement = false;
4620 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4623 ValueCounts.insert(std::make_pair(V, 0));
4624 unsigned &Count = ValueCounts[V];
4626 // Is this value dominant? (takes up more than half of the lanes)
4627 if (++Count > (NumElts / 2)) {
4628 hasDominantValue = true;
4632 if (ValueCounts.size() != 1)
4633 usesOnlyOneValue = false;
4634 if (!Value.getNode() && ValueCounts.size() > 0)
4635 Value = ValueCounts.begin()->first;
4637 if (ValueCounts.size() == 0)
4638 return DAG.getUNDEF(VT);
4640 if (isOnlyLowElement)
4641 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4643 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4645 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4646 // i32 and try again.
4647 if (hasDominantValue && EltSize <= 32) {
4651 // If we are VDUPing a value that comes directly from a vector, that will
4652 // cause an unnecessary move to and from a GPR, where instead we could
4653 // just use VDUPLANE. We can only do this if the lane being extracted
4654 // is at a constant index, as the VDUP from lane instructions only have
4655 // constant-index forms.
4656 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4657 isa<ConstantSDNode>(Value->getOperand(1))) {
4658 // We need to create a new undef vector to use for the VDUPLANE if the
4659 // size of the vector from which we get the value is different than the
4660 // size of the vector that we need to create. We will insert the element
4661 // such that the register coalescer will remove unnecessary copies.
4662 if (VT != Value->getOperand(0).getValueType()) {
4663 ConstantSDNode *constIndex;
4664 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4665 assert(constIndex && "The index is not a constant!");
4666 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4667 VT.getVectorNumElements();
4668 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4669 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4670 Value, DAG.getConstant(index, MVT::i32)),
4671 DAG.getConstant(index, MVT::i32));
4673 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4674 Value->getOperand(0), Value->getOperand(1));
4676 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4678 if (!usesOnlyOneValue) {
4679 // The dominant value was splatted as 'N', but we now have to insert
4680 // all differing elements.
4681 for (unsigned I = 0; I < NumElts; ++I) {
4682 if (Op.getOperand(I) == Value)
4684 SmallVector<SDValue, 3> Ops;
4686 Ops.push_back(Op.getOperand(I));
4687 Ops.push_back(DAG.getConstant(I, MVT::i32));
4688 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4693 if (VT.getVectorElementType().isFloatingPoint()) {
4694 SmallVector<SDValue, 8> Ops;
4695 for (unsigned i = 0; i < NumElts; ++i)
4696 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4698 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4699 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4700 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4702 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4704 if (usesOnlyOneValue) {
4705 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4706 if (isConstant && Val.getNode())
4707 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4711 // If all elements are constants and the case above didn't get hit, fall back
4712 // to the default expansion, which will generate a load from the constant
4717 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4719 SDValue shuffle = ReconstructShuffle(Op, DAG);
4720 if (shuffle != SDValue())
4724 // Vectors with 32- or 64-bit elements can be built by directly assigning
4725 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4726 // will be legalized.
4727 if (EltSize >= 32) {
4728 // Do the expansion with floating-point types, since that is what the VFP
4729 // registers are defined to use, and since i64 is not legal.
4730 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4731 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4732 SmallVector<SDValue, 8> Ops;
4733 for (unsigned i = 0; i < NumElts; ++i)
4734 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4735 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4736 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4742 // Gather data to see if the operation can be modelled as a
4743 // shuffle in combination with VEXTs.
4744 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4745 SelectionDAG &DAG) const {
4747 EVT VT = Op.getValueType();
4748 unsigned NumElts = VT.getVectorNumElements();
4750 SmallVector<SDValue, 2> SourceVecs;
4751 SmallVector<unsigned, 2> MinElts;
4752 SmallVector<unsigned, 2> MaxElts;
4754 for (unsigned i = 0; i < NumElts; ++i) {
4755 SDValue V = Op.getOperand(i);
4756 if (V.getOpcode() == ISD::UNDEF)
4758 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4759 // A shuffle can only come from building a vector from various
4760 // elements of other vectors.
4762 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4763 VT.getVectorElementType()) {
4764 // This code doesn't know how to handle shuffles where the vector
4765 // element types do not match (this happens because type legalization
4766 // promotes the return type of EXTRACT_VECTOR_ELT).
4767 // FIXME: It might be appropriate to extend this code to handle
4768 // mismatched types.
4772 // Record this extraction against the appropriate vector if possible...
4773 SDValue SourceVec = V.getOperand(0);
4774 // If the element number isn't a constant, we can't effectively
4775 // analyze what's going on.
4776 if (!isa<ConstantSDNode>(V.getOperand(1)))
4778 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4779 bool FoundSource = false;
4780 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4781 if (SourceVecs[j] == SourceVec) {
4782 if (MinElts[j] > EltNo)
4784 if (MaxElts[j] < EltNo)
4791 // Or record a new source if not...
4793 SourceVecs.push_back(SourceVec);
4794 MinElts.push_back(EltNo);
4795 MaxElts.push_back(EltNo);
4799 // Currently only do something sane when at most two source vectors
4801 if (SourceVecs.size() > 2)
4804 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4805 int VEXTOffsets[2] = {0, 0};
4807 // This loop extracts the usage patterns of the source vectors
4808 // and prepares appropriate SDValues for a shuffle if possible.
4809 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4810 if (SourceVecs[i].getValueType() == VT) {
4811 // No VEXT necessary
4812 ShuffleSrcs[i] = SourceVecs[i];
4815 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4816 // It probably isn't worth padding out a smaller vector just to
4817 // break it down again in a shuffle.
4821 // Since only 64-bit and 128-bit vectors are legal on ARM and
4822 // we've eliminated the other cases...
4823 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4824 "unexpected vector sizes in ReconstructShuffle");
4826 if (MaxElts[i] - MinElts[i] >= NumElts) {
4827 // Span too large for a VEXT to cope
4831 if (MinElts[i] >= NumElts) {
4832 // The extraction can just take the second half
4833 VEXTOffsets[i] = NumElts;
4834 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4836 DAG.getIntPtrConstant(NumElts));
4837 } else if (MaxElts[i] < NumElts) {
4838 // The extraction can just take the first half
4840 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4842 DAG.getIntPtrConstant(0));
4844 // An actual VEXT is needed
4845 VEXTOffsets[i] = MinElts[i];
4846 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4848 DAG.getIntPtrConstant(0));
4849 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4851 DAG.getIntPtrConstant(NumElts));
4852 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4853 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4857 SmallVector<int, 8> Mask;
4859 for (unsigned i = 0; i < NumElts; ++i) {
4860 SDValue Entry = Op.getOperand(i);
4861 if (Entry.getOpcode() == ISD::UNDEF) {
4866 SDValue ExtractVec = Entry.getOperand(0);
4867 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4868 .getOperand(1))->getSExtValue();
4869 if (ExtractVec == SourceVecs[0]) {
4870 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4872 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4876 // Final check before we try to produce nonsense...
4877 if (isShuffleMaskLegal(Mask, VT))
4878 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4884 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4885 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4886 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4887 /// are assumed to be legal.
4889 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4891 if (VT.getVectorNumElements() == 4 &&
4892 (VT.is128BitVector() || VT.is64BitVector())) {
4893 unsigned PFIndexes[4];
4894 for (unsigned i = 0; i != 4; ++i) {
4898 PFIndexes[i] = M[i];
4901 // Compute the index in the perfect shuffle table.
4902 unsigned PFTableIndex =
4903 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4904 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4905 unsigned Cost = (PFEntry >> 30);
4912 unsigned Imm, WhichResult;
4914 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4915 return (EltSize >= 32 ||
4916 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4917 isVREVMask(M, VT, 64) ||
4918 isVREVMask(M, VT, 32) ||
4919 isVREVMask(M, VT, 16) ||
4920 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4921 isVTBLMask(M, VT) ||
4922 isVTRNMask(M, VT, WhichResult) ||
4923 isVUZPMask(M, VT, WhichResult) ||
4924 isVZIPMask(M, VT, WhichResult) ||
4925 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4926 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4927 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4928 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4931 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4932 /// the specified operations to build the shuffle.
4933 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4934 SDValue RHS, SelectionDAG &DAG,
4936 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4937 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4938 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4941 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4950 OP_VUZPL, // VUZP, left result
4951 OP_VUZPR, // VUZP, right result
4952 OP_VZIPL, // VZIP, left result
4953 OP_VZIPR, // VZIP, right result
4954 OP_VTRNL, // VTRN, left result
4955 OP_VTRNR // VTRN, right result
4958 if (OpNum == OP_COPY) {
4959 if (LHSID == (1*9+2)*9+3) return LHS;
4960 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4964 SDValue OpLHS, OpRHS;
4965 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4966 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4967 EVT VT = OpLHS.getValueType();
4970 default: llvm_unreachable("Unknown shuffle opcode!");
4972 // VREV divides the vector in half and swaps within the half.
4973 if (VT.getVectorElementType() == MVT::i32 ||
4974 VT.getVectorElementType() == MVT::f32)
4975 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4976 // vrev <4 x i16> -> VREV32
4977 if (VT.getVectorElementType() == MVT::i16)
4978 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4979 // vrev <4 x i8> -> VREV16
4980 assert(VT.getVectorElementType() == MVT::i8);
4981 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4986 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4987 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4991 return DAG.getNode(ARMISD::VEXT, dl, VT,
4993 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4996 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4997 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5000 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5001 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5004 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5005 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5009 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5010 ArrayRef<int> ShuffleMask,
5011 SelectionDAG &DAG) {
5012 // Check to see if we can use the VTBL instruction.
5013 SDValue V1 = Op.getOperand(0);
5014 SDValue V2 = Op.getOperand(1);
5017 SmallVector<SDValue, 8> VTBLMask;
5018 for (ArrayRef<int>::iterator
5019 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5020 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5022 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5023 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5024 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5027 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5028 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5032 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5033 SelectionDAG &DAG) {
5035 SDValue OpLHS = Op.getOperand(0);
5036 EVT VT = OpLHS.getValueType();
5038 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5039 "Expect an v8i16/v16i8 type");
5040 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5041 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5042 // extract the first 8 bytes into the top double word and the last 8 bytes
5043 // into the bottom double word. The v8i16 case is similar.
5044 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5045 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5046 DAG.getConstant(ExtractNum, MVT::i32));
5049 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5050 SDValue V1 = Op.getOperand(0);
5051 SDValue V2 = Op.getOperand(1);
5053 EVT VT = Op.getValueType();
5054 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5056 // Convert shuffles that are directly supported on NEON to target-specific
5057 // DAG nodes, instead of keeping them as shuffles and matching them again
5058 // during code selection. This is more efficient and avoids the possibility
5059 // of inconsistencies between legalization and selection.
5060 // FIXME: floating-point vectors should be canonicalized to integer vectors
5061 // of the same time so that they get CSEd properly.
5062 ArrayRef<int> ShuffleMask = SVN->getMask();
5064 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5065 if (EltSize <= 32) {
5066 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5067 int Lane = SVN->getSplatIndex();
5068 // If this is undef splat, generate it via "just" vdup, if possible.
5069 if (Lane == -1) Lane = 0;
5071 // Test if V1 is a SCALAR_TO_VECTOR.
5072 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5073 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5075 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5076 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5078 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5079 !isa<ConstantSDNode>(V1.getOperand(0))) {
5080 bool IsScalarToVector = true;
5081 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5082 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5083 IsScalarToVector = false;
5086 if (IsScalarToVector)
5087 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5089 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5090 DAG.getConstant(Lane, MVT::i32));
5095 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5098 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5099 DAG.getConstant(Imm, MVT::i32));
5102 if (isVREVMask(ShuffleMask, VT, 64))
5103 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5104 if (isVREVMask(ShuffleMask, VT, 32))
5105 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5106 if (isVREVMask(ShuffleMask, VT, 16))
5107 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5109 if (V2->getOpcode() == ISD::UNDEF &&
5110 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5111 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5112 DAG.getConstant(Imm, MVT::i32));
5115 // Check for Neon shuffles that modify both input vectors in place.
5116 // If both results are used, i.e., if there are two shuffles with the same
5117 // source operands and with masks corresponding to both results of one of
5118 // these operations, DAG memoization will ensure that a single node is
5119 // used for both shuffles.
5120 unsigned WhichResult;
5121 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5122 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5123 V1, V2).getValue(WhichResult);
5124 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5125 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5126 V1, V2).getValue(WhichResult);
5127 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5128 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5129 V1, V2).getValue(WhichResult);
5131 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5132 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5133 V1, V1).getValue(WhichResult);
5134 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5135 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5136 V1, V1).getValue(WhichResult);
5137 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5138 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5139 V1, V1).getValue(WhichResult);
5142 // If the shuffle is not directly supported and it has 4 elements, use
5143 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5144 unsigned NumElts = VT.getVectorNumElements();
5146 unsigned PFIndexes[4];
5147 for (unsigned i = 0; i != 4; ++i) {
5148 if (ShuffleMask[i] < 0)
5151 PFIndexes[i] = ShuffleMask[i];
5154 // Compute the index in the perfect shuffle table.
5155 unsigned PFTableIndex =
5156 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5157 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5158 unsigned Cost = (PFEntry >> 30);
5161 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5164 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5165 if (EltSize >= 32) {
5166 // Do the expansion with floating-point types, since that is what the VFP
5167 // registers are defined to use, and since i64 is not legal.
5168 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5169 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5170 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5171 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5172 SmallVector<SDValue, 8> Ops;
5173 for (unsigned i = 0; i < NumElts; ++i) {
5174 if (ShuffleMask[i] < 0)
5175 Ops.push_back(DAG.getUNDEF(EltVT));
5177 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5178 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5179 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5182 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5183 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5186 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5187 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5189 if (VT == MVT::v8i8) {
5190 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5191 if (NewOp.getNode())
5198 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5199 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5200 SDValue Lane = Op.getOperand(2);
5201 if (!isa<ConstantSDNode>(Lane))
5207 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5208 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5209 SDValue Lane = Op.getOperand(1);
5210 if (!isa<ConstantSDNode>(Lane))
5213 SDValue Vec = Op.getOperand(0);
5214 if (Op.getValueType() == MVT::i32 &&
5215 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5217 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5223 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5224 // The only time a CONCAT_VECTORS operation can have legal types is when
5225 // two 64-bit vectors are concatenated to a 128-bit vector.
5226 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5227 "unexpected CONCAT_VECTORS");
5229 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5230 SDValue Op0 = Op.getOperand(0);
5231 SDValue Op1 = Op.getOperand(1);
5232 if (Op0.getOpcode() != ISD::UNDEF)
5233 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5234 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5235 DAG.getIntPtrConstant(0));
5236 if (Op1.getOpcode() != ISD::UNDEF)
5237 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5238 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5239 DAG.getIntPtrConstant(1));
5240 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5243 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5244 /// element has been zero/sign-extended, depending on the isSigned parameter,
5245 /// from an integer type half its size.
5246 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5248 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5249 EVT VT = N->getValueType(0);
5250 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5251 SDNode *BVN = N->getOperand(0).getNode();
5252 if (BVN->getValueType(0) != MVT::v4i32 ||
5253 BVN->getOpcode() != ISD::BUILD_VECTOR)
5255 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5256 unsigned HiElt = 1 - LoElt;
5257 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5258 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5259 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5260 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5261 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5264 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5265 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5268 if (Hi0->isNullValue() && Hi1->isNullValue())
5274 if (N->getOpcode() != ISD::BUILD_VECTOR)
5277 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5278 SDNode *Elt = N->getOperand(i).getNode();
5279 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5280 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5281 unsigned HalfSize = EltSize / 2;
5283 if (!isIntN(HalfSize, C->getSExtValue()))
5286 if (!isUIntN(HalfSize, C->getZExtValue()))
5297 /// isSignExtended - Check if a node is a vector value that is sign-extended
5298 /// or a constant BUILD_VECTOR with sign-extended elements.
5299 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5300 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5302 if (isExtendedBUILD_VECTOR(N, DAG, true))
5307 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5308 /// or a constant BUILD_VECTOR with zero-extended elements.
5309 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5310 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5312 if (isExtendedBUILD_VECTOR(N, DAG, false))
5317 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5318 if (OrigVT.getSizeInBits() >= 64)
5321 assert(OrigVT.isSimple() && "Expecting a simple value type");
5323 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5324 switch (OrigSimpleTy) {
5325 default: llvm_unreachable("Unexpected Vector Type");
5334 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5335 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5336 /// We insert the required extension here to get the vector to fill a D register.
5337 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5340 unsigned ExtOpcode) {
5341 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5342 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5343 // 64-bits we need to insert a new extension so that it will be 64-bits.
5344 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5345 if (OrigTy.getSizeInBits() >= 64)
5348 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5349 EVT NewVT = getExtensionTo64Bits(OrigTy);
5351 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5354 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5355 /// does not do any sign/zero extension. If the original vector is less
5356 /// than 64 bits, an appropriate extension will be added after the load to
5357 /// reach a total size of 64 bits. We have to add the extension separately
5358 /// because ARM does not have a sign/zero extending load for vectors.
5359 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5360 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5362 // The load already has the right type.
5363 if (ExtendedTy == LD->getMemoryVT())
5364 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5365 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5366 LD->isNonTemporal(), LD->isInvariant(),
5367 LD->getAlignment());
5369 // We need to create a zextload/sextload. We cannot just create a load
5370 // followed by a zext/zext node because LowerMUL is also run during normal
5371 // operation legalization where we can't create illegal types.
5372 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5373 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5374 LD->getMemoryVT(), LD->isVolatile(),
5375 LD->isNonTemporal(), LD->getAlignment());
5378 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5379 /// extending load, or BUILD_VECTOR with extended elements, return the
5380 /// unextended value. The unextended vector should be 64 bits so that it can
5381 /// be used as an operand to a VMULL instruction. If the original vector size
5382 /// before extension is less than 64 bits we add a an extension to resize
5383 /// the vector to 64 bits.
5384 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5385 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5386 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5387 N->getOperand(0)->getValueType(0),
5391 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5392 return SkipLoadExtensionForVMULL(LD, DAG);
5394 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5395 // have been legalized as a BITCAST from v4i32.
5396 if (N->getOpcode() == ISD::BITCAST) {
5397 SDNode *BVN = N->getOperand(0).getNode();
5398 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5399 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5400 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5401 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5402 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5404 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5405 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5406 EVT VT = N->getValueType(0);
5407 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5408 unsigned NumElts = VT.getVectorNumElements();
5409 MVT TruncVT = MVT::getIntegerVT(EltSize);
5410 SmallVector<SDValue, 8> Ops;
5411 for (unsigned i = 0; i != NumElts; ++i) {
5412 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5413 const APInt &CInt = C->getAPIntValue();
5414 // Element types smaller than 32 bits are not legal, so use i32 elements.
5415 // The values are implicitly truncated so sext vs. zext doesn't matter.
5416 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5418 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5419 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5422 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5423 unsigned Opcode = N->getOpcode();
5424 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5425 SDNode *N0 = N->getOperand(0).getNode();
5426 SDNode *N1 = N->getOperand(1).getNode();
5427 return N0->hasOneUse() && N1->hasOneUse() &&
5428 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5433 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5434 unsigned Opcode = N->getOpcode();
5435 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5436 SDNode *N0 = N->getOperand(0).getNode();
5437 SDNode *N1 = N->getOperand(1).getNode();
5438 return N0->hasOneUse() && N1->hasOneUse() &&
5439 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5444 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5445 // Multiplications are only custom-lowered for 128-bit vectors so that
5446 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5447 EVT VT = Op.getValueType();
5448 assert(VT.is128BitVector() && VT.isInteger() &&
5449 "unexpected type for custom-lowering ISD::MUL");
5450 SDNode *N0 = Op.getOperand(0).getNode();
5451 SDNode *N1 = Op.getOperand(1).getNode();
5452 unsigned NewOpc = 0;
5454 bool isN0SExt = isSignExtended(N0, DAG);
5455 bool isN1SExt = isSignExtended(N1, DAG);
5456 if (isN0SExt && isN1SExt)
5457 NewOpc = ARMISD::VMULLs;
5459 bool isN0ZExt = isZeroExtended(N0, DAG);
5460 bool isN1ZExt = isZeroExtended(N1, DAG);
5461 if (isN0ZExt && isN1ZExt)
5462 NewOpc = ARMISD::VMULLu;
5463 else if (isN1SExt || isN1ZExt) {
5464 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5465 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5466 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5467 NewOpc = ARMISD::VMULLs;
5469 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5470 NewOpc = ARMISD::VMULLu;
5472 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5474 NewOpc = ARMISD::VMULLu;
5480 if (VT == MVT::v2i64)
5481 // Fall through to expand this. It is not legal.
5484 // Other vector multiplications are legal.
5489 // Legalize to a VMULL instruction.
5492 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5494 Op0 = SkipExtensionForVMULL(N0, DAG);
5495 assert(Op0.getValueType().is64BitVector() &&
5496 Op1.getValueType().is64BitVector() &&
5497 "unexpected types for extended operands to VMULL");
5498 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5501 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5502 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5509 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5510 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5511 EVT Op1VT = Op1.getValueType();
5512 return DAG.getNode(N0->getOpcode(), DL, VT,
5513 DAG.getNode(NewOpc, DL, VT,
5514 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5515 DAG.getNode(NewOpc, DL, VT,
5516 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5520 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5522 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5523 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5524 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5525 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5526 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5527 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5528 // Get reciprocal estimate.
5529 // float4 recip = vrecpeq_f32(yf);
5530 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5531 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5532 // Because char has a smaller range than uchar, we can actually get away
5533 // without any newton steps. This requires that we use a weird bias
5534 // of 0xb000, however (again, this has been exhaustively tested).
5535 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5536 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5537 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5538 Y = DAG.getConstant(0xb000, MVT::i32);
5539 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5540 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5541 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5542 // Convert back to short.
5543 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5544 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5549 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5551 // Convert to float.
5552 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5553 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5554 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5555 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5556 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5557 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5559 // Use reciprocal estimate and one refinement step.
5560 // float4 recip = vrecpeq_f32(yf);
5561 // recip *= vrecpsq_f32(yf, recip);
5562 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5563 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5564 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5565 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5567 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5568 // Because short has a smaller range than ushort, we can actually get away
5569 // with only a single newton step. This requires that we use a weird bias
5570 // of 89, however (again, this has been exhaustively tested).
5571 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5572 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5573 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5574 N1 = DAG.getConstant(0x89, MVT::i32);
5575 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5576 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5577 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5578 // Convert back to integer and return.
5579 // return vmovn_s32(vcvt_s32_f32(result));
5580 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5581 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5585 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5586 EVT VT = Op.getValueType();
5587 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5588 "unexpected type for custom-lowering ISD::SDIV");
5591 SDValue N0 = Op.getOperand(0);
5592 SDValue N1 = Op.getOperand(1);
5595 if (VT == MVT::v8i8) {
5596 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5597 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5599 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5600 DAG.getIntPtrConstant(4));
5601 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5602 DAG.getIntPtrConstant(4));
5603 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5604 DAG.getIntPtrConstant(0));
5605 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5606 DAG.getIntPtrConstant(0));
5608 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5609 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5611 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5612 N0 = LowerCONCAT_VECTORS(N0, DAG);
5614 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5617 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5620 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5621 EVT VT = Op.getValueType();
5622 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5623 "unexpected type for custom-lowering ISD::UDIV");
5626 SDValue N0 = Op.getOperand(0);
5627 SDValue N1 = Op.getOperand(1);
5630 if (VT == MVT::v8i8) {
5631 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5632 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5634 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5635 DAG.getIntPtrConstant(4));
5636 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5637 DAG.getIntPtrConstant(4));
5638 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5639 DAG.getIntPtrConstant(0));
5640 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5641 DAG.getIntPtrConstant(0));
5643 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5644 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5646 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5647 N0 = LowerCONCAT_VECTORS(N0, DAG);
5649 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5650 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5655 // v4i16 sdiv ... Convert to float.
5656 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5657 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5658 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5659 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5660 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5661 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5663 // Use reciprocal estimate and two refinement steps.
5664 // float4 recip = vrecpeq_f32(yf);
5665 // recip *= vrecpsq_f32(yf, recip);
5666 // recip *= vrecpsq_f32(yf, recip);
5667 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5668 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5669 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5670 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5672 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5673 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5674 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5676 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5677 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5678 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5679 // and that it will never cause us to return an answer too large).
5680 // float4 result = as_float4(as_int4(xf*recip) + 2);
5681 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5682 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5683 N1 = DAG.getConstant(2, MVT::i32);
5684 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5685 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5686 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5687 // Convert back to integer and return.
5688 // return vmovn_u32(vcvt_s32_f32(result));
5689 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5690 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5694 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5695 EVT VT = Op.getNode()->getValueType(0);
5696 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5699 bool ExtraOp = false;
5700 switch (Op.getOpcode()) {
5701 default: llvm_unreachable("Invalid code");
5702 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5703 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5704 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5705 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5709 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5711 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5712 Op.getOperand(1), Op.getOperand(2));
5715 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5716 // Monotonic load/store is legal for all targets
5717 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5720 // Aquire/Release load/store is not legal for targets without a
5721 // dmb or equivalent available.
5726 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5727 SelectionDAG &DAG, unsigned NewOp) {
5729 assert (Node->getValueType(0) == MVT::i64 &&
5730 "Only know how to expand i64 atomics");
5732 SmallVector<SDValue, 6> Ops;
5733 Ops.push_back(Node->getOperand(0)); // Chain
5734 Ops.push_back(Node->getOperand(1)); // Ptr
5736 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5737 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5738 // High part of Val1
5739 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5740 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5741 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5742 // High part of Val1
5743 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5744 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5745 // High part of Val2
5746 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5747 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5749 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5751 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5752 cast<MemSDNode>(Node)->getMemOperand());
5753 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5754 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5755 Results.push_back(Result.getValue(2));
5758 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5759 SmallVectorImpl<SDValue> &Results,
5761 const ARMSubtarget *Subtarget) {
5763 SDValue Cycles32, OutChain;
5765 if (Subtarget->hasPerfMon()) {
5766 // Under Power Management extensions, the cycle-count is:
5767 // mrc p15, #0, <Rt>, c9, c13, #0
5768 SDValue Ops[] = { N->getOperand(0), // Chain
5769 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5770 DAG.getConstant(15, MVT::i32),
5771 DAG.getConstant(0, MVT::i32),
5772 DAG.getConstant(9, MVT::i32),
5773 DAG.getConstant(13, MVT::i32),
5774 DAG.getConstant(0, MVT::i32)
5777 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
5778 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
5779 array_lengthof(Ops));
5780 OutChain = Cycles32.getValue(1);
5782 // Intrinsic is defined to return 0 on unsupported platforms. Technically
5783 // there are older ARM CPUs that have implementation-specific ways of
5784 // obtaining this information (FIXME!).
5785 Cycles32 = DAG.getConstant(0, MVT::i32);
5786 OutChain = DAG.getEntryNode();
5790 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
5791 Cycles32, DAG.getConstant(0, MVT::i32));
5792 Results.push_back(Cycles64);
5793 Results.push_back(OutChain);
5796 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5797 switch (Op.getOpcode()) {
5798 default: llvm_unreachable("Don't know how to custom lower this!");
5799 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5800 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5801 case ISD::GlobalAddress:
5802 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5803 LowerGlobalAddressELF(Op, DAG);
5804 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5805 case ISD::SELECT: return LowerSELECT(Op, DAG);
5806 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5807 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5808 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5809 case ISD::VASTART: return LowerVASTART(Op, DAG);
5810 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5811 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5812 case ISD::SINT_TO_FP:
5813 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5814 case ISD::FP_TO_SINT:
5815 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5816 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5817 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5818 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5819 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5820 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5821 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5822 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5824 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5827 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5828 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5829 case ISD::SRL_PARTS:
5830 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5831 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5832 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5833 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5834 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5835 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5836 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5837 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5838 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5839 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5840 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5841 case ISD::MUL: return LowerMUL(Op, DAG);
5842 case ISD::SDIV: return LowerSDIV(Op, DAG);
5843 case ISD::UDIV: return LowerUDIV(Op, DAG);
5847 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5848 case ISD::ATOMIC_LOAD:
5849 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5853 /// ReplaceNodeResults - Replace the results of node with an illegal result
5854 /// type with new values built out of custom code.
5855 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5856 SmallVectorImpl<SDValue>&Results,
5857 SelectionDAG &DAG) const {
5859 switch (N->getOpcode()) {
5861 llvm_unreachable("Don't know how to custom expand this!");
5863 Res = ExpandBITCAST(N, DAG);
5865 case ISD::SIGN_EXTEND:
5866 case ISD::ZERO_EXTEND:
5867 Res = ExpandVectorExtension(N, DAG);
5871 Res = Expand64BitShift(N, DAG, Subtarget);
5873 case ISD::READCYCLECOUNTER:
5874 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
5876 case ISD::ATOMIC_LOAD_ADD:
5877 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5879 case ISD::ATOMIC_LOAD_AND:
5880 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5882 case ISD::ATOMIC_LOAD_NAND:
5883 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5885 case ISD::ATOMIC_LOAD_OR:
5886 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5888 case ISD::ATOMIC_LOAD_SUB:
5889 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5891 case ISD::ATOMIC_LOAD_XOR:
5892 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5894 case ISD::ATOMIC_SWAP:
5895 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5897 case ISD::ATOMIC_CMP_SWAP:
5898 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5900 case ISD::ATOMIC_LOAD_MIN:
5901 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5903 case ISD::ATOMIC_LOAD_UMIN:
5904 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5906 case ISD::ATOMIC_LOAD_MAX:
5907 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5909 case ISD::ATOMIC_LOAD_UMAX:
5910 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5914 Results.push_back(Res);
5917 //===----------------------------------------------------------------------===//
5918 // ARM Scheduler Hooks
5919 //===----------------------------------------------------------------------===//
5922 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5923 MachineBasicBlock *BB,
5924 unsigned Size) const {
5925 unsigned dest = MI->getOperand(0).getReg();
5926 unsigned ptr = MI->getOperand(1).getReg();
5927 unsigned oldval = MI->getOperand(2).getReg();
5928 unsigned newval = MI->getOperand(3).getReg();
5929 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5930 DebugLoc dl = MI->getDebugLoc();
5931 bool isThumb2 = Subtarget->isThumb2();
5933 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5934 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5935 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5936 (const TargetRegisterClass*)&ARM::GPRRegClass);
5939 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5940 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5941 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5944 unsigned ldrOpc, strOpc;
5946 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5948 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5949 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5952 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5953 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5956 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5957 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5961 MachineFunction *MF = BB->getParent();
5962 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5963 MachineFunction::iterator It = BB;
5964 ++It; // insert the new blocks after the current block
5966 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5967 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5968 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5969 MF->insert(It, loop1MBB);
5970 MF->insert(It, loop2MBB);
5971 MF->insert(It, exitMBB);
5973 // Transfer the remainder of BB and its successor edges to exitMBB.
5974 exitMBB->splice(exitMBB->begin(), BB,
5975 llvm::next(MachineBasicBlock::iterator(MI)),
5977 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5981 // fallthrough --> loop1MBB
5982 BB->addSuccessor(loop1MBB);
5985 // ldrex dest, [ptr]
5989 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5990 if (ldrOpc == ARM::t2LDREX)
5992 AddDefaultPred(MIB);
5993 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5994 .addReg(dest).addReg(oldval));
5995 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5996 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5997 BB->addSuccessor(loop2MBB);
5998 BB->addSuccessor(exitMBB);
6001 // strex scratch, newval, [ptr]
6005 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6006 if (strOpc == ARM::t2STREX)
6008 AddDefaultPred(MIB);
6009 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6010 .addReg(scratch).addImm(0));
6011 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6012 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6013 BB->addSuccessor(loop1MBB);
6014 BB->addSuccessor(exitMBB);
6020 MI->eraseFromParent(); // The instruction is gone now.
6026 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6027 unsigned Size, unsigned BinOpcode) const {
6028 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6029 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6031 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6032 MachineFunction *MF = BB->getParent();
6033 MachineFunction::iterator It = BB;
6036 unsigned dest = MI->getOperand(0).getReg();
6037 unsigned ptr = MI->getOperand(1).getReg();
6038 unsigned incr = MI->getOperand(2).getReg();
6039 DebugLoc dl = MI->getDebugLoc();
6040 bool isThumb2 = Subtarget->isThumb2();
6042 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6044 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6045 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6048 unsigned ldrOpc, strOpc;
6050 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6052 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6053 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6056 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6057 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6060 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6061 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6065 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6066 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6067 MF->insert(It, loopMBB);
6068 MF->insert(It, exitMBB);
6070 // Transfer the remainder of BB and its successor edges to exitMBB.
6071 exitMBB->splice(exitMBB->begin(), BB,
6072 llvm::next(MachineBasicBlock::iterator(MI)),
6074 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6076 const TargetRegisterClass *TRC = isThumb2 ?
6077 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6078 (const TargetRegisterClass*)&ARM::GPRRegClass;
6079 unsigned scratch = MRI.createVirtualRegister(TRC);
6080 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6084 // fallthrough --> loopMBB
6085 BB->addSuccessor(loopMBB);
6089 // <binop> scratch2, dest, incr
6090 // strex scratch, scratch2, ptr
6093 // fallthrough --> exitMBB
6095 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6096 if (ldrOpc == ARM::t2LDREX)
6098 AddDefaultPred(MIB);
6100 // operand order needs to go the other way for NAND
6101 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6102 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6103 addReg(incr).addReg(dest)).addReg(0);
6105 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6106 addReg(dest).addReg(incr)).addReg(0);
6109 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6110 if (strOpc == ARM::t2STREX)
6112 AddDefaultPred(MIB);
6113 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6114 .addReg(scratch).addImm(0));
6115 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6116 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6118 BB->addSuccessor(loopMBB);
6119 BB->addSuccessor(exitMBB);
6125 MI->eraseFromParent(); // The instruction is gone now.
6131 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6132 MachineBasicBlock *BB,
6135 ARMCC::CondCodes Cond) const {
6136 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6138 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6139 MachineFunction *MF = BB->getParent();
6140 MachineFunction::iterator It = BB;
6143 unsigned dest = MI->getOperand(0).getReg();
6144 unsigned ptr = MI->getOperand(1).getReg();
6145 unsigned incr = MI->getOperand(2).getReg();
6146 unsigned oldval = dest;
6147 DebugLoc dl = MI->getDebugLoc();
6148 bool isThumb2 = Subtarget->isThumb2();
6150 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6152 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6153 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6156 unsigned ldrOpc, strOpc, extendOpc;
6158 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6160 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6161 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6162 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6165 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6166 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6167 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6170 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6171 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6176 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6177 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6178 MF->insert(It, loopMBB);
6179 MF->insert(It, exitMBB);
6181 // Transfer the remainder of BB and its successor edges to exitMBB.
6182 exitMBB->splice(exitMBB->begin(), BB,
6183 llvm::next(MachineBasicBlock::iterator(MI)),
6185 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6187 const TargetRegisterClass *TRC = isThumb2 ?
6188 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6189 (const TargetRegisterClass*)&ARM::GPRRegClass;
6190 unsigned scratch = MRI.createVirtualRegister(TRC);
6191 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6195 // fallthrough --> loopMBB
6196 BB->addSuccessor(loopMBB);
6200 // (sign extend dest, if required)
6202 // cmov.cond scratch2, incr, dest
6203 // strex scratch, scratch2, ptr
6206 // fallthrough --> exitMBB
6208 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6209 if (ldrOpc == ARM::t2LDREX)
6211 AddDefaultPred(MIB);
6213 // Sign extend the value, if necessary.
6214 if (signExtend && extendOpc) {
6215 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6216 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6221 // Build compare and cmov instructions.
6222 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6223 .addReg(oldval).addReg(incr));
6224 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6225 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6227 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6228 if (strOpc == ARM::t2STREX)
6230 AddDefaultPred(MIB);
6231 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6232 .addReg(scratch).addImm(0));
6233 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6234 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6236 BB->addSuccessor(loopMBB);
6237 BB->addSuccessor(exitMBB);
6243 MI->eraseFromParent(); // The instruction is gone now.
6249 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6250 unsigned Op1, unsigned Op2,
6251 bool NeedsCarry, bool IsCmpxchg,
6252 bool IsMinMax, ARMCC::CondCodes CC) const {
6253 // This also handles ATOMIC_SWAP, indicated by Op1==0.
6254 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6256 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6257 MachineFunction *MF = BB->getParent();
6258 MachineFunction::iterator It = BB;
6261 unsigned destlo = MI->getOperand(0).getReg();
6262 unsigned desthi = MI->getOperand(1).getReg();
6263 unsigned ptr = MI->getOperand(2).getReg();
6264 unsigned vallo = MI->getOperand(3).getReg();
6265 unsigned valhi = MI->getOperand(4).getReg();
6266 DebugLoc dl = MI->getDebugLoc();
6267 bool isThumb2 = Subtarget->isThumb2();
6269 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6271 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6272 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6273 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6276 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6277 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6278 if (IsCmpxchg || IsMinMax)
6279 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6281 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6282 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6284 MF->insert(It, loopMBB);
6285 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6286 if (IsCmpxchg) MF->insert(It, cont2BB);
6287 MF->insert(It, exitMBB);
6289 // Transfer the remainder of BB and its successor edges to exitMBB.
6290 exitMBB->splice(exitMBB->begin(), BB,
6291 llvm::next(MachineBasicBlock::iterator(MI)),
6293 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6295 const TargetRegisterClass *TRC = isThumb2 ?
6296 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6297 (const TargetRegisterClass*)&ARM::GPRRegClass;
6298 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6302 // fallthrough --> loopMBB
6303 BB->addSuccessor(loopMBB);
6306 // ldrexd r2, r3, ptr
6307 // <binopa> r0, r2, incr
6308 // <binopb> r1, r3, incr
6309 // strexd storesuccess, r0, r1, ptr
6310 // cmp storesuccess, #0
6312 // fallthrough --> exitMBB
6317 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6318 .addReg(destlo, RegState::Define)
6319 .addReg(desthi, RegState::Define)
6322 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6323 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6324 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6325 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6326 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6327 .addReg(GPRPair0, 0, ARM::gsub_0);
6328 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6329 .addReg(GPRPair0, 0, ARM::gsub_1);
6332 unsigned StoreLo, StoreHi;
6335 for (unsigned i = 0; i < 2; i++) {
6336 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6338 .addReg(i == 0 ? destlo : desthi)
6339 .addReg(i == 0 ? vallo : valhi));
6340 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6341 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6342 BB->addSuccessor(exitMBB);
6343 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6344 BB = (i == 0 ? contBB : cont2BB);
6347 // Copy to physregs for strexd
6348 StoreLo = MI->getOperand(5).getReg();
6349 StoreHi = MI->getOperand(6).getReg();
6351 // Perform binary operation
6352 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6353 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6354 .addReg(destlo).addReg(vallo))
6355 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6356 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6357 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6358 .addReg(desthi).addReg(valhi))
6359 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6364 // Copy to physregs for strexd
6369 // Compare and branch to exit block.
6370 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6371 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6372 BB->addSuccessor(exitMBB);
6373 BB->addSuccessor(contBB);
6381 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6382 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6384 // Marshal a pair...
6385 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6386 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6387 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6388 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6389 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6392 .addImm(ARM::gsub_0);
6393 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6396 .addImm(ARM::gsub_1);
6399 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6400 .addReg(StorePair).addReg(ptr));
6403 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6404 .addReg(storesuccess).addImm(0));
6405 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6406 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6408 BB->addSuccessor(loopMBB);
6409 BB->addSuccessor(exitMBB);
6415 MI->eraseFromParent(); // The instruction is gone now.
6420 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6421 /// registers the function context.
6422 void ARMTargetLowering::
6423 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6424 MachineBasicBlock *DispatchBB, int FI) const {
6425 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6426 DebugLoc dl = MI->getDebugLoc();
6427 MachineFunction *MF = MBB->getParent();
6428 MachineRegisterInfo *MRI = &MF->getRegInfo();
6429 MachineConstantPool *MCP = MF->getConstantPool();
6430 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6431 const Function *F = MF->getFunction();
6433 bool isThumb = Subtarget->isThumb();
6434 bool isThumb2 = Subtarget->isThumb2();
6436 unsigned PCLabelId = AFI->createPICLabelUId();
6437 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6438 ARMConstantPoolValue *CPV =
6439 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6440 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6442 const TargetRegisterClass *TRC = isThumb ?
6443 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6444 (const TargetRegisterClass*)&ARM::GPRRegClass;
6446 // Grab constant pool and fixed stack memory operands.
6447 MachineMemOperand *CPMMO =
6448 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6449 MachineMemOperand::MOLoad, 4, 4);
6451 MachineMemOperand *FIMMOSt =
6452 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6453 MachineMemOperand::MOStore, 4, 4);
6455 // Load the address of the dispatch MBB into the jump buffer.
6457 // Incoming value: jbuf
6458 // ldr.n r5, LCPI1_1
6461 // str r5, [$jbuf, #+4] ; &jbuf[1]
6462 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6463 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6464 .addConstantPoolIndex(CPI)
6465 .addMemOperand(CPMMO));
6466 // Set the low bit because of thumb mode.
6467 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6469 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6470 .addReg(NewVReg1, RegState::Kill)
6472 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6473 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6474 .addReg(NewVReg2, RegState::Kill)
6476 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6477 .addReg(NewVReg3, RegState::Kill)
6479 .addImm(36) // &jbuf[1] :: pc
6480 .addMemOperand(FIMMOSt));
6481 } else if (isThumb) {
6482 // Incoming value: jbuf
6483 // ldr.n r1, LCPI1_4
6487 // add r2, $jbuf, #+4 ; &jbuf[1]
6489 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6490 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6491 .addConstantPoolIndex(CPI)
6492 .addMemOperand(CPMMO));
6493 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6494 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6495 .addReg(NewVReg1, RegState::Kill)
6497 // Set the low bit because of thumb mode.
6498 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6499 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6500 .addReg(ARM::CPSR, RegState::Define)
6502 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6503 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6504 .addReg(ARM::CPSR, RegState::Define)
6505 .addReg(NewVReg2, RegState::Kill)
6506 .addReg(NewVReg3, RegState::Kill));
6507 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6508 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6510 .addImm(36)); // &jbuf[1] :: pc
6511 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6512 .addReg(NewVReg4, RegState::Kill)
6513 .addReg(NewVReg5, RegState::Kill)
6515 .addMemOperand(FIMMOSt));
6517 // Incoming value: jbuf
6520 // str r1, [$jbuf, #+4] ; &jbuf[1]
6521 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6522 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6523 .addConstantPoolIndex(CPI)
6525 .addMemOperand(CPMMO));
6526 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6527 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6528 .addReg(NewVReg1, RegState::Kill)
6529 .addImm(PCLabelId));
6530 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6531 .addReg(NewVReg2, RegState::Kill)
6533 .addImm(36) // &jbuf[1] :: pc
6534 .addMemOperand(FIMMOSt));
6538 MachineBasicBlock *ARMTargetLowering::
6539 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6540 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6541 DebugLoc dl = MI->getDebugLoc();
6542 MachineFunction *MF = MBB->getParent();
6543 MachineRegisterInfo *MRI = &MF->getRegInfo();
6544 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6545 MachineFrameInfo *MFI = MF->getFrameInfo();
6546 int FI = MFI->getFunctionContextIndex();
6548 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6549 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6550 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6552 // Get a mapping of the call site numbers to all of the landing pads they're
6554 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6555 unsigned MaxCSNum = 0;
6556 MachineModuleInfo &MMI = MF->getMMI();
6557 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6559 if (!BB->isLandingPad()) continue;
6561 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6563 for (MachineBasicBlock::iterator
6564 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6565 if (!II->isEHLabel()) continue;
6567 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6568 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6570 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6571 for (SmallVectorImpl<unsigned>::iterator
6572 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6573 CSI != CSE; ++CSI) {
6574 CallSiteNumToLPad[*CSI].push_back(BB);
6575 MaxCSNum = std::max(MaxCSNum, *CSI);
6581 // Get an ordered list of the machine basic blocks for the jump table.
6582 std::vector<MachineBasicBlock*> LPadList;
6583 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6584 LPadList.reserve(CallSiteNumToLPad.size());
6585 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6586 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6587 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6588 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6589 LPadList.push_back(*II);
6590 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6594 assert(!LPadList.empty() &&
6595 "No landing pad destinations for the dispatch jump table!");
6597 // Create the jump table and associated information.
6598 MachineJumpTableInfo *JTI =
6599 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6600 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6601 unsigned UId = AFI->createJumpTableUId();
6602 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6604 // Create the MBBs for the dispatch code.
6606 // Shove the dispatch's address into the return slot in the function context.
6607 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6608 DispatchBB->setIsLandingPad();
6610 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6611 unsigned trap_opcode;
6612 if (Subtarget->isThumb())
6613 trap_opcode = ARM::tTRAP;
6615 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6617 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6618 DispatchBB->addSuccessor(TrapBB);
6620 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6621 DispatchBB->addSuccessor(DispContBB);
6624 MF->insert(MF->end(), DispatchBB);
6625 MF->insert(MF->end(), DispContBB);
6626 MF->insert(MF->end(), TrapBB);
6628 // Insert code into the entry block that creates and registers the function
6630 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6632 MachineMemOperand *FIMMOLd =
6633 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6634 MachineMemOperand::MOLoad |
6635 MachineMemOperand::MOVolatile, 4, 4);
6637 MachineInstrBuilder MIB;
6638 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6640 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6641 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6643 // Add a register mask with no preserved registers. This results in all
6644 // registers being marked as clobbered.
6645 MIB.addRegMask(RI.getNoPreservedMask());
6647 unsigned NumLPads = LPadList.size();
6648 if (Subtarget->isThumb2()) {
6649 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6650 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6653 .addMemOperand(FIMMOLd));
6655 if (NumLPads < 256) {
6656 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6658 .addImm(LPadList.size()));
6660 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6661 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6662 .addImm(NumLPads & 0xFFFF));
6664 unsigned VReg2 = VReg1;
6665 if ((NumLPads & 0xFFFF0000) != 0) {
6666 VReg2 = MRI->createVirtualRegister(TRC);
6667 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6669 .addImm(NumLPads >> 16));
6672 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6677 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6682 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6683 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6684 .addJumpTableIndex(MJTI)
6687 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6690 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6691 .addReg(NewVReg3, RegState::Kill)
6693 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6695 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6696 .addReg(NewVReg4, RegState::Kill)
6698 .addJumpTableIndex(MJTI)
6700 } else if (Subtarget->isThumb()) {
6701 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6702 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6705 .addMemOperand(FIMMOLd));
6707 if (NumLPads < 256) {
6708 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6712 MachineConstantPool *ConstantPool = MF->getConstantPool();
6713 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6714 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6716 // MachineConstantPool wants an explicit alignment.
6717 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6719 Align = getDataLayout()->getTypeAllocSize(C->getType());
6720 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6722 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6723 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6724 .addReg(VReg1, RegState::Define)
6725 .addConstantPoolIndex(Idx));
6726 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6731 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6736 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6737 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6738 .addReg(ARM::CPSR, RegState::Define)
6742 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6743 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6744 .addJumpTableIndex(MJTI)
6747 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6748 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6749 .addReg(ARM::CPSR, RegState::Define)
6750 .addReg(NewVReg2, RegState::Kill)
6753 MachineMemOperand *JTMMOLd =
6754 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6755 MachineMemOperand::MOLoad, 4, 4);
6757 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6758 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6759 .addReg(NewVReg4, RegState::Kill)
6761 .addMemOperand(JTMMOLd));
6763 unsigned NewVReg6 = NewVReg5;
6764 if (RelocM == Reloc::PIC_) {
6765 NewVReg6 = MRI->createVirtualRegister(TRC);
6766 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6767 .addReg(ARM::CPSR, RegState::Define)
6768 .addReg(NewVReg5, RegState::Kill)
6772 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6773 .addReg(NewVReg6, RegState::Kill)
6774 .addJumpTableIndex(MJTI)
6777 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6778 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6781 .addMemOperand(FIMMOLd));
6783 if (NumLPads < 256) {
6784 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6787 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6788 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6789 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6790 .addImm(NumLPads & 0xFFFF));
6792 unsigned VReg2 = VReg1;
6793 if ((NumLPads & 0xFFFF0000) != 0) {
6794 VReg2 = MRI->createVirtualRegister(TRC);
6795 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6797 .addImm(NumLPads >> 16));
6800 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6804 MachineConstantPool *ConstantPool = MF->getConstantPool();
6805 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6806 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6808 // MachineConstantPool wants an explicit alignment.
6809 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6811 Align = getDataLayout()->getTypeAllocSize(C->getType());
6812 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6814 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6815 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6816 .addReg(VReg1, RegState::Define)
6817 .addConstantPoolIndex(Idx)
6819 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6821 .addReg(VReg1, RegState::Kill));
6824 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6829 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6831 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6833 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6834 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6835 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6836 .addJumpTableIndex(MJTI)
6839 MachineMemOperand *JTMMOLd =
6840 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6841 MachineMemOperand::MOLoad, 4, 4);
6842 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6844 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6845 .addReg(NewVReg3, RegState::Kill)
6848 .addMemOperand(JTMMOLd));
6850 if (RelocM == Reloc::PIC_) {
6851 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6852 .addReg(NewVReg5, RegState::Kill)
6854 .addJumpTableIndex(MJTI)
6857 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6858 .addReg(NewVReg5, RegState::Kill)
6859 .addJumpTableIndex(MJTI)
6864 // Add the jump table entries as successors to the MBB.
6865 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6866 for (std::vector<MachineBasicBlock*>::iterator
6867 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6868 MachineBasicBlock *CurMBB = *I;
6869 if (SeenMBBs.insert(CurMBB))
6870 DispContBB->addSuccessor(CurMBB);
6873 // N.B. the order the invoke BBs are processed in doesn't matter here.
6874 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6875 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6876 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6877 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6878 MachineBasicBlock *BB = *I;
6880 // Remove the landing pad successor from the invoke block and replace it
6881 // with the new dispatch block.
6882 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6884 while (!Successors.empty()) {
6885 MachineBasicBlock *SMBB = Successors.pop_back_val();
6886 if (SMBB->isLandingPad()) {
6887 BB->removeSuccessor(SMBB);
6888 MBBLPads.push_back(SMBB);
6892 BB->addSuccessor(DispatchBB);
6894 // Find the invoke call and mark all of the callee-saved registers as
6895 // 'implicit defined' so that they're spilled. This prevents code from
6896 // moving instructions to before the EH block, where they will never be
6898 for (MachineBasicBlock::reverse_iterator
6899 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6900 if (!II->isCall()) continue;
6902 DenseMap<unsigned, bool> DefRegs;
6903 for (MachineInstr::mop_iterator
6904 OI = II->operands_begin(), OE = II->operands_end();
6906 if (!OI->isReg()) continue;
6907 DefRegs[OI->getReg()] = true;
6910 MachineInstrBuilder MIB(*MF, &*II);
6912 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6913 unsigned Reg = SavedRegs[i];
6914 if (Subtarget->isThumb2() &&
6915 !ARM::tGPRRegClass.contains(Reg) &&
6916 !ARM::hGPRRegClass.contains(Reg))
6918 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6920 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6923 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6930 // Mark all former landing pads as non-landing pads. The dispatch is the only
6932 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6933 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6934 (*I)->setIsLandingPad(false);
6936 // The instruction is gone now.
6937 MI->eraseFromParent();
6943 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6944 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6945 E = MBB->succ_end(); I != E; ++I)
6948 llvm_unreachable("Expecting a BB with two successors!");
6951 MachineBasicBlock *ARMTargetLowering::
6952 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6953 // This pseudo instruction has 3 operands: dst, src, size
6954 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6955 // Otherwise, we will generate unrolled scalar copies.
6956 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6957 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6958 MachineFunction::iterator It = BB;
6961 unsigned dest = MI->getOperand(0).getReg();
6962 unsigned src = MI->getOperand(1).getReg();
6963 unsigned SizeVal = MI->getOperand(2).getImm();
6964 unsigned Align = MI->getOperand(3).getImm();
6965 DebugLoc dl = MI->getDebugLoc();
6967 bool isThumb2 = Subtarget->isThumb2();
6968 MachineFunction *MF = BB->getParent();
6969 MachineRegisterInfo &MRI = MF->getRegInfo();
6970 unsigned ldrOpc, strOpc, UnitSize = 0;
6972 const TargetRegisterClass *TRC = isThumb2 ?
6973 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6974 (const TargetRegisterClass*)&ARM::GPRRegClass;
6975 const TargetRegisterClass *TRC_Vec = 0;
6978 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6979 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6981 } else if (Align & 2) {
6982 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6983 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6986 // Check whether we can use NEON instructions.
6987 if (!MF->getFunction()->getAttributes().
6988 hasAttribute(AttributeSet::FunctionIndex,
6989 Attribute::NoImplicitFloat) &&
6990 Subtarget->hasNEON()) {
6991 if ((Align % 16 == 0) && SizeVal >= 16) {
6992 ldrOpc = ARM::VLD1q32wb_fixed;
6993 strOpc = ARM::VST1q32wb_fixed;
6995 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6997 else if ((Align % 8 == 0) && SizeVal >= 8) {
6998 ldrOpc = ARM::VLD1d32wb_fixed;
6999 strOpc = ARM::VST1d32wb_fixed;
7001 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
7004 // Can't use NEON instructions.
7005 if (UnitSize == 0) {
7006 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
7007 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
7012 unsigned BytesLeft = SizeVal % UnitSize;
7013 unsigned LoopSize = SizeVal - BytesLeft;
7015 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7016 // Use LDR and STR to copy.
7017 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7018 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7019 unsigned srcIn = src;
7020 unsigned destIn = dest;
7021 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7022 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7023 unsigned srcOut = MRI.createVirtualRegister(TRC);
7024 unsigned destOut = MRI.createVirtualRegister(TRC);
7025 if (UnitSize >= 8) {
7026 AddDefaultPred(BuildMI(*BB, MI, dl,
7027 TII->get(ldrOpc), scratch)
7028 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7030 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7031 .addReg(destIn).addImm(0).addReg(scratch));
7032 } else if (isThumb2) {
7033 AddDefaultPred(BuildMI(*BB, MI, dl,
7034 TII->get(ldrOpc), scratch)
7035 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7037 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7038 .addReg(scratch).addReg(destIn)
7041 AddDefaultPred(BuildMI(*BB, MI, dl,
7042 TII->get(ldrOpc), scratch)
7043 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7046 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7047 .addReg(scratch).addReg(destIn)
7048 .addReg(0).addImm(UnitSize));
7054 // Handle the leftover bytes with LDRB and STRB.
7055 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7056 // [destOut] = STRB_POST(scratch, destIn, 1)
7057 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7058 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7059 for (unsigned i = 0; i < BytesLeft; i++) {
7060 unsigned scratch = MRI.createVirtualRegister(TRC);
7061 unsigned srcOut = MRI.createVirtualRegister(TRC);
7062 unsigned destOut = MRI.createVirtualRegister(TRC);
7064 AddDefaultPred(BuildMI(*BB, MI, dl,
7065 TII->get(ldrOpc),scratch)
7066 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7068 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7069 .addReg(scratch).addReg(destIn)
7070 .addReg(0).addImm(1));
7072 AddDefaultPred(BuildMI(*BB, MI, dl,
7073 TII->get(ldrOpc),scratch)
7074 .addReg(srcOut, RegState::Define).addReg(srcIn)
7075 .addReg(0).addImm(1));
7077 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7078 .addReg(scratch).addReg(destIn)
7079 .addReg(0).addImm(1));
7084 MI->eraseFromParent(); // The instruction is gone now.
7088 // Expand the pseudo op to a loop.
7091 // movw varEnd, # --> with thumb2
7093 // ldrcp varEnd, idx --> without thumb2
7094 // fallthrough --> loopMBB
7096 // PHI varPhi, varEnd, varLoop
7097 // PHI srcPhi, src, srcLoop
7098 // PHI destPhi, dst, destLoop
7099 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7100 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7101 // subs varLoop, varPhi, #UnitSize
7103 // fallthrough --> exitMBB
7105 // epilogue to handle left-over bytes
7106 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7107 // [destOut] = STRB_POST(scratch, destLoop, 1)
7108 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7109 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7110 MF->insert(It, loopMBB);
7111 MF->insert(It, exitMBB);
7113 // Transfer the remainder of BB and its successor edges to exitMBB.
7114 exitMBB->splice(exitMBB->begin(), BB,
7115 llvm::next(MachineBasicBlock::iterator(MI)),
7117 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7119 // Load an immediate to varEnd.
7120 unsigned varEnd = MRI.createVirtualRegister(TRC);
7122 unsigned VReg1 = varEnd;
7123 if ((LoopSize & 0xFFFF0000) != 0)
7124 VReg1 = MRI.createVirtualRegister(TRC);
7125 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7126 .addImm(LoopSize & 0xFFFF));
7128 if ((LoopSize & 0xFFFF0000) != 0)
7129 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7131 .addImm(LoopSize >> 16));
7133 MachineConstantPool *ConstantPool = MF->getConstantPool();
7134 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7135 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7137 // MachineConstantPool wants an explicit alignment.
7138 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7140 Align = getDataLayout()->getTypeAllocSize(C->getType());
7141 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7143 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7144 .addReg(varEnd, RegState::Define)
7145 .addConstantPoolIndex(Idx)
7148 BB->addSuccessor(loopMBB);
7150 // Generate the loop body:
7151 // varPhi = PHI(varLoop, varEnd)
7152 // srcPhi = PHI(srcLoop, src)
7153 // destPhi = PHI(destLoop, dst)
7154 MachineBasicBlock *entryBB = BB;
7156 unsigned varLoop = MRI.createVirtualRegister(TRC);
7157 unsigned varPhi = MRI.createVirtualRegister(TRC);
7158 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7159 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7160 unsigned destLoop = MRI.createVirtualRegister(TRC);
7161 unsigned destPhi = MRI.createVirtualRegister(TRC);
7163 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7164 .addReg(varLoop).addMBB(loopMBB)
7165 .addReg(varEnd).addMBB(entryBB);
7166 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7167 .addReg(srcLoop).addMBB(loopMBB)
7168 .addReg(src).addMBB(entryBB);
7169 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7170 .addReg(destLoop).addMBB(loopMBB)
7171 .addReg(dest).addMBB(entryBB);
7173 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7174 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7175 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7176 if (UnitSize >= 8) {
7177 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7178 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7180 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7181 .addReg(destPhi).addImm(0).addReg(scratch));
7182 } else if (isThumb2) {
7183 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7184 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7186 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7187 .addReg(scratch).addReg(destPhi)
7190 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7191 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7194 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7195 .addReg(scratch).addReg(destPhi)
7196 .addReg(0).addImm(UnitSize));
7199 // Decrement loop variable by UnitSize.
7200 MachineInstrBuilder MIB = BuildMI(BB, dl,
7201 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7202 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7203 MIB->getOperand(5).setReg(ARM::CPSR);
7204 MIB->getOperand(5).setIsDef(true);
7206 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7207 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7209 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7210 BB->addSuccessor(loopMBB);
7211 BB->addSuccessor(exitMBB);
7213 // Add epilogue to handle BytesLeft.
7215 MachineInstr *StartOfExit = exitMBB->begin();
7216 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7217 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7219 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7220 // [destOut] = STRB_POST(scratch, destLoop, 1)
7221 unsigned srcIn = srcLoop;
7222 unsigned destIn = destLoop;
7223 for (unsigned i = 0; i < BytesLeft; i++) {
7224 unsigned scratch = MRI.createVirtualRegister(TRC);
7225 unsigned srcOut = MRI.createVirtualRegister(TRC);
7226 unsigned destOut = MRI.createVirtualRegister(TRC);
7228 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7229 TII->get(ldrOpc),scratch)
7230 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7232 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7233 .addReg(scratch).addReg(destIn)
7236 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7237 TII->get(ldrOpc),scratch)
7238 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7240 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7241 .addReg(scratch).addReg(destIn)
7242 .addReg(0).addImm(1));
7248 MI->eraseFromParent(); // The instruction is gone now.
7253 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7254 MachineBasicBlock *BB) const {
7255 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7256 DebugLoc dl = MI->getDebugLoc();
7257 bool isThumb2 = Subtarget->isThumb2();
7258 switch (MI->getOpcode()) {
7261 llvm_unreachable("Unexpected instr type to insert");
7263 // The Thumb2 pre-indexed stores have the same MI operands, they just
7264 // define them differently in the .td files from the isel patterns, so
7265 // they need pseudos.
7266 case ARM::t2STR_preidx:
7267 MI->setDesc(TII->get(ARM::t2STR_PRE));
7269 case ARM::t2STRB_preidx:
7270 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7272 case ARM::t2STRH_preidx:
7273 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7276 case ARM::STRi_preidx:
7277 case ARM::STRBi_preidx: {
7278 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7279 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7280 // Decode the offset.
7281 unsigned Offset = MI->getOperand(4).getImm();
7282 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7283 Offset = ARM_AM::getAM2Offset(Offset);
7287 MachineMemOperand *MMO = *MI->memoperands_begin();
7288 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7289 .addOperand(MI->getOperand(0)) // Rn_wb
7290 .addOperand(MI->getOperand(1)) // Rt
7291 .addOperand(MI->getOperand(2)) // Rn
7292 .addImm(Offset) // offset (skip GPR==zero_reg)
7293 .addOperand(MI->getOperand(5)) // pred
7294 .addOperand(MI->getOperand(6))
7295 .addMemOperand(MMO);
7296 MI->eraseFromParent();
7299 case ARM::STRr_preidx:
7300 case ARM::STRBr_preidx:
7301 case ARM::STRH_preidx: {
7303 switch (MI->getOpcode()) {
7304 default: llvm_unreachable("unexpected opcode!");
7305 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7306 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7307 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7309 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7310 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7311 MIB.addOperand(MI->getOperand(i));
7312 MI->eraseFromParent();
7315 case ARM::ATOMIC_LOAD_ADD_I8:
7316 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7317 case ARM::ATOMIC_LOAD_ADD_I16:
7318 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7319 case ARM::ATOMIC_LOAD_ADD_I32:
7320 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7322 case ARM::ATOMIC_LOAD_AND_I8:
7323 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7324 case ARM::ATOMIC_LOAD_AND_I16:
7325 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7326 case ARM::ATOMIC_LOAD_AND_I32:
7327 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7329 case ARM::ATOMIC_LOAD_OR_I8:
7330 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7331 case ARM::ATOMIC_LOAD_OR_I16:
7332 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7333 case ARM::ATOMIC_LOAD_OR_I32:
7334 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7336 case ARM::ATOMIC_LOAD_XOR_I8:
7337 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7338 case ARM::ATOMIC_LOAD_XOR_I16:
7339 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7340 case ARM::ATOMIC_LOAD_XOR_I32:
7341 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7343 case ARM::ATOMIC_LOAD_NAND_I8:
7344 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7345 case ARM::ATOMIC_LOAD_NAND_I16:
7346 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7347 case ARM::ATOMIC_LOAD_NAND_I32:
7348 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7350 case ARM::ATOMIC_LOAD_SUB_I8:
7351 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7352 case ARM::ATOMIC_LOAD_SUB_I16:
7353 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7354 case ARM::ATOMIC_LOAD_SUB_I32:
7355 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7357 case ARM::ATOMIC_LOAD_MIN_I8:
7358 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7359 case ARM::ATOMIC_LOAD_MIN_I16:
7360 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7361 case ARM::ATOMIC_LOAD_MIN_I32:
7362 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7364 case ARM::ATOMIC_LOAD_MAX_I8:
7365 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7366 case ARM::ATOMIC_LOAD_MAX_I16:
7367 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7368 case ARM::ATOMIC_LOAD_MAX_I32:
7369 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7371 case ARM::ATOMIC_LOAD_UMIN_I8:
7372 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7373 case ARM::ATOMIC_LOAD_UMIN_I16:
7374 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7375 case ARM::ATOMIC_LOAD_UMIN_I32:
7376 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7378 case ARM::ATOMIC_LOAD_UMAX_I8:
7379 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7380 case ARM::ATOMIC_LOAD_UMAX_I16:
7381 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7382 case ARM::ATOMIC_LOAD_UMAX_I32:
7383 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7385 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7386 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7387 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7389 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7390 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7391 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7394 case ARM::ATOMADD6432:
7395 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7396 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7397 /*NeedsCarry*/ true);
7398 case ARM::ATOMSUB6432:
7399 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7400 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7401 /*NeedsCarry*/ true);
7402 case ARM::ATOMOR6432:
7403 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7404 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7405 case ARM::ATOMXOR6432:
7406 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7407 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7408 case ARM::ATOMAND6432:
7409 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7410 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7411 case ARM::ATOMSWAP6432:
7412 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7413 case ARM::ATOMCMPXCHG6432:
7414 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7415 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7416 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7417 case ARM::ATOMMIN6432:
7418 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7419 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7420 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7421 /*IsMinMax*/ true, ARMCC::LT);
7422 case ARM::ATOMMAX6432:
7423 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7424 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7425 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7426 /*IsMinMax*/ true, ARMCC::GE);
7427 case ARM::ATOMUMIN6432:
7428 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7429 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7430 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7431 /*IsMinMax*/ true, ARMCC::LO);
7432 case ARM::ATOMUMAX6432:
7433 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7434 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7435 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7436 /*IsMinMax*/ true, ARMCC::HS);
7438 case ARM::tMOVCCr_pseudo: {
7439 // To "insert" a SELECT_CC instruction, we actually have to insert the
7440 // diamond control-flow pattern. The incoming instruction knows the
7441 // destination vreg to set, the condition code register to branch on, the
7442 // true/false values to select between, and a branch opcode to use.
7443 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7444 MachineFunction::iterator It = BB;
7450 // cmpTY ccX, r1, r2
7452 // fallthrough --> copy0MBB
7453 MachineBasicBlock *thisMBB = BB;
7454 MachineFunction *F = BB->getParent();
7455 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7456 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7457 F->insert(It, copy0MBB);
7458 F->insert(It, sinkMBB);
7460 // Transfer the remainder of BB and its successor edges to sinkMBB.
7461 sinkMBB->splice(sinkMBB->begin(), BB,
7462 llvm::next(MachineBasicBlock::iterator(MI)),
7464 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7466 BB->addSuccessor(copy0MBB);
7467 BB->addSuccessor(sinkMBB);
7469 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7470 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7473 // %FalseValue = ...
7474 // # fallthrough to sinkMBB
7477 // Update machine-CFG edges
7478 BB->addSuccessor(sinkMBB);
7481 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7484 BuildMI(*BB, BB->begin(), dl,
7485 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7486 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7487 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7489 MI->eraseFromParent(); // The pseudo instruction is gone now.
7494 case ARM::BCCZi64: {
7495 // If there is an unconditional branch to the other successor, remove it.
7496 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7498 // Compare both parts that make up the double comparison separately for
7500 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7502 unsigned LHS1 = MI->getOperand(1).getReg();
7503 unsigned LHS2 = MI->getOperand(2).getReg();
7505 AddDefaultPred(BuildMI(BB, dl,
7506 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7507 .addReg(LHS1).addImm(0));
7508 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7509 .addReg(LHS2).addImm(0)
7510 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7512 unsigned RHS1 = MI->getOperand(3).getReg();
7513 unsigned RHS2 = MI->getOperand(4).getReg();
7514 AddDefaultPred(BuildMI(BB, dl,
7515 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7516 .addReg(LHS1).addReg(RHS1));
7517 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7518 .addReg(LHS2).addReg(RHS2)
7519 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7522 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7523 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7524 if (MI->getOperand(0).getImm() == ARMCC::NE)
7525 std::swap(destMBB, exitMBB);
7527 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7528 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7530 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7532 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7534 MI->eraseFromParent(); // The pseudo instruction is gone now.
7538 case ARM::Int_eh_sjlj_setjmp:
7539 case ARM::Int_eh_sjlj_setjmp_nofp:
7540 case ARM::tInt_eh_sjlj_setjmp:
7541 case ARM::t2Int_eh_sjlj_setjmp:
7542 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7543 EmitSjLjDispatchBlock(MI, BB);
7548 // To insert an ABS instruction, we have to insert the
7549 // diamond control-flow pattern. The incoming instruction knows the
7550 // source vreg to test against 0, the destination vreg to set,
7551 // the condition code register to branch on, the
7552 // true/false values to select between, and a branch opcode to use.
7557 // BCC (branch to SinkBB if V0 >= 0)
7558 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7559 // SinkBB: V1 = PHI(V2, V3)
7560 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7561 MachineFunction::iterator BBI = BB;
7563 MachineFunction *Fn = BB->getParent();
7564 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7565 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7566 Fn->insert(BBI, RSBBB);
7567 Fn->insert(BBI, SinkBB);
7569 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7570 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7571 bool isThumb2 = Subtarget->isThumb2();
7572 MachineRegisterInfo &MRI = Fn->getRegInfo();
7573 // In Thumb mode S must not be specified if source register is the SP or
7574 // PC and if destination register is the SP, so restrict register class
7575 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7576 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7577 (const TargetRegisterClass*)&ARM::GPRRegClass);
7579 // Transfer the remainder of BB and its successor edges to sinkMBB.
7580 SinkBB->splice(SinkBB->begin(), BB,
7581 llvm::next(MachineBasicBlock::iterator(MI)),
7583 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7585 BB->addSuccessor(RSBBB);
7586 BB->addSuccessor(SinkBB);
7588 // fall through to SinkMBB
7589 RSBBB->addSuccessor(SinkBB);
7591 // insert a cmp at the end of BB
7592 AddDefaultPred(BuildMI(BB, dl,
7593 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7594 .addReg(ABSSrcReg).addImm(0));
7596 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7598 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7599 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7601 // insert rsbri in RSBBB
7602 // Note: BCC and rsbri will be converted into predicated rsbmi
7603 // by if-conversion pass
7604 BuildMI(*RSBBB, RSBBB->begin(), dl,
7605 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7606 .addReg(ABSSrcReg, RegState::Kill)
7607 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7609 // insert PHI in SinkBB,
7610 // reuse ABSDstReg to not change uses of ABS instruction
7611 BuildMI(*SinkBB, SinkBB->begin(), dl,
7612 TII->get(ARM::PHI), ABSDstReg)
7613 .addReg(NewRsbDstReg).addMBB(RSBBB)
7614 .addReg(ABSSrcReg).addMBB(BB);
7616 // remove ABS instruction
7617 MI->eraseFromParent();
7619 // return last added BB
7622 case ARM::COPY_STRUCT_BYVAL_I32:
7624 return EmitStructByval(MI, BB);
7628 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7629 SDNode *Node) const {
7630 if (!MI->hasPostISelHook()) {
7631 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7632 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7636 const MCInstrDesc *MCID = &MI->getDesc();
7637 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7638 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7639 // operand is still set to noreg. If needed, set the optional operand's
7640 // register to CPSR, and remove the redundant implicit def.
7642 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7644 // Rename pseudo opcodes.
7645 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7647 const ARMBaseInstrInfo *TII =
7648 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7649 MCID = &TII->get(NewOpc);
7651 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7652 "converted opcode should be the same except for cc_out");
7656 // Add the optional cc_out operand
7657 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7659 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7661 // Any ARM instruction that sets the 's' bit should specify an optional
7662 // "cc_out" operand in the last operand position.
7663 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7664 assert(!NewOpc && "Optional cc_out operand required");
7667 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7668 // since we already have an optional CPSR def.
7669 bool definesCPSR = false;
7670 bool deadCPSR = false;
7671 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7673 const MachineOperand &MO = MI->getOperand(i);
7674 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7678 MI->RemoveOperand(i);
7683 assert(!NewOpc && "Optional cc_out operand required");
7686 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7688 assert(!MI->getOperand(ccOutIdx).getReg() &&
7689 "expect uninitialized optional cc_out operand");
7693 // If this instruction was defined with an optional CPSR def and its dag node
7694 // had a live implicit CPSR def, then activate the optional CPSR def.
7695 MachineOperand &MO = MI->getOperand(ccOutIdx);
7696 MO.setReg(ARM::CPSR);
7700 //===----------------------------------------------------------------------===//
7701 // ARM Optimization Hooks
7702 //===----------------------------------------------------------------------===//
7704 // Helper function that checks if N is a null or all ones constant.
7705 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7706 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7709 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7712 // Return true if N is conditionally 0 or all ones.
7713 // Detects these expressions where cc is an i1 value:
7715 // (select cc 0, y) [AllOnes=0]
7716 // (select cc y, 0) [AllOnes=0]
7717 // (zext cc) [AllOnes=0]
7718 // (sext cc) [AllOnes=0/1]
7719 // (select cc -1, y) [AllOnes=1]
7720 // (select cc y, -1) [AllOnes=1]
7722 // Invert is set when N is the null/all ones constant when CC is false.
7723 // OtherOp is set to the alternative value of N.
7724 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7725 SDValue &CC, bool &Invert,
7727 SelectionDAG &DAG) {
7728 switch (N->getOpcode()) {
7729 default: return false;
7731 CC = N->getOperand(0);
7732 SDValue N1 = N->getOperand(1);
7733 SDValue N2 = N->getOperand(2);
7734 if (isZeroOrAllOnes(N1, AllOnes)) {
7739 if (isZeroOrAllOnes(N2, AllOnes)) {
7746 case ISD::ZERO_EXTEND:
7747 // (zext cc) can never be the all ones value.
7751 case ISD::SIGN_EXTEND: {
7752 EVT VT = N->getValueType(0);
7753 CC = N->getOperand(0);
7754 if (CC.getValueType() != MVT::i1)
7758 // When looking for an AllOnes constant, N is an sext, and the 'other'
7760 OtherOp = DAG.getConstant(0, VT);
7761 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7762 // When looking for a 0 constant, N can be zext or sext.
7763 OtherOp = DAG.getConstant(1, VT);
7765 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7771 // Combine a constant select operand into its use:
7773 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7774 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7775 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7776 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7777 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7779 // The transform is rejected if the select doesn't have a constant operand that
7780 // is null, or all ones when AllOnes is set.
7782 // Also recognize sext/zext from i1:
7784 // (add (zext cc), x) -> (select cc (add x, 1), x)
7785 // (add (sext cc), x) -> (select cc (add x, -1), x)
7787 // These transformations eventually create predicated instructions.
7789 // @param N The node to transform.
7790 // @param Slct The N operand that is a select.
7791 // @param OtherOp The other N operand (x above).
7792 // @param DCI Context.
7793 // @param AllOnes Require the select constant to be all ones instead of null.
7794 // @returns The new node, or SDValue() on failure.
7796 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7797 TargetLowering::DAGCombinerInfo &DCI,
7798 bool AllOnes = false) {
7799 SelectionDAG &DAG = DCI.DAG;
7800 EVT VT = N->getValueType(0);
7801 SDValue NonConstantVal;
7804 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7805 NonConstantVal, DAG))
7808 // Slct is now know to be the desired identity constant when CC is true.
7809 SDValue TrueVal = OtherOp;
7810 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7811 OtherOp, NonConstantVal);
7812 // Unless SwapSelectOps says CC should be false.
7814 std::swap(TrueVal, FalseVal);
7816 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7817 CCOp, TrueVal, FalseVal);
7820 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7822 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7823 TargetLowering::DAGCombinerInfo &DCI) {
7824 SDValue N0 = N->getOperand(0);
7825 SDValue N1 = N->getOperand(1);
7826 if (N0.getNode()->hasOneUse()) {
7827 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7828 if (Result.getNode())
7831 if (N1.getNode()->hasOneUse()) {
7832 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7833 if (Result.getNode())
7839 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7840 // (only after legalization).
7841 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7842 TargetLowering::DAGCombinerInfo &DCI,
7843 const ARMSubtarget *Subtarget) {
7845 // Only perform optimization if after legalize, and if NEON is available. We
7846 // also expected both operands to be BUILD_VECTORs.
7847 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7848 || N0.getOpcode() != ISD::BUILD_VECTOR
7849 || N1.getOpcode() != ISD::BUILD_VECTOR)
7852 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7853 EVT VT = N->getValueType(0);
7854 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7857 // Check that the vector operands are of the right form.
7858 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7859 // operands, where N is the size of the formed vector.
7860 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7861 // index such that we have a pair wise add pattern.
7863 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7864 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7866 SDValue Vec = N0->getOperand(0)->getOperand(0);
7867 SDNode *V = Vec.getNode();
7868 unsigned nextIndex = 0;
7870 // For each operands to the ADD which are BUILD_VECTORs,
7871 // check to see if each of their operands are an EXTRACT_VECTOR with
7872 // the same vector and appropriate index.
7873 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7874 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7875 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7877 SDValue ExtVec0 = N0->getOperand(i);
7878 SDValue ExtVec1 = N1->getOperand(i);
7880 // First operand is the vector, verify its the same.
7881 if (V != ExtVec0->getOperand(0).getNode() ||
7882 V != ExtVec1->getOperand(0).getNode())
7885 // Second is the constant, verify its correct.
7886 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7887 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7889 // For the constant, we want to see all the even or all the odd.
7890 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7891 || C1->getZExtValue() != nextIndex+1)
7900 // Create VPADDL node.
7901 SelectionDAG &DAG = DCI.DAG;
7902 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7904 // Build operand list.
7905 SmallVector<SDValue, 8> Ops;
7906 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7907 TLI.getPointerTy()));
7909 // Input is the vector.
7912 // Get widened type and narrowed type.
7914 unsigned numElem = VT.getVectorNumElements();
7915 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7916 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7917 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7918 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7920 llvm_unreachable("Invalid vector element type for padd optimization.");
7923 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
7924 widenType, &Ops[0], Ops.size());
7925 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
7928 static SDValue findMUL_LOHI(SDValue V) {
7929 if (V->getOpcode() == ISD::UMUL_LOHI ||
7930 V->getOpcode() == ISD::SMUL_LOHI)
7935 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7936 TargetLowering::DAGCombinerInfo &DCI,
7937 const ARMSubtarget *Subtarget) {
7939 if (Subtarget->isThumb1Only()) return SDValue();
7941 // Only perform the checks after legalize when the pattern is available.
7942 if (DCI.isBeforeLegalize()) return SDValue();
7944 // Look for multiply add opportunities.
7945 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7946 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7947 // a glue link from the first add to the second add.
7948 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7949 // a S/UMLAL instruction.
7952 // \ / \ [no multiline comment]
7958 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7959 SDValue AddcOp0 = AddcNode->getOperand(0);
7960 SDValue AddcOp1 = AddcNode->getOperand(1);
7962 // Check if the two operands are from the same mul_lohi node.
7963 if (AddcOp0.getNode() == AddcOp1.getNode())
7966 assert(AddcNode->getNumValues() == 2 &&
7967 AddcNode->getValueType(0) == MVT::i32 &&
7968 "Expect ADDC with two result values. First: i32");
7970 // Check that we have a glued ADDC node.
7971 if (AddcNode->getValueType(1) != MVT::Glue)
7974 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7975 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7976 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7977 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7978 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7981 // Look for the glued ADDE.
7982 SDNode* AddeNode = AddcNode->getGluedUser();
7983 if (AddeNode == NULL)
7986 // Make sure it is really an ADDE.
7987 if (AddeNode->getOpcode() != ISD::ADDE)
7990 assert(AddeNode->getNumOperands() == 3 &&
7991 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7992 "ADDE node has the wrong inputs");
7994 // Check for the triangle shape.
7995 SDValue AddeOp0 = AddeNode->getOperand(0);
7996 SDValue AddeOp1 = AddeNode->getOperand(1);
7998 // Make sure that the ADDE operands are not coming from the same node.
7999 if (AddeOp0.getNode() == AddeOp1.getNode())
8002 // Find the MUL_LOHI node walking up ADDE's operands.
8003 bool IsLeftOperandMUL = false;
8004 SDValue MULOp = findMUL_LOHI(AddeOp0);
8005 if (MULOp == SDValue())
8006 MULOp = findMUL_LOHI(AddeOp1);
8008 IsLeftOperandMUL = true;
8009 if (MULOp == SDValue())
8012 // Figure out the right opcode.
8013 unsigned Opc = MULOp->getOpcode();
8014 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8016 // Figure out the high and low input values to the MLAL node.
8017 SDValue* HiMul = &MULOp;
8018 SDValue* HiAdd = NULL;
8019 SDValue* LoMul = NULL;
8020 SDValue* LowAdd = NULL;
8022 if (IsLeftOperandMUL)
8028 if (AddcOp0->getOpcode() == Opc) {
8032 if (AddcOp1->getOpcode() == Opc) {
8040 if (LoMul->getNode() != HiMul->getNode())
8043 // Create the merged node.
8044 SelectionDAG &DAG = DCI.DAG;
8046 // Build operand list.
8047 SmallVector<SDValue, 8> Ops;
8048 Ops.push_back(LoMul->getOperand(0));
8049 Ops.push_back(LoMul->getOperand(1));
8050 Ops.push_back(*LowAdd);
8051 Ops.push_back(*HiAdd);
8053 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8054 DAG.getVTList(MVT::i32, MVT::i32),
8055 &Ops[0], Ops.size());
8057 // Replace the ADDs' nodes uses by the MLA node's values.
8058 SDValue HiMLALResult(MLALNode.getNode(), 1);
8059 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8061 SDValue LoMLALResult(MLALNode.getNode(), 0);
8062 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8064 // Return original node to notify the driver to stop replacing.
8065 SDValue resNode(AddcNode, 0);
8069 /// PerformADDCCombine - Target-specific dag combine transform from
8070 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8071 static SDValue PerformADDCCombine(SDNode *N,
8072 TargetLowering::DAGCombinerInfo &DCI,
8073 const ARMSubtarget *Subtarget) {
8075 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8079 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8080 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8081 /// called with the default operands, and if that fails, with commuted
8083 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8084 TargetLowering::DAGCombinerInfo &DCI,
8085 const ARMSubtarget *Subtarget){
8087 // Attempt to create vpaddl for this add.
8088 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8089 if (Result.getNode())
8092 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8093 if (N0.getNode()->hasOneUse()) {
8094 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8095 if (Result.getNode()) return Result;
8100 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8102 static SDValue PerformADDCombine(SDNode *N,
8103 TargetLowering::DAGCombinerInfo &DCI,
8104 const ARMSubtarget *Subtarget) {
8105 SDValue N0 = N->getOperand(0);
8106 SDValue N1 = N->getOperand(1);
8108 // First try with the default operand order.
8109 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8110 if (Result.getNode())
8113 // If that didn't work, try again with the operands commuted.
8114 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8117 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8119 static SDValue PerformSUBCombine(SDNode *N,
8120 TargetLowering::DAGCombinerInfo &DCI) {
8121 SDValue N0 = N->getOperand(0);
8122 SDValue N1 = N->getOperand(1);
8124 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8125 if (N1.getNode()->hasOneUse()) {
8126 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8127 if (Result.getNode()) return Result;
8133 /// PerformVMULCombine
8134 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8135 /// special multiplier accumulator forwarding.
8141 static SDValue PerformVMULCombine(SDNode *N,
8142 TargetLowering::DAGCombinerInfo &DCI,
8143 const ARMSubtarget *Subtarget) {
8144 if (!Subtarget->hasVMLxForwarding())
8147 SelectionDAG &DAG = DCI.DAG;
8148 SDValue N0 = N->getOperand(0);
8149 SDValue N1 = N->getOperand(1);
8150 unsigned Opcode = N0.getOpcode();
8151 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8152 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8153 Opcode = N1.getOpcode();
8154 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8155 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8160 EVT VT = N->getValueType(0);
8162 SDValue N00 = N0->getOperand(0);
8163 SDValue N01 = N0->getOperand(1);
8164 return DAG.getNode(Opcode, DL, VT,
8165 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8166 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8169 static SDValue PerformMULCombine(SDNode *N,
8170 TargetLowering::DAGCombinerInfo &DCI,
8171 const ARMSubtarget *Subtarget) {
8172 SelectionDAG &DAG = DCI.DAG;
8174 if (Subtarget->isThumb1Only())
8177 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8180 EVT VT = N->getValueType(0);
8181 if (VT.is64BitVector() || VT.is128BitVector())
8182 return PerformVMULCombine(N, DCI, Subtarget);
8186 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8190 int64_t MulAmt = C->getSExtValue();
8191 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8193 ShiftAmt = ShiftAmt & (32 - 1);
8194 SDValue V = N->getOperand(0);
8198 MulAmt >>= ShiftAmt;
8201 if (isPowerOf2_32(MulAmt - 1)) {
8202 // (mul x, 2^N + 1) => (add (shl x, N), x)
8203 Res = DAG.getNode(ISD::ADD, DL, VT,
8205 DAG.getNode(ISD::SHL, DL, VT,
8207 DAG.getConstant(Log2_32(MulAmt - 1),
8209 } else if (isPowerOf2_32(MulAmt + 1)) {
8210 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8211 Res = DAG.getNode(ISD::SUB, DL, VT,
8212 DAG.getNode(ISD::SHL, DL, VT,
8214 DAG.getConstant(Log2_32(MulAmt + 1),
8220 uint64_t MulAmtAbs = -MulAmt;
8221 if (isPowerOf2_32(MulAmtAbs + 1)) {
8222 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8223 Res = DAG.getNode(ISD::SUB, DL, VT,
8225 DAG.getNode(ISD::SHL, DL, VT,
8227 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8229 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8230 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8231 Res = DAG.getNode(ISD::ADD, DL, VT,
8233 DAG.getNode(ISD::SHL, DL, VT,
8235 DAG.getConstant(Log2_32(MulAmtAbs-1),
8237 Res = DAG.getNode(ISD::SUB, DL, VT,
8238 DAG.getConstant(0, MVT::i32),Res);
8245 Res = DAG.getNode(ISD::SHL, DL, VT,
8246 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8248 // Do not add new nodes to DAG combiner worklist.
8249 DCI.CombineTo(N, Res, false);
8253 static SDValue PerformANDCombine(SDNode *N,
8254 TargetLowering::DAGCombinerInfo &DCI,
8255 const ARMSubtarget *Subtarget) {
8257 // Attempt to use immediate-form VBIC
8258 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8260 EVT VT = N->getValueType(0);
8261 SelectionDAG &DAG = DCI.DAG;
8263 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8266 APInt SplatBits, SplatUndef;
8267 unsigned SplatBitSize;
8270 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8271 if (SplatBitSize <= 64) {
8273 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8274 SplatUndef.getZExtValue(), SplatBitSize,
8275 DAG, VbicVT, VT.is128BitVector(),
8277 if (Val.getNode()) {
8279 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8280 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8281 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8286 if (!Subtarget->isThumb1Only()) {
8287 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8288 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8289 if (Result.getNode())
8296 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8297 static SDValue PerformORCombine(SDNode *N,
8298 TargetLowering::DAGCombinerInfo &DCI,
8299 const ARMSubtarget *Subtarget) {
8300 // Attempt to use immediate-form VORR
8301 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8303 EVT VT = N->getValueType(0);
8304 SelectionDAG &DAG = DCI.DAG;
8306 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8309 APInt SplatBits, SplatUndef;
8310 unsigned SplatBitSize;
8312 if (BVN && Subtarget->hasNEON() &&
8313 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8314 if (SplatBitSize <= 64) {
8316 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8317 SplatUndef.getZExtValue(), SplatBitSize,
8318 DAG, VorrVT, VT.is128BitVector(),
8320 if (Val.getNode()) {
8322 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8323 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8324 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8329 if (!Subtarget->isThumb1Only()) {
8330 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8331 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8332 if (Result.getNode())
8336 // The code below optimizes (or (and X, Y), Z).
8337 // The AND operand needs to have a single user to make these optimizations
8339 SDValue N0 = N->getOperand(0);
8340 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8342 SDValue N1 = N->getOperand(1);
8344 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8345 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8346 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8348 unsigned SplatBitSize;
8351 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8353 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8354 HasAnyUndefs) && !HasAnyUndefs) {
8355 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8357 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8358 HasAnyUndefs) && !HasAnyUndefs &&
8359 SplatBits0 == ~SplatBits1) {
8360 // Canonicalize the vector type to make instruction selection simpler.
8361 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8362 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8363 N0->getOperand(1), N0->getOperand(0),
8365 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8370 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8373 // BFI is only available on V6T2+
8374 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8378 // 1) or (and A, mask), val => ARMbfi A, val, mask
8379 // iff (val & mask) == val
8381 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8382 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8383 // && mask == ~mask2
8384 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8385 // && ~mask == mask2
8386 // (i.e., copy a bitfield value into another bitfield of the same width)
8391 SDValue N00 = N0.getOperand(0);
8393 // The value and the mask need to be constants so we can verify this is
8394 // actually a bitfield set. If the mask is 0xffff, we can do better
8395 // via a movt instruction, so don't use BFI in that case.
8396 SDValue MaskOp = N0.getOperand(1);
8397 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8400 unsigned Mask = MaskC->getZExtValue();
8404 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8405 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8407 unsigned Val = N1C->getZExtValue();
8408 if ((Val & ~Mask) != Val)
8411 if (ARM::isBitFieldInvertedMask(Mask)) {
8412 Val >>= countTrailingZeros(~Mask);
8414 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8415 DAG.getConstant(Val, MVT::i32),
8416 DAG.getConstant(Mask, MVT::i32));
8418 // Do not add new nodes to DAG combiner worklist.
8419 DCI.CombineTo(N, Res, false);
8422 } else if (N1.getOpcode() == ISD::AND) {
8423 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8424 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8427 unsigned Mask2 = N11C->getZExtValue();
8429 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8431 if (ARM::isBitFieldInvertedMask(Mask) &&
8433 // The pack halfword instruction works better for masks that fit it,
8434 // so use that when it's available.
8435 if (Subtarget->hasT2ExtractPack() &&
8436 (Mask == 0xffff || Mask == 0xffff0000))
8439 unsigned amt = countTrailingZeros(Mask2);
8440 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8441 DAG.getConstant(amt, MVT::i32));
8442 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8443 DAG.getConstant(Mask, MVT::i32));
8444 // Do not add new nodes to DAG combiner worklist.
8445 DCI.CombineTo(N, Res, false);
8447 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8449 // The pack halfword instruction works better for masks that fit it,
8450 // so use that when it's available.
8451 if (Subtarget->hasT2ExtractPack() &&
8452 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8455 unsigned lsb = countTrailingZeros(Mask);
8456 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8457 DAG.getConstant(lsb, MVT::i32));
8458 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8459 DAG.getConstant(Mask2, MVT::i32));
8460 // Do not add new nodes to DAG combiner worklist.
8461 DCI.CombineTo(N, Res, false);
8466 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8467 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8468 ARM::isBitFieldInvertedMask(~Mask)) {
8469 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8470 // where lsb(mask) == #shamt and masked bits of B are known zero.
8471 SDValue ShAmt = N00.getOperand(1);
8472 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8473 unsigned LSB = countTrailingZeros(Mask);
8477 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8478 DAG.getConstant(~Mask, MVT::i32));
8480 // Do not add new nodes to DAG combiner worklist.
8481 DCI.CombineTo(N, Res, false);
8487 static SDValue PerformXORCombine(SDNode *N,
8488 TargetLowering::DAGCombinerInfo &DCI,
8489 const ARMSubtarget *Subtarget) {
8490 EVT VT = N->getValueType(0);
8491 SelectionDAG &DAG = DCI.DAG;
8493 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8496 if (!Subtarget->isThumb1Only()) {
8497 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8498 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8499 if (Result.getNode())
8506 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8507 /// the bits being cleared by the AND are not demanded by the BFI.
8508 static SDValue PerformBFICombine(SDNode *N,
8509 TargetLowering::DAGCombinerInfo &DCI) {
8510 SDValue N1 = N->getOperand(1);
8511 if (N1.getOpcode() == ISD::AND) {
8512 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8515 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8516 unsigned LSB = countTrailingZeros(~InvMask);
8517 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8518 unsigned Mask = (1 << Width)-1;
8519 unsigned Mask2 = N11C->getZExtValue();
8520 if ((Mask & (~Mask2)) == 0)
8521 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8522 N->getOperand(0), N1.getOperand(0),
8528 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8529 /// ARMISD::VMOVRRD.
8530 static SDValue PerformVMOVRRDCombine(SDNode *N,
8531 TargetLowering::DAGCombinerInfo &DCI) {
8532 // vmovrrd(vmovdrr x, y) -> x,y
8533 SDValue InDouble = N->getOperand(0);
8534 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8535 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8537 // vmovrrd(load f64) -> (load i32), (load i32)
8538 SDNode *InNode = InDouble.getNode();
8539 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8540 InNode->getValueType(0) == MVT::f64 &&
8541 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8542 !cast<LoadSDNode>(InNode)->isVolatile()) {
8543 // TODO: Should this be done for non-FrameIndex operands?
8544 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8546 SelectionDAG &DAG = DCI.DAG;
8548 SDValue BasePtr = LD->getBasePtr();
8549 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8550 LD->getPointerInfo(), LD->isVolatile(),
8551 LD->isNonTemporal(), LD->isInvariant(),
8552 LD->getAlignment());
8554 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8555 DAG.getConstant(4, MVT::i32));
8556 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8557 LD->getPointerInfo(), LD->isVolatile(),
8558 LD->isNonTemporal(), LD->isInvariant(),
8559 std::min(4U, LD->getAlignment() / 2));
8561 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8562 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8563 DCI.RemoveFromWorklist(LD);
8571 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8572 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8573 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8574 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8575 SDValue Op0 = N->getOperand(0);
8576 SDValue Op1 = N->getOperand(1);
8577 if (Op0.getOpcode() == ISD::BITCAST)
8578 Op0 = Op0.getOperand(0);
8579 if (Op1.getOpcode() == ISD::BITCAST)
8580 Op1 = Op1.getOperand(0);
8581 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8582 Op0.getNode() == Op1.getNode() &&
8583 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8584 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8585 N->getValueType(0), Op0.getOperand(0));
8589 /// PerformSTORECombine - Target-specific dag combine xforms for
8591 static SDValue PerformSTORECombine(SDNode *N,
8592 TargetLowering::DAGCombinerInfo &DCI) {
8593 StoreSDNode *St = cast<StoreSDNode>(N);
8594 if (St->isVolatile())
8597 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8598 // pack all of the elements in one place. Next, store to memory in fewer
8600 SDValue StVal = St->getValue();
8601 EVT VT = StVal.getValueType();
8602 if (St->isTruncatingStore() && VT.isVector()) {
8603 SelectionDAG &DAG = DCI.DAG;
8604 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8605 EVT StVT = St->getMemoryVT();
8606 unsigned NumElems = VT.getVectorNumElements();
8607 assert(StVT != VT && "Cannot truncate to the same type");
8608 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8609 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8611 // From, To sizes and ElemCount must be pow of two
8612 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8614 // We are going to use the original vector elt for storing.
8615 // Accumulated smaller vector elements must be a multiple of the store size.
8616 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8618 unsigned SizeRatio = FromEltSz / ToEltSz;
8619 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8621 // Create a type on which we perform the shuffle.
8622 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8623 NumElems*SizeRatio);
8624 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8627 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8628 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8629 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8631 // Can't shuffle using an illegal type.
8632 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8634 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8635 DAG.getUNDEF(WideVec.getValueType()),
8637 // At this point all of the data is stored at the bottom of the
8638 // register. We now need to save it to mem.
8640 // Find the largest store unit
8641 MVT StoreType = MVT::i8;
8642 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8643 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8644 MVT Tp = (MVT::SimpleValueType)tp;
8645 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8648 // Didn't find a legal store type.
8649 if (!TLI.isTypeLegal(StoreType))
8652 // Bitcast the original vector into a vector of store-size units
8653 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8654 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8655 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8656 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8657 SmallVector<SDValue, 8> Chains;
8658 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8659 TLI.getPointerTy());
8660 SDValue BasePtr = St->getBasePtr();
8662 // Perform one or more big stores into memory.
8663 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8664 for (unsigned I = 0; I < E; I++) {
8665 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8666 StoreType, ShuffWide,
8667 DAG.getIntPtrConstant(I));
8668 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8669 St->getPointerInfo(), St->isVolatile(),
8670 St->isNonTemporal(), St->getAlignment());
8671 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8673 Chains.push_back(Ch);
8675 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8679 if (!ISD::isNormalStore(St))
8682 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8683 // ARM stores of arguments in the same cache line.
8684 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8685 StVal.getNode()->hasOneUse()) {
8686 SelectionDAG &DAG = DCI.DAG;
8688 SDValue BasePtr = St->getBasePtr();
8689 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8690 StVal.getNode()->getOperand(0), BasePtr,
8691 St->getPointerInfo(), St->isVolatile(),
8692 St->isNonTemporal(), St->getAlignment());
8694 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8695 DAG.getConstant(4, MVT::i32));
8696 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8697 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8698 St->isNonTemporal(),
8699 std::min(4U, St->getAlignment() / 2));
8702 if (StVal.getValueType() != MVT::i64 ||
8703 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8706 // Bitcast an i64 store extracted from a vector to f64.
8707 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8708 SelectionDAG &DAG = DCI.DAG;
8710 SDValue IntVec = StVal.getOperand(0);
8711 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8712 IntVec.getValueType().getVectorNumElements());
8713 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8714 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8715 Vec, StVal.getOperand(1));
8717 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8718 // Make the DAGCombiner fold the bitcasts.
8719 DCI.AddToWorklist(Vec.getNode());
8720 DCI.AddToWorklist(ExtElt.getNode());
8721 DCI.AddToWorklist(V.getNode());
8722 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8723 St->getPointerInfo(), St->isVolatile(),
8724 St->isNonTemporal(), St->getAlignment(),
8728 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8729 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8730 /// i64 vector to have f64 elements, since the value can then be loaded
8731 /// directly into a VFP register.
8732 static bool hasNormalLoadOperand(SDNode *N) {
8733 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8734 for (unsigned i = 0; i < NumElts; ++i) {
8735 SDNode *Elt = N->getOperand(i).getNode();
8736 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8742 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8743 /// ISD::BUILD_VECTOR.
8744 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8745 TargetLowering::DAGCombinerInfo &DCI){
8746 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8747 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8748 // into a pair of GPRs, which is fine when the value is used as a scalar,
8749 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8750 SelectionDAG &DAG = DCI.DAG;
8751 if (N->getNumOperands() == 2) {
8752 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8757 // Load i64 elements as f64 values so that type legalization does not split
8758 // them up into i32 values.
8759 EVT VT = N->getValueType(0);
8760 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8763 SmallVector<SDValue, 8> Ops;
8764 unsigned NumElts = VT.getVectorNumElements();
8765 for (unsigned i = 0; i < NumElts; ++i) {
8766 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8768 // Make the DAGCombiner fold the bitcast.
8769 DCI.AddToWorklist(V.getNode());
8771 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8772 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8773 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8776 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8777 /// ISD::INSERT_VECTOR_ELT.
8778 static SDValue PerformInsertEltCombine(SDNode *N,
8779 TargetLowering::DAGCombinerInfo &DCI) {
8780 // Bitcast an i64 load inserted into a vector to f64.
8781 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8782 EVT VT = N->getValueType(0);
8783 SDNode *Elt = N->getOperand(1).getNode();
8784 if (VT.getVectorElementType() != MVT::i64 ||
8785 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8788 SelectionDAG &DAG = DCI.DAG;
8790 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8791 VT.getVectorNumElements());
8792 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8793 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8794 // Make the DAGCombiner fold the bitcasts.
8795 DCI.AddToWorklist(Vec.getNode());
8796 DCI.AddToWorklist(V.getNode());
8797 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8798 Vec, V, N->getOperand(2));
8799 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8802 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8803 /// ISD::VECTOR_SHUFFLE.
8804 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8805 // The LLVM shufflevector instruction does not require the shuffle mask
8806 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8807 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8808 // operands do not match the mask length, they are extended by concatenating
8809 // them with undef vectors. That is probably the right thing for other
8810 // targets, but for NEON it is better to concatenate two double-register
8811 // size vector operands into a single quad-register size vector. Do that
8812 // transformation here:
8813 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8814 // shuffle(concat(v1, v2), undef)
8815 SDValue Op0 = N->getOperand(0);
8816 SDValue Op1 = N->getOperand(1);
8817 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8818 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8819 Op0.getNumOperands() != 2 ||
8820 Op1.getNumOperands() != 2)
8822 SDValue Concat0Op1 = Op0.getOperand(1);
8823 SDValue Concat1Op1 = Op1.getOperand(1);
8824 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8825 Concat1Op1.getOpcode() != ISD::UNDEF)
8827 // Skip the transformation if any of the types are illegal.
8828 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8829 EVT VT = N->getValueType(0);
8830 if (!TLI.isTypeLegal(VT) ||
8831 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8832 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8835 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8836 Op0.getOperand(0), Op1.getOperand(0));
8837 // Translate the shuffle mask.
8838 SmallVector<int, 16> NewMask;
8839 unsigned NumElts = VT.getVectorNumElements();
8840 unsigned HalfElts = NumElts/2;
8841 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8842 for (unsigned n = 0; n < NumElts; ++n) {
8843 int MaskElt = SVN->getMaskElt(n);
8845 if (MaskElt < (int)HalfElts)
8847 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8848 NewElt = HalfElts + MaskElt - NumElts;
8849 NewMask.push_back(NewElt);
8851 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8852 DAG.getUNDEF(VT), NewMask.data());
8855 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8856 /// NEON load/store intrinsics to merge base address updates.
8857 static SDValue CombineBaseUpdate(SDNode *N,
8858 TargetLowering::DAGCombinerInfo &DCI) {
8859 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8862 SelectionDAG &DAG = DCI.DAG;
8863 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8864 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8865 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8866 SDValue Addr = N->getOperand(AddrOpIdx);
8868 // Search for a use of the address operand that is an increment.
8869 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8870 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8872 if (User->getOpcode() != ISD::ADD ||
8873 UI.getUse().getResNo() != Addr.getResNo())
8876 // Check that the add is independent of the load/store. Otherwise, folding
8877 // it would create a cycle.
8878 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8881 // Find the new opcode for the updating load/store.
8883 bool isLaneOp = false;
8884 unsigned NewOpc = 0;
8885 unsigned NumVecs = 0;
8887 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8889 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8890 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8892 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8894 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8896 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8898 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8899 NumVecs = 2; isLaneOp = true; break;
8900 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8901 NumVecs = 3; isLaneOp = true; break;
8902 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8903 NumVecs = 4; isLaneOp = true; break;
8904 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8905 NumVecs = 1; isLoad = false; break;
8906 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8907 NumVecs = 2; isLoad = false; break;
8908 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8909 NumVecs = 3; isLoad = false; break;
8910 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8911 NumVecs = 4; isLoad = false; break;
8912 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8913 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8914 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8915 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8916 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8917 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8921 switch (N->getOpcode()) {
8922 default: llvm_unreachable("unexpected opcode for Neon base update");
8923 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8924 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8925 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8929 // Find the size of memory referenced by the load/store.
8932 VecTy = N->getValueType(0);
8934 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8935 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8937 NumBytes /= VecTy.getVectorNumElements();
8939 // If the increment is a constant, it must match the memory ref size.
8940 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8941 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8942 uint64_t IncVal = CInc->getZExtValue();
8943 if (IncVal != NumBytes)
8945 } else if (NumBytes >= 3 * 16) {
8946 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8947 // separate instructions that make it harder to use a non-constant update.
8951 // Create the new updating load/store node.
8953 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8955 for (n = 0; n < NumResultVecs; ++n)
8957 Tys[n++] = MVT::i32;
8958 Tys[n] = MVT::Other;
8959 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8960 SmallVector<SDValue, 8> Ops;
8961 Ops.push_back(N->getOperand(0)); // incoming chain
8962 Ops.push_back(N->getOperand(AddrOpIdx));
8964 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8965 Ops.push_back(N->getOperand(i));
8967 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8968 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8969 Ops.data(), Ops.size(),
8970 MemInt->getMemoryVT(),
8971 MemInt->getMemOperand());
8974 std::vector<SDValue> NewResults;
8975 for (unsigned i = 0; i < NumResultVecs; ++i) {
8976 NewResults.push_back(SDValue(UpdN.getNode(), i));
8978 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8979 DCI.CombineTo(N, NewResults);
8980 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8987 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8988 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8989 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8991 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8992 SelectionDAG &DAG = DCI.DAG;
8993 EVT VT = N->getValueType(0);
8994 // vldN-dup instructions only support 64-bit vectors for N > 1.
8995 if (!VT.is64BitVector())
8998 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8999 SDNode *VLD = N->getOperand(0).getNode();
9000 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9002 unsigned NumVecs = 0;
9003 unsigned NewOpc = 0;
9004 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9005 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9007 NewOpc = ARMISD::VLD2DUP;
9008 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9010 NewOpc = ARMISD::VLD3DUP;
9011 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9013 NewOpc = ARMISD::VLD4DUP;
9018 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9019 // numbers match the load.
9020 unsigned VLDLaneNo =
9021 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9022 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9024 // Ignore uses of the chain result.
9025 if (UI.getUse().getResNo() == NumVecs)
9028 if (User->getOpcode() != ARMISD::VDUPLANE ||
9029 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9033 // Create the vldN-dup node.
9036 for (n = 0; n < NumVecs; ++n)
9038 Tys[n] = MVT::Other;
9039 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9040 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9041 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9042 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9043 Ops, 2, VLDMemInt->getMemoryVT(),
9044 VLDMemInt->getMemOperand());
9047 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9049 unsigned ResNo = UI.getUse().getResNo();
9050 // Ignore uses of the chain result.
9051 if (ResNo == NumVecs)
9054 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9057 // Now the vldN-lane intrinsic is dead except for its chain result.
9058 // Update uses of the chain.
9059 std::vector<SDValue> VLDDupResults;
9060 for (unsigned n = 0; n < NumVecs; ++n)
9061 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9062 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9063 DCI.CombineTo(VLD, VLDDupResults);
9068 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9069 /// ARMISD::VDUPLANE.
9070 static SDValue PerformVDUPLANECombine(SDNode *N,
9071 TargetLowering::DAGCombinerInfo &DCI) {
9072 SDValue Op = N->getOperand(0);
9074 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9075 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9076 if (CombineVLDDUP(N, DCI))
9077 return SDValue(N, 0);
9079 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9080 // redundant. Ignore bit_converts for now; element sizes are checked below.
9081 while (Op.getOpcode() == ISD::BITCAST)
9082 Op = Op.getOperand(0);
9083 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9086 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9087 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9088 // The canonical VMOV for a zero vector uses a 32-bit element size.
9089 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9091 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9093 EVT VT = N->getValueType(0);
9094 if (EltSize > VT.getVectorElementType().getSizeInBits())
9097 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9100 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9101 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9102 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9106 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9108 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9113 APFloat APF = C->getValueAPF();
9114 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9115 != APFloat::opOK || !isExact)
9118 c0 = (I == 0) ? cN : c0;
9119 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9126 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9127 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9128 /// when the VMUL has a constant operand that is a power of 2.
9130 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9131 /// vmul.f32 d16, d17, d16
9132 /// vcvt.s32.f32 d16, d16
9134 /// vcvt.s32.f32 d16, d16, #3
9135 static SDValue PerformVCVTCombine(SDNode *N,
9136 TargetLowering::DAGCombinerInfo &DCI,
9137 const ARMSubtarget *Subtarget) {
9138 SelectionDAG &DAG = DCI.DAG;
9139 SDValue Op = N->getOperand(0);
9141 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9142 Op.getOpcode() != ISD::FMUL)
9146 SDValue N0 = Op->getOperand(0);
9147 SDValue ConstVec = Op->getOperand(1);
9148 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9150 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9151 !isConstVecPow2(ConstVec, isSigned, C))
9154 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9155 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9156 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9157 // These instructions only exist converting from f32 to i32. We can handle
9158 // smaller integers by generating an extra truncate, but larger ones would
9163 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9164 Intrinsic::arm_neon_vcvtfp2fxu;
9165 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9166 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9167 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9168 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9169 DAG.getConstant(Log2_64(C), MVT::i32));
9171 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9172 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9177 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9178 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9179 /// when the VDIV has a constant operand that is a power of 2.
9181 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9182 /// vcvt.f32.s32 d16, d16
9183 /// vdiv.f32 d16, d17, d16
9185 /// vcvt.f32.s32 d16, d16, #3
9186 static SDValue PerformVDIVCombine(SDNode *N,
9187 TargetLowering::DAGCombinerInfo &DCI,
9188 const ARMSubtarget *Subtarget) {
9189 SelectionDAG &DAG = DCI.DAG;
9190 SDValue Op = N->getOperand(0);
9191 unsigned OpOpcode = Op.getNode()->getOpcode();
9193 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9194 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9198 SDValue ConstVec = N->getOperand(1);
9199 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9201 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9202 !isConstVecPow2(ConstVec, isSigned, C))
9205 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9206 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9207 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9208 // These instructions only exist converting from i32 to f32. We can handle
9209 // smaller integers by generating an extra extend, but larger ones would
9214 SDValue ConvInput = Op.getOperand(0);
9215 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9216 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9217 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9218 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9221 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9222 Intrinsic::arm_neon_vcvtfxu2fp;
9223 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9225 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9226 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9229 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9230 /// operand of a vector shift operation, where all the elements of the
9231 /// build_vector must have the same constant integer value.
9232 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9233 // Ignore bit_converts.
9234 while (Op.getOpcode() == ISD::BITCAST)
9235 Op = Op.getOperand(0);
9236 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9237 APInt SplatBits, SplatUndef;
9238 unsigned SplatBitSize;
9240 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9241 HasAnyUndefs, ElementBits) ||
9242 SplatBitSize > ElementBits)
9244 Cnt = SplatBits.getSExtValue();
9248 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9249 /// operand of a vector shift left operation. That value must be in the range:
9250 /// 0 <= Value < ElementBits for a left shift; or
9251 /// 0 <= Value <= ElementBits for a long left shift.
9252 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9253 assert(VT.isVector() && "vector shift count is not a vector type");
9254 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9255 if (! getVShiftImm(Op, ElementBits, Cnt))
9257 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9260 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9261 /// operand of a vector shift right operation. For a shift opcode, the value
9262 /// is positive, but for an intrinsic the value count must be negative. The
9263 /// absolute value must be in the range:
9264 /// 1 <= |Value| <= ElementBits for a right shift; or
9265 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9266 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9268 assert(VT.isVector() && "vector shift count is not a vector type");
9269 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9270 if (! getVShiftImm(Op, ElementBits, Cnt))
9274 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9277 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9278 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9279 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9282 // Don't do anything for most intrinsics.
9285 // Vector shifts: check for immediate versions and lower them.
9286 // Note: This is done during DAG combining instead of DAG legalizing because
9287 // the build_vectors for 64-bit vector element shift counts are generally
9288 // not legal, and it is hard to see their values after they get legalized to
9289 // loads from a constant pool.
9290 case Intrinsic::arm_neon_vshifts:
9291 case Intrinsic::arm_neon_vshiftu:
9292 case Intrinsic::arm_neon_vshiftls:
9293 case Intrinsic::arm_neon_vshiftlu:
9294 case Intrinsic::arm_neon_vshiftn:
9295 case Intrinsic::arm_neon_vrshifts:
9296 case Intrinsic::arm_neon_vrshiftu:
9297 case Intrinsic::arm_neon_vrshiftn:
9298 case Intrinsic::arm_neon_vqshifts:
9299 case Intrinsic::arm_neon_vqshiftu:
9300 case Intrinsic::arm_neon_vqshiftsu:
9301 case Intrinsic::arm_neon_vqshiftns:
9302 case Intrinsic::arm_neon_vqshiftnu:
9303 case Intrinsic::arm_neon_vqshiftnsu:
9304 case Intrinsic::arm_neon_vqrshiftns:
9305 case Intrinsic::arm_neon_vqrshiftnu:
9306 case Intrinsic::arm_neon_vqrshiftnsu: {
9307 EVT VT = N->getOperand(1).getValueType();
9309 unsigned VShiftOpc = 0;
9312 case Intrinsic::arm_neon_vshifts:
9313 case Intrinsic::arm_neon_vshiftu:
9314 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9315 VShiftOpc = ARMISD::VSHL;
9318 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9319 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9320 ARMISD::VSHRs : ARMISD::VSHRu);
9325 case Intrinsic::arm_neon_vshiftls:
9326 case Intrinsic::arm_neon_vshiftlu:
9327 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9329 llvm_unreachable("invalid shift count for vshll intrinsic");
9331 case Intrinsic::arm_neon_vrshifts:
9332 case Intrinsic::arm_neon_vrshiftu:
9333 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9337 case Intrinsic::arm_neon_vqshifts:
9338 case Intrinsic::arm_neon_vqshiftu:
9339 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9343 case Intrinsic::arm_neon_vqshiftsu:
9344 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9346 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9348 case Intrinsic::arm_neon_vshiftn:
9349 case Intrinsic::arm_neon_vrshiftn:
9350 case Intrinsic::arm_neon_vqshiftns:
9351 case Intrinsic::arm_neon_vqshiftnu:
9352 case Intrinsic::arm_neon_vqshiftnsu:
9353 case Intrinsic::arm_neon_vqrshiftns:
9354 case Intrinsic::arm_neon_vqrshiftnu:
9355 case Intrinsic::arm_neon_vqrshiftnsu:
9356 // Narrowing shifts require an immediate right shift.
9357 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9359 llvm_unreachable("invalid shift count for narrowing vector shift "
9363 llvm_unreachable("unhandled vector shift");
9367 case Intrinsic::arm_neon_vshifts:
9368 case Intrinsic::arm_neon_vshiftu:
9369 // Opcode already set above.
9371 case Intrinsic::arm_neon_vshiftls:
9372 case Intrinsic::arm_neon_vshiftlu:
9373 if (Cnt == VT.getVectorElementType().getSizeInBits())
9374 VShiftOpc = ARMISD::VSHLLi;
9376 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9377 ARMISD::VSHLLs : ARMISD::VSHLLu);
9379 case Intrinsic::arm_neon_vshiftn:
9380 VShiftOpc = ARMISD::VSHRN; break;
9381 case Intrinsic::arm_neon_vrshifts:
9382 VShiftOpc = ARMISD::VRSHRs; break;
9383 case Intrinsic::arm_neon_vrshiftu:
9384 VShiftOpc = ARMISD::VRSHRu; break;
9385 case Intrinsic::arm_neon_vrshiftn:
9386 VShiftOpc = ARMISD::VRSHRN; break;
9387 case Intrinsic::arm_neon_vqshifts:
9388 VShiftOpc = ARMISD::VQSHLs; break;
9389 case Intrinsic::arm_neon_vqshiftu:
9390 VShiftOpc = ARMISD::VQSHLu; break;
9391 case Intrinsic::arm_neon_vqshiftsu:
9392 VShiftOpc = ARMISD::VQSHLsu; break;
9393 case Intrinsic::arm_neon_vqshiftns:
9394 VShiftOpc = ARMISD::VQSHRNs; break;
9395 case Intrinsic::arm_neon_vqshiftnu:
9396 VShiftOpc = ARMISD::VQSHRNu; break;
9397 case Intrinsic::arm_neon_vqshiftnsu:
9398 VShiftOpc = ARMISD::VQSHRNsu; break;
9399 case Intrinsic::arm_neon_vqrshiftns:
9400 VShiftOpc = ARMISD::VQRSHRNs; break;
9401 case Intrinsic::arm_neon_vqrshiftnu:
9402 VShiftOpc = ARMISD::VQRSHRNu; break;
9403 case Intrinsic::arm_neon_vqrshiftnsu:
9404 VShiftOpc = ARMISD::VQRSHRNsu; break;
9407 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9408 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9411 case Intrinsic::arm_neon_vshiftins: {
9412 EVT VT = N->getOperand(1).getValueType();
9414 unsigned VShiftOpc = 0;
9416 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9417 VShiftOpc = ARMISD::VSLI;
9418 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9419 VShiftOpc = ARMISD::VSRI;
9421 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9424 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9425 N->getOperand(1), N->getOperand(2),
9426 DAG.getConstant(Cnt, MVT::i32));
9429 case Intrinsic::arm_neon_vqrshifts:
9430 case Intrinsic::arm_neon_vqrshiftu:
9431 // No immediate versions of these to check for.
9438 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9439 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9440 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9441 /// vector element shift counts are generally not legal, and it is hard to see
9442 /// their values after they get legalized to loads from a constant pool.
9443 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9444 const ARMSubtarget *ST) {
9445 EVT VT = N->getValueType(0);
9446 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9447 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9448 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9449 SDValue N1 = N->getOperand(1);
9450 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9451 SDValue N0 = N->getOperand(0);
9452 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9453 DAG.MaskedValueIsZero(N0.getOperand(0),
9454 APInt::getHighBitsSet(32, 16)))
9455 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9459 // Nothing to be done for scalar shifts.
9460 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9461 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9464 assert(ST->hasNEON() && "unexpected vector shift");
9467 switch (N->getOpcode()) {
9468 default: llvm_unreachable("unexpected shift opcode");
9471 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9472 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9473 DAG.getConstant(Cnt, MVT::i32));
9478 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9479 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9480 ARMISD::VSHRs : ARMISD::VSHRu);
9481 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9482 DAG.getConstant(Cnt, MVT::i32));
9488 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9489 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9490 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9491 const ARMSubtarget *ST) {
9492 SDValue N0 = N->getOperand(0);
9494 // Check for sign- and zero-extensions of vector extract operations of 8-
9495 // and 16-bit vector elements. NEON supports these directly. They are
9496 // handled during DAG combining because type legalization will promote them
9497 // to 32-bit types and it is messy to recognize the operations after that.
9498 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9499 SDValue Vec = N0.getOperand(0);
9500 SDValue Lane = N0.getOperand(1);
9501 EVT VT = N->getValueType(0);
9502 EVT EltVT = N0.getValueType();
9503 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9505 if (VT == MVT::i32 &&
9506 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9507 TLI.isTypeLegal(Vec.getValueType()) &&
9508 isa<ConstantSDNode>(Lane)) {
9511 switch (N->getOpcode()) {
9512 default: llvm_unreachable("unexpected opcode");
9513 case ISD::SIGN_EXTEND:
9514 Opc = ARMISD::VGETLANEs;
9516 case ISD::ZERO_EXTEND:
9517 case ISD::ANY_EXTEND:
9518 Opc = ARMISD::VGETLANEu;
9521 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9528 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9529 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9530 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9531 const ARMSubtarget *ST) {
9532 // If the target supports NEON, try to use vmax/vmin instructions for f32
9533 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9534 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9535 // a NaN; only do the transformation when it matches that behavior.
9537 // For now only do this when using NEON for FP operations; if using VFP, it
9538 // is not obvious that the benefit outweighs the cost of switching to the
9540 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9541 N->getValueType(0) != MVT::f32)
9544 SDValue CondLHS = N->getOperand(0);
9545 SDValue CondRHS = N->getOperand(1);
9546 SDValue LHS = N->getOperand(2);
9547 SDValue RHS = N->getOperand(3);
9548 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9550 unsigned Opcode = 0;
9552 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9553 IsReversed = false; // x CC y ? x : y
9554 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9555 IsReversed = true ; // x CC y ? y : x
9569 // If LHS is NaN, an ordered comparison will be false and the result will
9570 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9571 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9572 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9573 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9575 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9576 // will return -0, so vmin can only be used for unsafe math or if one of
9577 // the operands is known to be nonzero.
9578 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9579 !DAG.getTarget().Options.UnsafeFPMath &&
9580 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9582 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9591 // If LHS is NaN, an ordered comparison will be false and the result will
9592 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9593 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9594 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9595 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9597 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9598 // will return +0, so vmax can only be used for unsafe math or if one of
9599 // the operands is known to be nonzero.
9600 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9601 !DAG.getTarget().Options.UnsafeFPMath &&
9602 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9604 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9610 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9613 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9615 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9616 SDValue Cmp = N->getOperand(4);
9617 if (Cmp.getOpcode() != ARMISD::CMPZ)
9618 // Only looking at EQ and NE cases.
9621 EVT VT = N->getValueType(0);
9623 SDValue LHS = Cmp.getOperand(0);
9624 SDValue RHS = Cmp.getOperand(1);
9625 SDValue FalseVal = N->getOperand(0);
9626 SDValue TrueVal = N->getOperand(1);
9627 SDValue ARMcc = N->getOperand(2);
9628 ARMCC::CondCodes CC =
9629 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9647 /// FIXME: Turn this into a target neutral optimization?
9649 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9650 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9651 N->getOperand(3), Cmp);
9652 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9654 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9655 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9656 N->getOperand(3), NewCmp);
9659 if (Res.getNode()) {
9660 APInt KnownZero, KnownOne;
9661 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9662 // Capture demanded bits information that would be otherwise lost.
9663 if (KnownZero == 0xfffffffe)
9664 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9665 DAG.getValueType(MVT::i1));
9666 else if (KnownZero == 0xffffff00)
9667 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9668 DAG.getValueType(MVT::i8));
9669 else if (KnownZero == 0xffff0000)
9670 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9671 DAG.getValueType(MVT::i16));
9677 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9678 DAGCombinerInfo &DCI) const {
9679 switch (N->getOpcode()) {
9681 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9682 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9683 case ISD::SUB: return PerformSUBCombine(N, DCI);
9684 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9685 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9686 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9687 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9688 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9689 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9690 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9691 case ISD::STORE: return PerformSTORECombine(N, DCI);
9692 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9693 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9694 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9695 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9696 case ISD::FP_TO_SINT:
9697 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9698 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9699 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9702 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9703 case ISD::SIGN_EXTEND:
9704 case ISD::ZERO_EXTEND:
9705 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9706 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9707 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9708 case ARMISD::VLD2DUP:
9709 case ARMISD::VLD3DUP:
9710 case ARMISD::VLD4DUP:
9711 return CombineBaseUpdate(N, DCI);
9712 case ISD::INTRINSIC_VOID:
9713 case ISD::INTRINSIC_W_CHAIN:
9714 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9715 case Intrinsic::arm_neon_vld1:
9716 case Intrinsic::arm_neon_vld2:
9717 case Intrinsic::arm_neon_vld3:
9718 case Intrinsic::arm_neon_vld4:
9719 case Intrinsic::arm_neon_vld2lane:
9720 case Intrinsic::arm_neon_vld3lane:
9721 case Intrinsic::arm_neon_vld4lane:
9722 case Intrinsic::arm_neon_vst1:
9723 case Intrinsic::arm_neon_vst2:
9724 case Intrinsic::arm_neon_vst3:
9725 case Intrinsic::arm_neon_vst4:
9726 case Intrinsic::arm_neon_vst2lane:
9727 case Intrinsic::arm_neon_vst3lane:
9728 case Intrinsic::arm_neon_vst4lane:
9729 return CombineBaseUpdate(N, DCI);
9737 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9739 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9742 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9743 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9744 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9746 switch (VT.getSimpleVT().SimpleTy) {
9752 // Unaligned access can use (for example) LRDB, LRDH, LDR
9753 if (AllowsUnaligned) {
9755 *Fast = Subtarget->hasV7Ops();
9762 // For any little-endian targets with neon, we can support unaligned ld/st
9763 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9764 // A big-endian target may also explictly support unaligned accesses
9765 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9775 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9776 unsigned AlignCheck) {
9777 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9778 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9781 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9782 unsigned DstAlign, unsigned SrcAlign,
9783 bool IsMemset, bool ZeroMemset,
9785 MachineFunction &MF) const {
9786 const Function *F = MF.getFunction();
9788 // See if we can use NEON instructions for this...
9789 if ((!IsMemset || ZeroMemset) &&
9790 Subtarget->hasNEON() &&
9791 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9792 Attribute::NoImplicitFloat)) {
9795 (memOpAlign(SrcAlign, DstAlign, 16) ||
9796 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9798 } else if (Size >= 8 &&
9799 (memOpAlign(SrcAlign, DstAlign, 8) ||
9800 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9805 // Lowering to i32/i16 if the size permits.
9811 // Let the target-independent logic figure it out.
9815 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9816 if (Val.getOpcode() != ISD::LOAD)
9819 EVT VT1 = Val.getValueType();
9820 if (!VT1.isSimple() || !VT1.isInteger() ||
9821 !VT2.isSimple() || !VT2.isInteger())
9824 switch (VT1.getSimpleVT().SimpleTy) {
9829 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9836 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9841 switch (VT.getSimpleVT().SimpleTy) {
9842 default: return false;
9857 if ((V & (Scale - 1)) != 0)
9860 return V == (V & ((1LL << 5) - 1));
9863 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9864 const ARMSubtarget *Subtarget) {
9871 switch (VT.getSimpleVT().SimpleTy) {
9872 default: return false;
9877 // + imm12 or - imm8
9879 return V == (V & ((1LL << 8) - 1));
9880 return V == (V & ((1LL << 12) - 1));
9883 // Same as ARM mode. FIXME: NEON?
9884 if (!Subtarget->hasVFP2())
9889 return V == (V & ((1LL << 8) - 1));
9893 /// isLegalAddressImmediate - Return true if the integer value can be used
9894 /// as the offset of the target addressing mode for load / store of the
9896 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9897 const ARMSubtarget *Subtarget) {
9904 if (Subtarget->isThumb1Only())
9905 return isLegalT1AddressImmediate(V, VT);
9906 else if (Subtarget->isThumb2())
9907 return isLegalT2AddressImmediate(V, VT, Subtarget);
9912 switch (VT.getSimpleVT().SimpleTy) {
9913 default: return false;
9918 return V == (V & ((1LL << 12) - 1));
9921 return V == (V & ((1LL << 8) - 1));
9924 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9929 return V == (V & ((1LL << 8) - 1));
9933 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9935 int Scale = AM.Scale;
9939 switch (VT.getSimpleVT().SimpleTy) {
9940 default: return false;
9949 return Scale == 2 || Scale == 4 || Scale == 8;
9952 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9956 // Note, we allow "void" uses (basically, uses that aren't loads or
9957 // stores), because arm allows folding a scale into many arithmetic
9958 // operations. This should be made more precise and revisited later.
9960 // Allow r << imm, but the imm has to be a multiple of two.
9961 if (Scale & 1) return false;
9962 return isPowerOf2_32(Scale);
9966 /// isLegalAddressingMode - Return true if the addressing mode represented
9967 /// by AM is legal for this target, for a load/store of the specified type.
9968 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9970 EVT VT = getValueType(Ty, true);
9971 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9974 // Can never fold addr of global into load/store.
9979 case 0: // no scale reg, must be "r+i" or "r", or "i".
9982 if (Subtarget->isThumb1Only())
9986 // ARM doesn't support any R+R*scale+imm addr modes.
9993 if (Subtarget->isThumb2())
9994 return isLegalT2ScaledAddressingMode(AM, VT);
9996 int Scale = AM.Scale;
9997 switch (VT.getSimpleVT().SimpleTy) {
9998 default: return false;
10002 if (Scale < 0) Scale = -Scale;
10006 return isPowerOf2_32(Scale & ~1);
10010 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10015 // Note, we allow "void" uses (basically, uses that aren't loads or
10016 // stores), because arm allows folding a scale into many arithmetic
10017 // operations. This should be made more precise and revisited later.
10019 // Allow r << imm, but the imm has to be a multiple of two.
10020 if (Scale & 1) return false;
10021 return isPowerOf2_32(Scale);
10027 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10028 /// icmp immediate, that is the target has icmp instructions which can compare
10029 /// a register against the immediate without having to materialize the
10030 /// immediate into a register.
10031 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10032 // Thumb2 and ARM modes can use cmn for negative immediates.
10033 if (!Subtarget->isThumb())
10034 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10035 if (Subtarget->isThumb2())
10036 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10037 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10038 return Imm >= 0 && Imm <= 255;
10041 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10042 /// *or sub* immediate, that is the target has add or sub instructions which can
10043 /// add a register with the immediate without having to materialize the
10044 /// immediate into a register.
10045 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10046 // Same encoding for add/sub, just flip the sign.
10047 int64_t AbsImm = llvm::abs64(Imm);
10048 if (!Subtarget->isThumb())
10049 return ARM_AM::getSOImmVal(AbsImm) != -1;
10050 if (Subtarget->isThumb2())
10051 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10052 // Thumb1 only has 8-bit unsigned immediate.
10053 return AbsImm >= 0 && AbsImm <= 255;
10056 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10057 bool isSEXTLoad, SDValue &Base,
10058 SDValue &Offset, bool &isInc,
10059 SelectionDAG &DAG) {
10060 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10063 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10064 // AddressingMode 3
10065 Base = Ptr->getOperand(0);
10066 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10067 int RHSC = (int)RHS->getZExtValue();
10068 if (RHSC < 0 && RHSC > -256) {
10069 assert(Ptr->getOpcode() == ISD::ADD);
10071 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10075 isInc = (Ptr->getOpcode() == ISD::ADD);
10076 Offset = Ptr->getOperand(1);
10078 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10079 // AddressingMode 2
10080 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10081 int RHSC = (int)RHS->getZExtValue();
10082 if (RHSC < 0 && RHSC > -0x1000) {
10083 assert(Ptr->getOpcode() == ISD::ADD);
10085 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10086 Base = Ptr->getOperand(0);
10091 if (Ptr->getOpcode() == ISD::ADD) {
10093 ARM_AM::ShiftOpc ShOpcVal=
10094 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10095 if (ShOpcVal != ARM_AM::no_shift) {
10096 Base = Ptr->getOperand(1);
10097 Offset = Ptr->getOperand(0);
10099 Base = Ptr->getOperand(0);
10100 Offset = Ptr->getOperand(1);
10105 isInc = (Ptr->getOpcode() == ISD::ADD);
10106 Base = Ptr->getOperand(0);
10107 Offset = Ptr->getOperand(1);
10111 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10115 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10116 bool isSEXTLoad, SDValue &Base,
10117 SDValue &Offset, bool &isInc,
10118 SelectionDAG &DAG) {
10119 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10122 Base = Ptr->getOperand(0);
10123 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10124 int RHSC = (int)RHS->getZExtValue();
10125 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10126 assert(Ptr->getOpcode() == ISD::ADD);
10128 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10130 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10131 isInc = Ptr->getOpcode() == ISD::ADD;
10132 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10140 /// getPreIndexedAddressParts - returns true by value, base pointer and
10141 /// offset pointer and addressing mode by reference if the node's address
10142 /// can be legally represented as pre-indexed load / store address.
10144 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10146 ISD::MemIndexedMode &AM,
10147 SelectionDAG &DAG) const {
10148 if (Subtarget->isThumb1Only())
10153 bool isSEXTLoad = false;
10154 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10155 Ptr = LD->getBasePtr();
10156 VT = LD->getMemoryVT();
10157 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10158 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10159 Ptr = ST->getBasePtr();
10160 VT = ST->getMemoryVT();
10165 bool isLegal = false;
10166 if (Subtarget->isThumb2())
10167 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10168 Offset, isInc, DAG);
10170 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10171 Offset, isInc, DAG);
10175 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10179 /// getPostIndexedAddressParts - returns true by value, base pointer and
10180 /// offset pointer and addressing mode by reference if this node can be
10181 /// combined with a load / store to form a post-indexed load / store.
10182 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10185 ISD::MemIndexedMode &AM,
10186 SelectionDAG &DAG) const {
10187 if (Subtarget->isThumb1Only())
10192 bool isSEXTLoad = false;
10193 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10194 VT = LD->getMemoryVT();
10195 Ptr = LD->getBasePtr();
10196 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10197 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10198 VT = ST->getMemoryVT();
10199 Ptr = ST->getBasePtr();
10204 bool isLegal = false;
10205 if (Subtarget->isThumb2())
10206 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10209 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10215 // Swap base ptr and offset to catch more post-index load / store when
10216 // it's legal. In Thumb2 mode, offset must be an immediate.
10217 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10218 !Subtarget->isThumb2())
10219 std::swap(Base, Offset);
10221 // Post-indexed load / store update the base pointer.
10226 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10230 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10233 const SelectionDAG &DAG,
10234 unsigned Depth) const {
10235 unsigned BitWidth = KnownOne.getBitWidth();
10236 KnownZero = KnownOne = APInt(BitWidth, 0);
10237 switch (Op.getOpcode()) {
10243 // These nodes' second result is a boolean
10244 if (Op.getResNo() == 0)
10246 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10248 case ARMISD::CMOV: {
10249 // Bits are known zero/one if known on the LHS and RHS.
10250 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10251 if (KnownZero == 0 && KnownOne == 0) return;
10253 APInt KnownZeroRHS, KnownOneRHS;
10254 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10255 KnownZero &= KnownZeroRHS;
10256 KnownOne &= KnownOneRHS;
10262 //===----------------------------------------------------------------------===//
10263 // ARM Inline Assembly Support
10264 //===----------------------------------------------------------------------===//
10266 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10267 // Looking for "rev" which is V6+.
10268 if (!Subtarget->hasV6Ops())
10271 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10272 std::string AsmStr = IA->getAsmString();
10273 SmallVector<StringRef, 4> AsmPieces;
10274 SplitString(AsmStr, AsmPieces, ";\n");
10276 switch (AsmPieces.size()) {
10277 default: return false;
10279 AsmStr = AsmPieces[0];
10281 SplitString(AsmStr, AsmPieces, " \t,");
10284 if (AsmPieces.size() == 3 &&
10285 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10286 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10287 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10288 if (Ty && Ty->getBitWidth() == 32)
10289 return IntrinsicLowering::LowerToByteSwap(CI);
10297 /// getConstraintType - Given a constraint letter, return the type of
10298 /// constraint it is for this target.
10299 ARMTargetLowering::ConstraintType
10300 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10301 if (Constraint.size() == 1) {
10302 switch (Constraint[0]) {
10304 case 'l': return C_RegisterClass;
10305 case 'w': return C_RegisterClass;
10306 case 'h': return C_RegisterClass;
10307 case 'x': return C_RegisterClass;
10308 case 't': return C_RegisterClass;
10309 case 'j': return C_Other; // Constant for movw.
10310 // An address with a single base register. Due to the way we
10311 // currently handle addresses it is the same as an 'r' memory constraint.
10312 case 'Q': return C_Memory;
10314 } else if (Constraint.size() == 2) {
10315 switch (Constraint[0]) {
10317 // All 'U+' constraints are addresses.
10318 case 'U': return C_Memory;
10321 return TargetLowering::getConstraintType(Constraint);
10324 /// Examine constraint type and operand type and determine a weight value.
10325 /// This object must already have been set up with the operand type
10326 /// and the current alternative constraint selected.
10327 TargetLowering::ConstraintWeight
10328 ARMTargetLowering::getSingleConstraintMatchWeight(
10329 AsmOperandInfo &info, const char *constraint) const {
10330 ConstraintWeight weight = CW_Invalid;
10331 Value *CallOperandVal = info.CallOperandVal;
10332 // If we don't have a value, we can't do a match,
10333 // but allow it at the lowest weight.
10334 if (CallOperandVal == NULL)
10336 Type *type = CallOperandVal->getType();
10337 // Look at the constraint type.
10338 switch (*constraint) {
10340 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10343 if (type->isIntegerTy()) {
10344 if (Subtarget->isThumb())
10345 weight = CW_SpecificReg;
10347 weight = CW_Register;
10351 if (type->isFloatingPointTy())
10352 weight = CW_Register;
10358 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10360 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10362 if (Constraint.size() == 1) {
10363 // GCC ARM Constraint Letters
10364 switch (Constraint[0]) {
10365 case 'l': // Low regs or general regs.
10366 if (Subtarget->isThumb())
10367 return RCPair(0U, &ARM::tGPRRegClass);
10368 return RCPair(0U, &ARM::GPRRegClass);
10369 case 'h': // High regs or no regs.
10370 if (Subtarget->isThumb())
10371 return RCPair(0U, &ARM::hGPRRegClass);
10374 return RCPair(0U, &ARM::GPRRegClass);
10376 if (VT == MVT::f32)
10377 return RCPair(0U, &ARM::SPRRegClass);
10378 if (VT.getSizeInBits() == 64)
10379 return RCPair(0U, &ARM::DPRRegClass);
10380 if (VT.getSizeInBits() == 128)
10381 return RCPair(0U, &ARM::QPRRegClass);
10384 if (VT == MVT::f32)
10385 return RCPair(0U, &ARM::SPR_8RegClass);
10386 if (VT.getSizeInBits() == 64)
10387 return RCPair(0U, &ARM::DPR_8RegClass);
10388 if (VT.getSizeInBits() == 128)
10389 return RCPair(0U, &ARM::QPR_8RegClass);
10392 if (VT == MVT::f32)
10393 return RCPair(0U, &ARM::SPRRegClass);
10397 if (StringRef("{cc}").equals_lower(Constraint))
10398 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10400 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10403 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10404 /// vector. If it is invalid, don't add anything to Ops.
10405 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10406 std::string &Constraint,
10407 std::vector<SDValue>&Ops,
10408 SelectionDAG &DAG) const {
10409 SDValue Result(0, 0);
10411 // Currently only support length 1 constraints.
10412 if (Constraint.length() != 1) return;
10414 char ConstraintLetter = Constraint[0];
10415 switch (ConstraintLetter) {
10418 case 'I': case 'J': case 'K': case 'L':
10419 case 'M': case 'N': case 'O':
10420 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10424 int64_t CVal64 = C->getSExtValue();
10425 int CVal = (int) CVal64;
10426 // None of these constraints allow values larger than 32 bits. Check
10427 // that the value fits in an int.
10428 if (CVal != CVal64)
10431 switch (ConstraintLetter) {
10433 // Constant suitable for movw, must be between 0 and
10435 if (Subtarget->hasV6T2Ops())
10436 if (CVal >= 0 && CVal <= 65535)
10440 if (Subtarget->isThumb1Only()) {
10441 // This must be a constant between 0 and 255, for ADD
10443 if (CVal >= 0 && CVal <= 255)
10445 } else if (Subtarget->isThumb2()) {
10446 // A constant that can be used as an immediate value in a
10447 // data-processing instruction.
10448 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10451 // A constant that can be used as an immediate value in a
10452 // data-processing instruction.
10453 if (ARM_AM::getSOImmVal(CVal) != -1)
10459 if (Subtarget->isThumb()) { // FIXME thumb2
10460 // This must be a constant between -255 and -1, for negated ADD
10461 // immediates. This can be used in GCC with an "n" modifier that
10462 // prints the negated value, for use with SUB instructions. It is
10463 // not useful otherwise but is implemented for compatibility.
10464 if (CVal >= -255 && CVal <= -1)
10467 // This must be a constant between -4095 and 4095. It is not clear
10468 // what this constraint is intended for. Implemented for
10469 // compatibility with GCC.
10470 if (CVal >= -4095 && CVal <= 4095)
10476 if (Subtarget->isThumb1Only()) {
10477 // A 32-bit value where only one byte has a nonzero value. Exclude
10478 // zero to match GCC. This constraint is used by GCC internally for
10479 // constants that can be loaded with a move/shift combination.
10480 // It is not useful otherwise but is implemented for compatibility.
10481 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10483 } else if (Subtarget->isThumb2()) {
10484 // A constant whose bitwise inverse can be used as an immediate
10485 // value in a data-processing instruction. This can be used in GCC
10486 // with a "B" modifier that prints the inverted value, for use with
10487 // BIC and MVN instructions. It is not useful otherwise but is
10488 // implemented for compatibility.
10489 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10492 // A constant whose bitwise inverse can be used as an immediate
10493 // value in a data-processing instruction. This can be used in GCC
10494 // with a "B" modifier that prints the inverted value, for use with
10495 // BIC and MVN instructions. It is not useful otherwise but is
10496 // implemented for compatibility.
10497 if (ARM_AM::getSOImmVal(~CVal) != -1)
10503 if (Subtarget->isThumb1Only()) {
10504 // This must be a constant between -7 and 7,
10505 // for 3-operand ADD/SUB immediate instructions.
10506 if (CVal >= -7 && CVal < 7)
10508 } else if (Subtarget->isThumb2()) {
10509 // A constant whose negation can be used as an immediate value in a
10510 // data-processing instruction. This can be used in GCC with an "n"
10511 // modifier that prints the negated value, for use with SUB
10512 // instructions. It is not useful otherwise but is implemented for
10514 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10517 // A constant whose negation can be used as an immediate value in a
10518 // data-processing instruction. This can be used in GCC with an "n"
10519 // modifier that prints the negated value, for use with SUB
10520 // instructions. It is not useful otherwise but is implemented for
10522 if (ARM_AM::getSOImmVal(-CVal) != -1)
10528 if (Subtarget->isThumb()) { // FIXME thumb2
10529 // This must be a multiple of 4 between 0 and 1020, for
10530 // ADD sp + immediate.
10531 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10534 // A power of two or a constant between 0 and 32. This is used in
10535 // GCC for the shift amount on shifted register operands, but it is
10536 // useful in general for any shift amounts.
10537 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10543 if (Subtarget->isThumb()) { // FIXME thumb2
10544 // This must be a constant between 0 and 31, for shift amounts.
10545 if (CVal >= 0 && CVal <= 31)
10551 if (Subtarget->isThumb()) { // FIXME thumb2
10552 // This must be a multiple of 4 between -508 and 508, for
10553 // ADD/SUB sp = sp + immediate.
10554 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10559 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10563 if (Result.getNode()) {
10564 Ops.push_back(Result);
10567 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10571 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10572 // The ARM target isn't yet aware of offsets.
10576 bool ARM::isBitFieldInvertedMask(unsigned v) {
10577 if (v == 0xffffffff)
10580 // there can be 1's on either or both "outsides", all the "inside"
10581 // bits must be 0's
10582 unsigned TO = CountTrailingOnes_32(v);
10583 unsigned LO = CountLeadingOnes_32(v);
10584 v = (v >> TO) << TO;
10585 v = (v << LO) >> LO;
10589 /// isFPImmLegal - Returns true if the target can instruction select the
10590 /// specified FP immediate natively. If false, the legalizer will
10591 /// materialize the FP immediate as a load from a constant pool.
10592 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10593 if (!Subtarget->hasVFP3())
10595 if (VT == MVT::f32)
10596 return ARM_AM::getFP32Imm(Imm) != -1;
10597 if (VT == MVT::f64)
10598 return ARM_AM::getFP64Imm(Imm) != -1;
10602 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10603 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10604 /// specified in the intrinsic calls.
10605 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10607 unsigned Intrinsic) const {
10608 switch (Intrinsic) {
10609 case Intrinsic::arm_neon_vld1:
10610 case Intrinsic::arm_neon_vld2:
10611 case Intrinsic::arm_neon_vld3:
10612 case Intrinsic::arm_neon_vld4:
10613 case Intrinsic::arm_neon_vld2lane:
10614 case Intrinsic::arm_neon_vld3lane:
10615 case Intrinsic::arm_neon_vld4lane: {
10616 Info.opc = ISD::INTRINSIC_W_CHAIN;
10617 // Conservatively set memVT to the entire set of vectors loaded.
10618 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10619 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10620 Info.ptrVal = I.getArgOperand(0);
10622 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10623 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10624 Info.vol = false; // volatile loads with NEON intrinsics not supported
10625 Info.readMem = true;
10626 Info.writeMem = false;
10629 case Intrinsic::arm_neon_vst1:
10630 case Intrinsic::arm_neon_vst2:
10631 case Intrinsic::arm_neon_vst3:
10632 case Intrinsic::arm_neon_vst4:
10633 case Intrinsic::arm_neon_vst2lane:
10634 case Intrinsic::arm_neon_vst3lane:
10635 case Intrinsic::arm_neon_vst4lane: {
10636 Info.opc = ISD::INTRINSIC_VOID;
10637 // Conservatively set memVT to the entire set of vectors stored.
10638 unsigned NumElts = 0;
10639 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10640 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10641 if (!ArgTy->isVectorTy())
10643 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10645 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10646 Info.ptrVal = I.getArgOperand(0);
10648 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10649 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10650 Info.vol = false; // volatile stores with NEON intrinsics not supported
10651 Info.readMem = false;
10652 Info.writeMem = true;
10655 case Intrinsic::arm_strexd: {
10656 Info.opc = ISD::INTRINSIC_W_CHAIN;
10657 Info.memVT = MVT::i64;
10658 Info.ptrVal = I.getArgOperand(2);
10662 Info.readMem = false;
10663 Info.writeMem = true;
10666 case Intrinsic::arm_ldrexd: {
10667 Info.opc = ISD::INTRINSIC_W_CHAIN;
10668 Info.memVT = MVT::i64;
10669 Info.ptrVal = I.getArgOperand(0);
10673 Info.readMem = true;
10674 Info.writeMem = false;