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 DebugLoc 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 DebugLoc 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(DebugLoc 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;
1362 DebugLoc &dl = CLI.DL;
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));
1413 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1415 RegsToPassVector RegsToPass;
1416 SmallVector<SDValue, 8> MemOpChains;
1418 // Walk the register/memloc assignments, inserting copies/loads. In the case
1419 // of tail call optimization, arguments are handled later.
1420 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1422 ++i, ++realArgIdx) {
1423 CCValAssign &VA = ArgLocs[i];
1424 SDValue Arg = OutVals[realArgIdx];
1425 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1426 bool isByVal = Flags.isByVal();
1428 // Promote the value if needed.
1429 switch (VA.getLocInfo()) {
1430 default: llvm_unreachable("Unknown loc info!");
1431 case CCValAssign::Full: break;
1432 case CCValAssign::SExt:
1433 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1435 case CCValAssign::ZExt:
1436 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1438 case CCValAssign::AExt:
1439 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1441 case CCValAssign::BCvt:
1442 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1446 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1447 if (VA.needsCustom()) {
1448 if (VA.getLocVT() == MVT::v2f64) {
1449 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1450 DAG.getConstant(0, MVT::i32));
1451 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1452 DAG.getConstant(1, MVT::i32));
1454 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1455 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1457 VA = ArgLocs[++i]; // skip ahead to next loc
1458 if (VA.isRegLoc()) {
1459 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1460 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1462 assert(VA.isMemLoc());
1464 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1465 dl, DAG, VA, Flags));
1468 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1469 StackPtr, MemOpChains, Flags);
1471 } else if (VA.isRegLoc()) {
1472 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1473 assert(VA.getLocVT() == MVT::i32 &&
1474 "unexpected calling convention register assignment");
1475 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1476 "unexpected use of 'returned'");
1477 isThisReturn = true;
1479 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1480 } else if (isByVal) {
1481 assert(VA.isMemLoc());
1482 unsigned offset = 0;
1484 // True if this byval aggregate will be split between registers
1486 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1487 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1489 if (CurByValIdx < ByValArgsCount) {
1491 unsigned RegBegin, RegEnd;
1492 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1494 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1496 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1497 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1498 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1499 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1500 MachinePointerInfo(),
1501 false, false, false, 0);
1502 MemOpChains.push_back(Load.getValue(1));
1503 RegsToPass.push_back(std::make_pair(j, Load));
1506 // If parameter size outsides register area, "offset" value
1507 // helps us to calculate stack slot for remained part properly.
1508 offset = RegEnd - RegBegin;
1510 CCInfo.nextInRegsParam();
1513 if (Flags.getByValSize() > 4*offset) {
1514 unsigned LocMemOffset = VA.getLocMemOffset();
1515 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1516 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1518 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1519 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1520 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1522 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1524 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1525 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1526 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1527 Ops, array_lengthof(Ops)));
1529 } else if (!isSibCall) {
1530 assert(VA.isMemLoc());
1532 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1533 dl, DAG, VA, Flags));
1537 if (!MemOpChains.empty())
1538 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1539 &MemOpChains[0], MemOpChains.size());
1541 // Build a sequence of copy-to-reg nodes chained together with token chain
1542 // and flag operands which copy the outgoing args into the appropriate regs.
1544 // Tail call byval lowering might overwrite argument registers so in case of
1545 // tail call optimization the copies to registers are lowered later.
1547 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1548 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1549 RegsToPass[i].second, InFlag);
1550 InFlag = Chain.getValue(1);
1553 // For tail calls lower the arguments to the 'real' stack slot.
1555 // Force all the incoming stack arguments to be loaded from the stack
1556 // before any new outgoing arguments are stored to the stack, because the
1557 // outgoing stack slots may alias the incoming argument stack slots, and
1558 // the alias isn't otherwise explicit. This is slightly more conservative
1559 // than necessary, because it means that each store effectively depends
1560 // on every argument instead of just those arguments it would clobber.
1562 // Do not flag preceding copytoreg stuff together with the following stuff.
1564 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1565 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1566 RegsToPass[i].second, InFlag);
1567 InFlag = Chain.getValue(1);
1572 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1573 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1574 // node so that legalize doesn't hack it.
1575 bool isDirect = false;
1576 bool isARMFunc = false;
1577 bool isLocalARMFunc = false;
1578 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1580 if (EnableARMLongCalls) {
1581 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1582 && "long-calls with non-static relocation model!");
1583 // Handle a global address or an external symbol. If it's not one of
1584 // those, the target's already in a register, so we don't need to do
1586 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1587 const GlobalValue *GV = G->getGlobal();
1588 // Create a constant pool entry for the callee address
1589 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1590 ARMConstantPoolValue *CPV =
1591 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1593 // Get the address of the callee into a register
1594 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1595 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1596 Callee = DAG.getLoad(getPointerTy(), dl,
1597 DAG.getEntryNode(), CPAddr,
1598 MachinePointerInfo::getConstantPool(),
1599 false, false, false, 0);
1600 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1601 const char *Sym = S->getSymbol();
1603 // Create a constant pool entry for the callee address
1604 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1605 ARMConstantPoolValue *CPV =
1606 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1607 ARMPCLabelIndex, 0);
1608 // Get the address of the callee into a register
1609 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1610 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1611 Callee = DAG.getLoad(getPointerTy(), dl,
1612 DAG.getEntryNode(), CPAddr,
1613 MachinePointerInfo::getConstantPool(),
1614 false, false, false, 0);
1616 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1617 const GlobalValue *GV = G->getGlobal();
1619 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1620 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1621 getTargetMachine().getRelocationModel() != Reloc::Static;
1622 isARMFunc = !Subtarget->isThumb() || isStub;
1623 // ARM call to a local ARM function is predicable.
1624 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1625 // tBX takes a register source operand.
1626 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1627 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1628 ARMConstantPoolValue *CPV =
1629 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1630 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1631 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1632 Callee = DAG.getLoad(getPointerTy(), dl,
1633 DAG.getEntryNode(), CPAddr,
1634 MachinePointerInfo::getConstantPool(),
1635 false, false, false, 0);
1636 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1637 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1638 getPointerTy(), Callee, PICLabel);
1640 // On ELF targets for PIC code, direct calls should go through the PLT
1641 unsigned OpFlags = 0;
1642 if (Subtarget->isTargetELF() &&
1643 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1644 OpFlags = ARMII::MO_PLT;
1645 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1647 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1649 bool isStub = Subtarget->isTargetDarwin() &&
1650 getTargetMachine().getRelocationModel() != Reloc::Static;
1651 isARMFunc = !Subtarget->isThumb() || isStub;
1652 // tBX takes a register source operand.
1653 const char *Sym = S->getSymbol();
1654 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1655 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1656 ARMConstantPoolValue *CPV =
1657 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1658 ARMPCLabelIndex, 4);
1659 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1660 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1661 Callee = DAG.getLoad(getPointerTy(), dl,
1662 DAG.getEntryNode(), CPAddr,
1663 MachinePointerInfo::getConstantPool(),
1664 false, false, false, 0);
1665 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1666 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1667 getPointerTy(), Callee, PICLabel);
1669 unsigned OpFlags = 0;
1670 // On ELF targets for PIC code, direct calls should go through the PLT
1671 if (Subtarget->isTargetELF() &&
1672 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1673 OpFlags = ARMII::MO_PLT;
1674 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1678 // FIXME: handle tail calls differently.
1680 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1681 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1682 if (Subtarget->isThumb()) {
1683 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1684 CallOpc = ARMISD::CALL_NOLINK;
1686 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1688 if (!isDirect && !Subtarget->hasV5TOps())
1689 CallOpc = ARMISD::CALL_NOLINK;
1690 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1691 // Emit regular call when code size is the priority
1693 // "mov lr, pc; b _foo" to avoid confusing the RSP
1694 CallOpc = ARMISD::CALL_NOLINK;
1696 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1699 std::vector<SDValue> Ops;
1700 Ops.push_back(Chain);
1701 Ops.push_back(Callee);
1703 // Add argument registers to the end of the list so that they are known live
1705 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1706 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1707 RegsToPass[i].second.getValueType()));
1709 // Add a register mask operand representing the call-preserved registers.
1710 const uint32_t *Mask;
1711 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1712 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1714 // For 'this' returns, use the R0-preserving mask
1715 Mask = ARI->getThisReturnPreservedMask(CallConv);
1717 Mask = ARI->getCallPreservedMask(CallConv);
1719 assert(Mask && "Missing call preserved mask for calling convention");
1720 Ops.push_back(DAG.getRegisterMask(Mask));
1722 if (InFlag.getNode())
1723 Ops.push_back(InFlag);
1725 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1727 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1729 // Returns a chain and a flag for retval copy to use.
1730 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1731 InFlag = Chain.getValue(1);
1733 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1734 DAG.getIntPtrConstant(0, true), InFlag);
1736 InFlag = Chain.getValue(1);
1738 // Handle result values, copying them out of physregs into vregs that we
1740 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1741 InVals, isThisReturn,
1742 isThisReturn ? OutVals[0] : SDValue());
1745 /// HandleByVal - Every parameter *after* a byval parameter is passed
1746 /// on the stack. Remember the next parameter register to allocate,
1747 /// and then confiscate the rest of the parameter registers to insure
1750 ARMTargetLowering::HandleByVal(
1751 CCState *State, unsigned &size, unsigned Align) const {
1752 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1753 assert((State->getCallOrPrologue() == Prologue ||
1754 State->getCallOrPrologue() == Call) &&
1755 "unhandled ParmContext");
1757 // For in-prologue parameters handling, we also introduce stack offset
1758 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1759 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1760 // NSAA should be evaluted (NSAA means "next stacked argument address").
1761 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1762 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1763 unsigned NSAAOffset = State->getNextStackOffset();
1764 if (State->getCallOrPrologue() != Call) {
1765 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1767 State->getInRegsParamInfo(i, RB, RE);
1768 assert(NSAAOffset >= (RE-RB)*4 &&
1769 "Stack offset for byval regs doesn't introduced anymore?");
1770 NSAAOffset -= (RE-RB)*4;
1773 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1774 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1775 unsigned AlignInRegs = Align / 4;
1776 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1777 for (unsigned i = 0; i < Waste; ++i)
1778 reg = State->AllocateReg(GPRArgRegs, 4);
1781 unsigned excess = 4 * (ARM::R4 - reg);
1783 // Special case when NSAA != SP and parameter size greater than size of
1784 // all remained GPR regs. In that case we can't split parameter, we must
1785 // send it to stack. We also must set NCRN to R4, so waste all
1786 // remained registers.
1787 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1788 while (State->AllocateReg(GPRArgRegs, 4))
1793 // First register for byval parameter is the first register that wasn't
1794 // allocated before this method call, so it would be "reg".
1795 // If parameter is small enough to be saved in range [reg, r4), then
1796 // the end (first after last) register would be reg + param-size-in-regs,
1797 // else parameter would be splitted between registers and stack,
1798 // end register would be r4 in this case.
1799 unsigned ByValRegBegin = reg;
1800 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1801 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1802 // Note, first register is allocated in the beginning of function already,
1803 // allocate remained amount of registers we need.
1804 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1805 State->AllocateReg(GPRArgRegs, 4);
1806 // At a call site, a byval parameter that is split between
1807 // registers and memory needs its size truncated here. In a
1808 // function prologue, such byval parameters are reassembled in
1809 // memory, and are not truncated.
1810 if (State->getCallOrPrologue() == Call) {
1811 // Make remained size equal to 0 in case, when
1812 // the whole structure may be stored into registers.
1822 /// MatchingStackOffset - Return true if the given stack call argument is
1823 /// already available in the same position (relatively) of the caller's
1824 /// incoming argument stack.
1826 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1827 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1828 const TargetInstrInfo *TII) {
1829 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1831 if (Arg.getOpcode() == ISD::CopyFromReg) {
1832 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1833 if (!TargetRegisterInfo::isVirtualRegister(VR))
1835 MachineInstr *Def = MRI->getVRegDef(VR);
1838 if (!Flags.isByVal()) {
1839 if (!TII->isLoadFromStackSlot(Def, FI))
1844 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1845 if (Flags.isByVal())
1846 // ByVal argument is passed in as a pointer but it's now being
1847 // dereferenced. e.g.
1848 // define @foo(%struct.X* %A) {
1849 // tail call @bar(%struct.X* byval %A)
1852 SDValue Ptr = Ld->getBasePtr();
1853 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1856 FI = FINode->getIndex();
1860 assert(FI != INT_MAX);
1861 if (!MFI->isFixedObjectIndex(FI))
1863 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1866 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1867 /// for tail call optimization. Targets which want to do tail call
1868 /// optimization should implement this function.
1870 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1871 CallingConv::ID CalleeCC,
1873 bool isCalleeStructRet,
1874 bool isCallerStructRet,
1875 const SmallVectorImpl<ISD::OutputArg> &Outs,
1876 const SmallVectorImpl<SDValue> &OutVals,
1877 const SmallVectorImpl<ISD::InputArg> &Ins,
1878 SelectionDAG& DAG) const {
1879 const Function *CallerF = DAG.getMachineFunction().getFunction();
1880 CallingConv::ID CallerCC = CallerF->getCallingConv();
1881 bool CCMatch = CallerCC == CalleeCC;
1883 // Look for obvious safe cases to perform tail call optimization that do not
1884 // require ABI changes. This is what gcc calls sibcall.
1886 // Do not sibcall optimize vararg calls unless the call site is not passing
1888 if (isVarArg && !Outs.empty())
1891 // Also avoid sibcall optimization if either caller or callee uses struct
1892 // return semantics.
1893 if (isCalleeStructRet || isCallerStructRet)
1896 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1897 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1898 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1899 // support in the assembler and linker to be used. This would need to be
1900 // fixed to fully support tail calls in Thumb1.
1902 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1903 // LR. This means if we need to reload LR, it takes an extra instructions,
1904 // which outweighs the value of the tail call; but here we don't know yet
1905 // whether LR is going to be used. Probably the right approach is to
1906 // generate the tail call here and turn it back into CALL/RET in
1907 // emitEpilogue if LR is used.
1909 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1910 // but we need to make sure there are enough registers; the only valid
1911 // registers are the 4 used for parameters. We don't currently do this
1913 if (Subtarget->isThumb1Only())
1916 // If the calling conventions do not match, then we'd better make sure the
1917 // results are returned in the same way as what the caller expects.
1919 SmallVector<CCValAssign, 16> RVLocs1;
1920 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1921 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1922 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1924 SmallVector<CCValAssign, 16> RVLocs2;
1925 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1926 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1927 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1929 if (RVLocs1.size() != RVLocs2.size())
1931 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1932 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1934 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1936 if (RVLocs1[i].isRegLoc()) {
1937 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1940 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1946 // If Caller's vararg or byval argument has been split between registers and
1947 // stack, do not perform tail call, since part of the argument is in caller's
1949 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1950 getInfo<ARMFunctionInfo>();
1951 if (AFI_Caller->getArgRegsSaveSize())
1954 // If the callee takes no arguments then go on to check the results of the
1956 if (!Outs.empty()) {
1957 // Check if stack adjustment is needed. For now, do not do this if any
1958 // argument is passed on the stack.
1959 SmallVector<CCValAssign, 16> ArgLocs;
1960 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1961 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1962 CCInfo.AnalyzeCallOperands(Outs,
1963 CCAssignFnForNode(CalleeCC, false, isVarArg));
1964 if (CCInfo.getNextStackOffset()) {
1965 MachineFunction &MF = DAG.getMachineFunction();
1967 // Check if the arguments are already laid out in the right way as
1968 // the caller's fixed stack objects.
1969 MachineFrameInfo *MFI = MF.getFrameInfo();
1970 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1971 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1972 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1974 ++i, ++realArgIdx) {
1975 CCValAssign &VA = ArgLocs[i];
1976 EVT RegVT = VA.getLocVT();
1977 SDValue Arg = OutVals[realArgIdx];
1978 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1979 if (VA.getLocInfo() == CCValAssign::Indirect)
1981 if (VA.needsCustom()) {
1982 // f64 and vector types are split into multiple registers or
1983 // register/stack-slot combinations. The types will not match
1984 // the registers; give up on memory f64 refs until we figure
1985 // out what to do about this.
1988 if (!ArgLocs[++i].isRegLoc())
1990 if (RegVT == MVT::v2f64) {
1991 if (!ArgLocs[++i].isRegLoc())
1993 if (!ArgLocs[++i].isRegLoc())
1996 } else if (!VA.isRegLoc()) {
1997 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2009 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2010 MachineFunction &MF, bool isVarArg,
2011 const SmallVectorImpl<ISD::OutputArg> &Outs,
2012 LLVMContext &Context) const {
2013 SmallVector<CCValAssign, 16> RVLocs;
2014 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2015 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2020 ARMTargetLowering::LowerReturn(SDValue Chain,
2021 CallingConv::ID CallConv, bool isVarArg,
2022 const SmallVectorImpl<ISD::OutputArg> &Outs,
2023 const SmallVectorImpl<SDValue> &OutVals,
2024 DebugLoc dl, SelectionDAG &DAG) const {
2026 // CCValAssign - represent the assignment of the return value to a location.
2027 SmallVector<CCValAssign, 16> RVLocs;
2029 // CCState - Info about the registers and stack slots.
2030 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2031 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2033 // Analyze outgoing return values.
2034 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2038 SmallVector<SDValue, 4> RetOps;
2039 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2041 // Copy the result values into the output registers.
2042 for (unsigned i = 0, realRVLocIdx = 0;
2044 ++i, ++realRVLocIdx) {
2045 CCValAssign &VA = RVLocs[i];
2046 assert(VA.isRegLoc() && "Can only return in registers!");
2048 SDValue Arg = OutVals[realRVLocIdx];
2050 switch (VA.getLocInfo()) {
2051 default: llvm_unreachable("Unknown loc info!");
2052 case CCValAssign::Full: break;
2053 case CCValAssign::BCvt:
2054 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2058 if (VA.needsCustom()) {
2059 if (VA.getLocVT() == MVT::v2f64) {
2060 // Extract the first half and return it in two registers.
2061 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2062 DAG.getConstant(0, MVT::i32));
2063 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2064 DAG.getVTList(MVT::i32, MVT::i32), Half);
2066 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2067 Flag = Chain.getValue(1);
2068 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2069 VA = RVLocs[++i]; // skip ahead to next loc
2070 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2071 HalfGPRs.getValue(1), Flag);
2072 Flag = Chain.getValue(1);
2073 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2074 VA = RVLocs[++i]; // skip ahead to next loc
2076 // Extract the 2nd half and fall through to handle it as an f64 value.
2077 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2078 DAG.getConstant(1, MVT::i32));
2080 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2082 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2083 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2084 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2085 Flag = Chain.getValue(1);
2086 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2087 VA = RVLocs[++i]; // skip ahead to next loc
2088 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2091 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2093 // Guarantee that all emitted copies are
2094 // stuck together, avoiding something bad.
2095 Flag = Chain.getValue(1);
2096 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2099 // Update chain and glue.
2102 RetOps.push_back(Flag);
2104 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2105 RetOps.data(), RetOps.size());
2108 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2109 if (N->getNumValues() != 1)
2111 if (!N->hasNUsesOfValue(1, 0))
2114 SDValue TCChain = Chain;
2115 SDNode *Copy = *N->use_begin();
2116 if (Copy->getOpcode() == ISD::CopyToReg) {
2117 // If the copy has a glue operand, we conservatively assume it isn't safe to
2118 // perform a tail call.
2119 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2121 TCChain = Copy->getOperand(0);
2122 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2123 SDNode *VMov = Copy;
2124 // f64 returned in a pair of GPRs.
2125 SmallPtrSet<SDNode*, 2> Copies;
2126 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2128 if (UI->getOpcode() != ISD::CopyToReg)
2132 if (Copies.size() > 2)
2135 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2137 SDValue UseChain = UI->getOperand(0);
2138 if (Copies.count(UseChain.getNode()))
2145 } else if (Copy->getOpcode() == ISD::BITCAST) {
2146 // f32 returned in a single GPR.
2147 if (!Copy->hasOneUse())
2149 Copy = *Copy->use_begin();
2150 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2152 TCChain = Copy->getOperand(0);
2157 bool HasRet = false;
2158 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2160 if (UI->getOpcode() != ARMISD::RET_FLAG)
2172 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2173 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2176 if (!CI->isTailCall())
2179 return !Subtarget->isThumb1Only();
2182 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2183 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2184 // one of the above mentioned nodes. It has to be wrapped because otherwise
2185 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2186 // be used to form addressing mode. These wrapped nodes will be selected
2188 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2189 EVT PtrVT = Op.getValueType();
2190 // FIXME there is no actual debug info here
2191 DebugLoc dl = Op.getDebugLoc();
2192 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2194 if (CP->isMachineConstantPoolEntry())
2195 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2196 CP->getAlignment());
2198 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2199 CP->getAlignment());
2200 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2203 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2204 return MachineJumpTableInfo::EK_Inline;
2207 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2208 SelectionDAG &DAG) const {
2209 MachineFunction &MF = DAG.getMachineFunction();
2210 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2211 unsigned ARMPCLabelIndex = 0;
2212 DebugLoc DL = Op.getDebugLoc();
2213 EVT PtrVT = getPointerTy();
2214 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2215 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2217 if (RelocM == Reloc::Static) {
2218 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2220 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2221 ARMPCLabelIndex = AFI->createPICLabelUId();
2222 ARMConstantPoolValue *CPV =
2223 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2224 ARMCP::CPBlockAddress, PCAdj);
2225 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2227 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2228 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2229 MachinePointerInfo::getConstantPool(),
2230 false, false, false, 0);
2231 if (RelocM == Reloc::Static)
2233 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2234 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2237 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2239 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2240 SelectionDAG &DAG) const {
2241 DebugLoc dl = GA->getDebugLoc();
2242 EVT PtrVT = getPointerTy();
2243 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2244 MachineFunction &MF = DAG.getMachineFunction();
2245 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2246 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2247 ARMConstantPoolValue *CPV =
2248 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2249 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2250 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2251 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2252 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2253 MachinePointerInfo::getConstantPool(),
2254 false, false, false, 0);
2255 SDValue Chain = Argument.getValue(1);
2257 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2258 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2260 // call __tls_get_addr.
2263 Entry.Node = Argument;
2264 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2265 Args.push_back(Entry);
2266 // FIXME: is there useful debug info available here?
2267 TargetLowering::CallLoweringInfo CLI(Chain,
2268 (Type *) Type::getInt32Ty(*DAG.getContext()),
2269 false, false, false, false,
2270 0, CallingConv::C, /*isTailCall=*/false,
2271 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2272 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2273 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2274 return CallResult.first;
2277 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2278 // "local exec" model.
2280 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2282 TLSModel::Model model) const {
2283 const GlobalValue *GV = GA->getGlobal();
2284 DebugLoc dl = GA->getDebugLoc();
2286 SDValue Chain = DAG.getEntryNode();
2287 EVT PtrVT = getPointerTy();
2288 // Get the Thread Pointer
2289 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2291 if (model == TLSModel::InitialExec) {
2292 MachineFunction &MF = DAG.getMachineFunction();
2293 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2294 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2295 // Initial exec model.
2296 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2297 ARMConstantPoolValue *CPV =
2298 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2299 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2301 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2302 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2303 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2304 MachinePointerInfo::getConstantPool(),
2305 false, false, false, 0);
2306 Chain = Offset.getValue(1);
2308 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2309 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2311 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2312 MachinePointerInfo::getConstantPool(),
2313 false, false, false, 0);
2316 assert(model == TLSModel::LocalExec);
2317 ARMConstantPoolValue *CPV =
2318 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2319 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2320 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2321 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2322 MachinePointerInfo::getConstantPool(),
2323 false, false, false, 0);
2326 // The address of the thread local variable is the add of the thread
2327 // pointer with the offset of the variable.
2328 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2332 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2333 // TODO: implement the "local dynamic" model
2334 assert(Subtarget->isTargetELF() &&
2335 "TLS not implemented for non-ELF targets");
2336 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2338 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2341 case TLSModel::GeneralDynamic:
2342 case TLSModel::LocalDynamic:
2343 return LowerToTLSGeneralDynamicModel(GA, DAG);
2344 case TLSModel::InitialExec:
2345 case TLSModel::LocalExec:
2346 return LowerToTLSExecModels(GA, DAG, model);
2348 llvm_unreachable("bogus TLS model");
2351 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2352 SelectionDAG &DAG) const {
2353 EVT PtrVT = getPointerTy();
2354 DebugLoc dl = Op.getDebugLoc();
2355 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2356 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2357 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2358 ARMConstantPoolValue *CPV =
2359 ARMConstantPoolConstant::Create(GV,
2360 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2361 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2362 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2363 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2365 MachinePointerInfo::getConstantPool(),
2366 false, false, false, 0);
2367 SDValue Chain = Result.getValue(1);
2368 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2369 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2371 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2372 MachinePointerInfo::getGOT(),
2373 false, false, false, 0);
2377 // If we have T2 ops, we can materialize the address directly via movt/movw
2378 // pair. This is always cheaper.
2379 if (Subtarget->useMovt()) {
2381 // FIXME: Once remat is capable of dealing with instructions with register
2382 // operands, expand this into two nodes.
2383 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2384 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2386 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2387 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2388 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2389 MachinePointerInfo::getConstantPool(),
2390 false, false, false, 0);
2394 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2395 SelectionDAG &DAG) const {
2396 EVT PtrVT = getPointerTy();
2397 DebugLoc dl = Op.getDebugLoc();
2398 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2399 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2401 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2402 // update ARMFastISel::ARMMaterializeGV.
2403 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2405 // FIXME: Once remat is capable of dealing with instructions with register
2406 // operands, expand this into two nodes.
2407 if (RelocM == Reloc::Static)
2408 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2409 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2411 unsigned Wrapper = (RelocM == Reloc::PIC_)
2412 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2413 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2414 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2415 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2416 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2417 MachinePointerInfo::getGOT(),
2418 false, false, false, 0);
2422 unsigned ARMPCLabelIndex = 0;
2424 if (RelocM == Reloc::Static) {
2425 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2427 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2428 ARMPCLabelIndex = AFI->createPICLabelUId();
2429 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2430 ARMConstantPoolValue *CPV =
2431 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2433 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2435 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2437 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2438 MachinePointerInfo::getConstantPool(),
2439 false, false, false, 0);
2440 SDValue Chain = Result.getValue(1);
2442 if (RelocM == Reloc::PIC_) {
2443 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2444 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2447 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2448 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2449 false, false, false, 0);
2454 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2455 SelectionDAG &DAG) const {
2456 assert(Subtarget->isTargetELF() &&
2457 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2458 MachineFunction &MF = DAG.getMachineFunction();
2459 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2460 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2461 EVT PtrVT = getPointerTy();
2462 DebugLoc dl = Op.getDebugLoc();
2463 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2464 ARMConstantPoolValue *CPV =
2465 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2466 ARMPCLabelIndex, PCAdj);
2467 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2468 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2469 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2470 MachinePointerInfo::getConstantPool(),
2471 false, false, false, 0);
2472 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2473 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2477 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2478 DebugLoc dl = Op.getDebugLoc();
2479 SDValue Val = DAG.getConstant(0, MVT::i32);
2480 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2481 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2482 Op.getOperand(1), Val);
2486 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2487 DebugLoc dl = Op.getDebugLoc();
2488 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2489 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2493 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2494 const ARMSubtarget *Subtarget) const {
2495 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2496 DebugLoc dl = Op.getDebugLoc();
2498 default: return SDValue(); // Don't custom lower most intrinsics.
2499 case Intrinsic::arm_thread_pointer: {
2500 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2501 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2503 case Intrinsic::eh_sjlj_lsda: {
2504 MachineFunction &MF = DAG.getMachineFunction();
2505 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2506 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2507 EVT PtrVT = getPointerTy();
2508 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2510 unsigned PCAdj = (RelocM != Reloc::PIC_)
2511 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2512 ARMConstantPoolValue *CPV =
2513 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2514 ARMCP::CPLSDA, PCAdj);
2515 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2516 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2518 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2519 MachinePointerInfo::getConstantPool(),
2520 false, false, false, 0);
2522 if (RelocM == Reloc::PIC_) {
2523 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2524 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2528 case Intrinsic::arm_neon_vmulls:
2529 case Intrinsic::arm_neon_vmullu: {
2530 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2531 ? ARMISD::VMULLs : ARMISD::VMULLu;
2532 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2533 Op.getOperand(1), Op.getOperand(2));
2538 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2539 const ARMSubtarget *Subtarget) {
2540 // FIXME: handle "fence singlethread" more efficiently.
2541 DebugLoc dl = Op.getDebugLoc();
2542 if (!Subtarget->hasDataBarrier()) {
2543 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2544 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2546 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2547 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2548 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2549 DAG.getConstant(0, MVT::i32));
2552 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2553 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2556 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2557 const ARMSubtarget *Subtarget) {
2558 // ARM pre v5TE and Thumb1 does not have preload instructions.
2559 if (!(Subtarget->isThumb2() ||
2560 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2561 // Just preserve the chain.
2562 return Op.getOperand(0);
2564 DebugLoc dl = Op.getDebugLoc();
2565 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2567 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2568 // ARMv7 with MP extension has PLDW.
2569 return Op.getOperand(0);
2571 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2572 if (Subtarget->isThumb()) {
2574 isRead = ~isRead & 1;
2575 isData = ~isData & 1;
2578 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2579 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2580 DAG.getConstant(isData, MVT::i32));
2583 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2584 MachineFunction &MF = DAG.getMachineFunction();
2585 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2587 // vastart just stores the address of the VarArgsFrameIndex slot into the
2588 // memory location argument.
2589 DebugLoc dl = Op.getDebugLoc();
2590 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2591 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2592 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2593 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2594 MachinePointerInfo(SV), false, false, 0);
2598 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2599 SDValue &Root, SelectionDAG &DAG,
2600 DebugLoc dl) const {
2601 MachineFunction &MF = DAG.getMachineFunction();
2602 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2604 const TargetRegisterClass *RC;
2605 if (AFI->isThumb1OnlyFunction())
2606 RC = &ARM::tGPRRegClass;
2608 RC = &ARM::GPRRegClass;
2610 // Transform the arguments stored in physical registers into virtual ones.
2611 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2612 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2615 if (NextVA.isMemLoc()) {
2616 MachineFrameInfo *MFI = MF.getFrameInfo();
2617 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2619 // Create load node to retrieve arguments from the stack.
2620 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2621 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2622 MachinePointerInfo::getFixedStack(FI),
2623 false, false, false, 0);
2625 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2626 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2629 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2633 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2634 unsigned InRegsParamRecordIdx,
2636 unsigned &ArgRegsSize,
2637 unsigned &ArgRegsSaveSize)
2640 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2641 unsigned RBegin, REnd;
2642 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2643 NumGPRs = REnd - RBegin;
2645 unsigned int firstUnalloced;
2646 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2647 sizeof(GPRArgRegs) /
2648 sizeof(GPRArgRegs[0]));
2649 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2652 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2653 ArgRegsSize = NumGPRs * 4;
2655 // If parameter is split between stack and GPRs...
2656 if (NumGPRs && Align == 8 &&
2657 (ArgRegsSize < ArgSize ||
2658 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2659 // Add padding for part of param recovered from GPRs, so
2660 // its last byte must be at address K*8 - 1.
2661 // We need to do it, since remained (stack) part of parameter has
2662 // stack alignment, and we need to "attach" "GPRs head" without gaps
2665 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2666 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2668 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2670 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2671 (ArgRegsSize + AFI->getArgRegsSaveSize());
2672 ArgRegsSaveSize = ArgRegsSize + Padding;
2674 // We don't need to extend regs save size for byval parameters if they
2675 // are passed via GPRs only.
2676 ArgRegsSaveSize = ArgRegsSize;
2679 // The remaining GPRs hold either the beginning of variable-argument
2680 // data, or the beginning of an aggregate passed by value (usually
2681 // byval). Either way, we allocate stack slots adjacent to the data
2682 // provided by our caller, and store the unallocated registers there.
2683 // If this is a variadic function, the va_list pointer will begin with
2684 // these values; otherwise, this reassembles a (byval) structure that
2685 // was split between registers and memory.
2686 // Return: The frame index registers were stored into.
2688 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2689 DebugLoc dl, SDValue &Chain,
2690 const Value *OrigArg,
2691 unsigned InRegsParamRecordIdx,
2692 unsigned OffsetFromOrigArg,
2695 bool ForceMutable) const {
2697 // Currently, two use-cases possible:
2698 // Case #1. Non var-args function, and we meet first byval parameter.
2699 // Setup first unallocated register as first byval register;
2700 // eat all remained registers
2701 // (these two actions are performed by HandleByVal method).
2702 // Then, here, we initialize stack frame with
2703 // "store-reg" instructions.
2704 // Case #2. Var-args function, that doesn't contain byval parameters.
2705 // The same: eat all remained unallocated registers,
2706 // initialize stack frame.
2708 MachineFunction &MF = DAG.getMachineFunction();
2709 MachineFrameInfo *MFI = MF.getFrameInfo();
2710 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2711 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2712 unsigned RBegin, REnd;
2713 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2714 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2715 firstRegToSaveIndex = RBegin - ARM::R0;
2716 lastRegToSaveIndex = REnd - ARM::R0;
2718 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2719 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2720 lastRegToSaveIndex = 4;
2723 unsigned ArgRegsSize, ArgRegsSaveSize;
2724 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2725 ArgRegsSize, ArgRegsSaveSize);
2727 // Store any by-val regs to their spots on the stack so that they may be
2728 // loaded by deferencing the result of formal parameter pointer or va_next.
2729 // Note: once stack area for byval/varargs registers
2730 // was initialized, it can't be initialized again.
2731 if (ArgRegsSaveSize) {
2733 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2736 assert(AFI->getStoredByValParamsPadding() == 0 &&
2737 "The only parameter may be padded.");
2738 AFI->setStoredByValParamsPadding(Padding);
2741 int FrameIndex = MFI->CreateFixedObject(
2743 Padding + ArgOffset,
2745 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2747 SmallVector<SDValue, 4> MemOps;
2748 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2749 ++firstRegToSaveIndex, ++i) {
2750 const TargetRegisterClass *RC;
2751 if (AFI->isThumb1OnlyFunction())
2752 RC = &ARM::tGPRRegClass;
2754 RC = &ARM::GPRRegClass;
2756 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2757 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2759 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2760 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2762 MemOps.push_back(Store);
2763 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2764 DAG.getConstant(4, getPointerTy()));
2767 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2769 if (!MemOps.empty())
2770 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2771 &MemOps[0], MemOps.size());
2774 // This will point to the next argument passed via stack.
2775 return MFI->CreateFixedObject(
2776 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2779 // Setup stack frame, the va_list pointer will start from.
2781 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2782 DebugLoc dl, SDValue &Chain,
2784 bool ForceMutable) const {
2785 MachineFunction &MF = DAG.getMachineFunction();
2786 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2788 // Try to store any remaining integer argument regs
2789 // to their spots on the stack so that they may be loaded by deferencing
2790 // the result of va_next.
2791 // If there is no regs to be stored, just point address after last
2792 // argument passed via stack.
2794 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2795 0, ArgOffset, 0, ForceMutable);
2797 AFI->setVarArgsFrameIndex(FrameIndex);
2801 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2802 CallingConv::ID CallConv, bool isVarArg,
2803 const SmallVectorImpl<ISD::InputArg>
2805 DebugLoc dl, SelectionDAG &DAG,
2806 SmallVectorImpl<SDValue> &InVals)
2808 MachineFunction &MF = DAG.getMachineFunction();
2809 MachineFrameInfo *MFI = MF.getFrameInfo();
2811 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2813 // Assign locations to all of the incoming arguments.
2814 SmallVector<CCValAssign, 16> ArgLocs;
2815 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2816 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2817 CCInfo.AnalyzeFormalArguments(Ins,
2818 CCAssignFnForNode(CallConv, /* Return*/ false,
2821 SmallVector<SDValue, 16> ArgValues;
2822 int lastInsIndex = -1;
2824 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2825 unsigned CurArgIdx = 0;
2827 // Initially ArgRegsSaveSize is zero.
2828 // Then we increase this value each time we meet byval parameter.
2829 // We also increase this value in case of varargs function.
2830 AFI->setArgRegsSaveSize(0);
2832 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2833 CCValAssign &VA = ArgLocs[i];
2834 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2835 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2836 // Arguments stored in registers.
2837 if (VA.isRegLoc()) {
2838 EVT RegVT = VA.getLocVT();
2840 if (VA.needsCustom()) {
2841 // f64 and vector types are split up into multiple registers or
2842 // combinations of registers and stack slots.
2843 if (VA.getLocVT() == MVT::v2f64) {
2844 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2846 VA = ArgLocs[++i]; // skip ahead to next loc
2848 if (VA.isMemLoc()) {
2849 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2850 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2851 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2852 MachinePointerInfo::getFixedStack(FI),
2853 false, false, false, 0);
2855 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2858 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2859 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2860 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2861 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2862 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2864 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2867 const TargetRegisterClass *RC;
2869 if (RegVT == MVT::f32)
2870 RC = &ARM::SPRRegClass;
2871 else if (RegVT == MVT::f64)
2872 RC = &ARM::DPRRegClass;
2873 else if (RegVT == MVT::v2f64)
2874 RC = &ARM::QPRRegClass;
2875 else if (RegVT == MVT::i32)
2876 RC = AFI->isThumb1OnlyFunction() ?
2877 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2878 (const TargetRegisterClass*)&ARM::GPRRegClass;
2880 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2882 // Transform the arguments in physical registers into virtual ones.
2883 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2884 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2887 // If this is an 8 or 16-bit value, it is really passed promoted
2888 // to 32 bits. Insert an assert[sz]ext to capture this, then
2889 // truncate to the right size.
2890 switch (VA.getLocInfo()) {
2891 default: llvm_unreachable("Unknown loc info!");
2892 case CCValAssign::Full: break;
2893 case CCValAssign::BCvt:
2894 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2896 case CCValAssign::SExt:
2897 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2898 DAG.getValueType(VA.getValVT()));
2899 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2901 case CCValAssign::ZExt:
2902 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2903 DAG.getValueType(VA.getValVT()));
2904 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2908 InVals.push_back(ArgValue);
2910 } else { // VA.isRegLoc()
2913 assert(VA.isMemLoc());
2914 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2916 int index = ArgLocs[i].getValNo();
2918 // Some Ins[] entries become multiple ArgLoc[] entries.
2919 // Process them only once.
2920 if (index != lastInsIndex)
2922 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2923 // FIXME: For now, all byval parameter objects are marked mutable.
2924 // This can be changed with more analysis.
2925 // In case of tail call optimization mark all arguments mutable.
2926 // Since they could be overwritten by lowering of arguments in case of
2928 if (Flags.isByVal()) {
2929 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2930 int FrameIndex = StoreByValRegs(
2931 CCInfo, DAG, dl, Chain, CurOrigArg,
2933 Ins[VA.getValNo()].PartOffset,
2934 VA.getLocMemOffset(),
2935 Flags.getByValSize(),
2936 true /*force mutable frames*/);
2937 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2938 CCInfo.nextInRegsParam();
2940 unsigned FIOffset = VA.getLocMemOffset() +
2941 AFI->getStoredByValParamsPadding();
2942 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2945 // Create load nodes to retrieve arguments from the stack.
2946 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2947 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2948 MachinePointerInfo::getFixedStack(FI),
2949 false, false, false, 0));
2951 lastInsIndex = index;
2958 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2959 CCInfo.getNextStackOffset());
2964 /// isFloatingPointZero - Return true if this is +0.0.
2965 static bool isFloatingPointZero(SDValue Op) {
2966 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2967 return CFP->getValueAPF().isPosZero();
2968 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2969 // Maybe this has already been legalized into the constant pool?
2970 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2971 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2972 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2973 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2974 return CFP->getValueAPF().isPosZero();
2980 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2981 /// the given operands.
2983 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2984 SDValue &ARMcc, SelectionDAG &DAG,
2985 DebugLoc dl) const {
2986 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2987 unsigned C = RHSC->getZExtValue();
2988 if (!isLegalICmpImmediate(C)) {
2989 // Constant does not fit, try adjusting it by one?
2994 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2995 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2996 RHS = DAG.getConstant(C-1, MVT::i32);
3001 if (C != 0 && isLegalICmpImmediate(C-1)) {
3002 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3003 RHS = DAG.getConstant(C-1, MVT::i32);
3008 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3009 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3010 RHS = DAG.getConstant(C+1, MVT::i32);
3015 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3016 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3017 RHS = DAG.getConstant(C+1, MVT::i32);
3024 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3025 ARMISD::NodeType CompareType;
3028 CompareType = ARMISD::CMP;
3033 CompareType = ARMISD::CMPZ;
3036 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3037 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3040 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3042 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3043 DebugLoc dl) const {
3045 if (!isFloatingPointZero(RHS))
3046 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3048 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3049 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3052 /// duplicateCmp - Glue values can have only one use, so this function
3053 /// duplicates a comparison node.
3055 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3056 unsigned Opc = Cmp.getOpcode();
3057 DebugLoc DL = Cmp.getDebugLoc();
3058 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3059 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3061 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3062 Cmp = Cmp.getOperand(0);
3063 Opc = Cmp.getOpcode();
3064 if (Opc == ARMISD::CMPFP)
3065 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3067 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3068 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3070 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3073 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3074 SDValue Cond = Op.getOperand(0);
3075 SDValue SelectTrue = Op.getOperand(1);
3076 SDValue SelectFalse = Op.getOperand(2);
3077 DebugLoc dl = Op.getDebugLoc();
3081 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3082 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3084 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3085 const ConstantSDNode *CMOVTrue =
3086 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3087 const ConstantSDNode *CMOVFalse =
3088 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3090 if (CMOVTrue && CMOVFalse) {
3091 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3092 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3096 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3098 False = SelectFalse;
3099 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3104 if (True.getNode() && False.getNode()) {
3105 EVT VT = Op.getValueType();
3106 SDValue ARMcc = Cond.getOperand(2);
3107 SDValue CCR = Cond.getOperand(3);
3108 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3109 assert(True.getValueType() == VT);
3110 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3115 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3116 // undefined bits before doing a full-word comparison with zero.
3117 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3118 DAG.getConstant(1, Cond.getValueType()));
3120 return DAG.getSelectCC(dl, Cond,
3121 DAG.getConstant(0, Cond.getValueType()),
3122 SelectTrue, SelectFalse, ISD::SETNE);
3125 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3126 EVT VT = Op.getValueType();
3127 SDValue LHS = Op.getOperand(0);
3128 SDValue RHS = Op.getOperand(1);
3129 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3130 SDValue TrueVal = Op.getOperand(2);
3131 SDValue FalseVal = Op.getOperand(3);
3132 DebugLoc dl = Op.getDebugLoc();
3134 if (LHS.getValueType() == MVT::i32) {
3136 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3137 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3138 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3141 ARMCC::CondCodes CondCode, CondCode2;
3142 FPCCToARMCC(CC, CondCode, CondCode2);
3144 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3145 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3146 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3147 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3149 if (CondCode2 != ARMCC::AL) {
3150 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3151 // FIXME: Needs another CMP because flag can have but one use.
3152 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3153 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3154 Result, TrueVal, ARMcc2, CCR, Cmp2);
3159 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3160 /// to morph to an integer compare sequence.
3161 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3162 const ARMSubtarget *Subtarget) {
3163 SDNode *N = Op.getNode();
3164 if (!N->hasOneUse())
3165 // Otherwise it requires moving the value from fp to integer registers.
3167 if (!N->getNumValues())
3169 EVT VT = Op.getValueType();
3170 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3171 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3172 // vmrs are very slow, e.g. cortex-a8.
3175 if (isFloatingPointZero(Op)) {
3179 return ISD::isNormalLoad(N);
3182 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3183 if (isFloatingPointZero(Op))
3184 return DAG.getConstant(0, MVT::i32);
3186 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3187 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3188 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3189 Ld->isVolatile(), Ld->isNonTemporal(),
3190 Ld->isInvariant(), Ld->getAlignment());
3192 llvm_unreachable("Unknown VFP cmp argument!");
3195 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3196 SDValue &RetVal1, SDValue &RetVal2) {
3197 if (isFloatingPointZero(Op)) {
3198 RetVal1 = DAG.getConstant(0, MVT::i32);
3199 RetVal2 = DAG.getConstant(0, MVT::i32);
3203 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3204 SDValue Ptr = Ld->getBasePtr();
3205 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3206 Ld->getChain(), Ptr,
3207 Ld->getPointerInfo(),
3208 Ld->isVolatile(), Ld->isNonTemporal(),
3209 Ld->isInvariant(), Ld->getAlignment());
3211 EVT PtrType = Ptr.getValueType();
3212 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3213 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3214 PtrType, Ptr, DAG.getConstant(4, PtrType));
3215 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3216 Ld->getChain(), NewPtr,
3217 Ld->getPointerInfo().getWithOffset(4),
3218 Ld->isVolatile(), Ld->isNonTemporal(),
3219 Ld->isInvariant(), NewAlign);
3223 llvm_unreachable("Unknown VFP cmp argument!");
3226 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3227 /// f32 and even f64 comparisons to integer ones.
3229 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3230 SDValue Chain = Op.getOperand(0);
3231 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3232 SDValue LHS = Op.getOperand(2);
3233 SDValue RHS = Op.getOperand(3);
3234 SDValue Dest = Op.getOperand(4);
3235 DebugLoc dl = Op.getDebugLoc();
3237 bool LHSSeenZero = false;
3238 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3239 bool RHSSeenZero = false;
3240 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3241 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3242 // If unsafe fp math optimization is enabled and there are no other uses of
3243 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3244 // to an integer comparison.
3245 if (CC == ISD::SETOEQ)
3247 else if (CC == ISD::SETUNE)
3250 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3252 if (LHS.getValueType() == MVT::f32) {
3253 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3254 bitcastf32Toi32(LHS, DAG), Mask);
3255 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3256 bitcastf32Toi32(RHS, DAG), Mask);
3257 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3258 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3259 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3260 Chain, Dest, ARMcc, CCR, Cmp);
3265 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3266 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3267 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3268 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3269 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3270 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3271 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3272 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3273 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3279 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3280 SDValue Chain = Op.getOperand(0);
3281 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3282 SDValue LHS = Op.getOperand(2);
3283 SDValue RHS = Op.getOperand(3);
3284 SDValue Dest = Op.getOperand(4);
3285 DebugLoc dl = Op.getDebugLoc();
3287 if (LHS.getValueType() == MVT::i32) {
3289 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3290 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3291 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3292 Chain, Dest, ARMcc, CCR, Cmp);
3295 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3297 if (getTargetMachine().Options.UnsafeFPMath &&
3298 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3299 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3300 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3301 if (Result.getNode())
3305 ARMCC::CondCodes CondCode, CondCode2;
3306 FPCCToARMCC(CC, CondCode, CondCode2);
3308 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3309 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3310 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3311 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3312 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3313 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3314 if (CondCode2 != ARMCC::AL) {
3315 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3316 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3317 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3322 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3323 SDValue Chain = Op.getOperand(0);
3324 SDValue Table = Op.getOperand(1);
3325 SDValue Index = Op.getOperand(2);
3326 DebugLoc dl = Op.getDebugLoc();
3328 EVT PTy = getPointerTy();
3329 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3330 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3331 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3332 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3333 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3334 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3335 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3336 if (Subtarget->isThumb2()) {
3337 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3338 // which does another jump to the destination. This also makes it easier
3339 // to translate it to TBB / TBH later.
3340 // FIXME: This might not work if the function is extremely large.
3341 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3342 Addr, Op.getOperand(2), JTI, UId);
3344 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3345 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3346 MachinePointerInfo::getJumpTable(),
3347 false, false, false, 0);
3348 Chain = Addr.getValue(1);
3349 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3350 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3352 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3353 MachinePointerInfo::getJumpTable(),
3354 false, false, false, 0);
3355 Chain = Addr.getValue(1);
3356 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3360 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3361 EVT VT = Op.getValueType();
3362 DebugLoc dl = Op.getDebugLoc();
3364 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3365 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3367 return DAG.UnrollVectorOp(Op.getNode());
3370 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3371 "Invalid type for custom lowering!");
3372 if (VT != MVT::v4i16)
3373 return DAG.UnrollVectorOp(Op.getNode());
3375 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3376 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3379 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3380 EVT VT = Op.getValueType();
3382 return LowerVectorFP_TO_INT(Op, DAG);
3384 DebugLoc dl = Op.getDebugLoc();
3387 switch (Op.getOpcode()) {
3388 default: llvm_unreachable("Invalid opcode!");
3389 case ISD::FP_TO_SINT:
3390 Opc = ARMISD::FTOSI;
3392 case ISD::FP_TO_UINT:
3393 Opc = ARMISD::FTOUI;
3396 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3397 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3400 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3401 EVT VT = Op.getValueType();
3402 DebugLoc dl = Op.getDebugLoc();
3404 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3405 if (VT.getVectorElementType() == MVT::f32)
3407 return DAG.UnrollVectorOp(Op.getNode());
3410 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3411 "Invalid type for custom lowering!");
3412 if (VT != MVT::v4f32)
3413 return DAG.UnrollVectorOp(Op.getNode());
3417 switch (Op.getOpcode()) {
3418 default: llvm_unreachable("Invalid opcode!");
3419 case ISD::SINT_TO_FP:
3420 CastOpc = ISD::SIGN_EXTEND;
3421 Opc = ISD::SINT_TO_FP;
3423 case ISD::UINT_TO_FP:
3424 CastOpc = ISD::ZERO_EXTEND;
3425 Opc = ISD::UINT_TO_FP;
3429 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3430 return DAG.getNode(Opc, dl, VT, Op);
3433 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3434 EVT VT = Op.getValueType();
3436 return LowerVectorINT_TO_FP(Op, DAG);
3438 DebugLoc dl = Op.getDebugLoc();
3441 switch (Op.getOpcode()) {
3442 default: llvm_unreachable("Invalid opcode!");
3443 case ISD::SINT_TO_FP:
3444 Opc = ARMISD::SITOF;
3446 case ISD::UINT_TO_FP:
3447 Opc = ARMISD::UITOF;
3451 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3452 return DAG.getNode(Opc, dl, VT, Op);
3455 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3456 // Implement fcopysign with a fabs and a conditional fneg.
3457 SDValue Tmp0 = Op.getOperand(0);
3458 SDValue Tmp1 = Op.getOperand(1);
3459 DebugLoc dl = Op.getDebugLoc();
3460 EVT VT = Op.getValueType();
3461 EVT SrcVT = Tmp1.getValueType();
3462 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3463 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3464 bool UseNEON = !InGPR && Subtarget->hasNEON();
3467 // Use VBSL to copy the sign bit.
3468 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3469 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3470 DAG.getTargetConstant(EncodedVal, MVT::i32));
3471 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3473 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3474 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3475 DAG.getConstant(32, MVT::i32));
3476 else /*if (VT == MVT::f32)*/
3477 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3478 if (SrcVT == MVT::f32) {
3479 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3481 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3482 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3483 DAG.getConstant(32, MVT::i32));
3484 } else if (VT == MVT::f32)
3485 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3486 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3487 DAG.getConstant(32, MVT::i32));
3488 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3489 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3491 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3493 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3494 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3495 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3497 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3498 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3499 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3500 if (VT == MVT::f32) {
3501 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3502 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3503 DAG.getConstant(0, MVT::i32));
3505 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3511 // Bitcast operand 1 to i32.
3512 if (SrcVT == MVT::f64)
3513 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3514 &Tmp1, 1).getValue(1);
3515 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3517 // Or in the signbit with integer operations.
3518 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3519 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3520 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3521 if (VT == MVT::f32) {
3522 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3523 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3524 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3525 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3528 // f64: Or the high part with signbit and then combine two parts.
3529 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3531 SDValue Lo = Tmp0.getValue(0);
3532 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3533 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3534 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3537 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3538 MachineFunction &MF = DAG.getMachineFunction();
3539 MachineFrameInfo *MFI = MF.getFrameInfo();
3540 MFI->setReturnAddressIsTaken(true);
3542 EVT VT = Op.getValueType();
3543 DebugLoc dl = Op.getDebugLoc();
3544 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3546 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3547 SDValue Offset = DAG.getConstant(4, MVT::i32);
3548 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3549 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3550 MachinePointerInfo(), false, false, false, 0);
3553 // Return LR, which contains the return address. Mark it an implicit live-in.
3554 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3555 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3558 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3559 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3560 MFI->setFrameAddressIsTaken(true);
3562 EVT VT = Op.getValueType();
3563 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3564 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3565 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3566 ? ARM::R7 : ARM::R11;
3567 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3569 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3570 MachinePointerInfo(),
3571 false, false, false, 0);
3575 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3576 /// and size(DestVec) > 128-bits.
3577 /// This is achieved by doing the one extension from the SrcVec, splitting the
3578 /// result, extending these parts, and then concatenating these into the
3580 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3581 SDValue Op = N->getOperand(0);
3582 EVT SrcVT = Op.getValueType();
3583 EVT DestVT = N->getValueType(0);
3585 assert(DestVT.getSizeInBits() > 128 &&
3586 "Custom sext/zext expansion needs >128-bit vector.");
3587 // If this is a normal length extension, use the default expansion.
3588 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3589 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3592 DebugLoc dl = N->getDebugLoc();
3593 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3594 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3595 unsigned NumElts = SrcVT.getVectorNumElements();
3596 LLVMContext &Ctx = *DAG.getContext();
3597 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3599 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3601 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3603 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3606 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3607 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3608 DAG.getIntPtrConstant(0));
3609 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3610 DAG.getIntPtrConstant(NumElts/2));
3611 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3612 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3613 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3616 /// ExpandBITCAST - If the target supports VFP, this function is called to
3617 /// expand a bit convert where either the source or destination type is i64 to
3618 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3619 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3620 /// vectors), since the legalizer won't know what to do with that.
3621 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3622 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3623 DebugLoc dl = N->getDebugLoc();
3624 SDValue Op = N->getOperand(0);
3626 // This function is only supposed to be called for i64 types, either as the
3627 // source or destination of the bit convert.
3628 EVT SrcVT = Op.getValueType();
3629 EVT DstVT = N->getValueType(0);
3630 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3631 "ExpandBITCAST called for non-i64 type");
3633 // Turn i64->f64 into VMOVDRR.
3634 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3635 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3636 DAG.getConstant(0, MVT::i32));
3637 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3638 DAG.getConstant(1, MVT::i32));
3639 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3640 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3643 // Turn f64->i64 into VMOVRRD.
3644 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3645 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3646 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3647 // Merge the pieces into a single i64 value.
3648 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3654 /// getZeroVector - Returns a vector of specified type with all zero elements.
3655 /// Zero vectors are used to represent vector negation and in those cases
3656 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3657 /// not support i64 elements, so sometimes the zero vectors will need to be
3658 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3660 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3661 assert(VT.isVector() && "Expected a vector type");
3662 // The canonical modified immediate encoding of a zero vector is....0!
3663 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3664 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3665 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3666 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3669 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3670 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3671 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3672 SelectionDAG &DAG) const {
3673 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3674 EVT VT = Op.getValueType();
3675 unsigned VTBits = VT.getSizeInBits();
3676 DebugLoc dl = Op.getDebugLoc();
3677 SDValue ShOpLo = Op.getOperand(0);
3678 SDValue ShOpHi = Op.getOperand(1);
3679 SDValue ShAmt = Op.getOperand(2);
3681 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3683 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3685 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3686 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3687 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3688 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3689 DAG.getConstant(VTBits, MVT::i32));
3690 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3691 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3692 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3694 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3695 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3697 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3698 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3701 SDValue Ops[2] = { Lo, Hi };
3702 return DAG.getMergeValues(Ops, 2, dl);
3705 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3706 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3707 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3708 SelectionDAG &DAG) const {
3709 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3710 EVT VT = Op.getValueType();
3711 unsigned VTBits = VT.getSizeInBits();
3712 DebugLoc dl = Op.getDebugLoc();
3713 SDValue ShOpLo = Op.getOperand(0);
3714 SDValue ShOpHi = Op.getOperand(1);
3715 SDValue ShAmt = Op.getOperand(2);
3718 assert(Op.getOpcode() == ISD::SHL_PARTS);
3719 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3720 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3721 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3722 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3723 DAG.getConstant(VTBits, MVT::i32));
3724 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3725 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3727 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3728 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3729 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3731 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3732 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3735 SDValue Ops[2] = { Lo, Hi };
3736 return DAG.getMergeValues(Ops, 2, dl);
3739 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3740 SelectionDAG &DAG) const {
3741 // The rounding mode is in bits 23:22 of the FPSCR.
3742 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3743 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3744 // so that the shift + and get folded into a bitfield extract.
3745 DebugLoc dl = Op.getDebugLoc();
3746 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3747 DAG.getConstant(Intrinsic::arm_get_fpscr,
3749 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3750 DAG.getConstant(1U << 22, MVT::i32));
3751 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3752 DAG.getConstant(22, MVT::i32));
3753 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3754 DAG.getConstant(3, MVT::i32));
3757 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3758 const ARMSubtarget *ST) {
3759 EVT VT = N->getValueType(0);
3760 DebugLoc dl = N->getDebugLoc();
3762 if (!ST->hasV6T2Ops())
3765 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3766 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3769 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3770 /// for each 16-bit element from operand, repeated. The basic idea is to
3771 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3773 /// Trace for v4i16:
3774 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3775 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3776 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3777 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3778 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3779 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3780 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3781 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3782 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3783 EVT VT = N->getValueType(0);
3784 DebugLoc DL = N->getDebugLoc();
3786 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3787 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3788 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3789 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3790 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3791 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3794 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3795 /// bit-count for each 16-bit element from the operand. We need slightly
3796 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3797 /// 64/128-bit registers.
3799 /// Trace for v4i16:
3800 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3801 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3802 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3803 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3804 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3805 EVT VT = N->getValueType(0);
3806 DebugLoc DL = N->getDebugLoc();
3808 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3809 if (VT.is64BitVector()) {
3810 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3811 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3812 DAG.getIntPtrConstant(0));
3814 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3815 BitCounts, DAG.getIntPtrConstant(0));
3816 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3820 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3821 /// bit-count for each 32-bit element from the operand. The idea here is
3822 /// to split the vector into 16-bit elements, leverage the 16-bit count
3823 /// routine, and then combine the results.
3825 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3826 /// input = [v0 v1 ] (vi: 32-bit elements)
3827 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3828 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3829 /// vrev: N0 = [k1 k0 k3 k2 ]
3831 /// N1 =+[k1 k0 k3 k2 ]
3833 /// N2 =+[k1 k3 k0 k2 ]
3835 /// Extended =+[k1 k3 k0 k2 ]
3837 /// Extracted=+[k1 k3 ]
3839 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3840 EVT VT = N->getValueType(0);
3841 DebugLoc DL = N->getDebugLoc();
3843 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3845 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3846 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3847 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3848 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3849 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3851 if (VT.is64BitVector()) {
3852 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3853 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3854 DAG.getIntPtrConstant(0));
3856 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3857 DAG.getIntPtrConstant(0));
3858 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3862 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3863 const ARMSubtarget *ST) {
3864 EVT VT = N->getValueType(0);
3866 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3867 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3868 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3869 "Unexpected type for custom ctpop lowering");
3871 if (VT.getVectorElementType() == MVT::i32)
3872 return lowerCTPOP32BitElements(N, DAG);
3874 return lowerCTPOP16BitElements(N, DAG);
3877 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3878 const ARMSubtarget *ST) {
3879 EVT VT = N->getValueType(0);
3880 DebugLoc dl = N->getDebugLoc();
3885 // Lower vector shifts on NEON to use VSHL.
3886 assert(ST->hasNEON() && "unexpected vector shift");
3888 // Left shifts translate directly to the vshiftu intrinsic.
3889 if (N->getOpcode() == ISD::SHL)
3890 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3891 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3892 N->getOperand(0), N->getOperand(1));
3894 assert((N->getOpcode() == ISD::SRA ||
3895 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3897 // NEON uses the same intrinsics for both left and right shifts. For
3898 // right shifts, the shift amounts are negative, so negate the vector of
3900 EVT ShiftVT = N->getOperand(1).getValueType();
3901 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3902 getZeroVector(ShiftVT, DAG, dl),
3904 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3905 Intrinsic::arm_neon_vshifts :
3906 Intrinsic::arm_neon_vshiftu);
3907 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3908 DAG.getConstant(vshiftInt, MVT::i32),
3909 N->getOperand(0), NegatedCount);
3912 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3913 const ARMSubtarget *ST) {
3914 EVT VT = N->getValueType(0);
3915 DebugLoc dl = N->getDebugLoc();
3917 // We can get here for a node like i32 = ISD::SHL i32, i64
3921 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3922 "Unknown shift to lower!");
3924 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3925 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3926 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3929 // If we are in thumb mode, we don't have RRX.
3930 if (ST->isThumb1Only()) return SDValue();
3932 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3933 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3934 DAG.getConstant(0, MVT::i32));
3935 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3936 DAG.getConstant(1, MVT::i32));
3938 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3939 // captures the result into a carry flag.
3940 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3941 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3943 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3944 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3946 // Merge the pieces into a single i64 value.
3947 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3950 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3951 SDValue TmpOp0, TmpOp1;
3952 bool Invert = false;
3956 SDValue Op0 = Op.getOperand(0);
3957 SDValue Op1 = Op.getOperand(1);
3958 SDValue CC = Op.getOperand(2);
3959 EVT VT = Op.getValueType();
3960 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3961 DebugLoc dl = Op.getDebugLoc();
3963 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3964 switch (SetCCOpcode) {
3965 default: llvm_unreachable("Illegal FP comparison");
3967 case ISD::SETNE: Invert = true; // Fallthrough
3969 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3971 case ISD::SETLT: Swap = true; // Fallthrough
3973 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3975 case ISD::SETLE: Swap = true; // Fallthrough
3977 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3978 case ISD::SETUGE: Swap = true; // Fallthrough
3979 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3980 case ISD::SETUGT: Swap = true; // Fallthrough
3981 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3982 case ISD::SETUEQ: Invert = true; // Fallthrough
3984 // Expand this to (OLT | OGT).
3988 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3989 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3991 case ISD::SETUO: Invert = true; // Fallthrough
3993 // Expand this to (OLT | OGE).
3997 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3998 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4002 // Integer comparisons.
4003 switch (SetCCOpcode) {
4004 default: llvm_unreachable("Illegal integer comparison");
4005 case ISD::SETNE: Invert = true;
4006 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4007 case ISD::SETLT: Swap = true;
4008 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4009 case ISD::SETLE: Swap = true;
4010 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4011 case ISD::SETULT: Swap = true;
4012 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4013 case ISD::SETULE: Swap = true;
4014 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4017 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4018 if (Opc == ARMISD::VCEQ) {
4021 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4023 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4026 // Ignore bitconvert.
4027 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4028 AndOp = AndOp.getOperand(0);
4030 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4032 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4033 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4040 std::swap(Op0, Op1);
4042 // If one of the operands is a constant vector zero, attempt to fold the
4043 // comparison to a specialized compare-against-zero form.
4045 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4047 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4048 if (Opc == ARMISD::VCGE)
4049 Opc = ARMISD::VCLEZ;
4050 else if (Opc == ARMISD::VCGT)
4051 Opc = ARMISD::VCLTZ;
4056 if (SingleOp.getNode()) {
4059 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4061 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4063 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4065 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4067 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4069 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4072 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4076 Result = DAG.getNOT(dl, Result, VT);
4081 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4082 /// valid vector constant for a NEON instruction with a "modified immediate"
4083 /// operand (e.g., VMOV). If so, return the encoded value.
4084 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4085 unsigned SplatBitSize, SelectionDAG &DAG,
4086 EVT &VT, bool is128Bits, NEONModImmType type) {
4087 unsigned OpCmode, Imm;
4089 // SplatBitSize is set to the smallest size that splats the vector, so a
4090 // zero vector will always have SplatBitSize == 8. However, NEON modified
4091 // immediate instructions others than VMOV do not support the 8-bit encoding
4092 // of a zero vector, and the default encoding of zero is supposed to be the
4097 switch (SplatBitSize) {
4099 if (type != VMOVModImm)
4101 // Any 1-byte value is OK. Op=0, Cmode=1110.
4102 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4105 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4109 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4110 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4111 if ((SplatBits & ~0xff) == 0) {
4112 // Value = 0x00nn: Op=x, Cmode=100x.
4117 if ((SplatBits & ~0xff00) == 0) {
4118 // Value = 0xnn00: Op=x, Cmode=101x.
4120 Imm = SplatBits >> 8;
4126 // NEON's 32-bit VMOV supports splat values where:
4127 // * only one byte is nonzero, or
4128 // * the least significant byte is 0xff and the second byte is nonzero, or
4129 // * the least significant 2 bytes are 0xff and the third is nonzero.
4130 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4131 if ((SplatBits & ~0xff) == 0) {
4132 // Value = 0x000000nn: Op=x, Cmode=000x.
4137 if ((SplatBits & ~0xff00) == 0) {
4138 // Value = 0x0000nn00: Op=x, Cmode=001x.
4140 Imm = SplatBits >> 8;
4143 if ((SplatBits & ~0xff0000) == 0) {
4144 // Value = 0x00nn0000: Op=x, Cmode=010x.
4146 Imm = SplatBits >> 16;
4149 if ((SplatBits & ~0xff000000) == 0) {
4150 // Value = 0xnn000000: Op=x, Cmode=011x.
4152 Imm = SplatBits >> 24;
4156 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4157 if (type == OtherModImm) return SDValue();
4159 if ((SplatBits & ~0xffff) == 0 &&
4160 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4161 // Value = 0x0000nnff: Op=x, Cmode=1100.
4163 Imm = SplatBits >> 8;
4168 if ((SplatBits & ~0xffffff) == 0 &&
4169 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4170 // Value = 0x00nnffff: Op=x, Cmode=1101.
4172 Imm = SplatBits >> 16;
4173 SplatBits |= 0xffff;
4177 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4178 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4179 // VMOV.I32. A (very) minor optimization would be to replicate the value
4180 // and fall through here to test for a valid 64-bit splat. But, then the
4181 // caller would also need to check and handle the change in size.
4185 if (type != VMOVModImm)
4187 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4188 uint64_t BitMask = 0xff;
4190 unsigned ImmMask = 1;
4192 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4193 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4196 } else if ((SplatBits & BitMask) != 0) {
4202 // Op=1, Cmode=1110.
4205 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4210 llvm_unreachable("unexpected size for isNEONModifiedImm");
4213 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4214 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4217 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4218 const ARMSubtarget *ST) const {
4219 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4222 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4223 assert(Op.getValueType() == MVT::f32 &&
4224 "ConstantFP custom lowering should only occur for f32.");
4226 // Try splatting with a VMOV.f32...
4227 APFloat FPVal = CFP->getValueAPF();
4228 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4230 DebugLoc DL = Op.getDebugLoc();
4231 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4232 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4234 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4235 DAG.getConstant(0, MVT::i32));
4238 // If that fails, try a VMOV.i32
4240 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4241 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4243 if (NewVal != SDValue()) {
4244 DebugLoc DL = Op.getDebugLoc();
4245 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4247 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4249 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4250 DAG.getConstant(0, MVT::i32));
4253 // Finally, try a VMVN.i32
4254 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4256 if (NewVal != SDValue()) {
4257 DebugLoc DL = Op.getDebugLoc();
4258 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4259 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4261 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4262 DAG.getConstant(0, MVT::i32));
4268 // check if an VEXT instruction can handle the shuffle mask when the
4269 // vector sources of the shuffle are the same.
4270 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4271 unsigned NumElts = VT.getVectorNumElements();
4273 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4279 // If this is a VEXT shuffle, the immediate value is the index of the first
4280 // element. The other shuffle indices must be the successive elements after
4282 unsigned ExpectedElt = Imm;
4283 for (unsigned i = 1; i < NumElts; ++i) {
4284 // Increment the expected index. If it wraps around, just follow it
4285 // back to index zero and keep going.
4287 if (ExpectedElt == NumElts)
4290 if (M[i] < 0) continue; // ignore UNDEF indices
4291 if (ExpectedElt != static_cast<unsigned>(M[i]))
4299 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4300 bool &ReverseVEXT, unsigned &Imm) {
4301 unsigned NumElts = VT.getVectorNumElements();
4302 ReverseVEXT = false;
4304 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4310 // If this is a VEXT shuffle, the immediate value is the index of the first
4311 // element. The other shuffle indices must be the successive elements after
4313 unsigned ExpectedElt = Imm;
4314 for (unsigned i = 1; i < NumElts; ++i) {
4315 // Increment the expected index. If it wraps around, it may still be
4316 // a VEXT but the source vectors must be swapped.
4318 if (ExpectedElt == NumElts * 2) {
4323 if (M[i] < 0) continue; // ignore UNDEF indices
4324 if (ExpectedElt != static_cast<unsigned>(M[i]))
4328 // Adjust the index value if the source operands will be swapped.
4335 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4336 /// instruction with the specified blocksize. (The order of the elements
4337 /// within each block of the vector is reversed.)
4338 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4339 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4340 "Only possible block sizes for VREV are: 16, 32, 64");
4342 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4346 unsigned NumElts = VT.getVectorNumElements();
4347 unsigned BlockElts = M[0] + 1;
4348 // If the first shuffle index is UNDEF, be optimistic.
4350 BlockElts = BlockSize / EltSz;
4352 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4355 for (unsigned i = 0; i < NumElts; ++i) {
4356 if (M[i] < 0) continue; // ignore UNDEF indices
4357 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4364 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4365 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4366 // range, then 0 is placed into the resulting vector. So pretty much any mask
4367 // of 8 elements can work here.
4368 return VT == MVT::v8i8 && M.size() == 8;
4371 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4372 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4376 unsigned NumElts = VT.getVectorNumElements();
4377 WhichResult = (M[0] == 0 ? 0 : 1);
4378 for (unsigned i = 0; i < NumElts; i += 2) {
4379 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4380 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4386 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4387 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4388 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4389 static bool isVTRN_v_undef_Mask(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 + WhichResult))
4404 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4405 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4409 unsigned NumElts = VT.getVectorNumElements();
4410 WhichResult = (M[0] == 0 ? 0 : 1);
4411 for (unsigned i = 0; i != NumElts; ++i) {
4412 if (M[i] < 0) continue; // ignore UNDEF indices
4413 if ((unsigned) M[i] != 2 * i + WhichResult)
4417 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4418 if (VT.is64BitVector() && EltSz == 32)
4424 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4425 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4426 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4427 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4428 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4432 unsigned Half = VT.getVectorNumElements() / 2;
4433 WhichResult = (M[0] == 0 ? 0 : 1);
4434 for (unsigned j = 0; j != 2; ++j) {
4435 unsigned Idx = WhichResult;
4436 for (unsigned i = 0; i != Half; ++i) {
4437 int MIdx = M[i + j * Half];
4438 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4444 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4445 if (VT.is64BitVector() && EltSz == 32)
4451 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4452 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4456 unsigned NumElts = VT.getVectorNumElements();
4457 WhichResult = (M[0] == 0 ? 0 : 1);
4458 unsigned Idx = WhichResult * NumElts / 2;
4459 for (unsigned i = 0; i != NumElts; i += 2) {
4460 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4461 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4466 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4467 if (VT.is64BitVector() && EltSz == 32)
4473 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4474 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4475 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4476 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4477 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4481 unsigned NumElts = VT.getVectorNumElements();
4482 WhichResult = (M[0] == 0 ? 0 : 1);
4483 unsigned Idx = WhichResult * NumElts / 2;
4484 for (unsigned i = 0; i != NumElts; i += 2) {
4485 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4486 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4491 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4492 if (VT.is64BitVector() && EltSz == 32)
4498 /// \return true if this is a reverse operation on an vector.
4499 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4500 unsigned NumElts = VT.getVectorNumElements();
4501 // Make sure the mask has the right size.
4502 if (NumElts != M.size())
4505 // Look for <15, ..., 3, -1, 1, 0>.
4506 for (unsigned i = 0; i != NumElts; ++i)
4507 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4513 // If N is an integer constant that can be moved into a register in one
4514 // instruction, return an SDValue of such a constant (will become a MOV
4515 // instruction). Otherwise return null.
4516 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4517 const ARMSubtarget *ST, DebugLoc dl) {
4519 if (!isa<ConstantSDNode>(N))
4521 Val = cast<ConstantSDNode>(N)->getZExtValue();
4523 if (ST->isThumb1Only()) {
4524 if (Val <= 255 || ~Val <= 255)
4525 return DAG.getConstant(Val, MVT::i32);
4527 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4528 return DAG.getConstant(Val, MVT::i32);
4533 // If this is a case we can't handle, return null and let the default
4534 // expansion code take care of it.
4535 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4536 const ARMSubtarget *ST) const {
4537 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4538 DebugLoc dl = Op.getDebugLoc();
4539 EVT VT = Op.getValueType();
4541 APInt SplatBits, SplatUndef;
4542 unsigned SplatBitSize;
4544 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4545 if (SplatBitSize <= 64) {
4546 // Check if an immediate VMOV works.
4548 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4549 SplatUndef.getZExtValue(), SplatBitSize,
4550 DAG, VmovVT, VT.is128BitVector(),
4552 if (Val.getNode()) {
4553 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4554 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4557 // Try an immediate VMVN.
4558 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4559 Val = isNEONModifiedImm(NegatedImm,
4560 SplatUndef.getZExtValue(), SplatBitSize,
4561 DAG, VmovVT, VT.is128BitVector(),
4563 if (Val.getNode()) {
4564 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4565 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4568 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4569 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4570 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4572 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4573 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4579 // Scan through the operands to see if only one value is used.
4581 // As an optimisation, even if more than one value is used it may be more
4582 // profitable to splat with one value then change some lanes.
4584 // Heuristically we decide to do this if the vector has a "dominant" value,
4585 // defined as splatted to more than half of the lanes.
4586 unsigned NumElts = VT.getVectorNumElements();
4587 bool isOnlyLowElement = true;
4588 bool usesOnlyOneValue = true;
4589 bool hasDominantValue = false;
4590 bool isConstant = true;
4592 // Map of the number of times a particular SDValue appears in the
4594 DenseMap<SDValue, unsigned> ValueCounts;
4596 for (unsigned i = 0; i < NumElts; ++i) {
4597 SDValue V = Op.getOperand(i);
4598 if (V.getOpcode() == ISD::UNDEF)
4601 isOnlyLowElement = false;
4602 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4605 ValueCounts.insert(std::make_pair(V, 0));
4606 unsigned &Count = ValueCounts[V];
4608 // Is this value dominant? (takes up more than half of the lanes)
4609 if (++Count > (NumElts / 2)) {
4610 hasDominantValue = true;
4614 if (ValueCounts.size() != 1)
4615 usesOnlyOneValue = false;
4616 if (!Value.getNode() && ValueCounts.size() > 0)
4617 Value = ValueCounts.begin()->first;
4619 if (ValueCounts.size() == 0)
4620 return DAG.getUNDEF(VT);
4622 if (isOnlyLowElement)
4623 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4625 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4627 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4628 // i32 and try again.
4629 if (hasDominantValue && EltSize <= 32) {
4633 // If we are VDUPing a value that comes directly from a vector, that will
4634 // cause an unnecessary move to and from a GPR, where instead we could
4635 // just use VDUPLANE. We can only do this if the lane being extracted
4636 // is at a constant index, as the VDUP from lane instructions only have
4637 // constant-index forms.
4638 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4639 isa<ConstantSDNode>(Value->getOperand(1))) {
4640 // We need to create a new undef vector to use for the VDUPLANE if the
4641 // size of the vector from which we get the value is different than the
4642 // size of the vector that we need to create. We will insert the element
4643 // such that the register coalescer will remove unnecessary copies.
4644 if (VT != Value->getOperand(0).getValueType()) {
4645 ConstantSDNode *constIndex;
4646 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4647 assert(constIndex && "The index is not a constant!");
4648 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4649 VT.getVectorNumElements();
4650 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4651 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4652 Value, DAG.getConstant(index, MVT::i32)),
4653 DAG.getConstant(index, MVT::i32));
4655 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4656 Value->getOperand(0), Value->getOperand(1));
4658 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4660 if (!usesOnlyOneValue) {
4661 // The dominant value was splatted as 'N', but we now have to insert
4662 // all differing elements.
4663 for (unsigned I = 0; I < NumElts; ++I) {
4664 if (Op.getOperand(I) == Value)
4666 SmallVector<SDValue, 3> Ops;
4668 Ops.push_back(Op.getOperand(I));
4669 Ops.push_back(DAG.getConstant(I, MVT::i32));
4670 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4675 if (VT.getVectorElementType().isFloatingPoint()) {
4676 SmallVector<SDValue, 8> Ops;
4677 for (unsigned i = 0; i < NumElts; ++i)
4678 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4680 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4681 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4682 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4684 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4686 if (usesOnlyOneValue) {
4687 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4688 if (isConstant && Val.getNode())
4689 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4693 // If all elements are constants and the case above didn't get hit, fall back
4694 // to the default expansion, which will generate a load from the constant
4699 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4701 SDValue shuffle = ReconstructShuffle(Op, DAG);
4702 if (shuffle != SDValue())
4706 // Vectors with 32- or 64-bit elements can be built by directly assigning
4707 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4708 // will be legalized.
4709 if (EltSize >= 32) {
4710 // Do the expansion with floating-point types, since that is what the VFP
4711 // registers are defined to use, and since i64 is not legal.
4712 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4713 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4714 SmallVector<SDValue, 8> Ops;
4715 for (unsigned i = 0; i < NumElts; ++i)
4716 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4717 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4718 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4724 // Gather data to see if the operation can be modelled as a
4725 // shuffle in combination with VEXTs.
4726 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4727 SelectionDAG &DAG) const {
4728 DebugLoc dl = Op.getDebugLoc();
4729 EVT VT = Op.getValueType();
4730 unsigned NumElts = VT.getVectorNumElements();
4732 SmallVector<SDValue, 2> SourceVecs;
4733 SmallVector<unsigned, 2> MinElts;
4734 SmallVector<unsigned, 2> MaxElts;
4736 for (unsigned i = 0; i < NumElts; ++i) {
4737 SDValue V = Op.getOperand(i);
4738 if (V.getOpcode() == ISD::UNDEF)
4740 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4741 // A shuffle can only come from building a vector from various
4742 // elements of other vectors.
4744 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4745 VT.getVectorElementType()) {
4746 // This code doesn't know how to handle shuffles where the vector
4747 // element types do not match (this happens because type legalization
4748 // promotes the return type of EXTRACT_VECTOR_ELT).
4749 // FIXME: It might be appropriate to extend this code to handle
4750 // mismatched types.
4754 // Record this extraction against the appropriate vector if possible...
4755 SDValue SourceVec = V.getOperand(0);
4756 // If the element number isn't a constant, we can't effectively
4757 // analyze what's going on.
4758 if (!isa<ConstantSDNode>(V.getOperand(1)))
4760 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4761 bool FoundSource = false;
4762 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4763 if (SourceVecs[j] == SourceVec) {
4764 if (MinElts[j] > EltNo)
4766 if (MaxElts[j] < EltNo)
4773 // Or record a new source if not...
4775 SourceVecs.push_back(SourceVec);
4776 MinElts.push_back(EltNo);
4777 MaxElts.push_back(EltNo);
4781 // Currently only do something sane when at most two source vectors
4783 if (SourceVecs.size() > 2)
4786 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4787 int VEXTOffsets[2] = {0, 0};
4789 // This loop extracts the usage patterns of the source vectors
4790 // and prepares appropriate SDValues for a shuffle if possible.
4791 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4792 if (SourceVecs[i].getValueType() == VT) {
4793 // No VEXT necessary
4794 ShuffleSrcs[i] = SourceVecs[i];
4797 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4798 // It probably isn't worth padding out a smaller vector just to
4799 // break it down again in a shuffle.
4803 // Since only 64-bit and 128-bit vectors are legal on ARM and
4804 // we've eliminated the other cases...
4805 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4806 "unexpected vector sizes in ReconstructShuffle");
4808 if (MaxElts[i] - MinElts[i] >= NumElts) {
4809 // Span too large for a VEXT to cope
4813 if (MinElts[i] >= NumElts) {
4814 // The extraction can just take the second half
4815 VEXTOffsets[i] = NumElts;
4816 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4818 DAG.getIntPtrConstant(NumElts));
4819 } else if (MaxElts[i] < NumElts) {
4820 // The extraction can just take the first half
4822 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4824 DAG.getIntPtrConstant(0));
4826 // An actual VEXT is needed
4827 VEXTOffsets[i] = MinElts[i];
4828 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4830 DAG.getIntPtrConstant(0));
4831 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4833 DAG.getIntPtrConstant(NumElts));
4834 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4835 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4839 SmallVector<int, 8> Mask;
4841 for (unsigned i = 0; i < NumElts; ++i) {
4842 SDValue Entry = Op.getOperand(i);
4843 if (Entry.getOpcode() == ISD::UNDEF) {
4848 SDValue ExtractVec = Entry.getOperand(0);
4849 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4850 .getOperand(1))->getSExtValue();
4851 if (ExtractVec == SourceVecs[0]) {
4852 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4854 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4858 // Final check before we try to produce nonsense...
4859 if (isShuffleMaskLegal(Mask, VT))
4860 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4866 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4867 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4868 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4869 /// are assumed to be legal.
4871 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4873 if (VT.getVectorNumElements() == 4 &&
4874 (VT.is128BitVector() || VT.is64BitVector())) {
4875 unsigned PFIndexes[4];
4876 for (unsigned i = 0; i != 4; ++i) {
4880 PFIndexes[i] = M[i];
4883 // Compute the index in the perfect shuffle table.
4884 unsigned PFTableIndex =
4885 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4886 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4887 unsigned Cost = (PFEntry >> 30);
4894 unsigned Imm, WhichResult;
4896 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4897 return (EltSize >= 32 ||
4898 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4899 isVREVMask(M, VT, 64) ||
4900 isVREVMask(M, VT, 32) ||
4901 isVREVMask(M, VT, 16) ||
4902 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4903 isVTBLMask(M, VT) ||
4904 isVTRNMask(M, VT, WhichResult) ||
4905 isVUZPMask(M, VT, WhichResult) ||
4906 isVZIPMask(M, VT, WhichResult) ||
4907 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4908 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4909 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4910 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4913 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4914 /// the specified operations to build the shuffle.
4915 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4916 SDValue RHS, SelectionDAG &DAG,
4918 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4919 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4920 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4923 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4932 OP_VUZPL, // VUZP, left result
4933 OP_VUZPR, // VUZP, right result
4934 OP_VZIPL, // VZIP, left result
4935 OP_VZIPR, // VZIP, right result
4936 OP_VTRNL, // VTRN, left result
4937 OP_VTRNR // VTRN, right result
4940 if (OpNum == OP_COPY) {
4941 if (LHSID == (1*9+2)*9+3) return LHS;
4942 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4946 SDValue OpLHS, OpRHS;
4947 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4948 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4949 EVT VT = OpLHS.getValueType();
4952 default: llvm_unreachable("Unknown shuffle opcode!");
4954 // VREV divides the vector in half and swaps within the half.
4955 if (VT.getVectorElementType() == MVT::i32 ||
4956 VT.getVectorElementType() == MVT::f32)
4957 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4958 // vrev <4 x i16> -> VREV32
4959 if (VT.getVectorElementType() == MVT::i16)
4960 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4961 // vrev <4 x i8> -> VREV16
4962 assert(VT.getVectorElementType() == MVT::i8);
4963 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4968 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4969 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4973 return DAG.getNode(ARMISD::VEXT, dl, VT,
4975 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4978 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4979 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4982 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4983 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4986 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4987 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4991 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4992 ArrayRef<int> ShuffleMask,
4993 SelectionDAG &DAG) {
4994 // Check to see if we can use the VTBL instruction.
4995 SDValue V1 = Op.getOperand(0);
4996 SDValue V2 = Op.getOperand(1);
4997 DebugLoc DL = Op.getDebugLoc();
4999 SmallVector<SDValue, 8> VTBLMask;
5000 for (ArrayRef<int>::iterator
5001 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5002 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5004 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5005 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5006 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5009 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5010 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5014 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5015 SelectionDAG &DAG) {
5016 DebugLoc DL = Op.getDebugLoc();
5017 SDValue OpLHS = Op.getOperand(0);
5018 EVT VT = OpLHS.getValueType();
5020 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5021 "Expect an v8i16/v16i8 type");
5022 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5023 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5024 // extract the first 8 bytes into the top double word and the last 8 bytes
5025 // into the bottom double word. The v8i16 case is similar.
5026 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5027 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5028 DAG.getConstant(ExtractNum, MVT::i32));
5031 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5032 SDValue V1 = Op.getOperand(0);
5033 SDValue V2 = Op.getOperand(1);
5034 DebugLoc dl = Op.getDebugLoc();
5035 EVT VT = Op.getValueType();
5036 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5038 // Convert shuffles that are directly supported on NEON to target-specific
5039 // DAG nodes, instead of keeping them as shuffles and matching them again
5040 // during code selection. This is more efficient and avoids the possibility
5041 // of inconsistencies between legalization and selection.
5042 // FIXME: floating-point vectors should be canonicalized to integer vectors
5043 // of the same time so that they get CSEd properly.
5044 ArrayRef<int> ShuffleMask = SVN->getMask();
5046 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5047 if (EltSize <= 32) {
5048 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5049 int Lane = SVN->getSplatIndex();
5050 // If this is undef splat, generate it via "just" vdup, if possible.
5051 if (Lane == -1) Lane = 0;
5053 // Test if V1 is a SCALAR_TO_VECTOR.
5054 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5055 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5057 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5058 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5060 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5061 !isa<ConstantSDNode>(V1.getOperand(0))) {
5062 bool IsScalarToVector = true;
5063 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5064 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5065 IsScalarToVector = false;
5068 if (IsScalarToVector)
5069 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5071 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5072 DAG.getConstant(Lane, MVT::i32));
5077 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5080 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5081 DAG.getConstant(Imm, MVT::i32));
5084 if (isVREVMask(ShuffleMask, VT, 64))
5085 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5086 if (isVREVMask(ShuffleMask, VT, 32))
5087 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5088 if (isVREVMask(ShuffleMask, VT, 16))
5089 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5091 if (V2->getOpcode() == ISD::UNDEF &&
5092 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5093 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5094 DAG.getConstant(Imm, MVT::i32));
5097 // Check for Neon shuffles that modify both input vectors in place.
5098 // If both results are used, i.e., if there are two shuffles with the same
5099 // source operands and with masks corresponding to both results of one of
5100 // these operations, DAG memoization will ensure that a single node is
5101 // used for both shuffles.
5102 unsigned WhichResult;
5103 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5104 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5105 V1, V2).getValue(WhichResult);
5106 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5107 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5108 V1, V2).getValue(WhichResult);
5109 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5110 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5111 V1, V2).getValue(WhichResult);
5113 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5114 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5115 V1, V1).getValue(WhichResult);
5116 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5117 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5118 V1, V1).getValue(WhichResult);
5119 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5120 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5121 V1, V1).getValue(WhichResult);
5124 // If the shuffle is not directly supported and it has 4 elements, use
5125 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5126 unsigned NumElts = VT.getVectorNumElements();
5128 unsigned PFIndexes[4];
5129 for (unsigned i = 0; i != 4; ++i) {
5130 if (ShuffleMask[i] < 0)
5133 PFIndexes[i] = ShuffleMask[i];
5136 // Compute the index in the perfect shuffle table.
5137 unsigned PFTableIndex =
5138 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5139 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5140 unsigned Cost = (PFEntry >> 30);
5143 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5146 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5147 if (EltSize >= 32) {
5148 // Do the expansion with floating-point types, since that is what the VFP
5149 // registers are defined to use, and since i64 is not legal.
5150 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5151 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5152 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5153 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5154 SmallVector<SDValue, 8> Ops;
5155 for (unsigned i = 0; i < NumElts; ++i) {
5156 if (ShuffleMask[i] < 0)
5157 Ops.push_back(DAG.getUNDEF(EltVT));
5159 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5160 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5161 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5164 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5165 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5168 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5169 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5171 if (VT == MVT::v8i8) {
5172 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5173 if (NewOp.getNode())
5180 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5181 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5182 SDValue Lane = Op.getOperand(2);
5183 if (!isa<ConstantSDNode>(Lane))
5189 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5190 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5191 SDValue Lane = Op.getOperand(1);
5192 if (!isa<ConstantSDNode>(Lane))
5195 SDValue Vec = Op.getOperand(0);
5196 if (Op.getValueType() == MVT::i32 &&
5197 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5198 DebugLoc dl = Op.getDebugLoc();
5199 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5205 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5206 // The only time a CONCAT_VECTORS operation can have legal types is when
5207 // two 64-bit vectors are concatenated to a 128-bit vector.
5208 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5209 "unexpected CONCAT_VECTORS");
5210 DebugLoc dl = Op.getDebugLoc();
5211 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5212 SDValue Op0 = Op.getOperand(0);
5213 SDValue Op1 = Op.getOperand(1);
5214 if (Op0.getOpcode() != ISD::UNDEF)
5215 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5216 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5217 DAG.getIntPtrConstant(0));
5218 if (Op1.getOpcode() != ISD::UNDEF)
5219 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5220 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5221 DAG.getIntPtrConstant(1));
5222 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5225 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5226 /// element has been zero/sign-extended, depending on the isSigned parameter,
5227 /// from an integer type half its size.
5228 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5230 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5231 EVT VT = N->getValueType(0);
5232 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5233 SDNode *BVN = N->getOperand(0).getNode();
5234 if (BVN->getValueType(0) != MVT::v4i32 ||
5235 BVN->getOpcode() != ISD::BUILD_VECTOR)
5237 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5238 unsigned HiElt = 1 - LoElt;
5239 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5240 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5241 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5242 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5243 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5246 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5247 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5250 if (Hi0->isNullValue() && Hi1->isNullValue())
5256 if (N->getOpcode() != ISD::BUILD_VECTOR)
5259 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5260 SDNode *Elt = N->getOperand(i).getNode();
5261 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5262 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5263 unsigned HalfSize = EltSize / 2;
5265 if (!isIntN(HalfSize, C->getSExtValue()))
5268 if (!isUIntN(HalfSize, C->getZExtValue()))
5279 /// isSignExtended - Check if a node is a vector value that is sign-extended
5280 /// or a constant BUILD_VECTOR with sign-extended elements.
5281 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5282 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5284 if (isExtendedBUILD_VECTOR(N, DAG, true))
5289 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5290 /// or a constant BUILD_VECTOR with zero-extended elements.
5291 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5292 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5294 if (isExtendedBUILD_VECTOR(N, DAG, false))
5299 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5300 if (OrigVT.getSizeInBits() >= 64)
5303 assert(OrigVT.isSimple() && "Expecting a simple value type");
5305 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5306 switch (OrigSimpleTy) {
5307 default: llvm_unreachable("Unexpected Vector Type");
5316 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5317 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5318 /// We insert the required extension here to get the vector to fill a D register.
5319 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5322 unsigned ExtOpcode) {
5323 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5324 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5325 // 64-bits we need to insert a new extension so that it will be 64-bits.
5326 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5327 if (OrigTy.getSizeInBits() >= 64)
5330 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5331 EVT NewVT = getExtensionTo64Bits(OrigTy);
5333 return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5336 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5337 /// does not do any sign/zero extension. If the original vector is less
5338 /// than 64 bits, an appropriate extension will be added after the load to
5339 /// reach a total size of 64 bits. We have to add the extension separately
5340 /// because ARM does not have a sign/zero extending load for vectors.
5341 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5342 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5344 // The load already has the right type.
5345 if (ExtendedTy == LD->getMemoryVT())
5346 return DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5347 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5348 LD->isNonTemporal(), LD->isInvariant(),
5349 LD->getAlignment());
5351 // We need to create a zextload/sextload. We cannot just create a load
5352 // followed by a zext/zext node because LowerMUL is also run during normal
5353 // operation legalization where we can't create illegal types.
5354 return DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(), ExtendedTy,
5355 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5356 LD->getMemoryVT(), LD->isVolatile(),
5357 LD->isNonTemporal(), LD->getAlignment());
5360 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5361 /// extending load, or BUILD_VECTOR with extended elements, return the
5362 /// unextended value. The unextended vector should be 64 bits so that it can
5363 /// be used as an operand to a VMULL instruction. If the original vector size
5364 /// before extension is less than 64 bits we add a an extension to resize
5365 /// the vector to 64 bits.
5366 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5367 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5368 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5369 N->getOperand(0)->getValueType(0),
5373 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5374 return SkipLoadExtensionForVMULL(LD, DAG);
5376 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5377 // have been legalized as a BITCAST from v4i32.
5378 if (N->getOpcode() == ISD::BITCAST) {
5379 SDNode *BVN = N->getOperand(0).getNode();
5380 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5381 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5382 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5383 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5384 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5386 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5387 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5388 EVT VT = N->getValueType(0);
5389 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5390 unsigned NumElts = VT.getVectorNumElements();
5391 MVT TruncVT = MVT::getIntegerVT(EltSize);
5392 SmallVector<SDValue, 8> Ops;
5393 for (unsigned i = 0; i != NumElts; ++i) {
5394 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5395 const APInt &CInt = C->getAPIntValue();
5396 // Element types smaller than 32 bits are not legal, so use i32 elements.
5397 // The values are implicitly truncated so sext vs. zext doesn't matter.
5398 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5400 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5401 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5404 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5405 unsigned Opcode = N->getOpcode();
5406 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5407 SDNode *N0 = N->getOperand(0).getNode();
5408 SDNode *N1 = N->getOperand(1).getNode();
5409 return N0->hasOneUse() && N1->hasOneUse() &&
5410 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5415 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5416 unsigned Opcode = N->getOpcode();
5417 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5418 SDNode *N0 = N->getOperand(0).getNode();
5419 SDNode *N1 = N->getOperand(1).getNode();
5420 return N0->hasOneUse() && N1->hasOneUse() &&
5421 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5426 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5427 // Multiplications are only custom-lowered for 128-bit vectors so that
5428 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5429 EVT VT = Op.getValueType();
5430 assert(VT.is128BitVector() && VT.isInteger() &&
5431 "unexpected type for custom-lowering ISD::MUL");
5432 SDNode *N0 = Op.getOperand(0).getNode();
5433 SDNode *N1 = Op.getOperand(1).getNode();
5434 unsigned NewOpc = 0;
5436 bool isN0SExt = isSignExtended(N0, DAG);
5437 bool isN1SExt = isSignExtended(N1, DAG);
5438 if (isN0SExt && isN1SExt)
5439 NewOpc = ARMISD::VMULLs;
5441 bool isN0ZExt = isZeroExtended(N0, DAG);
5442 bool isN1ZExt = isZeroExtended(N1, DAG);
5443 if (isN0ZExt && isN1ZExt)
5444 NewOpc = ARMISD::VMULLu;
5445 else if (isN1SExt || isN1ZExt) {
5446 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5447 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5448 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5449 NewOpc = ARMISD::VMULLs;
5451 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5452 NewOpc = ARMISD::VMULLu;
5454 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5456 NewOpc = ARMISD::VMULLu;
5462 if (VT == MVT::v2i64)
5463 // Fall through to expand this. It is not legal.
5466 // Other vector multiplications are legal.
5471 // Legalize to a VMULL instruction.
5472 DebugLoc DL = Op.getDebugLoc();
5474 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5476 Op0 = SkipExtensionForVMULL(N0, DAG);
5477 assert(Op0.getValueType().is64BitVector() &&
5478 Op1.getValueType().is64BitVector() &&
5479 "unexpected types for extended operands to VMULL");
5480 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5483 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5484 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5491 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5492 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5493 EVT Op1VT = Op1.getValueType();
5494 return DAG.getNode(N0->getOpcode(), DL, VT,
5495 DAG.getNode(NewOpc, DL, VT,
5496 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5497 DAG.getNode(NewOpc, DL, VT,
5498 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5502 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5504 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5505 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5506 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5507 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5508 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5509 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5510 // Get reciprocal estimate.
5511 // float4 recip = vrecpeq_f32(yf);
5512 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5513 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5514 // Because char has a smaller range than uchar, we can actually get away
5515 // without any newton steps. This requires that we use a weird bias
5516 // of 0xb000, however (again, this has been exhaustively tested).
5517 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5518 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5519 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5520 Y = DAG.getConstant(0xb000, MVT::i32);
5521 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5522 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5523 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5524 // Convert back to short.
5525 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5526 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5531 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5533 // Convert to float.
5534 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5535 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5536 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5537 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5538 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5539 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5541 // Use reciprocal estimate and one refinement step.
5542 // float4 recip = vrecpeq_f32(yf);
5543 // recip *= vrecpsq_f32(yf, recip);
5544 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5545 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5546 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5547 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5549 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5550 // Because short has a smaller range than ushort, we can actually get away
5551 // with only a single newton step. This requires that we use a weird bias
5552 // of 89, however (again, this has been exhaustively tested).
5553 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5554 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5555 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5556 N1 = DAG.getConstant(0x89, MVT::i32);
5557 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5558 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5559 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5560 // Convert back to integer and return.
5561 // return vmovn_s32(vcvt_s32_f32(result));
5562 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5563 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5567 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5568 EVT VT = Op.getValueType();
5569 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5570 "unexpected type for custom-lowering ISD::SDIV");
5572 DebugLoc dl = Op.getDebugLoc();
5573 SDValue N0 = Op.getOperand(0);
5574 SDValue N1 = Op.getOperand(1);
5577 if (VT == MVT::v8i8) {
5578 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5579 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5581 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5582 DAG.getIntPtrConstant(4));
5583 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5584 DAG.getIntPtrConstant(4));
5585 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5586 DAG.getIntPtrConstant(0));
5587 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5588 DAG.getIntPtrConstant(0));
5590 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5591 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5593 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5594 N0 = LowerCONCAT_VECTORS(N0, DAG);
5596 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5599 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5602 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5603 EVT VT = Op.getValueType();
5604 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5605 "unexpected type for custom-lowering ISD::UDIV");
5607 DebugLoc dl = Op.getDebugLoc();
5608 SDValue N0 = Op.getOperand(0);
5609 SDValue N1 = Op.getOperand(1);
5612 if (VT == MVT::v8i8) {
5613 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5614 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5616 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5617 DAG.getIntPtrConstant(4));
5618 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5619 DAG.getIntPtrConstant(4));
5620 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5621 DAG.getIntPtrConstant(0));
5622 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5623 DAG.getIntPtrConstant(0));
5625 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5626 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5628 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5629 N0 = LowerCONCAT_VECTORS(N0, DAG);
5631 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5632 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5637 // v4i16 sdiv ... Convert to float.
5638 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5639 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5640 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5641 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5642 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5643 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5645 // Use reciprocal estimate and two refinement steps.
5646 // float4 recip = vrecpeq_f32(yf);
5647 // recip *= vrecpsq_f32(yf, recip);
5648 // recip *= vrecpsq_f32(yf, recip);
5649 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5650 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5651 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5652 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5654 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5655 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5656 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5658 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5659 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5660 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5661 // and that it will never cause us to return an answer too large).
5662 // float4 result = as_float4(as_int4(xf*recip) + 2);
5663 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5664 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5665 N1 = DAG.getConstant(2, MVT::i32);
5666 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5667 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5668 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5669 // Convert back to integer and return.
5670 // return vmovn_u32(vcvt_s32_f32(result));
5671 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5672 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5676 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5677 EVT VT = Op.getNode()->getValueType(0);
5678 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5681 bool ExtraOp = false;
5682 switch (Op.getOpcode()) {
5683 default: llvm_unreachable("Invalid code");
5684 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5685 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5686 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5687 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5691 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5693 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5694 Op.getOperand(1), Op.getOperand(2));
5697 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5698 // Monotonic load/store is legal for all targets
5699 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5702 // Aquire/Release load/store is not legal for targets without a
5703 // dmb or equivalent available.
5708 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5709 SelectionDAG &DAG, unsigned NewOp) {
5710 DebugLoc dl = Node->getDebugLoc();
5711 assert (Node->getValueType(0) == MVT::i64 &&
5712 "Only know how to expand i64 atomics");
5714 SmallVector<SDValue, 6> Ops;
5715 Ops.push_back(Node->getOperand(0)); // Chain
5716 Ops.push_back(Node->getOperand(1)); // Ptr
5718 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5719 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5720 // High part of Val1
5721 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5722 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5723 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5724 // High part of Val1
5725 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5726 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5727 // High part of Val2
5728 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5729 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5731 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5733 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5734 cast<MemSDNode>(Node)->getMemOperand());
5735 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5736 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5737 Results.push_back(Result.getValue(2));
5740 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5741 SmallVectorImpl<SDValue> &Results,
5743 const ARMSubtarget *Subtarget) {
5744 DebugLoc DL = N->getDebugLoc();
5745 SDValue Cycles32, OutChain;
5747 if (Subtarget->hasPerfMon()) {
5748 // Under Power Management extensions, the cycle-count is:
5749 // mrc p15, #0, <Rt>, c9, c13, #0
5750 SDValue Ops[] = { N->getOperand(0), // Chain
5751 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5752 DAG.getConstant(15, MVT::i32),
5753 DAG.getConstant(0, MVT::i32),
5754 DAG.getConstant(9, MVT::i32),
5755 DAG.getConstant(13, MVT::i32),
5756 DAG.getConstant(0, MVT::i32)
5759 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
5760 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
5761 array_lengthof(Ops));
5762 OutChain = Cycles32.getValue(1);
5764 // Intrinsic is defined to return 0 on unsupported platforms. Technically
5765 // there are older ARM CPUs that have implementation-specific ways of
5766 // obtaining this information (FIXME!).
5767 Cycles32 = DAG.getConstant(0, MVT::i32);
5768 OutChain = DAG.getEntryNode();
5772 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
5773 Cycles32, DAG.getConstant(0, MVT::i32));
5774 Results.push_back(Cycles64);
5775 Results.push_back(OutChain);
5778 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5779 switch (Op.getOpcode()) {
5780 default: llvm_unreachable("Don't know how to custom lower this!");
5781 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5782 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5783 case ISD::GlobalAddress:
5784 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5785 LowerGlobalAddressELF(Op, DAG);
5786 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5787 case ISD::SELECT: return LowerSELECT(Op, DAG);
5788 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5789 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5790 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5791 case ISD::VASTART: return LowerVASTART(Op, DAG);
5792 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5793 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5794 case ISD::SINT_TO_FP:
5795 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5796 case ISD::FP_TO_SINT:
5797 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5798 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5799 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5800 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5801 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5802 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5803 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5804 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5806 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5809 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5810 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5811 case ISD::SRL_PARTS:
5812 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5813 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5814 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5815 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5816 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5817 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5818 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5819 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5820 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5821 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5822 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5823 case ISD::MUL: return LowerMUL(Op, DAG);
5824 case ISD::SDIV: return LowerSDIV(Op, DAG);
5825 case ISD::UDIV: return LowerUDIV(Op, DAG);
5829 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5830 case ISD::ATOMIC_LOAD:
5831 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5835 /// ReplaceNodeResults - Replace the results of node with an illegal result
5836 /// type with new values built out of custom code.
5837 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5838 SmallVectorImpl<SDValue>&Results,
5839 SelectionDAG &DAG) const {
5841 switch (N->getOpcode()) {
5843 llvm_unreachable("Don't know how to custom expand this!");
5845 Res = ExpandBITCAST(N, DAG);
5847 case ISD::SIGN_EXTEND:
5848 case ISD::ZERO_EXTEND:
5849 Res = ExpandVectorExtension(N, DAG);
5853 Res = Expand64BitShift(N, DAG, Subtarget);
5855 case ISD::READCYCLECOUNTER:
5856 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
5858 case ISD::ATOMIC_LOAD_ADD:
5859 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5861 case ISD::ATOMIC_LOAD_AND:
5862 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5864 case ISD::ATOMIC_LOAD_NAND:
5865 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5867 case ISD::ATOMIC_LOAD_OR:
5868 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5870 case ISD::ATOMIC_LOAD_SUB:
5871 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5873 case ISD::ATOMIC_LOAD_XOR:
5874 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5876 case ISD::ATOMIC_SWAP:
5877 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5879 case ISD::ATOMIC_CMP_SWAP:
5880 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5882 case ISD::ATOMIC_LOAD_MIN:
5883 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5885 case ISD::ATOMIC_LOAD_UMIN:
5886 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5888 case ISD::ATOMIC_LOAD_MAX:
5889 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5891 case ISD::ATOMIC_LOAD_UMAX:
5892 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5896 Results.push_back(Res);
5899 //===----------------------------------------------------------------------===//
5900 // ARM Scheduler Hooks
5901 //===----------------------------------------------------------------------===//
5904 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5905 MachineBasicBlock *BB,
5906 unsigned Size) const {
5907 unsigned dest = MI->getOperand(0).getReg();
5908 unsigned ptr = MI->getOperand(1).getReg();
5909 unsigned oldval = MI->getOperand(2).getReg();
5910 unsigned newval = MI->getOperand(3).getReg();
5911 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5912 DebugLoc dl = MI->getDebugLoc();
5913 bool isThumb2 = Subtarget->isThumb2();
5915 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5916 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5917 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5918 (const TargetRegisterClass*)&ARM::GPRRegClass);
5921 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5922 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5923 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5926 unsigned ldrOpc, strOpc;
5928 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5930 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5931 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5934 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5935 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5938 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5939 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5943 MachineFunction *MF = BB->getParent();
5944 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5945 MachineFunction::iterator It = BB;
5946 ++It; // insert the new blocks after the current block
5948 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5949 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5950 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5951 MF->insert(It, loop1MBB);
5952 MF->insert(It, loop2MBB);
5953 MF->insert(It, exitMBB);
5955 // Transfer the remainder of BB and its successor edges to exitMBB.
5956 exitMBB->splice(exitMBB->begin(), BB,
5957 llvm::next(MachineBasicBlock::iterator(MI)),
5959 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5963 // fallthrough --> loop1MBB
5964 BB->addSuccessor(loop1MBB);
5967 // ldrex dest, [ptr]
5971 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5972 if (ldrOpc == ARM::t2LDREX)
5974 AddDefaultPred(MIB);
5975 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5976 .addReg(dest).addReg(oldval));
5977 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5978 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5979 BB->addSuccessor(loop2MBB);
5980 BB->addSuccessor(exitMBB);
5983 // strex scratch, newval, [ptr]
5987 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5988 if (strOpc == ARM::t2STREX)
5990 AddDefaultPred(MIB);
5991 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5992 .addReg(scratch).addImm(0));
5993 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5994 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5995 BB->addSuccessor(loop1MBB);
5996 BB->addSuccessor(exitMBB);
6002 MI->eraseFromParent(); // The instruction is gone now.
6008 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6009 unsigned Size, unsigned BinOpcode) const {
6010 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6011 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6013 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6014 MachineFunction *MF = BB->getParent();
6015 MachineFunction::iterator It = BB;
6018 unsigned dest = MI->getOperand(0).getReg();
6019 unsigned ptr = MI->getOperand(1).getReg();
6020 unsigned incr = MI->getOperand(2).getReg();
6021 DebugLoc dl = MI->getDebugLoc();
6022 bool isThumb2 = Subtarget->isThumb2();
6024 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6026 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6027 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6030 unsigned ldrOpc, strOpc;
6032 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6034 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6035 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6038 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6039 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6042 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6043 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6047 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6048 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6049 MF->insert(It, loopMBB);
6050 MF->insert(It, exitMBB);
6052 // Transfer the remainder of BB and its successor edges to exitMBB.
6053 exitMBB->splice(exitMBB->begin(), BB,
6054 llvm::next(MachineBasicBlock::iterator(MI)),
6056 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6058 const TargetRegisterClass *TRC = isThumb2 ?
6059 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6060 (const TargetRegisterClass*)&ARM::GPRRegClass;
6061 unsigned scratch = MRI.createVirtualRegister(TRC);
6062 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6066 // fallthrough --> loopMBB
6067 BB->addSuccessor(loopMBB);
6071 // <binop> scratch2, dest, incr
6072 // strex scratch, scratch2, ptr
6075 // fallthrough --> exitMBB
6077 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6078 if (ldrOpc == ARM::t2LDREX)
6080 AddDefaultPred(MIB);
6082 // operand order needs to go the other way for NAND
6083 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6084 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6085 addReg(incr).addReg(dest)).addReg(0);
6087 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6088 addReg(dest).addReg(incr)).addReg(0);
6091 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6092 if (strOpc == ARM::t2STREX)
6094 AddDefaultPred(MIB);
6095 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6096 .addReg(scratch).addImm(0));
6097 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6098 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6100 BB->addSuccessor(loopMBB);
6101 BB->addSuccessor(exitMBB);
6107 MI->eraseFromParent(); // The instruction is gone now.
6113 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6114 MachineBasicBlock *BB,
6117 ARMCC::CondCodes Cond) const {
6118 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6120 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6121 MachineFunction *MF = BB->getParent();
6122 MachineFunction::iterator It = BB;
6125 unsigned dest = MI->getOperand(0).getReg();
6126 unsigned ptr = MI->getOperand(1).getReg();
6127 unsigned incr = MI->getOperand(2).getReg();
6128 unsigned oldval = dest;
6129 DebugLoc dl = MI->getDebugLoc();
6130 bool isThumb2 = Subtarget->isThumb2();
6132 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6134 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6135 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6138 unsigned ldrOpc, strOpc, extendOpc;
6140 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6142 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6143 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6144 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6147 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6148 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6149 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6152 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6153 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6158 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6159 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6160 MF->insert(It, loopMBB);
6161 MF->insert(It, exitMBB);
6163 // Transfer the remainder of BB and its successor edges to exitMBB.
6164 exitMBB->splice(exitMBB->begin(), BB,
6165 llvm::next(MachineBasicBlock::iterator(MI)),
6167 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6169 const TargetRegisterClass *TRC = isThumb2 ?
6170 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6171 (const TargetRegisterClass*)&ARM::GPRRegClass;
6172 unsigned scratch = MRI.createVirtualRegister(TRC);
6173 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6177 // fallthrough --> loopMBB
6178 BB->addSuccessor(loopMBB);
6182 // (sign extend dest, if required)
6184 // cmov.cond scratch2, incr, dest
6185 // strex scratch, scratch2, ptr
6188 // fallthrough --> exitMBB
6190 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6191 if (ldrOpc == ARM::t2LDREX)
6193 AddDefaultPred(MIB);
6195 // Sign extend the value, if necessary.
6196 if (signExtend && extendOpc) {
6197 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6198 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6203 // Build compare and cmov instructions.
6204 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6205 .addReg(oldval).addReg(incr));
6206 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6207 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6209 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6210 if (strOpc == ARM::t2STREX)
6212 AddDefaultPred(MIB);
6213 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6214 .addReg(scratch).addImm(0));
6215 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6216 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6218 BB->addSuccessor(loopMBB);
6219 BB->addSuccessor(exitMBB);
6225 MI->eraseFromParent(); // The instruction is gone now.
6231 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6232 unsigned Op1, unsigned Op2,
6233 bool NeedsCarry, bool IsCmpxchg,
6234 bool IsMinMax, ARMCC::CondCodes CC) const {
6235 // This also handles ATOMIC_SWAP, indicated by Op1==0.
6236 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6238 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6239 MachineFunction *MF = BB->getParent();
6240 MachineFunction::iterator It = BB;
6243 unsigned destlo = MI->getOperand(0).getReg();
6244 unsigned desthi = MI->getOperand(1).getReg();
6245 unsigned ptr = MI->getOperand(2).getReg();
6246 unsigned vallo = MI->getOperand(3).getReg();
6247 unsigned valhi = MI->getOperand(4).getReg();
6248 DebugLoc dl = MI->getDebugLoc();
6249 bool isThumb2 = Subtarget->isThumb2();
6251 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6253 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6254 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6255 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6258 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6259 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6260 if (IsCmpxchg || IsMinMax)
6261 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6263 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6264 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6266 MF->insert(It, loopMBB);
6267 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6268 if (IsCmpxchg) MF->insert(It, cont2BB);
6269 MF->insert(It, exitMBB);
6271 // Transfer the remainder of BB and its successor edges to exitMBB.
6272 exitMBB->splice(exitMBB->begin(), BB,
6273 llvm::next(MachineBasicBlock::iterator(MI)),
6275 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6277 const TargetRegisterClass *TRC = isThumb2 ?
6278 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6279 (const TargetRegisterClass*)&ARM::GPRRegClass;
6280 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6284 // fallthrough --> loopMBB
6285 BB->addSuccessor(loopMBB);
6288 // ldrexd r2, r3, ptr
6289 // <binopa> r0, r2, incr
6290 // <binopb> r1, r3, incr
6291 // strexd storesuccess, r0, r1, ptr
6292 // cmp storesuccess, #0
6294 // fallthrough --> exitMBB
6299 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6300 .addReg(destlo, RegState::Define)
6301 .addReg(desthi, RegState::Define)
6304 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6305 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6306 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6307 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6308 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6309 .addReg(GPRPair0, 0, ARM::gsub_0);
6310 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6311 .addReg(GPRPair0, 0, ARM::gsub_1);
6314 unsigned StoreLo, StoreHi;
6317 for (unsigned i = 0; i < 2; i++) {
6318 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6320 .addReg(i == 0 ? destlo : desthi)
6321 .addReg(i == 0 ? vallo : valhi));
6322 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6323 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6324 BB->addSuccessor(exitMBB);
6325 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6326 BB = (i == 0 ? contBB : cont2BB);
6329 // Copy to physregs for strexd
6330 StoreLo = MI->getOperand(5).getReg();
6331 StoreHi = MI->getOperand(6).getReg();
6333 // Perform binary operation
6334 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6335 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6336 .addReg(destlo).addReg(vallo))
6337 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6338 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6339 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6340 .addReg(desthi).addReg(valhi))
6341 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6346 // Copy to physregs for strexd
6351 // Compare and branch to exit block.
6352 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6353 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6354 BB->addSuccessor(exitMBB);
6355 BB->addSuccessor(contBB);
6363 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6364 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6366 // Marshal a pair...
6367 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6368 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6369 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6370 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6371 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6374 .addImm(ARM::gsub_0);
6375 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6378 .addImm(ARM::gsub_1);
6381 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6382 .addReg(StorePair).addReg(ptr));
6385 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6386 .addReg(storesuccess).addImm(0));
6387 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6388 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6390 BB->addSuccessor(loopMBB);
6391 BB->addSuccessor(exitMBB);
6397 MI->eraseFromParent(); // The instruction is gone now.
6402 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6403 /// registers the function context.
6404 void ARMTargetLowering::
6405 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6406 MachineBasicBlock *DispatchBB, int FI) const {
6407 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6408 DebugLoc dl = MI->getDebugLoc();
6409 MachineFunction *MF = MBB->getParent();
6410 MachineRegisterInfo *MRI = &MF->getRegInfo();
6411 MachineConstantPool *MCP = MF->getConstantPool();
6412 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6413 const Function *F = MF->getFunction();
6415 bool isThumb = Subtarget->isThumb();
6416 bool isThumb2 = Subtarget->isThumb2();
6418 unsigned PCLabelId = AFI->createPICLabelUId();
6419 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6420 ARMConstantPoolValue *CPV =
6421 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6422 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6424 const TargetRegisterClass *TRC = isThumb ?
6425 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6426 (const TargetRegisterClass*)&ARM::GPRRegClass;
6428 // Grab constant pool and fixed stack memory operands.
6429 MachineMemOperand *CPMMO =
6430 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6431 MachineMemOperand::MOLoad, 4, 4);
6433 MachineMemOperand *FIMMOSt =
6434 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6435 MachineMemOperand::MOStore, 4, 4);
6437 // Load the address of the dispatch MBB into the jump buffer.
6439 // Incoming value: jbuf
6440 // ldr.n r5, LCPI1_1
6443 // str r5, [$jbuf, #+4] ; &jbuf[1]
6444 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6445 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6446 .addConstantPoolIndex(CPI)
6447 .addMemOperand(CPMMO));
6448 // Set the low bit because of thumb mode.
6449 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6451 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6452 .addReg(NewVReg1, RegState::Kill)
6454 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6455 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6456 .addReg(NewVReg2, RegState::Kill)
6458 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6459 .addReg(NewVReg3, RegState::Kill)
6461 .addImm(36) // &jbuf[1] :: pc
6462 .addMemOperand(FIMMOSt));
6463 } else if (isThumb) {
6464 // Incoming value: jbuf
6465 // ldr.n r1, LCPI1_4
6469 // add r2, $jbuf, #+4 ; &jbuf[1]
6471 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6472 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6473 .addConstantPoolIndex(CPI)
6474 .addMemOperand(CPMMO));
6475 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6476 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6477 .addReg(NewVReg1, RegState::Kill)
6479 // Set the low bit because of thumb mode.
6480 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6481 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6482 .addReg(ARM::CPSR, RegState::Define)
6484 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6485 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6486 .addReg(ARM::CPSR, RegState::Define)
6487 .addReg(NewVReg2, RegState::Kill)
6488 .addReg(NewVReg3, RegState::Kill));
6489 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6490 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6492 .addImm(36)); // &jbuf[1] :: pc
6493 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6494 .addReg(NewVReg4, RegState::Kill)
6495 .addReg(NewVReg5, RegState::Kill)
6497 .addMemOperand(FIMMOSt));
6499 // Incoming value: jbuf
6502 // str r1, [$jbuf, #+4] ; &jbuf[1]
6503 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6504 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6505 .addConstantPoolIndex(CPI)
6507 .addMemOperand(CPMMO));
6508 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6509 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6510 .addReg(NewVReg1, RegState::Kill)
6511 .addImm(PCLabelId));
6512 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6513 .addReg(NewVReg2, RegState::Kill)
6515 .addImm(36) // &jbuf[1] :: pc
6516 .addMemOperand(FIMMOSt));
6520 MachineBasicBlock *ARMTargetLowering::
6521 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6522 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6523 DebugLoc dl = MI->getDebugLoc();
6524 MachineFunction *MF = MBB->getParent();
6525 MachineRegisterInfo *MRI = &MF->getRegInfo();
6526 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6527 MachineFrameInfo *MFI = MF->getFrameInfo();
6528 int FI = MFI->getFunctionContextIndex();
6530 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6531 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6532 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6534 // Get a mapping of the call site numbers to all of the landing pads they're
6536 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6537 unsigned MaxCSNum = 0;
6538 MachineModuleInfo &MMI = MF->getMMI();
6539 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6541 if (!BB->isLandingPad()) continue;
6543 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6545 for (MachineBasicBlock::iterator
6546 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6547 if (!II->isEHLabel()) continue;
6549 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6550 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6552 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6553 for (SmallVectorImpl<unsigned>::iterator
6554 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6555 CSI != CSE; ++CSI) {
6556 CallSiteNumToLPad[*CSI].push_back(BB);
6557 MaxCSNum = std::max(MaxCSNum, *CSI);
6563 // Get an ordered list of the machine basic blocks for the jump table.
6564 std::vector<MachineBasicBlock*> LPadList;
6565 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6566 LPadList.reserve(CallSiteNumToLPad.size());
6567 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6568 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6569 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6570 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6571 LPadList.push_back(*II);
6572 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6576 assert(!LPadList.empty() &&
6577 "No landing pad destinations for the dispatch jump table!");
6579 // Create the jump table and associated information.
6580 MachineJumpTableInfo *JTI =
6581 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6582 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6583 unsigned UId = AFI->createJumpTableUId();
6584 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6586 // Create the MBBs for the dispatch code.
6588 // Shove the dispatch's address into the return slot in the function context.
6589 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6590 DispatchBB->setIsLandingPad();
6592 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6593 unsigned trap_opcode;
6594 if (Subtarget->isThumb())
6595 trap_opcode = ARM::tTRAP;
6597 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6599 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6600 DispatchBB->addSuccessor(TrapBB);
6602 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6603 DispatchBB->addSuccessor(DispContBB);
6606 MF->insert(MF->end(), DispatchBB);
6607 MF->insert(MF->end(), DispContBB);
6608 MF->insert(MF->end(), TrapBB);
6610 // Insert code into the entry block that creates and registers the function
6612 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6614 MachineMemOperand *FIMMOLd =
6615 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6616 MachineMemOperand::MOLoad |
6617 MachineMemOperand::MOVolatile, 4, 4);
6619 MachineInstrBuilder MIB;
6620 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6622 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6623 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6625 // Add a register mask with no preserved registers. This results in all
6626 // registers being marked as clobbered.
6627 MIB.addRegMask(RI.getNoPreservedMask());
6629 unsigned NumLPads = LPadList.size();
6630 if (Subtarget->isThumb2()) {
6631 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6632 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6635 .addMemOperand(FIMMOLd));
6637 if (NumLPads < 256) {
6638 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6640 .addImm(LPadList.size()));
6642 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6643 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6644 .addImm(NumLPads & 0xFFFF));
6646 unsigned VReg2 = VReg1;
6647 if ((NumLPads & 0xFFFF0000) != 0) {
6648 VReg2 = MRI->createVirtualRegister(TRC);
6649 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6651 .addImm(NumLPads >> 16));
6654 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6659 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6664 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6665 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6666 .addJumpTableIndex(MJTI)
6669 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6672 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6673 .addReg(NewVReg3, RegState::Kill)
6675 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6677 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6678 .addReg(NewVReg4, RegState::Kill)
6680 .addJumpTableIndex(MJTI)
6682 } else if (Subtarget->isThumb()) {
6683 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6684 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6687 .addMemOperand(FIMMOLd));
6689 if (NumLPads < 256) {
6690 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6694 MachineConstantPool *ConstantPool = MF->getConstantPool();
6695 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6696 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6698 // MachineConstantPool wants an explicit alignment.
6699 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6701 Align = getDataLayout()->getTypeAllocSize(C->getType());
6702 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6704 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6705 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6706 .addReg(VReg1, RegState::Define)
6707 .addConstantPoolIndex(Idx));
6708 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6713 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6718 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6719 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6720 .addReg(ARM::CPSR, RegState::Define)
6724 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6725 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6726 .addJumpTableIndex(MJTI)
6729 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6730 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6731 .addReg(ARM::CPSR, RegState::Define)
6732 .addReg(NewVReg2, RegState::Kill)
6735 MachineMemOperand *JTMMOLd =
6736 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6737 MachineMemOperand::MOLoad, 4, 4);
6739 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6740 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6741 .addReg(NewVReg4, RegState::Kill)
6743 .addMemOperand(JTMMOLd));
6745 unsigned NewVReg6 = NewVReg5;
6746 if (RelocM == Reloc::PIC_) {
6747 NewVReg6 = MRI->createVirtualRegister(TRC);
6748 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6749 .addReg(ARM::CPSR, RegState::Define)
6750 .addReg(NewVReg5, RegState::Kill)
6754 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6755 .addReg(NewVReg6, RegState::Kill)
6756 .addJumpTableIndex(MJTI)
6759 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6760 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6763 .addMemOperand(FIMMOLd));
6765 if (NumLPads < 256) {
6766 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6769 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6770 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6771 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6772 .addImm(NumLPads & 0xFFFF));
6774 unsigned VReg2 = VReg1;
6775 if ((NumLPads & 0xFFFF0000) != 0) {
6776 VReg2 = MRI->createVirtualRegister(TRC);
6777 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6779 .addImm(NumLPads >> 16));
6782 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6786 MachineConstantPool *ConstantPool = MF->getConstantPool();
6787 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6788 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6790 // MachineConstantPool wants an explicit alignment.
6791 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6793 Align = getDataLayout()->getTypeAllocSize(C->getType());
6794 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6796 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6797 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6798 .addReg(VReg1, RegState::Define)
6799 .addConstantPoolIndex(Idx)
6801 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6803 .addReg(VReg1, RegState::Kill));
6806 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6811 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6813 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6815 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6816 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6817 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6818 .addJumpTableIndex(MJTI)
6821 MachineMemOperand *JTMMOLd =
6822 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6823 MachineMemOperand::MOLoad, 4, 4);
6824 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6826 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6827 .addReg(NewVReg3, RegState::Kill)
6830 .addMemOperand(JTMMOLd));
6832 if (RelocM == Reloc::PIC_) {
6833 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6834 .addReg(NewVReg5, RegState::Kill)
6836 .addJumpTableIndex(MJTI)
6839 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6840 .addReg(NewVReg5, RegState::Kill)
6841 .addJumpTableIndex(MJTI)
6846 // Add the jump table entries as successors to the MBB.
6847 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6848 for (std::vector<MachineBasicBlock*>::iterator
6849 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6850 MachineBasicBlock *CurMBB = *I;
6851 if (SeenMBBs.insert(CurMBB))
6852 DispContBB->addSuccessor(CurMBB);
6855 // N.B. the order the invoke BBs are processed in doesn't matter here.
6856 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6857 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6858 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6859 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6860 MachineBasicBlock *BB = *I;
6862 // Remove the landing pad successor from the invoke block and replace it
6863 // with the new dispatch block.
6864 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6866 while (!Successors.empty()) {
6867 MachineBasicBlock *SMBB = Successors.pop_back_val();
6868 if (SMBB->isLandingPad()) {
6869 BB->removeSuccessor(SMBB);
6870 MBBLPads.push_back(SMBB);
6874 BB->addSuccessor(DispatchBB);
6876 // Find the invoke call and mark all of the callee-saved registers as
6877 // 'implicit defined' so that they're spilled. This prevents code from
6878 // moving instructions to before the EH block, where they will never be
6880 for (MachineBasicBlock::reverse_iterator
6881 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6882 if (!II->isCall()) continue;
6884 DenseMap<unsigned, bool> DefRegs;
6885 for (MachineInstr::mop_iterator
6886 OI = II->operands_begin(), OE = II->operands_end();
6888 if (!OI->isReg()) continue;
6889 DefRegs[OI->getReg()] = true;
6892 MachineInstrBuilder MIB(*MF, &*II);
6894 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6895 unsigned Reg = SavedRegs[i];
6896 if (Subtarget->isThumb2() &&
6897 !ARM::tGPRRegClass.contains(Reg) &&
6898 !ARM::hGPRRegClass.contains(Reg))
6900 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6902 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6905 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6912 // Mark all former landing pads as non-landing pads. The dispatch is the only
6914 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6915 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6916 (*I)->setIsLandingPad(false);
6918 // The instruction is gone now.
6919 MI->eraseFromParent();
6925 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6926 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6927 E = MBB->succ_end(); I != E; ++I)
6930 llvm_unreachable("Expecting a BB with two successors!");
6933 MachineBasicBlock *ARMTargetLowering::
6934 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6935 // This pseudo instruction has 3 operands: dst, src, size
6936 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6937 // Otherwise, we will generate unrolled scalar copies.
6938 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6939 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6940 MachineFunction::iterator It = BB;
6943 unsigned dest = MI->getOperand(0).getReg();
6944 unsigned src = MI->getOperand(1).getReg();
6945 unsigned SizeVal = MI->getOperand(2).getImm();
6946 unsigned Align = MI->getOperand(3).getImm();
6947 DebugLoc dl = MI->getDebugLoc();
6949 bool isThumb2 = Subtarget->isThumb2();
6950 MachineFunction *MF = BB->getParent();
6951 MachineRegisterInfo &MRI = MF->getRegInfo();
6952 unsigned ldrOpc, strOpc, UnitSize = 0;
6954 const TargetRegisterClass *TRC = isThumb2 ?
6955 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6956 (const TargetRegisterClass*)&ARM::GPRRegClass;
6957 const TargetRegisterClass *TRC_Vec = 0;
6960 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6961 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6963 } else if (Align & 2) {
6964 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6965 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6968 // Check whether we can use NEON instructions.
6969 if (!MF->getFunction()->getAttributes().
6970 hasAttribute(AttributeSet::FunctionIndex,
6971 Attribute::NoImplicitFloat) &&
6972 Subtarget->hasNEON()) {
6973 if ((Align % 16 == 0) && SizeVal >= 16) {
6974 ldrOpc = ARM::VLD1q32wb_fixed;
6975 strOpc = ARM::VST1q32wb_fixed;
6977 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6979 else if ((Align % 8 == 0) && SizeVal >= 8) {
6980 ldrOpc = ARM::VLD1d32wb_fixed;
6981 strOpc = ARM::VST1d32wb_fixed;
6983 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6986 // Can't use NEON instructions.
6987 if (UnitSize == 0) {
6988 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6989 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6994 unsigned BytesLeft = SizeVal % UnitSize;
6995 unsigned LoopSize = SizeVal - BytesLeft;
6997 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6998 // Use LDR and STR to copy.
6999 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7000 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7001 unsigned srcIn = src;
7002 unsigned destIn = dest;
7003 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7004 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7005 unsigned srcOut = MRI.createVirtualRegister(TRC);
7006 unsigned destOut = MRI.createVirtualRegister(TRC);
7007 if (UnitSize >= 8) {
7008 AddDefaultPred(BuildMI(*BB, MI, dl,
7009 TII->get(ldrOpc), scratch)
7010 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7012 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7013 .addReg(destIn).addImm(0).addReg(scratch));
7014 } else if (isThumb2) {
7015 AddDefaultPred(BuildMI(*BB, MI, dl,
7016 TII->get(ldrOpc), scratch)
7017 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7019 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7020 .addReg(scratch).addReg(destIn)
7023 AddDefaultPred(BuildMI(*BB, MI, dl,
7024 TII->get(ldrOpc), scratch)
7025 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7028 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7029 .addReg(scratch).addReg(destIn)
7030 .addReg(0).addImm(UnitSize));
7036 // Handle the leftover bytes with LDRB and STRB.
7037 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7038 // [destOut] = STRB_POST(scratch, destIn, 1)
7039 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7040 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7041 for (unsigned i = 0; i < BytesLeft; i++) {
7042 unsigned scratch = MRI.createVirtualRegister(TRC);
7043 unsigned srcOut = MRI.createVirtualRegister(TRC);
7044 unsigned destOut = MRI.createVirtualRegister(TRC);
7046 AddDefaultPred(BuildMI(*BB, MI, dl,
7047 TII->get(ldrOpc),scratch)
7048 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7050 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7051 .addReg(scratch).addReg(destIn)
7052 .addReg(0).addImm(1));
7054 AddDefaultPred(BuildMI(*BB, MI, dl,
7055 TII->get(ldrOpc),scratch)
7056 .addReg(srcOut, RegState::Define).addReg(srcIn)
7057 .addReg(0).addImm(1));
7059 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7060 .addReg(scratch).addReg(destIn)
7061 .addReg(0).addImm(1));
7066 MI->eraseFromParent(); // The instruction is gone now.
7070 // Expand the pseudo op to a loop.
7073 // movw varEnd, # --> with thumb2
7075 // ldrcp varEnd, idx --> without thumb2
7076 // fallthrough --> loopMBB
7078 // PHI varPhi, varEnd, varLoop
7079 // PHI srcPhi, src, srcLoop
7080 // PHI destPhi, dst, destLoop
7081 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7082 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7083 // subs varLoop, varPhi, #UnitSize
7085 // fallthrough --> exitMBB
7087 // epilogue to handle left-over bytes
7088 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7089 // [destOut] = STRB_POST(scratch, destLoop, 1)
7090 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7091 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7092 MF->insert(It, loopMBB);
7093 MF->insert(It, exitMBB);
7095 // Transfer the remainder of BB and its successor edges to exitMBB.
7096 exitMBB->splice(exitMBB->begin(), BB,
7097 llvm::next(MachineBasicBlock::iterator(MI)),
7099 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7101 // Load an immediate to varEnd.
7102 unsigned varEnd = MRI.createVirtualRegister(TRC);
7104 unsigned VReg1 = varEnd;
7105 if ((LoopSize & 0xFFFF0000) != 0)
7106 VReg1 = MRI.createVirtualRegister(TRC);
7107 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7108 .addImm(LoopSize & 0xFFFF));
7110 if ((LoopSize & 0xFFFF0000) != 0)
7111 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7113 .addImm(LoopSize >> 16));
7115 MachineConstantPool *ConstantPool = MF->getConstantPool();
7116 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7117 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7119 // MachineConstantPool wants an explicit alignment.
7120 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7122 Align = getDataLayout()->getTypeAllocSize(C->getType());
7123 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7125 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7126 .addReg(varEnd, RegState::Define)
7127 .addConstantPoolIndex(Idx)
7130 BB->addSuccessor(loopMBB);
7132 // Generate the loop body:
7133 // varPhi = PHI(varLoop, varEnd)
7134 // srcPhi = PHI(srcLoop, src)
7135 // destPhi = PHI(destLoop, dst)
7136 MachineBasicBlock *entryBB = BB;
7138 unsigned varLoop = MRI.createVirtualRegister(TRC);
7139 unsigned varPhi = MRI.createVirtualRegister(TRC);
7140 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7141 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7142 unsigned destLoop = MRI.createVirtualRegister(TRC);
7143 unsigned destPhi = MRI.createVirtualRegister(TRC);
7145 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7146 .addReg(varLoop).addMBB(loopMBB)
7147 .addReg(varEnd).addMBB(entryBB);
7148 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7149 .addReg(srcLoop).addMBB(loopMBB)
7150 .addReg(src).addMBB(entryBB);
7151 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7152 .addReg(destLoop).addMBB(loopMBB)
7153 .addReg(dest).addMBB(entryBB);
7155 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7156 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7157 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7158 if (UnitSize >= 8) {
7159 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7160 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7162 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7163 .addReg(destPhi).addImm(0).addReg(scratch));
7164 } else if (isThumb2) {
7165 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7166 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7168 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7169 .addReg(scratch).addReg(destPhi)
7172 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7173 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7176 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7177 .addReg(scratch).addReg(destPhi)
7178 .addReg(0).addImm(UnitSize));
7181 // Decrement loop variable by UnitSize.
7182 MachineInstrBuilder MIB = BuildMI(BB, dl,
7183 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7184 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7185 MIB->getOperand(5).setReg(ARM::CPSR);
7186 MIB->getOperand(5).setIsDef(true);
7188 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7189 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7191 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7192 BB->addSuccessor(loopMBB);
7193 BB->addSuccessor(exitMBB);
7195 // Add epilogue to handle BytesLeft.
7197 MachineInstr *StartOfExit = exitMBB->begin();
7198 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7199 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7201 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7202 // [destOut] = STRB_POST(scratch, destLoop, 1)
7203 unsigned srcIn = srcLoop;
7204 unsigned destIn = destLoop;
7205 for (unsigned i = 0; i < BytesLeft; i++) {
7206 unsigned scratch = MRI.createVirtualRegister(TRC);
7207 unsigned srcOut = MRI.createVirtualRegister(TRC);
7208 unsigned destOut = MRI.createVirtualRegister(TRC);
7210 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7211 TII->get(ldrOpc),scratch)
7212 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7214 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7215 .addReg(scratch).addReg(destIn)
7218 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7219 TII->get(ldrOpc),scratch)
7220 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7222 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7223 .addReg(scratch).addReg(destIn)
7224 .addReg(0).addImm(1));
7230 MI->eraseFromParent(); // The instruction is gone now.
7235 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7236 MachineBasicBlock *BB) const {
7237 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7238 DebugLoc dl = MI->getDebugLoc();
7239 bool isThumb2 = Subtarget->isThumb2();
7240 switch (MI->getOpcode()) {
7243 llvm_unreachable("Unexpected instr type to insert");
7245 // The Thumb2 pre-indexed stores have the same MI operands, they just
7246 // define them differently in the .td files from the isel patterns, so
7247 // they need pseudos.
7248 case ARM::t2STR_preidx:
7249 MI->setDesc(TII->get(ARM::t2STR_PRE));
7251 case ARM::t2STRB_preidx:
7252 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7254 case ARM::t2STRH_preidx:
7255 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7258 case ARM::STRi_preidx:
7259 case ARM::STRBi_preidx: {
7260 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7261 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7262 // Decode the offset.
7263 unsigned Offset = MI->getOperand(4).getImm();
7264 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7265 Offset = ARM_AM::getAM2Offset(Offset);
7269 MachineMemOperand *MMO = *MI->memoperands_begin();
7270 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7271 .addOperand(MI->getOperand(0)) // Rn_wb
7272 .addOperand(MI->getOperand(1)) // Rt
7273 .addOperand(MI->getOperand(2)) // Rn
7274 .addImm(Offset) // offset (skip GPR==zero_reg)
7275 .addOperand(MI->getOperand(5)) // pred
7276 .addOperand(MI->getOperand(6))
7277 .addMemOperand(MMO);
7278 MI->eraseFromParent();
7281 case ARM::STRr_preidx:
7282 case ARM::STRBr_preidx:
7283 case ARM::STRH_preidx: {
7285 switch (MI->getOpcode()) {
7286 default: llvm_unreachable("unexpected opcode!");
7287 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7288 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7289 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7291 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7292 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7293 MIB.addOperand(MI->getOperand(i));
7294 MI->eraseFromParent();
7297 case ARM::ATOMIC_LOAD_ADD_I8:
7298 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7299 case ARM::ATOMIC_LOAD_ADD_I16:
7300 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7301 case ARM::ATOMIC_LOAD_ADD_I32:
7302 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7304 case ARM::ATOMIC_LOAD_AND_I8:
7305 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7306 case ARM::ATOMIC_LOAD_AND_I16:
7307 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7308 case ARM::ATOMIC_LOAD_AND_I32:
7309 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7311 case ARM::ATOMIC_LOAD_OR_I8:
7312 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7313 case ARM::ATOMIC_LOAD_OR_I16:
7314 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7315 case ARM::ATOMIC_LOAD_OR_I32:
7316 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7318 case ARM::ATOMIC_LOAD_XOR_I8:
7319 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7320 case ARM::ATOMIC_LOAD_XOR_I16:
7321 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7322 case ARM::ATOMIC_LOAD_XOR_I32:
7323 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7325 case ARM::ATOMIC_LOAD_NAND_I8:
7326 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7327 case ARM::ATOMIC_LOAD_NAND_I16:
7328 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7329 case ARM::ATOMIC_LOAD_NAND_I32:
7330 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7332 case ARM::ATOMIC_LOAD_SUB_I8:
7333 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7334 case ARM::ATOMIC_LOAD_SUB_I16:
7335 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7336 case ARM::ATOMIC_LOAD_SUB_I32:
7337 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7339 case ARM::ATOMIC_LOAD_MIN_I8:
7340 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7341 case ARM::ATOMIC_LOAD_MIN_I16:
7342 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7343 case ARM::ATOMIC_LOAD_MIN_I32:
7344 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7346 case ARM::ATOMIC_LOAD_MAX_I8:
7347 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7348 case ARM::ATOMIC_LOAD_MAX_I16:
7349 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7350 case ARM::ATOMIC_LOAD_MAX_I32:
7351 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7353 case ARM::ATOMIC_LOAD_UMIN_I8:
7354 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7355 case ARM::ATOMIC_LOAD_UMIN_I16:
7356 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7357 case ARM::ATOMIC_LOAD_UMIN_I32:
7358 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7360 case ARM::ATOMIC_LOAD_UMAX_I8:
7361 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7362 case ARM::ATOMIC_LOAD_UMAX_I16:
7363 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7364 case ARM::ATOMIC_LOAD_UMAX_I32:
7365 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7367 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7368 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7369 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7371 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7372 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7373 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7376 case ARM::ATOMADD6432:
7377 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7378 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7379 /*NeedsCarry*/ true);
7380 case ARM::ATOMSUB6432:
7381 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7382 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7383 /*NeedsCarry*/ true);
7384 case ARM::ATOMOR6432:
7385 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7386 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7387 case ARM::ATOMXOR6432:
7388 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7389 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7390 case ARM::ATOMAND6432:
7391 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7392 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7393 case ARM::ATOMSWAP6432:
7394 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7395 case ARM::ATOMCMPXCHG6432:
7396 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7397 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7398 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7399 case ARM::ATOMMIN6432:
7400 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7401 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7402 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7403 /*IsMinMax*/ true, ARMCC::LT);
7404 case ARM::ATOMMAX6432:
7405 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7406 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7407 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7408 /*IsMinMax*/ true, ARMCC::GE);
7409 case ARM::ATOMUMIN6432:
7410 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7411 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7412 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7413 /*IsMinMax*/ true, ARMCC::LO);
7414 case ARM::ATOMUMAX6432:
7415 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7416 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7417 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7418 /*IsMinMax*/ true, ARMCC::HS);
7420 case ARM::tMOVCCr_pseudo: {
7421 // To "insert" a SELECT_CC instruction, we actually have to insert the
7422 // diamond control-flow pattern. The incoming instruction knows the
7423 // destination vreg to set, the condition code register to branch on, the
7424 // true/false values to select between, and a branch opcode to use.
7425 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7426 MachineFunction::iterator It = BB;
7432 // cmpTY ccX, r1, r2
7434 // fallthrough --> copy0MBB
7435 MachineBasicBlock *thisMBB = BB;
7436 MachineFunction *F = BB->getParent();
7437 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7438 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7439 F->insert(It, copy0MBB);
7440 F->insert(It, sinkMBB);
7442 // Transfer the remainder of BB and its successor edges to sinkMBB.
7443 sinkMBB->splice(sinkMBB->begin(), BB,
7444 llvm::next(MachineBasicBlock::iterator(MI)),
7446 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7448 BB->addSuccessor(copy0MBB);
7449 BB->addSuccessor(sinkMBB);
7451 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7452 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7455 // %FalseValue = ...
7456 // # fallthrough to sinkMBB
7459 // Update machine-CFG edges
7460 BB->addSuccessor(sinkMBB);
7463 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7466 BuildMI(*BB, BB->begin(), dl,
7467 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7468 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7469 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7471 MI->eraseFromParent(); // The pseudo instruction is gone now.
7476 case ARM::BCCZi64: {
7477 // If there is an unconditional branch to the other successor, remove it.
7478 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7480 // Compare both parts that make up the double comparison separately for
7482 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7484 unsigned LHS1 = MI->getOperand(1).getReg();
7485 unsigned LHS2 = MI->getOperand(2).getReg();
7487 AddDefaultPred(BuildMI(BB, dl,
7488 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7489 .addReg(LHS1).addImm(0));
7490 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7491 .addReg(LHS2).addImm(0)
7492 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7494 unsigned RHS1 = MI->getOperand(3).getReg();
7495 unsigned RHS2 = MI->getOperand(4).getReg();
7496 AddDefaultPred(BuildMI(BB, dl,
7497 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7498 .addReg(LHS1).addReg(RHS1));
7499 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7500 .addReg(LHS2).addReg(RHS2)
7501 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7504 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7505 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7506 if (MI->getOperand(0).getImm() == ARMCC::NE)
7507 std::swap(destMBB, exitMBB);
7509 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7510 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7512 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7514 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7516 MI->eraseFromParent(); // The pseudo instruction is gone now.
7520 case ARM::Int_eh_sjlj_setjmp:
7521 case ARM::Int_eh_sjlj_setjmp_nofp:
7522 case ARM::tInt_eh_sjlj_setjmp:
7523 case ARM::t2Int_eh_sjlj_setjmp:
7524 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7525 EmitSjLjDispatchBlock(MI, BB);
7530 // To insert an ABS instruction, we have to insert the
7531 // diamond control-flow pattern. The incoming instruction knows the
7532 // source vreg to test against 0, the destination vreg to set,
7533 // the condition code register to branch on, the
7534 // true/false values to select between, and a branch opcode to use.
7539 // BCC (branch to SinkBB if V0 >= 0)
7540 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7541 // SinkBB: V1 = PHI(V2, V3)
7542 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7543 MachineFunction::iterator BBI = BB;
7545 MachineFunction *Fn = BB->getParent();
7546 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7547 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7548 Fn->insert(BBI, RSBBB);
7549 Fn->insert(BBI, SinkBB);
7551 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7552 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7553 bool isThumb2 = Subtarget->isThumb2();
7554 MachineRegisterInfo &MRI = Fn->getRegInfo();
7555 // In Thumb mode S must not be specified if source register is the SP or
7556 // PC and if destination register is the SP, so restrict register class
7557 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7558 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7559 (const TargetRegisterClass*)&ARM::GPRRegClass);
7561 // Transfer the remainder of BB and its successor edges to sinkMBB.
7562 SinkBB->splice(SinkBB->begin(), BB,
7563 llvm::next(MachineBasicBlock::iterator(MI)),
7565 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7567 BB->addSuccessor(RSBBB);
7568 BB->addSuccessor(SinkBB);
7570 // fall through to SinkMBB
7571 RSBBB->addSuccessor(SinkBB);
7573 // insert a cmp at the end of BB
7574 AddDefaultPred(BuildMI(BB, dl,
7575 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7576 .addReg(ABSSrcReg).addImm(0));
7578 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7580 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7581 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7583 // insert rsbri in RSBBB
7584 // Note: BCC and rsbri will be converted into predicated rsbmi
7585 // by if-conversion pass
7586 BuildMI(*RSBBB, RSBBB->begin(), dl,
7587 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7588 .addReg(ABSSrcReg, RegState::Kill)
7589 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7591 // insert PHI in SinkBB,
7592 // reuse ABSDstReg to not change uses of ABS instruction
7593 BuildMI(*SinkBB, SinkBB->begin(), dl,
7594 TII->get(ARM::PHI), ABSDstReg)
7595 .addReg(NewRsbDstReg).addMBB(RSBBB)
7596 .addReg(ABSSrcReg).addMBB(BB);
7598 // remove ABS instruction
7599 MI->eraseFromParent();
7601 // return last added BB
7604 case ARM::COPY_STRUCT_BYVAL_I32:
7606 return EmitStructByval(MI, BB);
7610 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7611 SDNode *Node) const {
7612 if (!MI->hasPostISelHook()) {
7613 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7614 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7618 const MCInstrDesc *MCID = &MI->getDesc();
7619 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7620 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7621 // operand is still set to noreg. If needed, set the optional operand's
7622 // register to CPSR, and remove the redundant implicit def.
7624 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7626 // Rename pseudo opcodes.
7627 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7629 const ARMBaseInstrInfo *TII =
7630 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7631 MCID = &TII->get(NewOpc);
7633 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7634 "converted opcode should be the same except for cc_out");
7638 // Add the optional cc_out operand
7639 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7641 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7643 // Any ARM instruction that sets the 's' bit should specify an optional
7644 // "cc_out" operand in the last operand position.
7645 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7646 assert(!NewOpc && "Optional cc_out operand required");
7649 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7650 // since we already have an optional CPSR def.
7651 bool definesCPSR = false;
7652 bool deadCPSR = false;
7653 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7655 const MachineOperand &MO = MI->getOperand(i);
7656 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7660 MI->RemoveOperand(i);
7665 assert(!NewOpc && "Optional cc_out operand required");
7668 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7670 assert(!MI->getOperand(ccOutIdx).getReg() &&
7671 "expect uninitialized optional cc_out operand");
7675 // If this instruction was defined with an optional CPSR def and its dag node
7676 // had a live implicit CPSR def, then activate the optional CPSR def.
7677 MachineOperand &MO = MI->getOperand(ccOutIdx);
7678 MO.setReg(ARM::CPSR);
7682 //===----------------------------------------------------------------------===//
7683 // ARM Optimization Hooks
7684 //===----------------------------------------------------------------------===//
7686 // Helper function that checks if N is a null or all ones constant.
7687 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7688 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7691 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7694 // Return true if N is conditionally 0 or all ones.
7695 // Detects these expressions where cc is an i1 value:
7697 // (select cc 0, y) [AllOnes=0]
7698 // (select cc y, 0) [AllOnes=0]
7699 // (zext cc) [AllOnes=0]
7700 // (sext cc) [AllOnes=0/1]
7701 // (select cc -1, y) [AllOnes=1]
7702 // (select cc y, -1) [AllOnes=1]
7704 // Invert is set when N is the null/all ones constant when CC is false.
7705 // OtherOp is set to the alternative value of N.
7706 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7707 SDValue &CC, bool &Invert,
7709 SelectionDAG &DAG) {
7710 switch (N->getOpcode()) {
7711 default: return false;
7713 CC = N->getOperand(0);
7714 SDValue N1 = N->getOperand(1);
7715 SDValue N2 = N->getOperand(2);
7716 if (isZeroOrAllOnes(N1, AllOnes)) {
7721 if (isZeroOrAllOnes(N2, AllOnes)) {
7728 case ISD::ZERO_EXTEND:
7729 // (zext cc) can never be the all ones value.
7733 case ISD::SIGN_EXTEND: {
7734 EVT VT = N->getValueType(0);
7735 CC = N->getOperand(0);
7736 if (CC.getValueType() != MVT::i1)
7740 // When looking for an AllOnes constant, N is an sext, and the 'other'
7742 OtherOp = DAG.getConstant(0, VT);
7743 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7744 // When looking for a 0 constant, N can be zext or sext.
7745 OtherOp = DAG.getConstant(1, VT);
7747 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7753 // Combine a constant select operand into its use:
7755 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7756 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7757 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7758 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7759 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7761 // The transform is rejected if the select doesn't have a constant operand that
7762 // is null, or all ones when AllOnes is set.
7764 // Also recognize sext/zext from i1:
7766 // (add (zext cc), x) -> (select cc (add x, 1), x)
7767 // (add (sext cc), x) -> (select cc (add x, -1), x)
7769 // These transformations eventually create predicated instructions.
7771 // @param N The node to transform.
7772 // @param Slct The N operand that is a select.
7773 // @param OtherOp The other N operand (x above).
7774 // @param DCI Context.
7775 // @param AllOnes Require the select constant to be all ones instead of null.
7776 // @returns The new node, or SDValue() on failure.
7778 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7779 TargetLowering::DAGCombinerInfo &DCI,
7780 bool AllOnes = false) {
7781 SelectionDAG &DAG = DCI.DAG;
7782 EVT VT = N->getValueType(0);
7783 SDValue NonConstantVal;
7786 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7787 NonConstantVal, DAG))
7790 // Slct is now know to be the desired identity constant when CC is true.
7791 SDValue TrueVal = OtherOp;
7792 SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7793 OtherOp, NonConstantVal);
7794 // Unless SwapSelectOps says CC should be false.
7796 std::swap(TrueVal, FalseVal);
7798 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7799 CCOp, TrueVal, FalseVal);
7802 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7804 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7805 TargetLowering::DAGCombinerInfo &DCI) {
7806 SDValue N0 = N->getOperand(0);
7807 SDValue N1 = N->getOperand(1);
7808 if (N0.getNode()->hasOneUse()) {
7809 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7810 if (Result.getNode())
7813 if (N1.getNode()->hasOneUse()) {
7814 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7815 if (Result.getNode())
7821 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7822 // (only after legalization).
7823 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7824 TargetLowering::DAGCombinerInfo &DCI,
7825 const ARMSubtarget *Subtarget) {
7827 // Only perform optimization if after legalize, and if NEON is available. We
7828 // also expected both operands to be BUILD_VECTORs.
7829 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7830 || N0.getOpcode() != ISD::BUILD_VECTOR
7831 || N1.getOpcode() != ISD::BUILD_VECTOR)
7834 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7835 EVT VT = N->getValueType(0);
7836 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7839 // Check that the vector operands are of the right form.
7840 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7841 // operands, where N is the size of the formed vector.
7842 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7843 // index such that we have a pair wise add pattern.
7845 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7846 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7848 SDValue Vec = N0->getOperand(0)->getOperand(0);
7849 SDNode *V = Vec.getNode();
7850 unsigned nextIndex = 0;
7852 // For each operands to the ADD which are BUILD_VECTORs,
7853 // check to see if each of their operands are an EXTRACT_VECTOR with
7854 // the same vector and appropriate index.
7855 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7856 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7857 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7859 SDValue ExtVec0 = N0->getOperand(i);
7860 SDValue ExtVec1 = N1->getOperand(i);
7862 // First operand is the vector, verify its the same.
7863 if (V != ExtVec0->getOperand(0).getNode() ||
7864 V != ExtVec1->getOperand(0).getNode())
7867 // Second is the constant, verify its correct.
7868 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7869 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7871 // For the constant, we want to see all the even or all the odd.
7872 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7873 || C1->getZExtValue() != nextIndex+1)
7882 // Create VPADDL node.
7883 SelectionDAG &DAG = DCI.DAG;
7884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7886 // Build operand list.
7887 SmallVector<SDValue, 8> Ops;
7888 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7889 TLI.getPointerTy()));
7891 // Input is the vector.
7894 // Get widened type and narrowed type.
7896 unsigned numElem = VT.getVectorNumElements();
7897 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7898 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7899 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7900 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7902 llvm_unreachable("Invalid vector element type for padd optimization.");
7905 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7906 widenType, &Ops[0], Ops.size());
7907 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7910 static SDValue findMUL_LOHI(SDValue V) {
7911 if (V->getOpcode() == ISD::UMUL_LOHI ||
7912 V->getOpcode() == ISD::SMUL_LOHI)
7917 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7918 TargetLowering::DAGCombinerInfo &DCI,
7919 const ARMSubtarget *Subtarget) {
7921 if (Subtarget->isThumb1Only()) return SDValue();
7923 // Only perform the checks after legalize when the pattern is available.
7924 if (DCI.isBeforeLegalize()) return SDValue();
7926 // Look for multiply add opportunities.
7927 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7928 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7929 // a glue link from the first add to the second add.
7930 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7931 // a S/UMLAL instruction.
7934 // \ / \ [no multiline comment]
7940 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7941 SDValue AddcOp0 = AddcNode->getOperand(0);
7942 SDValue AddcOp1 = AddcNode->getOperand(1);
7944 // Check if the two operands are from the same mul_lohi node.
7945 if (AddcOp0.getNode() == AddcOp1.getNode())
7948 assert(AddcNode->getNumValues() == 2 &&
7949 AddcNode->getValueType(0) == MVT::i32 &&
7950 AddcNode->getValueType(1) == MVT::Glue &&
7951 "Expect ADDC with two result values: i32, glue");
7953 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7954 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7955 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7956 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7957 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7960 // Look for the glued ADDE.
7961 SDNode* AddeNode = AddcNode->getGluedUser();
7962 if (AddeNode == NULL)
7965 // Make sure it is really an ADDE.
7966 if (AddeNode->getOpcode() != ISD::ADDE)
7969 assert(AddeNode->getNumOperands() == 3 &&
7970 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7971 "ADDE node has the wrong inputs");
7973 // Check for the triangle shape.
7974 SDValue AddeOp0 = AddeNode->getOperand(0);
7975 SDValue AddeOp1 = AddeNode->getOperand(1);
7977 // Make sure that the ADDE operands are not coming from the same node.
7978 if (AddeOp0.getNode() == AddeOp1.getNode())
7981 // Find the MUL_LOHI node walking up ADDE's operands.
7982 bool IsLeftOperandMUL = false;
7983 SDValue MULOp = findMUL_LOHI(AddeOp0);
7984 if (MULOp == SDValue())
7985 MULOp = findMUL_LOHI(AddeOp1);
7987 IsLeftOperandMUL = true;
7988 if (MULOp == SDValue())
7991 // Figure out the right opcode.
7992 unsigned Opc = MULOp->getOpcode();
7993 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7995 // Figure out the high and low input values to the MLAL node.
7996 SDValue* HiMul = &MULOp;
7997 SDValue* HiAdd = NULL;
7998 SDValue* LoMul = NULL;
7999 SDValue* LowAdd = NULL;
8001 if (IsLeftOperandMUL)
8007 if (AddcOp0->getOpcode() == Opc) {
8011 if (AddcOp1->getOpcode() == Opc) {
8019 if (LoMul->getNode() != HiMul->getNode())
8022 // Create the merged node.
8023 SelectionDAG &DAG = DCI.DAG;
8025 // Build operand list.
8026 SmallVector<SDValue, 8> Ops;
8027 Ops.push_back(LoMul->getOperand(0));
8028 Ops.push_back(LoMul->getOperand(1));
8029 Ops.push_back(*LowAdd);
8030 Ops.push_back(*HiAdd);
8032 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
8033 DAG.getVTList(MVT::i32, MVT::i32),
8034 &Ops[0], Ops.size());
8036 // Replace the ADDs' nodes uses by the MLA node's values.
8037 SDValue HiMLALResult(MLALNode.getNode(), 1);
8038 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8040 SDValue LoMLALResult(MLALNode.getNode(), 0);
8041 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8043 // Return original node to notify the driver to stop replacing.
8044 SDValue resNode(AddcNode, 0);
8048 /// PerformADDCCombine - Target-specific dag combine transform from
8049 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8050 static SDValue PerformADDCCombine(SDNode *N,
8051 TargetLowering::DAGCombinerInfo &DCI,
8052 const ARMSubtarget *Subtarget) {
8054 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8058 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8059 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8060 /// called with the default operands, and if that fails, with commuted
8062 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8063 TargetLowering::DAGCombinerInfo &DCI,
8064 const ARMSubtarget *Subtarget){
8066 // Attempt to create vpaddl for this add.
8067 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8068 if (Result.getNode())
8071 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8072 if (N0.getNode()->hasOneUse()) {
8073 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8074 if (Result.getNode()) return Result;
8079 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8081 static SDValue PerformADDCombine(SDNode *N,
8082 TargetLowering::DAGCombinerInfo &DCI,
8083 const ARMSubtarget *Subtarget) {
8084 SDValue N0 = N->getOperand(0);
8085 SDValue N1 = N->getOperand(1);
8087 // First try with the default operand order.
8088 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8089 if (Result.getNode())
8092 // If that didn't work, try again with the operands commuted.
8093 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8096 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8098 static SDValue PerformSUBCombine(SDNode *N,
8099 TargetLowering::DAGCombinerInfo &DCI) {
8100 SDValue N0 = N->getOperand(0);
8101 SDValue N1 = N->getOperand(1);
8103 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8104 if (N1.getNode()->hasOneUse()) {
8105 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8106 if (Result.getNode()) return Result;
8112 /// PerformVMULCombine
8113 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8114 /// special multiplier accumulator forwarding.
8120 static SDValue PerformVMULCombine(SDNode *N,
8121 TargetLowering::DAGCombinerInfo &DCI,
8122 const ARMSubtarget *Subtarget) {
8123 if (!Subtarget->hasVMLxForwarding())
8126 SelectionDAG &DAG = DCI.DAG;
8127 SDValue N0 = N->getOperand(0);
8128 SDValue N1 = N->getOperand(1);
8129 unsigned Opcode = N0.getOpcode();
8130 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8131 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8132 Opcode = N1.getOpcode();
8133 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8134 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8139 EVT VT = N->getValueType(0);
8140 DebugLoc DL = N->getDebugLoc();
8141 SDValue N00 = N0->getOperand(0);
8142 SDValue N01 = N0->getOperand(1);
8143 return DAG.getNode(Opcode, DL, VT,
8144 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8145 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8148 static SDValue PerformMULCombine(SDNode *N,
8149 TargetLowering::DAGCombinerInfo &DCI,
8150 const ARMSubtarget *Subtarget) {
8151 SelectionDAG &DAG = DCI.DAG;
8153 if (Subtarget->isThumb1Only())
8156 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8159 EVT VT = N->getValueType(0);
8160 if (VT.is64BitVector() || VT.is128BitVector())
8161 return PerformVMULCombine(N, DCI, Subtarget);
8165 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8169 int64_t MulAmt = C->getSExtValue();
8170 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
8172 ShiftAmt = ShiftAmt & (32 - 1);
8173 SDValue V = N->getOperand(0);
8174 DebugLoc DL = N->getDebugLoc();
8177 MulAmt >>= ShiftAmt;
8180 if (isPowerOf2_32(MulAmt - 1)) {
8181 // (mul x, 2^N + 1) => (add (shl x, N), x)
8182 Res = DAG.getNode(ISD::ADD, DL, VT,
8184 DAG.getNode(ISD::SHL, DL, VT,
8186 DAG.getConstant(Log2_32(MulAmt - 1),
8188 } else if (isPowerOf2_32(MulAmt + 1)) {
8189 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8190 Res = DAG.getNode(ISD::SUB, DL, VT,
8191 DAG.getNode(ISD::SHL, DL, VT,
8193 DAG.getConstant(Log2_32(MulAmt + 1),
8199 uint64_t MulAmtAbs = -MulAmt;
8200 if (isPowerOf2_32(MulAmtAbs + 1)) {
8201 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8202 Res = DAG.getNode(ISD::SUB, DL, VT,
8204 DAG.getNode(ISD::SHL, DL, VT,
8206 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8208 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8209 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8210 Res = DAG.getNode(ISD::ADD, DL, VT,
8212 DAG.getNode(ISD::SHL, DL, VT,
8214 DAG.getConstant(Log2_32(MulAmtAbs-1),
8216 Res = DAG.getNode(ISD::SUB, DL, VT,
8217 DAG.getConstant(0, MVT::i32),Res);
8224 Res = DAG.getNode(ISD::SHL, DL, VT,
8225 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8227 // Do not add new nodes to DAG combiner worklist.
8228 DCI.CombineTo(N, Res, false);
8232 static SDValue PerformANDCombine(SDNode *N,
8233 TargetLowering::DAGCombinerInfo &DCI,
8234 const ARMSubtarget *Subtarget) {
8236 // Attempt to use immediate-form VBIC
8237 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8238 DebugLoc dl = N->getDebugLoc();
8239 EVT VT = N->getValueType(0);
8240 SelectionDAG &DAG = DCI.DAG;
8242 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8245 APInt SplatBits, SplatUndef;
8246 unsigned SplatBitSize;
8249 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8250 if (SplatBitSize <= 64) {
8252 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8253 SplatUndef.getZExtValue(), SplatBitSize,
8254 DAG, VbicVT, VT.is128BitVector(),
8256 if (Val.getNode()) {
8258 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8259 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8260 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8265 if (!Subtarget->isThumb1Only()) {
8266 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8267 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8268 if (Result.getNode())
8275 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8276 static SDValue PerformORCombine(SDNode *N,
8277 TargetLowering::DAGCombinerInfo &DCI,
8278 const ARMSubtarget *Subtarget) {
8279 // Attempt to use immediate-form VORR
8280 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8281 DebugLoc dl = N->getDebugLoc();
8282 EVT VT = N->getValueType(0);
8283 SelectionDAG &DAG = DCI.DAG;
8285 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8288 APInt SplatBits, SplatUndef;
8289 unsigned SplatBitSize;
8291 if (BVN && Subtarget->hasNEON() &&
8292 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8293 if (SplatBitSize <= 64) {
8295 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8296 SplatUndef.getZExtValue(), SplatBitSize,
8297 DAG, VorrVT, VT.is128BitVector(),
8299 if (Val.getNode()) {
8301 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8302 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8303 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8308 if (!Subtarget->isThumb1Only()) {
8309 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8310 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8311 if (Result.getNode())
8315 // The code below optimizes (or (and X, Y), Z).
8316 // The AND operand needs to have a single user to make these optimizations
8318 SDValue N0 = N->getOperand(0);
8319 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8321 SDValue N1 = N->getOperand(1);
8323 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8324 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8325 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8327 unsigned SplatBitSize;
8330 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8332 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8333 HasAnyUndefs) && !HasAnyUndefs) {
8334 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8336 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8337 HasAnyUndefs) && !HasAnyUndefs &&
8338 SplatBits0 == ~SplatBits1) {
8339 // Canonicalize the vector type to make instruction selection simpler.
8340 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8341 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8342 N0->getOperand(1), N0->getOperand(0),
8344 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8349 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8352 // BFI is only available on V6T2+
8353 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8356 DebugLoc DL = N->getDebugLoc();
8357 // 1) or (and A, mask), val => ARMbfi A, val, mask
8358 // iff (val & mask) == val
8360 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8361 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8362 // && mask == ~mask2
8363 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8364 // && ~mask == mask2
8365 // (i.e., copy a bitfield value into another bitfield of the same width)
8370 SDValue N00 = N0.getOperand(0);
8372 // The value and the mask need to be constants so we can verify this is
8373 // actually a bitfield set. If the mask is 0xffff, we can do better
8374 // via a movt instruction, so don't use BFI in that case.
8375 SDValue MaskOp = N0.getOperand(1);
8376 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8379 unsigned Mask = MaskC->getZExtValue();
8383 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8384 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8386 unsigned Val = N1C->getZExtValue();
8387 if ((Val & ~Mask) != Val)
8390 if (ARM::isBitFieldInvertedMask(Mask)) {
8391 Val >>= CountTrailingZeros_32(~Mask);
8393 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8394 DAG.getConstant(Val, MVT::i32),
8395 DAG.getConstant(Mask, MVT::i32));
8397 // Do not add new nodes to DAG combiner worklist.
8398 DCI.CombineTo(N, Res, false);
8401 } else if (N1.getOpcode() == ISD::AND) {
8402 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8403 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8406 unsigned Mask2 = N11C->getZExtValue();
8408 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8410 if (ARM::isBitFieldInvertedMask(Mask) &&
8412 // The pack halfword instruction works better for masks that fit it,
8413 // so use that when it's available.
8414 if (Subtarget->hasT2ExtractPack() &&
8415 (Mask == 0xffff || Mask == 0xffff0000))
8418 unsigned amt = CountTrailingZeros_32(Mask2);
8419 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8420 DAG.getConstant(amt, MVT::i32));
8421 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8422 DAG.getConstant(Mask, MVT::i32));
8423 // Do not add new nodes to DAG combiner worklist.
8424 DCI.CombineTo(N, Res, false);
8426 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8428 // The pack halfword instruction works better for masks that fit it,
8429 // so use that when it's available.
8430 if (Subtarget->hasT2ExtractPack() &&
8431 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8434 unsigned lsb = CountTrailingZeros_32(Mask);
8435 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8436 DAG.getConstant(lsb, MVT::i32));
8437 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8438 DAG.getConstant(Mask2, MVT::i32));
8439 // Do not add new nodes to DAG combiner worklist.
8440 DCI.CombineTo(N, Res, false);
8445 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8446 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8447 ARM::isBitFieldInvertedMask(~Mask)) {
8448 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8449 // where lsb(mask) == #shamt and masked bits of B are known zero.
8450 SDValue ShAmt = N00.getOperand(1);
8451 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8452 unsigned LSB = CountTrailingZeros_32(Mask);
8456 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8457 DAG.getConstant(~Mask, MVT::i32));
8459 // Do not add new nodes to DAG combiner worklist.
8460 DCI.CombineTo(N, Res, false);
8466 static SDValue PerformXORCombine(SDNode *N,
8467 TargetLowering::DAGCombinerInfo &DCI,
8468 const ARMSubtarget *Subtarget) {
8469 EVT VT = N->getValueType(0);
8470 SelectionDAG &DAG = DCI.DAG;
8472 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8475 if (!Subtarget->isThumb1Only()) {
8476 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8477 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8478 if (Result.getNode())
8485 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8486 /// the bits being cleared by the AND are not demanded by the BFI.
8487 static SDValue PerformBFICombine(SDNode *N,
8488 TargetLowering::DAGCombinerInfo &DCI) {
8489 SDValue N1 = N->getOperand(1);
8490 if (N1.getOpcode() == ISD::AND) {
8491 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8494 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8495 unsigned LSB = CountTrailingZeros_32(~InvMask);
8496 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8497 unsigned Mask = (1 << Width)-1;
8498 unsigned Mask2 = N11C->getZExtValue();
8499 if ((Mask & (~Mask2)) == 0)
8500 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8501 N->getOperand(0), N1.getOperand(0),
8507 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8508 /// ARMISD::VMOVRRD.
8509 static SDValue PerformVMOVRRDCombine(SDNode *N,
8510 TargetLowering::DAGCombinerInfo &DCI) {
8511 // vmovrrd(vmovdrr x, y) -> x,y
8512 SDValue InDouble = N->getOperand(0);
8513 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8514 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8516 // vmovrrd(load f64) -> (load i32), (load i32)
8517 SDNode *InNode = InDouble.getNode();
8518 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8519 InNode->getValueType(0) == MVT::f64 &&
8520 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8521 !cast<LoadSDNode>(InNode)->isVolatile()) {
8522 // TODO: Should this be done for non-FrameIndex operands?
8523 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8525 SelectionDAG &DAG = DCI.DAG;
8526 DebugLoc DL = LD->getDebugLoc();
8527 SDValue BasePtr = LD->getBasePtr();
8528 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8529 LD->getPointerInfo(), LD->isVolatile(),
8530 LD->isNonTemporal(), LD->isInvariant(),
8531 LD->getAlignment());
8533 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8534 DAG.getConstant(4, MVT::i32));
8535 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8536 LD->getPointerInfo(), LD->isVolatile(),
8537 LD->isNonTemporal(), LD->isInvariant(),
8538 std::min(4U, LD->getAlignment() / 2));
8540 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8541 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8542 DCI.RemoveFromWorklist(LD);
8550 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8551 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8552 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8553 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8554 SDValue Op0 = N->getOperand(0);
8555 SDValue Op1 = N->getOperand(1);
8556 if (Op0.getOpcode() == ISD::BITCAST)
8557 Op0 = Op0.getOperand(0);
8558 if (Op1.getOpcode() == ISD::BITCAST)
8559 Op1 = Op1.getOperand(0);
8560 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8561 Op0.getNode() == Op1.getNode() &&
8562 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8563 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8564 N->getValueType(0), Op0.getOperand(0));
8568 /// PerformSTORECombine - Target-specific dag combine xforms for
8570 static SDValue PerformSTORECombine(SDNode *N,
8571 TargetLowering::DAGCombinerInfo &DCI) {
8572 StoreSDNode *St = cast<StoreSDNode>(N);
8573 if (St->isVolatile())
8576 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8577 // pack all of the elements in one place. Next, store to memory in fewer
8579 SDValue StVal = St->getValue();
8580 EVT VT = StVal.getValueType();
8581 if (St->isTruncatingStore() && VT.isVector()) {
8582 SelectionDAG &DAG = DCI.DAG;
8583 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8584 EVT StVT = St->getMemoryVT();
8585 unsigned NumElems = VT.getVectorNumElements();
8586 assert(StVT != VT && "Cannot truncate to the same type");
8587 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8588 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8590 // From, To sizes and ElemCount must be pow of two
8591 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8593 // We are going to use the original vector elt for storing.
8594 // Accumulated smaller vector elements must be a multiple of the store size.
8595 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8597 unsigned SizeRatio = FromEltSz / ToEltSz;
8598 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8600 // Create a type on which we perform the shuffle.
8601 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8602 NumElems*SizeRatio);
8603 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8605 DebugLoc DL = St->getDebugLoc();
8606 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8607 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8608 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8610 // Can't shuffle using an illegal type.
8611 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8613 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8614 DAG.getUNDEF(WideVec.getValueType()),
8616 // At this point all of the data is stored at the bottom of the
8617 // register. We now need to save it to mem.
8619 // Find the largest store unit
8620 MVT StoreType = MVT::i8;
8621 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8622 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8623 MVT Tp = (MVT::SimpleValueType)tp;
8624 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8627 // Didn't find a legal store type.
8628 if (!TLI.isTypeLegal(StoreType))
8631 // Bitcast the original vector into a vector of store-size units
8632 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8633 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8634 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8635 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8636 SmallVector<SDValue, 8> Chains;
8637 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8638 TLI.getPointerTy());
8639 SDValue BasePtr = St->getBasePtr();
8641 // Perform one or more big stores into memory.
8642 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8643 for (unsigned I = 0; I < E; I++) {
8644 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8645 StoreType, ShuffWide,
8646 DAG.getIntPtrConstant(I));
8647 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8648 St->getPointerInfo(), St->isVolatile(),
8649 St->isNonTemporal(), St->getAlignment());
8650 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8652 Chains.push_back(Ch);
8654 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8658 if (!ISD::isNormalStore(St))
8661 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8662 // ARM stores of arguments in the same cache line.
8663 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8664 StVal.getNode()->hasOneUse()) {
8665 SelectionDAG &DAG = DCI.DAG;
8666 DebugLoc DL = St->getDebugLoc();
8667 SDValue BasePtr = St->getBasePtr();
8668 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8669 StVal.getNode()->getOperand(0), BasePtr,
8670 St->getPointerInfo(), St->isVolatile(),
8671 St->isNonTemporal(), St->getAlignment());
8673 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8674 DAG.getConstant(4, MVT::i32));
8675 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8676 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8677 St->isNonTemporal(),
8678 std::min(4U, St->getAlignment() / 2));
8681 if (StVal.getValueType() != MVT::i64 ||
8682 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8685 // Bitcast an i64 store extracted from a vector to f64.
8686 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8687 SelectionDAG &DAG = DCI.DAG;
8688 DebugLoc dl = StVal.getDebugLoc();
8689 SDValue IntVec = StVal.getOperand(0);
8690 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8691 IntVec.getValueType().getVectorNumElements());
8692 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8693 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8694 Vec, StVal.getOperand(1));
8695 dl = N->getDebugLoc();
8696 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8697 // Make the DAGCombiner fold the bitcasts.
8698 DCI.AddToWorklist(Vec.getNode());
8699 DCI.AddToWorklist(ExtElt.getNode());
8700 DCI.AddToWorklist(V.getNode());
8701 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8702 St->getPointerInfo(), St->isVolatile(),
8703 St->isNonTemporal(), St->getAlignment(),
8707 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8708 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8709 /// i64 vector to have f64 elements, since the value can then be loaded
8710 /// directly into a VFP register.
8711 static bool hasNormalLoadOperand(SDNode *N) {
8712 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8713 for (unsigned i = 0; i < NumElts; ++i) {
8714 SDNode *Elt = N->getOperand(i).getNode();
8715 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8721 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8722 /// ISD::BUILD_VECTOR.
8723 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8724 TargetLowering::DAGCombinerInfo &DCI){
8725 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8726 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8727 // into a pair of GPRs, which is fine when the value is used as a scalar,
8728 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8729 SelectionDAG &DAG = DCI.DAG;
8730 if (N->getNumOperands() == 2) {
8731 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8736 // Load i64 elements as f64 values so that type legalization does not split
8737 // them up into i32 values.
8738 EVT VT = N->getValueType(0);
8739 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8741 DebugLoc dl = N->getDebugLoc();
8742 SmallVector<SDValue, 8> Ops;
8743 unsigned NumElts = VT.getVectorNumElements();
8744 for (unsigned i = 0; i < NumElts; ++i) {
8745 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8747 // Make the DAGCombiner fold the bitcast.
8748 DCI.AddToWorklist(V.getNode());
8750 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8751 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8752 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8755 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8756 /// ISD::INSERT_VECTOR_ELT.
8757 static SDValue PerformInsertEltCombine(SDNode *N,
8758 TargetLowering::DAGCombinerInfo &DCI) {
8759 // Bitcast an i64 load inserted into a vector to f64.
8760 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8761 EVT VT = N->getValueType(0);
8762 SDNode *Elt = N->getOperand(1).getNode();
8763 if (VT.getVectorElementType() != MVT::i64 ||
8764 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8767 SelectionDAG &DAG = DCI.DAG;
8768 DebugLoc dl = N->getDebugLoc();
8769 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8770 VT.getVectorNumElements());
8771 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8772 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8773 // Make the DAGCombiner fold the bitcasts.
8774 DCI.AddToWorklist(Vec.getNode());
8775 DCI.AddToWorklist(V.getNode());
8776 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8777 Vec, V, N->getOperand(2));
8778 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8781 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8782 /// ISD::VECTOR_SHUFFLE.
8783 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8784 // The LLVM shufflevector instruction does not require the shuffle mask
8785 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8786 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8787 // operands do not match the mask length, they are extended by concatenating
8788 // them with undef vectors. That is probably the right thing for other
8789 // targets, but for NEON it is better to concatenate two double-register
8790 // size vector operands into a single quad-register size vector. Do that
8791 // transformation here:
8792 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8793 // shuffle(concat(v1, v2), undef)
8794 SDValue Op0 = N->getOperand(0);
8795 SDValue Op1 = N->getOperand(1);
8796 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8797 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8798 Op0.getNumOperands() != 2 ||
8799 Op1.getNumOperands() != 2)
8801 SDValue Concat0Op1 = Op0.getOperand(1);
8802 SDValue Concat1Op1 = Op1.getOperand(1);
8803 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8804 Concat1Op1.getOpcode() != ISD::UNDEF)
8806 // Skip the transformation if any of the types are illegal.
8807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8808 EVT VT = N->getValueType(0);
8809 if (!TLI.isTypeLegal(VT) ||
8810 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8811 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8814 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8815 Op0.getOperand(0), Op1.getOperand(0));
8816 // Translate the shuffle mask.
8817 SmallVector<int, 16> NewMask;
8818 unsigned NumElts = VT.getVectorNumElements();
8819 unsigned HalfElts = NumElts/2;
8820 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8821 for (unsigned n = 0; n < NumElts; ++n) {
8822 int MaskElt = SVN->getMaskElt(n);
8824 if (MaskElt < (int)HalfElts)
8826 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8827 NewElt = HalfElts + MaskElt - NumElts;
8828 NewMask.push_back(NewElt);
8830 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8831 DAG.getUNDEF(VT), NewMask.data());
8834 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8835 /// NEON load/store intrinsics to merge base address updates.
8836 static SDValue CombineBaseUpdate(SDNode *N,
8837 TargetLowering::DAGCombinerInfo &DCI) {
8838 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8841 SelectionDAG &DAG = DCI.DAG;
8842 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8843 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8844 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8845 SDValue Addr = N->getOperand(AddrOpIdx);
8847 // Search for a use of the address operand that is an increment.
8848 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8849 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8851 if (User->getOpcode() != ISD::ADD ||
8852 UI.getUse().getResNo() != Addr.getResNo())
8855 // Check that the add is independent of the load/store. Otherwise, folding
8856 // it would create a cycle.
8857 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8860 // Find the new opcode for the updating load/store.
8862 bool isLaneOp = false;
8863 unsigned NewOpc = 0;
8864 unsigned NumVecs = 0;
8866 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8868 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8869 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8871 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8873 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8875 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8877 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8878 NumVecs = 2; isLaneOp = true; break;
8879 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8880 NumVecs = 3; isLaneOp = true; break;
8881 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8882 NumVecs = 4; isLaneOp = true; break;
8883 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8884 NumVecs = 1; isLoad = false; break;
8885 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8886 NumVecs = 2; isLoad = false; break;
8887 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8888 NumVecs = 3; isLoad = false; break;
8889 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8890 NumVecs = 4; isLoad = false; break;
8891 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8892 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8893 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8894 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8895 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8896 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8900 switch (N->getOpcode()) {
8901 default: llvm_unreachable("unexpected opcode for Neon base update");
8902 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8903 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8904 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8908 // Find the size of memory referenced by the load/store.
8911 VecTy = N->getValueType(0);
8913 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8914 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8916 NumBytes /= VecTy.getVectorNumElements();
8918 // If the increment is a constant, it must match the memory ref size.
8919 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8920 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8921 uint64_t IncVal = CInc->getZExtValue();
8922 if (IncVal != NumBytes)
8924 } else if (NumBytes >= 3 * 16) {
8925 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8926 // separate instructions that make it harder to use a non-constant update.
8930 // Create the new updating load/store node.
8932 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8934 for (n = 0; n < NumResultVecs; ++n)
8936 Tys[n++] = MVT::i32;
8937 Tys[n] = MVT::Other;
8938 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8939 SmallVector<SDValue, 8> Ops;
8940 Ops.push_back(N->getOperand(0)); // incoming chain
8941 Ops.push_back(N->getOperand(AddrOpIdx));
8943 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8944 Ops.push_back(N->getOperand(i));
8946 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8947 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8948 Ops.data(), Ops.size(),
8949 MemInt->getMemoryVT(),
8950 MemInt->getMemOperand());
8953 std::vector<SDValue> NewResults;
8954 for (unsigned i = 0; i < NumResultVecs; ++i) {
8955 NewResults.push_back(SDValue(UpdN.getNode(), i));
8957 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8958 DCI.CombineTo(N, NewResults);
8959 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8966 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8967 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8968 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8970 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8971 SelectionDAG &DAG = DCI.DAG;
8972 EVT VT = N->getValueType(0);
8973 // vldN-dup instructions only support 64-bit vectors for N > 1.
8974 if (!VT.is64BitVector())
8977 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8978 SDNode *VLD = N->getOperand(0).getNode();
8979 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8981 unsigned NumVecs = 0;
8982 unsigned NewOpc = 0;
8983 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8984 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8986 NewOpc = ARMISD::VLD2DUP;
8987 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8989 NewOpc = ARMISD::VLD3DUP;
8990 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8992 NewOpc = ARMISD::VLD4DUP;
8997 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8998 // numbers match the load.
8999 unsigned VLDLaneNo =
9000 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9001 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9003 // Ignore uses of the chain result.
9004 if (UI.getUse().getResNo() == NumVecs)
9007 if (User->getOpcode() != ARMISD::VDUPLANE ||
9008 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9012 // Create the vldN-dup node.
9015 for (n = 0; n < NumVecs; ++n)
9017 Tys[n] = MVT::Other;
9018 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9019 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9020 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9021 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
9022 Ops, 2, VLDMemInt->getMemoryVT(),
9023 VLDMemInt->getMemOperand());
9026 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9028 unsigned ResNo = UI.getUse().getResNo();
9029 // Ignore uses of the chain result.
9030 if (ResNo == NumVecs)
9033 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9036 // Now the vldN-lane intrinsic is dead except for its chain result.
9037 // Update uses of the chain.
9038 std::vector<SDValue> VLDDupResults;
9039 for (unsigned n = 0; n < NumVecs; ++n)
9040 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9041 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9042 DCI.CombineTo(VLD, VLDDupResults);
9047 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9048 /// ARMISD::VDUPLANE.
9049 static SDValue PerformVDUPLANECombine(SDNode *N,
9050 TargetLowering::DAGCombinerInfo &DCI) {
9051 SDValue Op = N->getOperand(0);
9053 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9054 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9055 if (CombineVLDDUP(N, DCI))
9056 return SDValue(N, 0);
9058 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9059 // redundant. Ignore bit_converts for now; element sizes are checked below.
9060 while (Op.getOpcode() == ISD::BITCAST)
9061 Op = Op.getOperand(0);
9062 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9065 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9066 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9067 // The canonical VMOV for a zero vector uses a 32-bit element size.
9068 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9070 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9072 EVT VT = N->getValueType(0);
9073 if (EltSize > VT.getVectorElementType().getSizeInBits())
9076 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
9079 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9080 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9081 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9085 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9087 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9092 APFloat APF = C->getValueAPF();
9093 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9094 != APFloat::opOK || !isExact)
9097 c0 = (I == 0) ? cN : c0;
9098 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9105 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9106 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9107 /// when the VMUL has a constant operand that is a power of 2.
9109 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9110 /// vmul.f32 d16, d17, d16
9111 /// vcvt.s32.f32 d16, d16
9113 /// vcvt.s32.f32 d16, d16, #3
9114 static SDValue PerformVCVTCombine(SDNode *N,
9115 TargetLowering::DAGCombinerInfo &DCI,
9116 const ARMSubtarget *Subtarget) {
9117 SelectionDAG &DAG = DCI.DAG;
9118 SDValue Op = N->getOperand(0);
9120 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9121 Op.getOpcode() != ISD::FMUL)
9125 SDValue N0 = Op->getOperand(0);
9126 SDValue ConstVec = Op->getOperand(1);
9127 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9129 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9130 !isConstVecPow2(ConstVec, isSigned, C))
9133 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9134 Intrinsic::arm_neon_vcvtfp2fxu;
9135 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9137 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9138 DAG.getConstant(Log2_64(C), MVT::i32));
9141 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9142 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9143 /// when the VDIV has a constant operand that is a power of 2.
9145 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9146 /// vcvt.f32.s32 d16, d16
9147 /// vdiv.f32 d16, d17, d16
9149 /// vcvt.f32.s32 d16, d16, #3
9150 static SDValue PerformVDIVCombine(SDNode *N,
9151 TargetLowering::DAGCombinerInfo &DCI,
9152 const ARMSubtarget *Subtarget) {
9153 SelectionDAG &DAG = DCI.DAG;
9154 SDValue Op = N->getOperand(0);
9155 unsigned OpOpcode = Op.getNode()->getOpcode();
9157 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9158 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9162 SDValue ConstVec = N->getOperand(1);
9163 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9165 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9166 !isConstVecPow2(ConstVec, isSigned, C))
9169 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9170 Intrinsic::arm_neon_vcvtfxu2fp;
9171 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9173 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9174 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
9177 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9178 /// operand of a vector shift operation, where all the elements of the
9179 /// build_vector must have the same constant integer value.
9180 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9181 // Ignore bit_converts.
9182 while (Op.getOpcode() == ISD::BITCAST)
9183 Op = Op.getOperand(0);
9184 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9185 APInt SplatBits, SplatUndef;
9186 unsigned SplatBitSize;
9188 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9189 HasAnyUndefs, ElementBits) ||
9190 SplatBitSize > ElementBits)
9192 Cnt = SplatBits.getSExtValue();
9196 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9197 /// operand of a vector shift left operation. That value must be in the range:
9198 /// 0 <= Value < ElementBits for a left shift; or
9199 /// 0 <= Value <= ElementBits for a long left shift.
9200 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9201 assert(VT.isVector() && "vector shift count is not a vector type");
9202 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9203 if (! getVShiftImm(Op, ElementBits, Cnt))
9205 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9208 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9209 /// operand of a vector shift right operation. For a shift opcode, the value
9210 /// is positive, but for an intrinsic the value count must be negative. The
9211 /// absolute value must be in the range:
9212 /// 1 <= |Value| <= ElementBits for a right shift; or
9213 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9214 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9216 assert(VT.isVector() && "vector shift count is not a vector type");
9217 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9218 if (! getVShiftImm(Op, ElementBits, Cnt))
9222 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9225 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9226 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9227 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9230 // Don't do anything for most intrinsics.
9233 // Vector shifts: check for immediate versions and lower them.
9234 // Note: This is done during DAG combining instead of DAG legalizing because
9235 // the build_vectors for 64-bit vector element shift counts are generally
9236 // not legal, and it is hard to see their values after they get legalized to
9237 // loads from a constant pool.
9238 case Intrinsic::arm_neon_vshifts:
9239 case Intrinsic::arm_neon_vshiftu:
9240 case Intrinsic::arm_neon_vshiftls:
9241 case Intrinsic::arm_neon_vshiftlu:
9242 case Intrinsic::arm_neon_vshiftn:
9243 case Intrinsic::arm_neon_vrshifts:
9244 case Intrinsic::arm_neon_vrshiftu:
9245 case Intrinsic::arm_neon_vrshiftn:
9246 case Intrinsic::arm_neon_vqshifts:
9247 case Intrinsic::arm_neon_vqshiftu:
9248 case Intrinsic::arm_neon_vqshiftsu:
9249 case Intrinsic::arm_neon_vqshiftns:
9250 case Intrinsic::arm_neon_vqshiftnu:
9251 case Intrinsic::arm_neon_vqshiftnsu:
9252 case Intrinsic::arm_neon_vqrshiftns:
9253 case Intrinsic::arm_neon_vqrshiftnu:
9254 case Intrinsic::arm_neon_vqrshiftnsu: {
9255 EVT VT = N->getOperand(1).getValueType();
9257 unsigned VShiftOpc = 0;
9260 case Intrinsic::arm_neon_vshifts:
9261 case Intrinsic::arm_neon_vshiftu:
9262 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9263 VShiftOpc = ARMISD::VSHL;
9266 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9267 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9268 ARMISD::VSHRs : ARMISD::VSHRu);
9273 case Intrinsic::arm_neon_vshiftls:
9274 case Intrinsic::arm_neon_vshiftlu:
9275 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9277 llvm_unreachable("invalid shift count for vshll intrinsic");
9279 case Intrinsic::arm_neon_vrshifts:
9280 case Intrinsic::arm_neon_vrshiftu:
9281 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9285 case Intrinsic::arm_neon_vqshifts:
9286 case Intrinsic::arm_neon_vqshiftu:
9287 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9291 case Intrinsic::arm_neon_vqshiftsu:
9292 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9294 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9296 case Intrinsic::arm_neon_vshiftn:
9297 case Intrinsic::arm_neon_vrshiftn:
9298 case Intrinsic::arm_neon_vqshiftns:
9299 case Intrinsic::arm_neon_vqshiftnu:
9300 case Intrinsic::arm_neon_vqshiftnsu:
9301 case Intrinsic::arm_neon_vqrshiftns:
9302 case Intrinsic::arm_neon_vqrshiftnu:
9303 case Intrinsic::arm_neon_vqrshiftnsu:
9304 // Narrowing shifts require an immediate right shift.
9305 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9307 llvm_unreachable("invalid shift count for narrowing vector shift "
9311 llvm_unreachable("unhandled vector shift");
9315 case Intrinsic::arm_neon_vshifts:
9316 case Intrinsic::arm_neon_vshiftu:
9317 // Opcode already set above.
9319 case Intrinsic::arm_neon_vshiftls:
9320 case Intrinsic::arm_neon_vshiftlu:
9321 if (Cnt == VT.getVectorElementType().getSizeInBits())
9322 VShiftOpc = ARMISD::VSHLLi;
9324 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9325 ARMISD::VSHLLs : ARMISD::VSHLLu);
9327 case Intrinsic::arm_neon_vshiftn:
9328 VShiftOpc = ARMISD::VSHRN; break;
9329 case Intrinsic::arm_neon_vrshifts:
9330 VShiftOpc = ARMISD::VRSHRs; break;
9331 case Intrinsic::arm_neon_vrshiftu:
9332 VShiftOpc = ARMISD::VRSHRu; break;
9333 case Intrinsic::arm_neon_vrshiftn:
9334 VShiftOpc = ARMISD::VRSHRN; break;
9335 case Intrinsic::arm_neon_vqshifts:
9336 VShiftOpc = ARMISD::VQSHLs; break;
9337 case Intrinsic::arm_neon_vqshiftu:
9338 VShiftOpc = ARMISD::VQSHLu; break;
9339 case Intrinsic::arm_neon_vqshiftsu:
9340 VShiftOpc = ARMISD::VQSHLsu; break;
9341 case Intrinsic::arm_neon_vqshiftns:
9342 VShiftOpc = ARMISD::VQSHRNs; break;
9343 case Intrinsic::arm_neon_vqshiftnu:
9344 VShiftOpc = ARMISD::VQSHRNu; break;
9345 case Intrinsic::arm_neon_vqshiftnsu:
9346 VShiftOpc = ARMISD::VQSHRNsu; break;
9347 case Intrinsic::arm_neon_vqrshiftns:
9348 VShiftOpc = ARMISD::VQRSHRNs; break;
9349 case Intrinsic::arm_neon_vqrshiftnu:
9350 VShiftOpc = ARMISD::VQRSHRNu; break;
9351 case Intrinsic::arm_neon_vqrshiftnsu:
9352 VShiftOpc = ARMISD::VQRSHRNsu; break;
9355 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9356 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9359 case Intrinsic::arm_neon_vshiftins: {
9360 EVT VT = N->getOperand(1).getValueType();
9362 unsigned VShiftOpc = 0;
9364 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9365 VShiftOpc = ARMISD::VSLI;
9366 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9367 VShiftOpc = ARMISD::VSRI;
9369 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9372 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9373 N->getOperand(1), N->getOperand(2),
9374 DAG.getConstant(Cnt, MVT::i32));
9377 case Intrinsic::arm_neon_vqrshifts:
9378 case Intrinsic::arm_neon_vqrshiftu:
9379 // No immediate versions of these to check for.
9386 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9387 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9388 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9389 /// vector element shift counts are generally not legal, and it is hard to see
9390 /// their values after they get legalized to loads from a constant pool.
9391 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9392 const ARMSubtarget *ST) {
9393 EVT VT = N->getValueType(0);
9394 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9395 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9396 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9397 SDValue N1 = N->getOperand(1);
9398 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9399 SDValue N0 = N->getOperand(0);
9400 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9401 DAG.MaskedValueIsZero(N0.getOperand(0),
9402 APInt::getHighBitsSet(32, 16)))
9403 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9407 // Nothing to be done for scalar shifts.
9408 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9409 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9412 assert(ST->hasNEON() && "unexpected vector shift");
9415 switch (N->getOpcode()) {
9416 default: llvm_unreachable("unexpected shift opcode");
9419 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9420 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9421 DAG.getConstant(Cnt, MVT::i32));
9426 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9427 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9428 ARMISD::VSHRs : ARMISD::VSHRu);
9429 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9430 DAG.getConstant(Cnt, MVT::i32));
9436 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9437 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9438 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9439 const ARMSubtarget *ST) {
9440 SDValue N0 = N->getOperand(0);
9442 // Check for sign- and zero-extensions of vector extract operations of 8-
9443 // and 16-bit vector elements. NEON supports these directly. They are
9444 // handled during DAG combining because type legalization will promote them
9445 // to 32-bit types and it is messy to recognize the operations after that.
9446 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9447 SDValue Vec = N0.getOperand(0);
9448 SDValue Lane = N0.getOperand(1);
9449 EVT VT = N->getValueType(0);
9450 EVT EltVT = N0.getValueType();
9451 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9453 if (VT == MVT::i32 &&
9454 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9455 TLI.isTypeLegal(Vec.getValueType()) &&
9456 isa<ConstantSDNode>(Lane)) {
9459 switch (N->getOpcode()) {
9460 default: llvm_unreachable("unexpected opcode");
9461 case ISD::SIGN_EXTEND:
9462 Opc = ARMISD::VGETLANEs;
9464 case ISD::ZERO_EXTEND:
9465 case ISD::ANY_EXTEND:
9466 Opc = ARMISD::VGETLANEu;
9469 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9476 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9477 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9478 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9479 const ARMSubtarget *ST) {
9480 // If the target supports NEON, try to use vmax/vmin instructions for f32
9481 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9482 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9483 // a NaN; only do the transformation when it matches that behavior.
9485 // For now only do this when using NEON for FP operations; if using VFP, it
9486 // is not obvious that the benefit outweighs the cost of switching to the
9488 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9489 N->getValueType(0) != MVT::f32)
9492 SDValue CondLHS = N->getOperand(0);
9493 SDValue CondRHS = N->getOperand(1);
9494 SDValue LHS = N->getOperand(2);
9495 SDValue RHS = N->getOperand(3);
9496 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9498 unsigned Opcode = 0;
9500 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9501 IsReversed = false; // x CC y ? x : y
9502 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9503 IsReversed = true ; // x CC y ? y : x
9517 // If LHS is NaN, an ordered comparison will be false and the result will
9518 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9519 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9520 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9521 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9523 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9524 // will return -0, so vmin can only be used for unsafe math or if one of
9525 // the operands is known to be nonzero.
9526 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9527 !DAG.getTarget().Options.UnsafeFPMath &&
9528 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9530 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9539 // If LHS is NaN, an ordered comparison will be false and the result will
9540 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9541 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9542 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9543 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9545 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9546 // will return +0, so vmax can only be used for unsafe math or if one of
9547 // the operands is known to be nonzero.
9548 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9549 !DAG.getTarget().Options.UnsafeFPMath &&
9550 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9552 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9558 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9561 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9563 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9564 SDValue Cmp = N->getOperand(4);
9565 if (Cmp.getOpcode() != ARMISD::CMPZ)
9566 // Only looking at EQ and NE cases.
9569 EVT VT = N->getValueType(0);
9570 DebugLoc dl = N->getDebugLoc();
9571 SDValue LHS = Cmp.getOperand(0);
9572 SDValue RHS = Cmp.getOperand(1);
9573 SDValue FalseVal = N->getOperand(0);
9574 SDValue TrueVal = N->getOperand(1);
9575 SDValue ARMcc = N->getOperand(2);
9576 ARMCC::CondCodes CC =
9577 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9595 /// FIXME: Turn this into a target neutral optimization?
9597 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9598 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9599 N->getOperand(3), Cmp);
9600 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9602 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9603 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9604 N->getOperand(3), NewCmp);
9607 if (Res.getNode()) {
9608 APInt KnownZero, KnownOne;
9609 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9610 // Capture demanded bits information that would be otherwise lost.
9611 if (KnownZero == 0xfffffffe)
9612 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9613 DAG.getValueType(MVT::i1));
9614 else if (KnownZero == 0xffffff00)
9615 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9616 DAG.getValueType(MVT::i8));
9617 else if (KnownZero == 0xffff0000)
9618 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9619 DAG.getValueType(MVT::i16));
9625 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9626 DAGCombinerInfo &DCI) const {
9627 switch (N->getOpcode()) {
9629 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9630 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9631 case ISD::SUB: return PerformSUBCombine(N, DCI);
9632 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9633 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9634 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9635 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9636 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9637 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9638 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9639 case ISD::STORE: return PerformSTORECombine(N, DCI);
9640 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9641 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9642 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9643 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9644 case ISD::FP_TO_SINT:
9645 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9646 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9647 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9650 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9651 case ISD::SIGN_EXTEND:
9652 case ISD::ZERO_EXTEND:
9653 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9654 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9655 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9656 case ARMISD::VLD2DUP:
9657 case ARMISD::VLD3DUP:
9658 case ARMISD::VLD4DUP:
9659 return CombineBaseUpdate(N, DCI);
9660 case ISD::INTRINSIC_VOID:
9661 case ISD::INTRINSIC_W_CHAIN:
9662 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9663 case Intrinsic::arm_neon_vld1:
9664 case Intrinsic::arm_neon_vld2:
9665 case Intrinsic::arm_neon_vld3:
9666 case Intrinsic::arm_neon_vld4:
9667 case Intrinsic::arm_neon_vld2lane:
9668 case Intrinsic::arm_neon_vld3lane:
9669 case Intrinsic::arm_neon_vld4lane:
9670 case Intrinsic::arm_neon_vst1:
9671 case Intrinsic::arm_neon_vst2:
9672 case Intrinsic::arm_neon_vst3:
9673 case Intrinsic::arm_neon_vst4:
9674 case Intrinsic::arm_neon_vst2lane:
9675 case Intrinsic::arm_neon_vst3lane:
9676 case Intrinsic::arm_neon_vst4lane:
9677 return CombineBaseUpdate(N, DCI);
9685 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9687 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9690 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9691 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9692 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9694 switch (VT.getSimpleVT().SimpleTy) {
9700 // Unaligned access can use (for example) LRDB, LRDH, LDR
9701 if (AllowsUnaligned) {
9703 *Fast = Subtarget->hasV7Ops();
9710 // For any little-endian targets with neon, we can support unaligned ld/st
9711 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9712 // A big-endian target may also explictly support unaligned accesses
9713 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9723 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9724 unsigned AlignCheck) {
9725 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9726 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9729 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9730 unsigned DstAlign, unsigned SrcAlign,
9731 bool IsMemset, bool ZeroMemset,
9733 MachineFunction &MF) const {
9734 const Function *F = MF.getFunction();
9736 // See if we can use NEON instructions for this...
9737 if ((!IsMemset || ZeroMemset) &&
9738 Subtarget->hasNEON() &&
9739 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9740 Attribute::NoImplicitFloat)) {
9743 (memOpAlign(SrcAlign, DstAlign, 16) ||
9744 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9746 } else if (Size >= 8 &&
9747 (memOpAlign(SrcAlign, DstAlign, 8) ||
9748 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9753 // Lowering to i32/i16 if the size permits.
9759 // Let the target-independent logic figure it out.
9763 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9764 if (Val.getOpcode() != ISD::LOAD)
9767 EVT VT1 = Val.getValueType();
9768 if (!VT1.isSimple() || !VT1.isInteger() ||
9769 !VT2.isSimple() || !VT2.isInteger())
9772 switch (VT1.getSimpleVT().SimpleTy) {
9777 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9784 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9789 switch (VT.getSimpleVT().SimpleTy) {
9790 default: return false;
9805 if ((V & (Scale - 1)) != 0)
9808 return V == (V & ((1LL << 5) - 1));
9811 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9812 const ARMSubtarget *Subtarget) {
9819 switch (VT.getSimpleVT().SimpleTy) {
9820 default: return false;
9825 // + imm12 or - imm8
9827 return V == (V & ((1LL << 8) - 1));
9828 return V == (V & ((1LL << 12) - 1));
9831 // Same as ARM mode. FIXME: NEON?
9832 if (!Subtarget->hasVFP2())
9837 return V == (V & ((1LL << 8) - 1));
9841 /// isLegalAddressImmediate - Return true if the integer value can be used
9842 /// as the offset of the target addressing mode for load / store of the
9844 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9845 const ARMSubtarget *Subtarget) {
9852 if (Subtarget->isThumb1Only())
9853 return isLegalT1AddressImmediate(V, VT);
9854 else if (Subtarget->isThumb2())
9855 return isLegalT2AddressImmediate(V, VT, Subtarget);
9860 switch (VT.getSimpleVT().SimpleTy) {
9861 default: return false;
9866 return V == (V & ((1LL << 12) - 1));
9869 return V == (V & ((1LL << 8) - 1));
9872 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9877 return V == (V & ((1LL << 8) - 1));
9881 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9883 int Scale = AM.Scale;
9887 switch (VT.getSimpleVT().SimpleTy) {
9888 default: return false;
9897 return Scale == 2 || Scale == 4 || Scale == 8;
9900 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9904 // Note, we allow "void" uses (basically, uses that aren't loads or
9905 // stores), because arm allows folding a scale into many arithmetic
9906 // operations. This should be made more precise and revisited later.
9908 // Allow r << imm, but the imm has to be a multiple of two.
9909 if (Scale & 1) return false;
9910 return isPowerOf2_32(Scale);
9914 /// isLegalAddressingMode - Return true if the addressing mode represented
9915 /// by AM is legal for this target, for a load/store of the specified type.
9916 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9918 EVT VT = getValueType(Ty, true);
9919 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9922 // Can never fold addr of global into load/store.
9927 case 0: // no scale reg, must be "r+i" or "r", or "i".
9930 if (Subtarget->isThumb1Only())
9934 // ARM doesn't support any R+R*scale+imm addr modes.
9941 if (Subtarget->isThumb2())
9942 return isLegalT2ScaledAddressingMode(AM, VT);
9944 int Scale = AM.Scale;
9945 switch (VT.getSimpleVT().SimpleTy) {
9946 default: return false;
9950 if (Scale < 0) Scale = -Scale;
9954 return isPowerOf2_32(Scale & ~1);
9958 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9963 // Note, we allow "void" uses (basically, uses that aren't loads or
9964 // stores), because arm allows folding a scale into many arithmetic
9965 // operations. This should be made more precise and revisited later.
9967 // Allow r << imm, but the imm has to be a multiple of two.
9968 if (Scale & 1) return false;
9969 return isPowerOf2_32(Scale);
9975 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9976 /// icmp immediate, that is the target has icmp instructions which can compare
9977 /// a register against the immediate without having to materialize the
9978 /// immediate into a register.
9979 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9980 // Thumb2 and ARM modes can use cmn for negative immediates.
9981 if (!Subtarget->isThumb())
9982 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9983 if (Subtarget->isThumb2())
9984 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9985 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9986 return Imm >= 0 && Imm <= 255;
9989 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9990 /// *or sub* immediate, that is the target has add or sub instructions which can
9991 /// add a register with the immediate without having to materialize the
9992 /// immediate into a register.
9993 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9994 // Same encoding for add/sub, just flip the sign.
9995 int64_t AbsImm = llvm::abs64(Imm);
9996 if (!Subtarget->isThumb())
9997 return ARM_AM::getSOImmVal(AbsImm) != -1;
9998 if (Subtarget->isThumb2())
9999 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10000 // Thumb1 only has 8-bit unsigned immediate.
10001 return AbsImm >= 0 && AbsImm <= 255;
10004 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10005 bool isSEXTLoad, SDValue &Base,
10006 SDValue &Offset, bool &isInc,
10007 SelectionDAG &DAG) {
10008 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10011 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10012 // AddressingMode 3
10013 Base = Ptr->getOperand(0);
10014 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10015 int RHSC = (int)RHS->getZExtValue();
10016 if (RHSC < 0 && RHSC > -256) {
10017 assert(Ptr->getOpcode() == ISD::ADD);
10019 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10023 isInc = (Ptr->getOpcode() == ISD::ADD);
10024 Offset = Ptr->getOperand(1);
10026 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10027 // AddressingMode 2
10028 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10029 int RHSC = (int)RHS->getZExtValue();
10030 if (RHSC < 0 && RHSC > -0x1000) {
10031 assert(Ptr->getOpcode() == ISD::ADD);
10033 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10034 Base = Ptr->getOperand(0);
10039 if (Ptr->getOpcode() == ISD::ADD) {
10041 ARM_AM::ShiftOpc ShOpcVal=
10042 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10043 if (ShOpcVal != ARM_AM::no_shift) {
10044 Base = Ptr->getOperand(1);
10045 Offset = Ptr->getOperand(0);
10047 Base = Ptr->getOperand(0);
10048 Offset = Ptr->getOperand(1);
10053 isInc = (Ptr->getOpcode() == ISD::ADD);
10054 Base = Ptr->getOperand(0);
10055 Offset = Ptr->getOperand(1);
10059 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10063 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10064 bool isSEXTLoad, SDValue &Base,
10065 SDValue &Offset, bool &isInc,
10066 SelectionDAG &DAG) {
10067 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10070 Base = Ptr->getOperand(0);
10071 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10072 int RHSC = (int)RHS->getZExtValue();
10073 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10074 assert(Ptr->getOpcode() == ISD::ADD);
10076 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10078 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10079 isInc = Ptr->getOpcode() == ISD::ADD;
10080 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10088 /// getPreIndexedAddressParts - returns true by value, base pointer and
10089 /// offset pointer and addressing mode by reference if the node's address
10090 /// can be legally represented as pre-indexed load / store address.
10092 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10094 ISD::MemIndexedMode &AM,
10095 SelectionDAG &DAG) const {
10096 if (Subtarget->isThumb1Only())
10101 bool isSEXTLoad = false;
10102 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10103 Ptr = LD->getBasePtr();
10104 VT = LD->getMemoryVT();
10105 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10106 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10107 Ptr = ST->getBasePtr();
10108 VT = ST->getMemoryVT();
10113 bool isLegal = false;
10114 if (Subtarget->isThumb2())
10115 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10116 Offset, isInc, DAG);
10118 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10119 Offset, isInc, DAG);
10123 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10127 /// getPostIndexedAddressParts - returns true by value, base pointer and
10128 /// offset pointer and addressing mode by reference if this node can be
10129 /// combined with a load / store to form a post-indexed load / store.
10130 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10133 ISD::MemIndexedMode &AM,
10134 SelectionDAG &DAG) const {
10135 if (Subtarget->isThumb1Only())
10140 bool isSEXTLoad = false;
10141 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10142 VT = LD->getMemoryVT();
10143 Ptr = LD->getBasePtr();
10144 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10145 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10146 VT = ST->getMemoryVT();
10147 Ptr = ST->getBasePtr();
10152 bool isLegal = false;
10153 if (Subtarget->isThumb2())
10154 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10157 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10163 // Swap base ptr and offset to catch more post-index load / store when
10164 // it's legal. In Thumb2 mode, offset must be an immediate.
10165 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10166 !Subtarget->isThumb2())
10167 std::swap(Base, Offset);
10169 // Post-indexed load / store update the base pointer.
10174 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10178 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10181 const SelectionDAG &DAG,
10182 unsigned Depth) const {
10183 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
10184 switch (Op.getOpcode()) {
10186 case ARMISD::CMOV: {
10187 // Bits are known zero/one if known on the LHS and RHS.
10188 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10189 if (KnownZero == 0 && KnownOne == 0) return;
10191 APInt KnownZeroRHS, KnownOneRHS;
10192 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10193 KnownZero &= KnownZeroRHS;
10194 KnownOne &= KnownOneRHS;
10200 //===----------------------------------------------------------------------===//
10201 // ARM Inline Assembly Support
10202 //===----------------------------------------------------------------------===//
10204 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10205 // Looking for "rev" which is V6+.
10206 if (!Subtarget->hasV6Ops())
10209 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10210 std::string AsmStr = IA->getAsmString();
10211 SmallVector<StringRef, 4> AsmPieces;
10212 SplitString(AsmStr, AsmPieces, ";\n");
10214 switch (AsmPieces.size()) {
10215 default: return false;
10217 AsmStr = AsmPieces[0];
10219 SplitString(AsmStr, AsmPieces, " \t,");
10222 if (AsmPieces.size() == 3 &&
10223 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10224 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10225 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10226 if (Ty && Ty->getBitWidth() == 32)
10227 return IntrinsicLowering::LowerToByteSwap(CI);
10235 /// getConstraintType - Given a constraint letter, return the type of
10236 /// constraint it is for this target.
10237 ARMTargetLowering::ConstraintType
10238 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10239 if (Constraint.size() == 1) {
10240 switch (Constraint[0]) {
10242 case 'l': return C_RegisterClass;
10243 case 'w': return C_RegisterClass;
10244 case 'h': return C_RegisterClass;
10245 case 'x': return C_RegisterClass;
10246 case 't': return C_RegisterClass;
10247 case 'j': return C_Other; // Constant for movw.
10248 // An address with a single base register. Due to the way we
10249 // currently handle addresses it is the same as an 'r' memory constraint.
10250 case 'Q': return C_Memory;
10252 } else if (Constraint.size() == 2) {
10253 switch (Constraint[0]) {
10255 // All 'U+' constraints are addresses.
10256 case 'U': return C_Memory;
10259 return TargetLowering::getConstraintType(Constraint);
10262 /// Examine constraint type and operand type and determine a weight value.
10263 /// This object must already have been set up with the operand type
10264 /// and the current alternative constraint selected.
10265 TargetLowering::ConstraintWeight
10266 ARMTargetLowering::getSingleConstraintMatchWeight(
10267 AsmOperandInfo &info, const char *constraint) const {
10268 ConstraintWeight weight = CW_Invalid;
10269 Value *CallOperandVal = info.CallOperandVal;
10270 // If we don't have a value, we can't do a match,
10271 // but allow it at the lowest weight.
10272 if (CallOperandVal == NULL)
10274 Type *type = CallOperandVal->getType();
10275 // Look at the constraint type.
10276 switch (*constraint) {
10278 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10281 if (type->isIntegerTy()) {
10282 if (Subtarget->isThumb())
10283 weight = CW_SpecificReg;
10285 weight = CW_Register;
10289 if (type->isFloatingPointTy())
10290 weight = CW_Register;
10296 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10298 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10300 if (Constraint.size() == 1) {
10301 // GCC ARM Constraint Letters
10302 switch (Constraint[0]) {
10303 case 'l': // Low regs or general regs.
10304 if (Subtarget->isThumb())
10305 return RCPair(0U, &ARM::tGPRRegClass);
10306 return RCPair(0U, &ARM::GPRRegClass);
10307 case 'h': // High regs or no regs.
10308 if (Subtarget->isThumb())
10309 return RCPair(0U, &ARM::hGPRRegClass);
10312 return RCPair(0U, &ARM::GPRRegClass);
10314 if (VT == MVT::f32)
10315 return RCPair(0U, &ARM::SPRRegClass);
10316 if (VT.getSizeInBits() == 64)
10317 return RCPair(0U, &ARM::DPRRegClass);
10318 if (VT.getSizeInBits() == 128)
10319 return RCPair(0U, &ARM::QPRRegClass);
10322 if (VT == MVT::f32)
10323 return RCPair(0U, &ARM::SPR_8RegClass);
10324 if (VT.getSizeInBits() == 64)
10325 return RCPair(0U, &ARM::DPR_8RegClass);
10326 if (VT.getSizeInBits() == 128)
10327 return RCPair(0U, &ARM::QPR_8RegClass);
10330 if (VT == MVT::f32)
10331 return RCPair(0U, &ARM::SPRRegClass);
10335 if (StringRef("{cc}").equals_lower(Constraint))
10336 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10338 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10341 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10342 /// vector. If it is invalid, don't add anything to Ops.
10343 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10344 std::string &Constraint,
10345 std::vector<SDValue>&Ops,
10346 SelectionDAG &DAG) const {
10347 SDValue Result(0, 0);
10349 // Currently only support length 1 constraints.
10350 if (Constraint.length() != 1) return;
10352 char ConstraintLetter = Constraint[0];
10353 switch (ConstraintLetter) {
10356 case 'I': case 'J': case 'K': case 'L':
10357 case 'M': case 'N': case 'O':
10358 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10362 int64_t CVal64 = C->getSExtValue();
10363 int CVal = (int) CVal64;
10364 // None of these constraints allow values larger than 32 bits. Check
10365 // that the value fits in an int.
10366 if (CVal != CVal64)
10369 switch (ConstraintLetter) {
10371 // Constant suitable for movw, must be between 0 and
10373 if (Subtarget->hasV6T2Ops())
10374 if (CVal >= 0 && CVal <= 65535)
10378 if (Subtarget->isThumb1Only()) {
10379 // This must be a constant between 0 and 255, for ADD
10381 if (CVal >= 0 && CVal <= 255)
10383 } else if (Subtarget->isThumb2()) {
10384 // A constant that can be used as an immediate value in a
10385 // data-processing instruction.
10386 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10389 // A constant that can be used as an immediate value in a
10390 // data-processing instruction.
10391 if (ARM_AM::getSOImmVal(CVal) != -1)
10397 if (Subtarget->isThumb()) { // FIXME thumb2
10398 // This must be a constant between -255 and -1, for negated ADD
10399 // immediates. This can be used in GCC with an "n" modifier that
10400 // prints the negated value, for use with SUB instructions. It is
10401 // not useful otherwise but is implemented for compatibility.
10402 if (CVal >= -255 && CVal <= -1)
10405 // This must be a constant between -4095 and 4095. It is not clear
10406 // what this constraint is intended for. Implemented for
10407 // compatibility with GCC.
10408 if (CVal >= -4095 && CVal <= 4095)
10414 if (Subtarget->isThumb1Only()) {
10415 // A 32-bit value where only one byte has a nonzero value. Exclude
10416 // zero to match GCC. This constraint is used by GCC internally for
10417 // constants that can be loaded with a move/shift combination.
10418 // It is not useful otherwise but is implemented for compatibility.
10419 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10421 } else if (Subtarget->isThumb2()) {
10422 // A constant whose bitwise inverse can be used as an immediate
10423 // value in a data-processing instruction. This can be used in GCC
10424 // with a "B" modifier that prints the inverted value, for use with
10425 // BIC and MVN instructions. It is not useful otherwise but is
10426 // implemented for compatibility.
10427 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10430 // A constant whose bitwise inverse can be used as an immediate
10431 // value in a data-processing instruction. This can be used in GCC
10432 // with a "B" modifier that prints the inverted value, for use with
10433 // BIC and MVN instructions. It is not useful otherwise but is
10434 // implemented for compatibility.
10435 if (ARM_AM::getSOImmVal(~CVal) != -1)
10441 if (Subtarget->isThumb1Only()) {
10442 // This must be a constant between -7 and 7,
10443 // for 3-operand ADD/SUB immediate instructions.
10444 if (CVal >= -7 && CVal < 7)
10446 } else if (Subtarget->isThumb2()) {
10447 // A constant whose negation can be used as an immediate value in a
10448 // data-processing instruction. This can be used in GCC with an "n"
10449 // modifier that prints the negated value, for use with SUB
10450 // instructions. It is not useful otherwise but is implemented for
10452 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10455 // A constant whose negation can be used as an immediate value in a
10456 // data-processing instruction. This can be used in GCC with an "n"
10457 // modifier that prints the negated value, for use with SUB
10458 // instructions. It is not useful otherwise but is implemented for
10460 if (ARM_AM::getSOImmVal(-CVal) != -1)
10466 if (Subtarget->isThumb()) { // FIXME thumb2
10467 // This must be a multiple of 4 between 0 and 1020, for
10468 // ADD sp + immediate.
10469 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10472 // A power of two or a constant between 0 and 32. This is used in
10473 // GCC for the shift amount on shifted register operands, but it is
10474 // useful in general for any shift amounts.
10475 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10481 if (Subtarget->isThumb()) { // FIXME thumb2
10482 // This must be a constant between 0 and 31, for shift amounts.
10483 if (CVal >= 0 && CVal <= 31)
10489 if (Subtarget->isThumb()) { // FIXME thumb2
10490 // This must be a multiple of 4 between -508 and 508, for
10491 // ADD/SUB sp = sp + immediate.
10492 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10497 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10501 if (Result.getNode()) {
10502 Ops.push_back(Result);
10505 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10509 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10510 // The ARM target isn't yet aware of offsets.
10514 bool ARM::isBitFieldInvertedMask(unsigned v) {
10515 if (v == 0xffffffff)
10518 // there can be 1's on either or both "outsides", all the "inside"
10519 // bits must be 0's
10520 unsigned TO = CountTrailingOnes_32(v);
10521 unsigned LO = CountLeadingOnes_32(v);
10522 v = (v >> TO) << TO;
10523 v = (v << LO) >> LO;
10527 /// isFPImmLegal - Returns true if the target can instruction select the
10528 /// specified FP immediate natively. If false, the legalizer will
10529 /// materialize the FP immediate as a load from a constant pool.
10530 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10531 if (!Subtarget->hasVFP3())
10533 if (VT == MVT::f32)
10534 return ARM_AM::getFP32Imm(Imm) != -1;
10535 if (VT == MVT::f64)
10536 return ARM_AM::getFP64Imm(Imm) != -1;
10540 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10541 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10542 /// specified in the intrinsic calls.
10543 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10545 unsigned Intrinsic) const {
10546 switch (Intrinsic) {
10547 case Intrinsic::arm_neon_vld1:
10548 case Intrinsic::arm_neon_vld2:
10549 case Intrinsic::arm_neon_vld3:
10550 case Intrinsic::arm_neon_vld4:
10551 case Intrinsic::arm_neon_vld2lane:
10552 case Intrinsic::arm_neon_vld3lane:
10553 case Intrinsic::arm_neon_vld4lane: {
10554 Info.opc = ISD::INTRINSIC_W_CHAIN;
10555 // Conservatively set memVT to the entire set of vectors loaded.
10556 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10557 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10558 Info.ptrVal = I.getArgOperand(0);
10560 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10561 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10562 Info.vol = false; // volatile loads with NEON intrinsics not supported
10563 Info.readMem = true;
10564 Info.writeMem = false;
10567 case Intrinsic::arm_neon_vst1:
10568 case Intrinsic::arm_neon_vst2:
10569 case Intrinsic::arm_neon_vst3:
10570 case Intrinsic::arm_neon_vst4:
10571 case Intrinsic::arm_neon_vst2lane:
10572 case Intrinsic::arm_neon_vst3lane:
10573 case Intrinsic::arm_neon_vst4lane: {
10574 Info.opc = ISD::INTRINSIC_VOID;
10575 // Conservatively set memVT to the entire set of vectors stored.
10576 unsigned NumElts = 0;
10577 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10578 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10579 if (!ArgTy->isVectorTy())
10581 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10583 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10584 Info.ptrVal = I.getArgOperand(0);
10586 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10587 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10588 Info.vol = false; // volatile stores with NEON intrinsics not supported
10589 Info.readMem = false;
10590 Info.writeMem = true;
10593 case Intrinsic::arm_strexd: {
10594 Info.opc = ISD::INTRINSIC_W_CHAIN;
10595 Info.memVT = MVT::i64;
10596 Info.ptrVal = I.getArgOperand(2);
10600 Info.readMem = false;
10601 Info.writeMem = true;
10604 case Intrinsic::arm_ldrexd: {
10605 Info.opc = ISD::INTRINSIC_W_CHAIN;
10606 Info.memVT = MVT::i64;
10607 Info.ptrVal = I.getArgOperand(0);
10611 Info.readMem = true;
10612 Info.writeMem = false;