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 setExceptionPointerRegister(ARM::R0);
721 setExceptionSelectorRegister(ARM::R1);
724 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
725 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
726 // the default expansion.
727 // FIXME: This should be checking for v6k, not just v6.
728 if (Subtarget->hasDataBarrier() ||
729 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
730 // membarrier needs custom lowering; the rest are legal and handled
732 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
733 // Custom lowering for 64-bit ops
734 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
735 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
736 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
737 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
738 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
739 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
740 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
741 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
742 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
743 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
744 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
745 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
746 setInsertFencesForAtomic(true);
748 // Set them all for expansion, which will force libcalls.
749 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
750 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
751 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
752 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
753 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
754 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
755 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
756 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
757 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
758 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
759 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
760 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
761 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
762 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
763 // Unordered/Monotonic case.
764 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
765 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
768 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
770 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
771 if (!Subtarget->hasV6Ops()) {
772 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
773 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
775 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
777 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
778 !Subtarget->isThumb1Only()) {
779 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
780 // iff target supports vfp2.
781 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
782 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
785 // We want to custom lower some of our intrinsics.
786 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
787 if (Subtarget->isTargetDarwin()) {
788 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
789 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
790 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
793 setOperationAction(ISD::SETCC, MVT::i32, Expand);
794 setOperationAction(ISD::SETCC, MVT::f32, Expand);
795 setOperationAction(ISD::SETCC, MVT::f64, Expand);
796 setOperationAction(ISD::SELECT, MVT::i32, Custom);
797 setOperationAction(ISD::SELECT, MVT::f32, Custom);
798 setOperationAction(ISD::SELECT, MVT::f64, Custom);
799 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
800 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
801 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
803 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
804 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
805 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
806 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
807 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
809 // We don't support sin/cos/fmod/copysign/pow
810 setOperationAction(ISD::FSIN, MVT::f64, Expand);
811 setOperationAction(ISD::FSIN, MVT::f32, Expand);
812 setOperationAction(ISD::FCOS, MVT::f32, Expand);
813 setOperationAction(ISD::FCOS, MVT::f64, Expand);
814 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
815 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
816 setOperationAction(ISD::FREM, MVT::f64, Expand);
817 setOperationAction(ISD::FREM, MVT::f32, Expand);
818 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
819 !Subtarget->isThumb1Only()) {
820 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
821 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
823 setOperationAction(ISD::FPOW, MVT::f64, Expand);
824 setOperationAction(ISD::FPOW, MVT::f32, Expand);
826 if (!Subtarget->hasVFP4()) {
827 setOperationAction(ISD::FMA, MVT::f64, Expand);
828 setOperationAction(ISD::FMA, MVT::f32, Expand);
831 // Various VFP goodness
832 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
833 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
834 if (Subtarget->hasVFP2()) {
835 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
836 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
837 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
838 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
840 // Special handling for half-precision FP.
841 if (!Subtarget->hasFP16()) {
842 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
843 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
847 // We have target-specific dag combine patterns for the following nodes:
848 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
849 setTargetDAGCombine(ISD::ADD);
850 setTargetDAGCombine(ISD::SUB);
851 setTargetDAGCombine(ISD::MUL);
852 setTargetDAGCombine(ISD::AND);
853 setTargetDAGCombine(ISD::OR);
854 setTargetDAGCombine(ISD::XOR);
856 if (Subtarget->hasV6Ops())
857 setTargetDAGCombine(ISD::SRL);
859 setStackPointerRegisterToSaveRestore(ARM::SP);
861 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
862 !Subtarget->hasVFP2())
863 setSchedulingPreference(Sched::RegPressure);
865 setSchedulingPreference(Sched::Hybrid);
867 //// temporary - rewrite interface to use type
868 MaxStoresPerMemset = 8;
869 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
870 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
871 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
872 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
873 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
875 // On ARM arguments smaller than 4 bytes are extended, so all arguments
876 // are at least 4 bytes aligned.
877 setMinStackArgumentAlignment(4);
879 // Prefer likely predicted branches to selects on out-of-order cores.
880 PredictableSelectIsExpensive = Subtarget->isLikeA9();
882 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
885 // FIXME: It might make sense to define the representative register class as the
886 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
887 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
888 // SPR's representative would be DPR_VFP2. This should work well if register
889 // pressure tracking were modified such that a register use would increment the
890 // pressure of the register class's representative and all of it's super
891 // classes' representatives transitively. We have not implemented this because
892 // of the difficulty prior to coalescing of modeling operand register classes
893 // due to the common occurrence of cross class copies and subregister insertions
895 std::pair<const TargetRegisterClass*, uint8_t>
896 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
897 const TargetRegisterClass *RRC = 0;
899 switch (VT.SimpleTy) {
901 return TargetLowering::findRepresentativeClass(VT);
902 // Use DPR as representative register class for all floating point
903 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
904 // the cost is 1 for both f32 and f64.
905 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
906 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
907 RRC = &ARM::DPRRegClass;
908 // When NEON is used for SP, only half of the register file is available
909 // because operations that define both SP and DP results will be constrained
910 // to the VFP2 class (D0-D15). We currently model this constraint prior to
911 // coalescing by double-counting the SP regs. See the FIXME above.
912 if (Subtarget->useNEONForSinglePrecisionFP())
915 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
916 case MVT::v4f32: case MVT::v2f64:
917 RRC = &ARM::DPRRegClass;
921 RRC = &ARM::DPRRegClass;
925 RRC = &ARM::DPRRegClass;
929 return std::make_pair(RRC, Cost);
932 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
935 case ARMISD::Wrapper: return "ARMISD::Wrapper";
936 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
937 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
938 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
939 case ARMISD::CALL: return "ARMISD::CALL";
940 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
941 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
942 case ARMISD::tCALL: return "ARMISD::tCALL";
943 case ARMISD::BRCOND: return "ARMISD::BRCOND";
944 case ARMISD::BR_JT: return "ARMISD::BR_JT";
945 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
946 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
947 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
948 case ARMISD::CMP: return "ARMISD::CMP";
949 case ARMISD::CMN: return "ARMISD::CMN";
950 case ARMISD::CMPZ: return "ARMISD::CMPZ";
951 case ARMISD::CMPFP: return "ARMISD::CMPFP";
952 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
953 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
954 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
956 case ARMISD::CMOV: return "ARMISD::CMOV";
958 case ARMISD::RBIT: return "ARMISD::RBIT";
960 case ARMISD::FTOSI: return "ARMISD::FTOSI";
961 case ARMISD::FTOUI: return "ARMISD::FTOUI";
962 case ARMISD::SITOF: return "ARMISD::SITOF";
963 case ARMISD::UITOF: return "ARMISD::UITOF";
965 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
966 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
967 case ARMISD::RRX: return "ARMISD::RRX";
969 case ARMISD::ADDC: return "ARMISD::ADDC";
970 case ARMISD::ADDE: return "ARMISD::ADDE";
971 case ARMISD::SUBC: return "ARMISD::SUBC";
972 case ARMISD::SUBE: return "ARMISD::SUBE";
974 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
975 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
977 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
978 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
980 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
982 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
984 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
986 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
987 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
989 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
991 case ARMISD::VCEQ: return "ARMISD::VCEQ";
992 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
993 case ARMISD::VCGE: return "ARMISD::VCGE";
994 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
995 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
996 case ARMISD::VCGEU: return "ARMISD::VCGEU";
997 case ARMISD::VCGT: return "ARMISD::VCGT";
998 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
999 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1000 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1001 case ARMISD::VTST: return "ARMISD::VTST";
1003 case ARMISD::VSHL: return "ARMISD::VSHL";
1004 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1005 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1006 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1007 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1008 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1009 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1010 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1011 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1012 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1013 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1014 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1015 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1016 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1017 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1018 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1019 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1020 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1021 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1022 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1023 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1024 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1025 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1026 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1027 case ARMISD::VDUP: return "ARMISD::VDUP";
1028 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1029 case ARMISD::VEXT: return "ARMISD::VEXT";
1030 case ARMISD::VREV64: return "ARMISD::VREV64";
1031 case ARMISD::VREV32: return "ARMISD::VREV32";
1032 case ARMISD::VREV16: return "ARMISD::VREV16";
1033 case ARMISD::VZIP: return "ARMISD::VZIP";
1034 case ARMISD::VUZP: return "ARMISD::VUZP";
1035 case ARMISD::VTRN: return "ARMISD::VTRN";
1036 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1037 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1038 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1039 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1040 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1041 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1042 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1043 case ARMISD::FMAX: return "ARMISD::FMAX";
1044 case ARMISD::FMIN: return "ARMISD::FMIN";
1045 case ARMISD::BFI: return "ARMISD::BFI";
1046 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1047 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1048 case ARMISD::VBSL: return "ARMISD::VBSL";
1049 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1050 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1051 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1052 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1053 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1054 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1055 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1056 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1057 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1058 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1059 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1060 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1061 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1062 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1063 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1064 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1065 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1066 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1067 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1068 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1072 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1073 if (!VT.isVector()) return getPointerTy();
1074 return VT.changeVectorElementTypeToInteger();
1077 /// getRegClassFor - Return the register class that should be used for the
1078 /// specified value type.
1079 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1080 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1081 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1082 // load / store 4 to 8 consecutive D registers.
1083 if (Subtarget->hasNEON()) {
1084 if (VT == MVT::v4i64)
1085 return &ARM::QQPRRegClass;
1086 if (VT == MVT::v8i64)
1087 return &ARM::QQQQPRRegClass;
1089 return TargetLowering::getRegClassFor(VT);
1092 // Create a fast isel object.
1094 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1095 const TargetLibraryInfo *libInfo) const {
1096 return ARM::createFastISel(funcInfo, libInfo);
1099 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1100 /// be used for loads / stores from the global.
1101 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1102 return (Subtarget->isThumb1Only() ? 127 : 4095);
1105 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1106 unsigned NumVals = N->getNumValues();
1108 return Sched::RegPressure;
1110 for (unsigned i = 0; i != NumVals; ++i) {
1111 EVT VT = N->getValueType(i);
1112 if (VT == MVT::Glue || VT == MVT::Other)
1114 if (VT.isFloatingPoint() || VT.isVector())
1118 if (!N->isMachineOpcode())
1119 return Sched::RegPressure;
1121 // Load are scheduled for latency even if there instruction itinerary
1122 // is not available.
1123 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1124 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1126 if (MCID.getNumDefs() == 0)
1127 return Sched::RegPressure;
1128 if (!Itins->isEmpty() &&
1129 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1132 return Sched::RegPressure;
1135 //===----------------------------------------------------------------------===//
1137 //===----------------------------------------------------------------------===//
1139 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1140 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1142 default: llvm_unreachable("Unknown condition code!");
1143 case ISD::SETNE: return ARMCC::NE;
1144 case ISD::SETEQ: return ARMCC::EQ;
1145 case ISD::SETGT: return ARMCC::GT;
1146 case ISD::SETGE: return ARMCC::GE;
1147 case ISD::SETLT: return ARMCC::LT;
1148 case ISD::SETLE: return ARMCC::LE;
1149 case ISD::SETUGT: return ARMCC::HI;
1150 case ISD::SETUGE: return ARMCC::HS;
1151 case ISD::SETULT: return ARMCC::LO;
1152 case ISD::SETULE: return ARMCC::LS;
1156 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1157 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1158 ARMCC::CondCodes &CondCode2) {
1159 CondCode2 = ARMCC::AL;
1161 default: llvm_unreachable("Unknown FP condition!");
1163 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1165 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1167 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1168 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1169 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1170 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1171 case ISD::SETO: CondCode = ARMCC::VC; break;
1172 case ISD::SETUO: CondCode = ARMCC::VS; break;
1173 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1174 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1175 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1177 case ISD::SETULT: CondCode = ARMCC::LT; break;
1179 case ISD::SETULE: CondCode = ARMCC::LE; break;
1181 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1185 //===----------------------------------------------------------------------===//
1186 // Calling Convention Implementation
1187 //===----------------------------------------------------------------------===//
1189 #include "ARMGenCallingConv.inc"
1191 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1192 /// given CallingConvention value.
1193 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1195 bool isVarArg) const {
1198 llvm_unreachable("Unsupported calling convention");
1199 case CallingConv::Fast:
1200 if (Subtarget->hasVFP2() && !isVarArg) {
1201 if (!Subtarget->isAAPCS_ABI())
1202 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1203 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1204 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1207 case CallingConv::C: {
1208 // Use target triple & subtarget features to do actual dispatch.
1209 if (!Subtarget->isAAPCS_ABI())
1210 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1211 else if (Subtarget->hasVFP2() &&
1212 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1214 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1215 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1217 case CallingConv::ARM_AAPCS_VFP:
1219 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1221 case CallingConv::ARM_AAPCS:
1222 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1223 case CallingConv::ARM_APCS:
1224 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1225 case CallingConv::GHC:
1226 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1230 /// LowerCallResult - Lower the result values of a call into the
1231 /// appropriate copies out of appropriate physical registers.
1233 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1234 CallingConv::ID CallConv, bool isVarArg,
1235 const SmallVectorImpl<ISD::InputArg> &Ins,
1236 SDLoc dl, SelectionDAG &DAG,
1237 SmallVectorImpl<SDValue> &InVals,
1238 bool isThisReturn, SDValue ThisVal) const {
1240 // Assign locations to each value returned by this call.
1241 SmallVector<CCValAssign, 16> RVLocs;
1242 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1243 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1244 CCInfo.AnalyzeCallResult(Ins,
1245 CCAssignFnForNode(CallConv, /* Return*/ true,
1248 // Copy all of the result registers out of their specified physreg.
1249 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1250 CCValAssign VA = RVLocs[i];
1252 // Pass 'this' value directly from the argument to return value, to avoid
1253 // reg unit interference
1254 if (i == 0 && isThisReturn) {
1255 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1256 "unexpected return calling convention register assignment");
1257 InVals.push_back(ThisVal);
1262 if (VA.needsCustom()) {
1263 // Handle f64 or half of a v2f64.
1264 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1266 Chain = Lo.getValue(1);
1267 InFlag = Lo.getValue(2);
1268 VA = RVLocs[++i]; // skip ahead to next loc
1269 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1271 Chain = Hi.getValue(1);
1272 InFlag = Hi.getValue(2);
1273 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1275 if (VA.getLocVT() == MVT::v2f64) {
1276 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1277 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1278 DAG.getConstant(0, MVT::i32));
1280 VA = RVLocs[++i]; // skip ahead to next loc
1281 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1282 Chain = Lo.getValue(1);
1283 InFlag = Lo.getValue(2);
1284 VA = RVLocs[++i]; // skip ahead to next loc
1285 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1286 Chain = Hi.getValue(1);
1287 InFlag = Hi.getValue(2);
1288 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1289 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1290 DAG.getConstant(1, MVT::i32));
1293 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1295 Chain = Val.getValue(1);
1296 InFlag = Val.getValue(2);
1299 switch (VA.getLocInfo()) {
1300 default: llvm_unreachable("Unknown loc info!");
1301 case CCValAssign::Full: break;
1302 case CCValAssign::BCvt:
1303 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1307 InVals.push_back(Val);
1313 /// LowerMemOpCallTo - Store the argument to the stack.
1315 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1316 SDValue StackPtr, SDValue Arg,
1317 SDLoc dl, SelectionDAG &DAG,
1318 const CCValAssign &VA,
1319 ISD::ArgFlagsTy Flags) const {
1320 unsigned LocMemOffset = VA.getLocMemOffset();
1321 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1322 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1323 return DAG.getStore(Chain, dl, Arg, PtrOff,
1324 MachinePointerInfo::getStack(LocMemOffset),
1328 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1329 SDValue Chain, SDValue &Arg,
1330 RegsToPassVector &RegsToPass,
1331 CCValAssign &VA, CCValAssign &NextVA,
1333 SmallVector<SDValue, 8> &MemOpChains,
1334 ISD::ArgFlagsTy Flags) const {
1336 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1337 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1338 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1340 if (NextVA.isRegLoc())
1341 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1343 assert(NextVA.isMemLoc());
1344 if (StackPtr.getNode() == 0)
1345 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1347 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1353 /// LowerCall - Lowering a call into a callseq_start <-
1354 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1357 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1358 SmallVectorImpl<SDValue> &InVals) const {
1359 SelectionDAG &DAG = CLI.DAG;
1361 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1362 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1363 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1364 SDValue Chain = CLI.Chain;
1365 SDValue Callee = CLI.Callee;
1366 bool &isTailCall = CLI.IsTailCall;
1367 CallingConv::ID CallConv = CLI.CallConv;
1368 bool doesNotRet = CLI.DoesNotReturn;
1369 bool isVarArg = CLI.IsVarArg;
1371 MachineFunction &MF = DAG.getMachineFunction();
1372 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1373 bool isThisReturn = false;
1374 bool isSibCall = false;
1375 // Disable tail calls if they're not supported.
1376 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1379 // Check if it's really possible to do a tail call.
1380 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1381 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1382 Outs, OutVals, Ins, DAG);
1383 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1384 // detected sibcalls.
1391 // Analyze operands of the call, assigning locations to each operand.
1392 SmallVector<CCValAssign, 16> ArgLocs;
1393 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1394 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1395 CCInfo.AnalyzeCallOperands(Outs,
1396 CCAssignFnForNode(CallConv, /* Return*/ false,
1399 // Get a count of how many bytes are to be pushed on the stack.
1400 unsigned NumBytes = CCInfo.getNextStackOffset();
1402 // For tail calls, memory operands are available in our caller's stack.
1406 // Adjust the stack pointer for the new arguments...
1407 // These operations are automatically eliminated by the prolog/epilog pass
1409 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1412 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1414 RegsToPassVector RegsToPass;
1415 SmallVector<SDValue, 8> MemOpChains;
1417 // Walk the register/memloc assignments, inserting copies/loads. In the case
1418 // of tail call optimization, arguments are handled later.
1419 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1421 ++i, ++realArgIdx) {
1422 CCValAssign &VA = ArgLocs[i];
1423 SDValue Arg = OutVals[realArgIdx];
1424 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1425 bool isByVal = Flags.isByVal();
1427 // Promote the value if needed.
1428 switch (VA.getLocInfo()) {
1429 default: llvm_unreachable("Unknown loc info!");
1430 case CCValAssign::Full: break;
1431 case CCValAssign::SExt:
1432 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1434 case CCValAssign::ZExt:
1435 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1437 case CCValAssign::AExt:
1438 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1440 case CCValAssign::BCvt:
1441 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1445 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1446 if (VA.needsCustom()) {
1447 if (VA.getLocVT() == MVT::v2f64) {
1448 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1449 DAG.getConstant(0, MVT::i32));
1450 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1451 DAG.getConstant(1, MVT::i32));
1453 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1454 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1456 VA = ArgLocs[++i]; // skip ahead to next loc
1457 if (VA.isRegLoc()) {
1458 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1459 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1461 assert(VA.isMemLoc());
1463 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1464 dl, DAG, VA, Flags));
1467 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1468 StackPtr, MemOpChains, Flags);
1470 } else if (VA.isRegLoc()) {
1471 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1472 assert(VA.getLocVT() == MVT::i32 &&
1473 "unexpected calling convention register assignment");
1474 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1475 "unexpected use of 'returned'");
1476 isThisReturn = true;
1478 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1479 } else if (isByVal) {
1480 assert(VA.isMemLoc());
1481 unsigned offset = 0;
1483 // True if this byval aggregate will be split between registers
1485 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1486 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1488 if (CurByValIdx < ByValArgsCount) {
1490 unsigned RegBegin, RegEnd;
1491 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1493 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1495 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1496 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1497 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1498 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1499 MachinePointerInfo(),
1500 false, false, false, 0);
1501 MemOpChains.push_back(Load.getValue(1));
1502 RegsToPass.push_back(std::make_pair(j, Load));
1505 // If parameter size outsides register area, "offset" value
1506 // helps us to calculate stack slot for remained part properly.
1507 offset = RegEnd - RegBegin;
1509 CCInfo.nextInRegsParam();
1512 if (Flags.getByValSize() > 4*offset) {
1513 unsigned LocMemOffset = VA.getLocMemOffset();
1514 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1515 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1517 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1518 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1519 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1521 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1523 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1524 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1525 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1526 Ops, array_lengthof(Ops)));
1528 } else if (!isSibCall) {
1529 assert(VA.isMemLoc());
1531 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1532 dl, DAG, VA, Flags));
1536 if (!MemOpChains.empty())
1537 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1538 &MemOpChains[0], MemOpChains.size());
1540 // Build a sequence of copy-to-reg nodes chained together with token chain
1541 // and flag operands which copy the outgoing args into the appropriate regs.
1543 // Tail call byval lowering might overwrite argument registers so in case of
1544 // tail call optimization the copies to registers are lowered later.
1546 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1547 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1548 RegsToPass[i].second, InFlag);
1549 InFlag = Chain.getValue(1);
1552 // For tail calls lower the arguments to the 'real' stack slot.
1554 // Force all the incoming stack arguments to be loaded from the stack
1555 // before any new outgoing arguments are stored to the stack, because the
1556 // outgoing stack slots may alias the incoming argument stack slots, and
1557 // the alias isn't otherwise explicit. This is slightly more conservative
1558 // than necessary, because it means that each store effectively depends
1559 // on every argument instead of just those arguments it would clobber.
1561 // Do not flag preceding copytoreg stuff together with the following stuff.
1563 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1564 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1565 RegsToPass[i].second, InFlag);
1566 InFlag = Chain.getValue(1);
1571 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1572 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1573 // node so that legalize doesn't hack it.
1574 bool isDirect = false;
1575 bool isARMFunc = false;
1576 bool isLocalARMFunc = false;
1577 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1579 if (EnableARMLongCalls) {
1580 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1581 && "long-calls with non-static relocation model!");
1582 // Handle a global address or an external symbol. If it's not one of
1583 // those, the target's already in a register, so we don't need to do
1585 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1586 const GlobalValue *GV = G->getGlobal();
1587 // Create a constant pool entry for the callee address
1588 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1589 ARMConstantPoolValue *CPV =
1590 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1592 // Get the address of the callee into a register
1593 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1594 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1595 Callee = DAG.getLoad(getPointerTy(), dl,
1596 DAG.getEntryNode(), CPAddr,
1597 MachinePointerInfo::getConstantPool(),
1598 false, false, false, 0);
1599 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1600 const char *Sym = S->getSymbol();
1602 // Create a constant pool entry for the callee address
1603 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1604 ARMConstantPoolValue *CPV =
1605 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1606 ARMPCLabelIndex, 0);
1607 // Get the address of the callee into a register
1608 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1609 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1610 Callee = DAG.getLoad(getPointerTy(), dl,
1611 DAG.getEntryNode(), CPAddr,
1612 MachinePointerInfo::getConstantPool(),
1613 false, false, false, 0);
1615 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1616 const GlobalValue *GV = G->getGlobal();
1618 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1619 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1620 getTargetMachine().getRelocationModel() != Reloc::Static;
1621 isARMFunc = !Subtarget->isThumb() || isStub;
1622 // ARM call to a local ARM function is predicable.
1623 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1624 // tBX takes a register source operand.
1625 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1626 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1627 ARMConstantPoolValue *CPV =
1628 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1629 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1630 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1631 Callee = DAG.getLoad(getPointerTy(), dl,
1632 DAG.getEntryNode(), CPAddr,
1633 MachinePointerInfo::getConstantPool(),
1634 false, false, false, 0);
1635 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1636 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1637 getPointerTy(), Callee, PICLabel);
1639 // On ELF targets for PIC code, direct calls should go through the PLT
1640 unsigned OpFlags = 0;
1641 if (Subtarget->isTargetELF() &&
1642 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1643 OpFlags = ARMII::MO_PLT;
1644 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1646 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1648 bool isStub = Subtarget->isTargetDarwin() &&
1649 getTargetMachine().getRelocationModel() != Reloc::Static;
1650 isARMFunc = !Subtarget->isThumb() || isStub;
1651 // tBX takes a register source operand.
1652 const char *Sym = S->getSymbol();
1653 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1654 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1655 ARMConstantPoolValue *CPV =
1656 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1657 ARMPCLabelIndex, 4);
1658 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1659 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1660 Callee = DAG.getLoad(getPointerTy(), dl,
1661 DAG.getEntryNode(), CPAddr,
1662 MachinePointerInfo::getConstantPool(),
1663 false, false, false, 0);
1664 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1665 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1666 getPointerTy(), Callee, PICLabel);
1668 unsigned OpFlags = 0;
1669 // On ELF targets for PIC code, direct calls should go through the PLT
1670 if (Subtarget->isTargetELF() &&
1671 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1672 OpFlags = ARMII::MO_PLT;
1673 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1677 // FIXME: handle tail calls differently.
1679 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1680 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1681 if (Subtarget->isThumb()) {
1682 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1683 CallOpc = ARMISD::CALL_NOLINK;
1685 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1687 if (!isDirect && !Subtarget->hasV5TOps())
1688 CallOpc = ARMISD::CALL_NOLINK;
1689 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1690 // Emit regular call when code size is the priority
1692 // "mov lr, pc; b _foo" to avoid confusing the RSP
1693 CallOpc = ARMISD::CALL_NOLINK;
1695 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1698 std::vector<SDValue> Ops;
1699 Ops.push_back(Chain);
1700 Ops.push_back(Callee);
1702 // Add argument registers to the end of the list so that they are known live
1704 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1705 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1706 RegsToPass[i].second.getValueType()));
1708 // Add a register mask operand representing the call-preserved registers.
1709 const uint32_t *Mask;
1710 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1711 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1713 // For 'this' returns, use the R0-preserving mask if applicable
1714 Mask = ARI->getThisReturnPreservedMask(CallConv);
1716 // Set isThisReturn to false if the calling convention is not one that
1717 // allows 'returned' to be modeled in this way, so LowerCallResult does
1718 // not try to pass 'this' straight through
1719 isThisReturn = false;
1720 Mask = ARI->getCallPreservedMask(CallConv);
1723 Mask = ARI->getCallPreservedMask(CallConv);
1725 assert(Mask && "Missing call preserved mask for calling convention");
1726 Ops.push_back(DAG.getRegisterMask(Mask));
1728 if (InFlag.getNode())
1729 Ops.push_back(InFlag);
1731 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1733 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1735 // Returns a chain and a flag for retval copy to use.
1736 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1737 InFlag = Chain.getValue(1);
1739 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1740 DAG.getIntPtrConstant(0, true), InFlag, dl);
1742 InFlag = Chain.getValue(1);
1744 // Handle result values, copying them out of physregs into vregs that we
1746 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1747 InVals, isThisReturn,
1748 isThisReturn ? OutVals[0] : SDValue());
1751 /// HandleByVal - Every parameter *after* a byval parameter is passed
1752 /// on the stack. Remember the next parameter register to allocate,
1753 /// and then confiscate the rest of the parameter registers to insure
1756 ARMTargetLowering::HandleByVal(
1757 CCState *State, unsigned &size, unsigned Align) const {
1758 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1759 assert((State->getCallOrPrologue() == Prologue ||
1760 State->getCallOrPrologue() == Call) &&
1761 "unhandled ParmContext");
1763 // For in-prologue parameters handling, we also introduce stack offset
1764 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1765 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1766 // NSAA should be evaluted (NSAA means "next stacked argument address").
1767 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1768 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1769 unsigned NSAAOffset = State->getNextStackOffset();
1770 if (State->getCallOrPrologue() != Call) {
1771 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1773 State->getInRegsParamInfo(i, RB, RE);
1774 assert(NSAAOffset >= (RE-RB)*4 &&
1775 "Stack offset for byval regs doesn't introduced anymore?");
1776 NSAAOffset -= (RE-RB)*4;
1779 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1780 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1781 unsigned AlignInRegs = Align / 4;
1782 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1783 for (unsigned i = 0; i < Waste; ++i)
1784 reg = State->AllocateReg(GPRArgRegs, 4);
1787 unsigned excess = 4 * (ARM::R4 - reg);
1789 // Special case when NSAA != SP and parameter size greater than size of
1790 // all remained GPR regs. In that case we can't split parameter, we must
1791 // send it to stack. We also must set NCRN to R4, so waste all
1792 // remained registers.
1793 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1794 while (State->AllocateReg(GPRArgRegs, 4))
1799 // First register for byval parameter is the first register that wasn't
1800 // allocated before this method call, so it would be "reg".
1801 // If parameter is small enough to be saved in range [reg, r4), then
1802 // the end (first after last) register would be reg + param-size-in-regs,
1803 // else parameter would be splitted between registers and stack,
1804 // end register would be r4 in this case.
1805 unsigned ByValRegBegin = reg;
1806 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1807 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1808 // Note, first register is allocated in the beginning of function already,
1809 // allocate remained amount of registers we need.
1810 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1811 State->AllocateReg(GPRArgRegs, 4);
1812 // At a call site, a byval parameter that is split between
1813 // registers and memory needs its size truncated here. In a
1814 // function prologue, such byval parameters are reassembled in
1815 // memory, and are not truncated.
1816 if (State->getCallOrPrologue() == Call) {
1817 // Make remained size equal to 0 in case, when
1818 // the whole structure may be stored into registers.
1828 /// MatchingStackOffset - Return true if the given stack call argument is
1829 /// already available in the same position (relatively) of the caller's
1830 /// incoming argument stack.
1832 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1833 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1834 const TargetInstrInfo *TII) {
1835 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1837 if (Arg.getOpcode() == ISD::CopyFromReg) {
1838 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1839 if (!TargetRegisterInfo::isVirtualRegister(VR))
1841 MachineInstr *Def = MRI->getVRegDef(VR);
1844 if (!Flags.isByVal()) {
1845 if (!TII->isLoadFromStackSlot(Def, FI))
1850 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1851 if (Flags.isByVal())
1852 // ByVal argument is passed in as a pointer but it's now being
1853 // dereferenced. e.g.
1854 // define @foo(%struct.X* %A) {
1855 // tail call @bar(%struct.X* byval %A)
1858 SDValue Ptr = Ld->getBasePtr();
1859 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1862 FI = FINode->getIndex();
1866 assert(FI != INT_MAX);
1867 if (!MFI->isFixedObjectIndex(FI))
1869 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1872 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1873 /// for tail call optimization. Targets which want to do tail call
1874 /// optimization should implement this function.
1876 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1877 CallingConv::ID CalleeCC,
1879 bool isCalleeStructRet,
1880 bool isCallerStructRet,
1881 const SmallVectorImpl<ISD::OutputArg> &Outs,
1882 const SmallVectorImpl<SDValue> &OutVals,
1883 const SmallVectorImpl<ISD::InputArg> &Ins,
1884 SelectionDAG& DAG) const {
1885 const Function *CallerF = DAG.getMachineFunction().getFunction();
1886 CallingConv::ID CallerCC = CallerF->getCallingConv();
1887 bool CCMatch = CallerCC == CalleeCC;
1889 // Look for obvious safe cases to perform tail call optimization that do not
1890 // require ABI changes. This is what gcc calls sibcall.
1892 // Do not sibcall optimize vararg calls unless the call site is not passing
1894 if (isVarArg && !Outs.empty())
1897 // Also avoid sibcall optimization if either caller or callee uses struct
1898 // return semantics.
1899 if (isCalleeStructRet || isCallerStructRet)
1902 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1903 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1904 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1905 // support in the assembler and linker to be used. This would need to be
1906 // fixed to fully support tail calls in Thumb1.
1908 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1909 // LR. This means if we need to reload LR, it takes an extra instructions,
1910 // which outweighs the value of the tail call; but here we don't know yet
1911 // whether LR is going to be used. Probably the right approach is to
1912 // generate the tail call here and turn it back into CALL/RET in
1913 // emitEpilogue if LR is used.
1915 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1916 // but we need to make sure there are enough registers; the only valid
1917 // registers are the 4 used for parameters. We don't currently do this
1919 if (Subtarget->isThumb1Only())
1922 // If the calling conventions do not match, then we'd better make sure the
1923 // results are returned in the same way as what the caller expects.
1925 SmallVector<CCValAssign, 16> RVLocs1;
1926 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1927 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1928 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1930 SmallVector<CCValAssign, 16> RVLocs2;
1931 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1932 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1933 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1935 if (RVLocs1.size() != RVLocs2.size())
1937 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1938 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1940 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1942 if (RVLocs1[i].isRegLoc()) {
1943 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1946 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1952 // If Caller's vararg or byval argument has been split between registers and
1953 // stack, do not perform tail call, since part of the argument is in caller's
1955 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1956 getInfo<ARMFunctionInfo>();
1957 if (AFI_Caller->getArgRegsSaveSize())
1960 // If the callee takes no arguments then go on to check the results of the
1962 if (!Outs.empty()) {
1963 // Check if stack adjustment is needed. For now, do not do this if any
1964 // argument is passed on the stack.
1965 SmallVector<CCValAssign, 16> ArgLocs;
1966 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1967 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1968 CCInfo.AnalyzeCallOperands(Outs,
1969 CCAssignFnForNode(CalleeCC, false, isVarArg));
1970 if (CCInfo.getNextStackOffset()) {
1971 MachineFunction &MF = DAG.getMachineFunction();
1973 // Check if the arguments are already laid out in the right way as
1974 // the caller's fixed stack objects.
1975 MachineFrameInfo *MFI = MF.getFrameInfo();
1976 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1977 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1978 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1980 ++i, ++realArgIdx) {
1981 CCValAssign &VA = ArgLocs[i];
1982 EVT RegVT = VA.getLocVT();
1983 SDValue Arg = OutVals[realArgIdx];
1984 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1985 if (VA.getLocInfo() == CCValAssign::Indirect)
1987 if (VA.needsCustom()) {
1988 // f64 and vector types are split into multiple registers or
1989 // register/stack-slot combinations. The types will not match
1990 // the registers; give up on memory f64 refs until we figure
1991 // out what to do about this.
1994 if (!ArgLocs[++i].isRegLoc())
1996 if (RegVT == MVT::v2f64) {
1997 if (!ArgLocs[++i].isRegLoc())
1999 if (!ArgLocs[++i].isRegLoc())
2002 } else if (!VA.isRegLoc()) {
2003 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2015 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2016 MachineFunction &MF, bool isVarArg,
2017 const SmallVectorImpl<ISD::OutputArg> &Outs,
2018 LLVMContext &Context) const {
2019 SmallVector<CCValAssign, 16> RVLocs;
2020 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2021 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2026 ARMTargetLowering::LowerReturn(SDValue Chain,
2027 CallingConv::ID CallConv, bool isVarArg,
2028 const SmallVectorImpl<ISD::OutputArg> &Outs,
2029 const SmallVectorImpl<SDValue> &OutVals,
2030 SDLoc dl, SelectionDAG &DAG) const {
2032 // CCValAssign - represent the assignment of the return value to a location.
2033 SmallVector<CCValAssign, 16> RVLocs;
2035 // CCState - Info about the registers and stack slots.
2036 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2037 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2039 // Analyze outgoing return values.
2040 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2044 SmallVector<SDValue, 4> RetOps;
2045 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2047 // Copy the result values into the output registers.
2048 for (unsigned i = 0, realRVLocIdx = 0;
2050 ++i, ++realRVLocIdx) {
2051 CCValAssign &VA = RVLocs[i];
2052 assert(VA.isRegLoc() && "Can only return in registers!");
2054 SDValue Arg = OutVals[realRVLocIdx];
2056 switch (VA.getLocInfo()) {
2057 default: llvm_unreachable("Unknown loc info!");
2058 case CCValAssign::Full: break;
2059 case CCValAssign::BCvt:
2060 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2064 if (VA.needsCustom()) {
2065 if (VA.getLocVT() == MVT::v2f64) {
2066 // Extract the first half and return it in two registers.
2067 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2068 DAG.getConstant(0, MVT::i32));
2069 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2070 DAG.getVTList(MVT::i32, MVT::i32), Half);
2072 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2073 Flag = Chain.getValue(1);
2074 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2075 VA = RVLocs[++i]; // skip ahead to next loc
2076 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2077 HalfGPRs.getValue(1), Flag);
2078 Flag = Chain.getValue(1);
2079 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2080 VA = RVLocs[++i]; // skip ahead to next loc
2082 // Extract the 2nd half and fall through to handle it as an f64 value.
2083 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2084 DAG.getConstant(1, MVT::i32));
2086 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2088 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2089 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2090 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2091 Flag = Chain.getValue(1);
2092 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2093 VA = RVLocs[++i]; // skip ahead to next loc
2094 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2097 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2099 // Guarantee that all emitted copies are
2100 // stuck together, avoiding something bad.
2101 Flag = Chain.getValue(1);
2102 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2105 // Update chain and glue.
2108 RetOps.push_back(Flag);
2110 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2111 RetOps.data(), RetOps.size());
2114 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2115 if (N->getNumValues() != 1)
2117 if (!N->hasNUsesOfValue(1, 0))
2120 SDValue TCChain = Chain;
2121 SDNode *Copy = *N->use_begin();
2122 if (Copy->getOpcode() == ISD::CopyToReg) {
2123 // If the copy has a glue operand, we conservatively assume it isn't safe to
2124 // perform a tail call.
2125 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2127 TCChain = Copy->getOperand(0);
2128 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2129 SDNode *VMov = Copy;
2130 // f64 returned in a pair of GPRs.
2131 SmallPtrSet<SDNode*, 2> Copies;
2132 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2134 if (UI->getOpcode() != ISD::CopyToReg)
2138 if (Copies.size() > 2)
2141 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2143 SDValue UseChain = UI->getOperand(0);
2144 if (Copies.count(UseChain.getNode()))
2151 } else if (Copy->getOpcode() == ISD::BITCAST) {
2152 // f32 returned in a single GPR.
2153 if (!Copy->hasOneUse())
2155 Copy = *Copy->use_begin();
2156 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2158 TCChain = Copy->getOperand(0);
2163 bool HasRet = false;
2164 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2166 if (UI->getOpcode() != ARMISD::RET_FLAG)
2178 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2179 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2182 if (!CI->isTailCall())
2185 return !Subtarget->isThumb1Only();
2188 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2189 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2190 // one of the above mentioned nodes. It has to be wrapped because otherwise
2191 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2192 // be used to form addressing mode. These wrapped nodes will be selected
2194 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2195 EVT PtrVT = Op.getValueType();
2196 // FIXME there is no actual debug info here
2198 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2200 if (CP->isMachineConstantPoolEntry())
2201 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2202 CP->getAlignment());
2204 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2205 CP->getAlignment());
2206 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2209 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2210 return MachineJumpTableInfo::EK_Inline;
2213 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2214 SelectionDAG &DAG) const {
2215 MachineFunction &MF = DAG.getMachineFunction();
2216 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2217 unsigned ARMPCLabelIndex = 0;
2219 EVT PtrVT = getPointerTy();
2220 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2221 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2223 if (RelocM == Reloc::Static) {
2224 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2226 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2227 ARMPCLabelIndex = AFI->createPICLabelUId();
2228 ARMConstantPoolValue *CPV =
2229 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2230 ARMCP::CPBlockAddress, PCAdj);
2231 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2233 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2234 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2235 MachinePointerInfo::getConstantPool(),
2236 false, false, false, 0);
2237 if (RelocM == Reloc::Static)
2239 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2240 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2243 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2245 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2246 SelectionDAG &DAG) const {
2248 EVT PtrVT = getPointerTy();
2249 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2250 MachineFunction &MF = DAG.getMachineFunction();
2251 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2252 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2253 ARMConstantPoolValue *CPV =
2254 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2255 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2256 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2257 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2258 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2259 MachinePointerInfo::getConstantPool(),
2260 false, false, false, 0);
2261 SDValue Chain = Argument.getValue(1);
2263 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2264 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2266 // call __tls_get_addr.
2269 Entry.Node = Argument;
2270 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2271 Args.push_back(Entry);
2272 // FIXME: is there useful debug info available here?
2273 TargetLowering::CallLoweringInfo CLI(Chain,
2274 (Type *) Type::getInt32Ty(*DAG.getContext()),
2275 false, false, false, false,
2276 0, CallingConv::C, /*isTailCall=*/false,
2277 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2278 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2279 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2280 return CallResult.first;
2283 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2284 // "local exec" model.
2286 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2288 TLSModel::Model model) const {
2289 const GlobalValue *GV = GA->getGlobal();
2292 SDValue Chain = DAG.getEntryNode();
2293 EVT PtrVT = getPointerTy();
2294 // Get the Thread Pointer
2295 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2297 if (model == TLSModel::InitialExec) {
2298 MachineFunction &MF = DAG.getMachineFunction();
2299 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2300 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2301 // Initial exec model.
2302 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2303 ARMConstantPoolValue *CPV =
2304 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2305 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2307 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2308 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2309 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2310 MachinePointerInfo::getConstantPool(),
2311 false, false, false, 0);
2312 Chain = Offset.getValue(1);
2314 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2315 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2317 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2318 MachinePointerInfo::getConstantPool(),
2319 false, false, false, 0);
2322 assert(model == TLSModel::LocalExec);
2323 ARMConstantPoolValue *CPV =
2324 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2325 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2326 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2327 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2328 MachinePointerInfo::getConstantPool(),
2329 false, false, false, 0);
2332 // The address of the thread local variable is the add of the thread
2333 // pointer with the offset of the variable.
2334 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2338 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2339 // TODO: implement the "local dynamic" model
2340 assert(Subtarget->isTargetELF() &&
2341 "TLS not implemented for non-ELF targets");
2342 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2344 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2347 case TLSModel::GeneralDynamic:
2348 case TLSModel::LocalDynamic:
2349 return LowerToTLSGeneralDynamicModel(GA, DAG);
2350 case TLSModel::InitialExec:
2351 case TLSModel::LocalExec:
2352 return LowerToTLSExecModels(GA, DAG, model);
2354 llvm_unreachable("bogus TLS model");
2357 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2358 SelectionDAG &DAG) const {
2359 EVT PtrVT = getPointerTy();
2361 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2362 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2363 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2364 ARMConstantPoolValue *CPV =
2365 ARMConstantPoolConstant::Create(GV,
2366 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2367 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2368 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2369 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2371 MachinePointerInfo::getConstantPool(),
2372 false, false, false, 0);
2373 SDValue Chain = Result.getValue(1);
2374 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2375 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2377 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2378 MachinePointerInfo::getGOT(),
2379 false, false, false, 0);
2383 // If we have T2 ops, we can materialize the address directly via movt/movw
2384 // pair. This is always cheaper.
2385 if (Subtarget->useMovt()) {
2387 // FIXME: Once remat is capable of dealing with instructions with register
2388 // operands, expand this into two nodes.
2389 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2390 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2392 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2393 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2394 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2395 MachinePointerInfo::getConstantPool(),
2396 false, false, false, 0);
2400 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2401 SelectionDAG &DAG) const {
2402 EVT PtrVT = getPointerTy();
2404 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2405 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2407 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2408 // update ARMFastISel::ARMMaterializeGV.
2409 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2411 // FIXME: Once remat is capable of dealing with instructions with register
2412 // operands, expand this into two nodes.
2413 if (RelocM == Reloc::Static)
2414 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2415 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2417 unsigned Wrapper = (RelocM == Reloc::PIC_)
2418 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2419 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2420 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2421 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2422 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2423 MachinePointerInfo::getGOT(),
2424 false, false, false, 0);
2428 unsigned ARMPCLabelIndex = 0;
2430 if (RelocM == Reloc::Static) {
2431 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2433 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2434 ARMPCLabelIndex = AFI->createPICLabelUId();
2435 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2436 ARMConstantPoolValue *CPV =
2437 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2439 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2441 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2443 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2444 MachinePointerInfo::getConstantPool(),
2445 false, false, false, 0);
2446 SDValue Chain = Result.getValue(1);
2448 if (RelocM == Reloc::PIC_) {
2449 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2450 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2453 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2454 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2455 false, false, false, 0);
2460 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2461 SelectionDAG &DAG) const {
2462 assert(Subtarget->isTargetELF() &&
2463 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2464 MachineFunction &MF = DAG.getMachineFunction();
2465 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2466 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2467 EVT PtrVT = getPointerTy();
2469 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2470 ARMConstantPoolValue *CPV =
2471 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2472 ARMPCLabelIndex, PCAdj);
2473 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2474 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2475 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2476 MachinePointerInfo::getConstantPool(),
2477 false, false, false, 0);
2478 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2479 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2483 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2485 SDValue Val = DAG.getConstant(0, MVT::i32);
2486 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2487 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2488 Op.getOperand(1), Val);
2492 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2494 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2495 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2499 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2500 const ARMSubtarget *Subtarget) const {
2501 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2504 default: return SDValue(); // Don't custom lower most intrinsics.
2505 case Intrinsic::arm_thread_pointer: {
2506 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2507 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2509 case Intrinsic::eh_sjlj_lsda: {
2510 MachineFunction &MF = DAG.getMachineFunction();
2511 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2512 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2513 EVT PtrVT = getPointerTy();
2514 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2516 unsigned PCAdj = (RelocM != Reloc::PIC_)
2517 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2518 ARMConstantPoolValue *CPV =
2519 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2520 ARMCP::CPLSDA, PCAdj);
2521 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2522 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2524 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2525 MachinePointerInfo::getConstantPool(),
2526 false, false, false, 0);
2528 if (RelocM == Reloc::PIC_) {
2529 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2530 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2534 case Intrinsic::arm_neon_vmulls:
2535 case Intrinsic::arm_neon_vmullu: {
2536 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2537 ? ARMISD::VMULLs : ARMISD::VMULLu;
2538 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2539 Op.getOperand(1), Op.getOperand(2));
2544 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2545 const ARMSubtarget *Subtarget) {
2546 // FIXME: handle "fence singlethread" more efficiently.
2548 if (!Subtarget->hasDataBarrier()) {
2549 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2550 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2552 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2553 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2554 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2555 DAG.getConstant(0, MVT::i32));
2558 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2559 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2560 unsigned Domain = ARM_MB::ISH;
2561 if (Subtarget->isSwift() && Ord == Release) {
2562 // Swift happens to implement ISHST barriers in a way that's compatible with
2563 // Release semantics but weaker than ISH so we'd be fools not to use
2564 // it. Beware: other processors probably don't!
2565 Domain = ARM_MB::ISHST;
2568 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2569 DAG.getConstant(Domain, MVT::i32));
2572 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2573 const ARMSubtarget *Subtarget) {
2574 // ARM pre v5TE and Thumb1 does not have preload instructions.
2575 if (!(Subtarget->isThumb2() ||
2576 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2577 // Just preserve the chain.
2578 return Op.getOperand(0);
2581 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2583 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2584 // ARMv7 with MP extension has PLDW.
2585 return Op.getOperand(0);
2587 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2588 if (Subtarget->isThumb()) {
2590 isRead = ~isRead & 1;
2591 isData = ~isData & 1;
2594 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2595 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2596 DAG.getConstant(isData, MVT::i32));
2599 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2600 MachineFunction &MF = DAG.getMachineFunction();
2601 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2603 // vastart just stores the address of the VarArgsFrameIndex slot into the
2604 // memory location argument.
2606 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2607 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2608 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2609 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2610 MachinePointerInfo(SV), false, false, 0);
2614 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2615 SDValue &Root, SelectionDAG &DAG,
2617 MachineFunction &MF = DAG.getMachineFunction();
2618 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2620 const TargetRegisterClass *RC;
2621 if (AFI->isThumb1OnlyFunction())
2622 RC = &ARM::tGPRRegClass;
2624 RC = &ARM::GPRRegClass;
2626 // Transform the arguments stored in physical registers into virtual ones.
2627 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2628 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2631 if (NextVA.isMemLoc()) {
2632 MachineFrameInfo *MFI = MF.getFrameInfo();
2633 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2635 // Create load node to retrieve arguments from the stack.
2636 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2637 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2638 MachinePointerInfo::getFixedStack(FI),
2639 false, false, false, 0);
2641 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2642 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2645 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2649 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2650 unsigned InRegsParamRecordIdx,
2652 unsigned &ArgRegsSize,
2653 unsigned &ArgRegsSaveSize)
2656 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2657 unsigned RBegin, REnd;
2658 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2659 NumGPRs = REnd - RBegin;
2661 unsigned int firstUnalloced;
2662 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2663 sizeof(GPRArgRegs) /
2664 sizeof(GPRArgRegs[0]));
2665 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2668 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2669 ArgRegsSize = NumGPRs * 4;
2671 // If parameter is split between stack and GPRs...
2672 if (NumGPRs && Align == 8 &&
2673 (ArgRegsSize < ArgSize ||
2674 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2675 // Add padding for part of param recovered from GPRs, so
2676 // its last byte must be at address K*8 - 1.
2677 // We need to do it, since remained (stack) part of parameter has
2678 // stack alignment, and we need to "attach" "GPRs head" without gaps
2681 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2682 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2684 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2686 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2687 (ArgRegsSize + AFI->getArgRegsSaveSize());
2688 ArgRegsSaveSize = ArgRegsSize + Padding;
2690 // We don't need to extend regs save size for byval parameters if they
2691 // are passed via GPRs only.
2692 ArgRegsSaveSize = ArgRegsSize;
2695 // The remaining GPRs hold either the beginning of variable-argument
2696 // data, or the beginning of an aggregate passed by value (usually
2697 // byval). Either way, we allocate stack slots adjacent to the data
2698 // provided by our caller, and store the unallocated registers there.
2699 // If this is a variadic function, the va_list pointer will begin with
2700 // these values; otherwise, this reassembles a (byval) structure that
2701 // was split between registers and memory.
2702 // Return: The frame index registers were stored into.
2704 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2705 SDLoc dl, SDValue &Chain,
2706 const Value *OrigArg,
2707 unsigned InRegsParamRecordIdx,
2708 unsigned OffsetFromOrigArg,
2711 bool ForceMutable) const {
2713 // Currently, two use-cases possible:
2714 // Case #1. Non var-args function, and we meet first byval parameter.
2715 // Setup first unallocated register as first byval register;
2716 // eat all remained registers
2717 // (these two actions are performed by HandleByVal method).
2718 // Then, here, we initialize stack frame with
2719 // "store-reg" instructions.
2720 // Case #2. Var-args function, that doesn't contain byval parameters.
2721 // The same: eat all remained unallocated registers,
2722 // initialize stack frame.
2724 MachineFunction &MF = DAG.getMachineFunction();
2725 MachineFrameInfo *MFI = MF.getFrameInfo();
2726 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2727 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2728 unsigned RBegin, REnd;
2729 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2730 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2731 firstRegToSaveIndex = RBegin - ARM::R0;
2732 lastRegToSaveIndex = REnd - ARM::R0;
2734 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2735 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2736 lastRegToSaveIndex = 4;
2739 unsigned ArgRegsSize, ArgRegsSaveSize;
2740 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2741 ArgRegsSize, ArgRegsSaveSize);
2743 // Store any by-val regs to their spots on the stack so that they may be
2744 // loaded by deferencing the result of formal parameter pointer or va_next.
2745 // Note: once stack area for byval/varargs registers
2746 // was initialized, it can't be initialized again.
2747 if (ArgRegsSaveSize) {
2749 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2752 assert(AFI->getStoredByValParamsPadding() == 0 &&
2753 "The only parameter may be padded.");
2754 AFI->setStoredByValParamsPadding(Padding);
2757 int FrameIndex = MFI->CreateFixedObject(
2759 Padding + ArgOffset,
2761 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2763 SmallVector<SDValue, 4> MemOps;
2764 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2765 ++firstRegToSaveIndex, ++i) {
2766 const TargetRegisterClass *RC;
2767 if (AFI->isThumb1OnlyFunction())
2768 RC = &ARM::tGPRRegClass;
2770 RC = &ARM::GPRRegClass;
2772 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2773 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2775 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2776 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2778 MemOps.push_back(Store);
2779 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2780 DAG.getConstant(4, getPointerTy()));
2783 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2785 if (!MemOps.empty())
2786 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2787 &MemOps[0], MemOps.size());
2790 // This will point to the next argument passed via stack.
2791 return MFI->CreateFixedObject(
2792 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2795 // Setup stack frame, the va_list pointer will start from.
2797 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2798 SDLoc dl, SDValue &Chain,
2800 bool ForceMutable) const {
2801 MachineFunction &MF = DAG.getMachineFunction();
2802 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2804 // Try to store any remaining integer argument regs
2805 // to their spots on the stack so that they may be loaded by deferencing
2806 // the result of va_next.
2807 // If there is no regs to be stored, just point address after last
2808 // argument passed via stack.
2810 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2811 0, ArgOffset, 0, ForceMutable);
2813 AFI->setVarArgsFrameIndex(FrameIndex);
2817 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2818 CallingConv::ID CallConv, bool isVarArg,
2819 const SmallVectorImpl<ISD::InputArg>
2821 SDLoc dl, SelectionDAG &DAG,
2822 SmallVectorImpl<SDValue> &InVals)
2824 MachineFunction &MF = DAG.getMachineFunction();
2825 MachineFrameInfo *MFI = MF.getFrameInfo();
2827 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2829 // Assign locations to all of the incoming arguments.
2830 SmallVector<CCValAssign, 16> ArgLocs;
2831 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2832 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2833 CCInfo.AnalyzeFormalArguments(Ins,
2834 CCAssignFnForNode(CallConv, /* Return*/ false,
2837 SmallVector<SDValue, 16> ArgValues;
2838 int lastInsIndex = -1;
2840 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2841 unsigned CurArgIdx = 0;
2843 // Initially ArgRegsSaveSize is zero.
2844 // Then we increase this value each time we meet byval parameter.
2845 // We also increase this value in case of varargs function.
2846 AFI->setArgRegsSaveSize(0);
2848 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2849 CCValAssign &VA = ArgLocs[i];
2850 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2851 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2852 // Arguments stored in registers.
2853 if (VA.isRegLoc()) {
2854 EVT RegVT = VA.getLocVT();
2856 if (VA.needsCustom()) {
2857 // f64 and vector types are split up into multiple registers or
2858 // combinations of registers and stack slots.
2859 if (VA.getLocVT() == MVT::v2f64) {
2860 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2862 VA = ArgLocs[++i]; // skip ahead to next loc
2864 if (VA.isMemLoc()) {
2865 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2866 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2867 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2868 MachinePointerInfo::getFixedStack(FI),
2869 false, false, false, 0);
2871 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2874 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2875 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2876 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2877 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2878 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2880 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2883 const TargetRegisterClass *RC;
2885 if (RegVT == MVT::f32)
2886 RC = &ARM::SPRRegClass;
2887 else if (RegVT == MVT::f64)
2888 RC = &ARM::DPRRegClass;
2889 else if (RegVT == MVT::v2f64)
2890 RC = &ARM::QPRRegClass;
2891 else if (RegVT == MVT::i32)
2892 RC = AFI->isThumb1OnlyFunction() ?
2893 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2894 (const TargetRegisterClass*)&ARM::GPRRegClass;
2896 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2898 // Transform the arguments in physical registers into virtual ones.
2899 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2900 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2903 // If this is an 8 or 16-bit value, it is really passed promoted
2904 // to 32 bits. Insert an assert[sz]ext to capture this, then
2905 // truncate to the right size.
2906 switch (VA.getLocInfo()) {
2907 default: llvm_unreachable("Unknown loc info!");
2908 case CCValAssign::Full: break;
2909 case CCValAssign::BCvt:
2910 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2912 case CCValAssign::SExt:
2913 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2914 DAG.getValueType(VA.getValVT()));
2915 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2917 case CCValAssign::ZExt:
2918 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2919 DAG.getValueType(VA.getValVT()));
2920 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2924 InVals.push_back(ArgValue);
2926 } else { // VA.isRegLoc()
2929 assert(VA.isMemLoc());
2930 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2932 int index = ArgLocs[i].getValNo();
2934 // Some Ins[] entries become multiple ArgLoc[] entries.
2935 // Process them only once.
2936 if (index != lastInsIndex)
2938 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2939 // FIXME: For now, all byval parameter objects are marked mutable.
2940 // This can be changed with more analysis.
2941 // In case of tail call optimization mark all arguments mutable.
2942 // Since they could be overwritten by lowering of arguments in case of
2944 if (Flags.isByVal()) {
2945 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2946 int FrameIndex = StoreByValRegs(
2947 CCInfo, DAG, dl, Chain, CurOrigArg,
2949 Ins[VA.getValNo()].PartOffset,
2950 VA.getLocMemOffset(),
2951 Flags.getByValSize(),
2952 true /*force mutable frames*/);
2953 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2954 CCInfo.nextInRegsParam();
2956 unsigned FIOffset = VA.getLocMemOffset() +
2957 AFI->getStoredByValParamsPadding();
2958 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2961 // Create load nodes to retrieve arguments from the stack.
2962 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2963 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2964 MachinePointerInfo::getFixedStack(FI),
2965 false, false, false, 0));
2967 lastInsIndex = index;
2974 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2975 CCInfo.getNextStackOffset());
2980 /// isFloatingPointZero - Return true if this is +0.0.
2981 static bool isFloatingPointZero(SDValue Op) {
2982 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2983 return CFP->getValueAPF().isPosZero();
2984 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2985 // Maybe this has already been legalized into the constant pool?
2986 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2987 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2988 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2989 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2990 return CFP->getValueAPF().isPosZero();
2996 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2997 /// the given operands.
2999 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3000 SDValue &ARMcc, SelectionDAG &DAG,
3002 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3003 unsigned C = RHSC->getZExtValue();
3004 if (!isLegalICmpImmediate(C)) {
3005 // Constant does not fit, try adjusting it by one?
3010 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3011 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3012 RHS = DAG.getConstant(C-1, MVT::i32);
3017 if (C != 0 && isLegalICmpImmediate(C-1)) {
3018 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3019 RHS = DAG.getConstant(C-1, MVT::i32);
3024 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3025 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3026 RHS = DAG.getConstant(C+1, MVT::i32);
3031 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3032 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3033 RHS = DAG.getConstant(C+1, MVT::i32);
3040 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3041 ARMISD::NodeType CompareType;
3044 CompareType = ARMISD::CMP;
3049 CompareType = ARMISD::CMPZ;
3052 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3053 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3056 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3058 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3061 if (!isFloatingPointZero(RHS))
3062 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3064 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3065 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3068 /// duplicateCmp - Glue values can have only one use, so this function
3069 /// duplicates a comparison node.
3071 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3072 unsigned Opc = Cmp.getOpcode();
3074 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3075 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3077 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3078 Cmp = Cmp.getOperand(0);
3079 Opc = Cmp.getOpcode();
3080 if (Opc == ARMISD::CMPFP)
3081 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3083 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3084 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3086 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3089 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3090 SDValue Cond = Op.getOperand(0);
3091 SDValue SelectTrue = Op.getOperand(1);
3092 SDValue SelectFalse = Op.getOperand(2);
3097 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3098 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3100 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3101 const ConstantSDNode *CMOVTrue =
3102 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3103 const ConstantSDNode *CMOVFalse =
3104 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3106 if (CMOVTrue && CMOVFalse) {
3107 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3108 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3112 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3114 False = SelectFalse;
3115 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3120 if (True.getNode() && False.getNode()) {
3121 EVT VT = Op.getValueType();
3122 SDValue ARMcc = Cond.getOperand(2);
3123 SDValue CCR = Cond.getOperand(3);
3124 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3125 assert(True.getValueType() == VT);
3126 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3131 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3132 // undefined bits before doing a full-word comparison with zero.
3133 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3134 DAG.getConstant(1, Cond.getValueType()));
3136 return DAG.getSelectCC(dl, Cond,
3137 DAG.getConstant(0, Cond.getValueType()),
3138 SelectTrue, SelectFalse, ISD::SETNE);
3141 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3142 EVT VT = Op.getValueType();
3143 SDValue LHS = Op.getOperand(0);
3144 SDValue RHS = Op.getOperand(1);
3145 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3146 SDValue TrueVal = Op.getOperand(2);
3147 SDValue FalseVal = Op.getOperand(3);
3150 if (LHS.getValueType() == MVT::i32) {
3152 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3153 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3154 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3157 ARMCC::CondCodes CondCode, CondCode2;
3158 FPCCToARMCC(CC, CondCode, CondCode2);
3160 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3161 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3162 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3163 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3165 if (CondCode2 != ARMCC::AL) {
3166 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3167 // FIXME: Needs another CMP because flag can have but one use.
3168 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3169 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3170 Result, TrueVal, ARMcc2, CCR, Cmp2);
3175 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3176 /// to morph to an integer compare sequence.
3177 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3178 const ARMSubtarget *Subtarget) {
3179 SDNode *N = Op.getNode();
3180 if (!N->hasOneUse())
3181 // Otherwise it requires moving the value from fp to integer registers.
3183 if (!N->getNumValues())
3185 EVT VT = Op.getValueType();
3186 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3187 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3188 // vmrs are very slow, e.g. cortex-a8.
3191 if (isFloatingPointZero(Op)) {
3195 return ISD::isNormalLoad(N);
3198 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3199 if (isFloatingPointZero(Op))
3200 return DAG.getConstant(0, MVT::i32);
3202 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3203 return DAG.getLoad(MVT::i32, SDLoc(Op),
3204 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3205 Ld->isVolatile(), Ld->isNonTemporal(),
3206 Ld->isInvariant(), Ld->getAlignment());
3208 llvm_unreachable("Unknown VFP cmp argument!");
3211 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3212 SDValue &RetVal1, SDValue &RetVal2) {
3213 if (isFloatingPointZero(Op)) {
3214 RetVal1 = DAG.getConstant(0, MVT::i32);
3215 RetVal2 = DAG.getConstant(0, MVT::i32);
3219 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3220 SDValue Ptr = Ld->getBasePtr();
3221 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3222 Ld->getChain(), Ptr,
3223 Ld->getPointerInfo(),
3224 Ld->isVolatile(), Ld->isNonTemporal(),
3225 Ld->isInvariant(), Ld->getAlignment());
3227 EVT PtrType = Ptr.getValueType();
3228 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3229 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3230 PtrType, Ptr, DAG.getConstant(4, PtrType));
3231 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3232 Ld->getChain(), NewPtr,
3233 Ld->getPointerInfo().getWithOffset(4),
3234 Ld->isVolatile(), Ld->isNonTemporal(),
3235 Ld->isInvariant(), NewAlign);
3239 llvm_unreachable("Unknown VFP cmp argument!");
3242 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3243 /// f32 and even f64 comparisons to integer ones.
3245 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3246 SDValue Chain = Op.getOperand(0);
3247 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3248 SDValue LHS = Op.getOperand(2);
3249 SDValue RHS = Op.getOperand(3);
3250 SDValue Dest = Op.getOperand(4);
3253 bool LHSSeenZero = false;
3254 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3255 bool RHSSeenZero = false;
3256 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3257 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3258 // If unsafe fp math optimization is enabled and there are no other uses of
3259 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3260 // to an integer comparison.
3261 if (CC == ISD::SETOEQ)
3263 else if (CC == ISD::SETUNE)
3266 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3268 if (LHS.getValueType() == MVT::f32) {
3269 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3270 bitcastf32Toi32(LHS, DAG), Mask);
3271 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3272 bitcastf32Toi32(RHS, DAG), Mask);
3273 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3274 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3275 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3276 Chain, Dest, ARMcc, CCR, Cmp);
3281 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3282 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3283 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3284 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3285 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3286 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3287 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3288 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3289 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3295 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3296 SDValue Chain = Op.getOperand(0);
3297 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3298 SDValue LHS = Op.getOperand(2);
3299 SDValue RHS = Op.getOperand(3);
3300 SDValue Dest = Op.getOperand(4);
3303 if (LHS.getValueType() == MVT::i32) {
3305 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3306 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3307 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3308 Chain, Dest, ARMcc, CCR, Cmp);
3311 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3313 if (getTargetMachine().Options.UnsafeFPMath &&
3314 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3315 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3316 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3317 if (Result.getNode())
3321 ARMCC::CondCodes CondCode, CondCode2;
3322 FPCCToARMCC(CC, CondCode, CondCode2);
3324 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3325 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3326 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3327 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3328 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3329 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3330 if (CondCode2 != ARMCC::AL) {
3331 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3332 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3333 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3338 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3339 SDValue Chain = Op.getOperand(0);
3340 SDValue Table = Op.getOperand(1);
3341 SDValue Index = Op.getOperand(2);
3344 EVT PTy = getPointerTy();
3345 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3346 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3347 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3348 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3349 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3350 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3351 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3352 if (Subtarget->isThumb2()) {
3353 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3354 // which does another jump to the destination. This also makes it easier
3355 // to translate it to TBB / TBH later.
3356 // FIXME: This might not work if the function is extremely large.
3357 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3358 Addr, Op.getOperand(2), JTI, UId);
3360 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3361 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3362 MachinePointerInfo::getJumpTable(),
3363 false, false, false, 0);
3364 Chain = Addr.getValue(1);
3365 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3366 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3368 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3369 MachinePointerInfo::getJumpTable(),
3370 false, false, false, 0);
3371 Chain = Addr.getValue(1);
3372 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3376 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3377 EVT VT = Op.getValueType();
3380 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3381 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3383 return DAG.UnrollVectorOp(Op.getNode());
3386 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3387 "Invalid type for custom lowering!");
3388 if (VT != MVT::v4i16)
3389 return DAG.UnrollVectorOp(Op.getNode());
3391 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3392 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3395 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3396 EVT VT = Op.getValueType();
3398 return LowerVectorFP_TO_INT(Op, DAG);
3403 switch (Op.getOpcode()) {
3404 default: llvm_unreachable("Invalid opcode!");
3405 case ISD::FP_TO_SINT:
3406 Opc = ARMISD::FTOSI;
3408 case ISD::FP_TO_UINT:
3409 Opc = ARMISD::FTOUI;
3412 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3413 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3416 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3417 EVT VT = Op.getValueType();
3420 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3421 if (VT.getVectorElementType() == MVT::f32)
3423 return DAG.UnrollVectorOp(Op.getNode());
3426 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3427 "Invalid type for custom lowering!");
3428 if (VT != MVT::v4f32)
3429 return DAG.UnrollVectorOp(Op.getNode());
3433 switch (Op.getOpcode()) {
3434 default: llvm_unreachable("Invalid opcode!");
3435 case ISD::SINT_TO_FP:
3436 CastOpc = ISD::SIGN_EXTEND;
3437 Opc = ISD::SINT_TO_FP;
3439 case ISD::UINT_TO_FP:
3440 CastOpc = ISD::ZERO_EXTEND;
3441 Opc = ISD::UINT_TO_FP;
3445 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3446 return DAG.getNode(Opc, dl, VT, Op);
3449 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3450 EVT VT = Op.getValueType();
3452 return LowerVectorINT_TO_FP(Op, DAG);
3457 switch (Op.getOpcode()) {
3458 default: llvm_unreachable("Invalid opcode!");
3459 case ISD::SINT_TO_FP:
3460 Opc = ARMISD::SITOF;
3462 case ISD::UINT_TO_FP:
3463 Opc = ARMISD::UITOF;
3467 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3468 return DAG.getNode(Opc, dl, VT, Op);
3471 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3472 // Implement fcopysign with a fabs and a conditional fneg.
3473 SDValue Tmp0 = Op.getOperand(0);
3474 SDValue Tmp1 = Op.getOperand(1);
3476 EVT VT = Op.getValueType();
3477 EVT SrcVT = Tmp1.getValueType();
3478 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3479 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3480 bool UseNEON = !InGPR && Subtarget->hasNEON();
3483 // Use VBSL to copy the sign bit.
3484 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3485 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3486 DAG.getTargetConstant(EncodedVal, MVT::i32));
3487 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3489 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3490 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3491 DAG.getConstant(32, MVT::i32));
3492 else /*if (VT == MVT::f32)*/
3493 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3494 if (SrcVT == MVT::f32) {
3495 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3497 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3498 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3499 DAG.getConstant(32, MVT::i32));
3500 } else if (VT == MVT::f32)
3501 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3502 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3503 DAG.getConstant(32, MVT::i32));
3504 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3505 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3507 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3509 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3510 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3511 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3513 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3514 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3515 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3516 if (VT == MVT::f32) {
3517 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3518 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3519 DAG.getConstant(0, MVT::i32));
3521 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3527 // Bitcast operand 1 to i32.
3528 if (SrcVT == MVT::f64)
3529 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3530 &Tmp1, 1).getValue(1);
3531 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3533 // Or in the signbit with integer operations.
3534 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3535 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3536 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3537 if (VT == MVT::f32) {
3538 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3539 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3540 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3541 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3544 // f64: Or the high part with signbit and then combine two parts.
3545 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3547 SDValue Lo = Tmp0.getValue(0);
3548 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3549 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3550 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3553 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3554 MachineFunction &MF = DAG.getMachineFunction();
3555 MachineFrameInfo *MFI = MF.getFrameInfo();
3556 MFI->setReturnAddressIsTaken(true);
3558 EVT VT = Op.getValueType();
3560 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3562 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3563 SDValue Offset = DAG.getConstant(4, MVT::i32);
3564 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3565 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3566 MachinePointerInfo(), false, false, false, 0);
3569 // Return LR, which contains the return address. Mark it an implicit live-in.
3570 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3571 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3574 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3575 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3576 MFI->setFrameAddressIsTaken(true);
3578 EVT VT = Op.getValueType();
3579 SDLoc dl(Op); // FIXME probably not meaningful
3580 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3581 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3582 ? ARM::R7 : ARM::R11;
3583 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3585 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3586 MachinePointerInfo(),
3587 false, false, false, 0);
3591 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3592 /// and size(DestVec) > 128-bits.
3593 /// This is achieved by doing the one extension from the SrcVec, splitting the
3594 /// result, extending these parts, and then concatenating these into the
3596 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3597 SDValue Op = N->getOperand(0);
3598 EVT SrcVT = Op.getValueType();
3599 EVT DestVT = N->getValueType(0);
3601 assert(DestVT.getSizeInBits() > 128 &&
3602 "Custom sext/zext expansion needs >128-bit vector.");
3603 // If this is a normal length extension, use the default expansion.
3604 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3605 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3609 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3610 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3611 unsigned NumElts = SrcVT.getVectorNumElements();
3612 LLVMContext &Ctx = *DAG.getContext();
3613 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3615 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3617 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3619 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3622 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3623 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3624 DAG.getIntPtrConstant(0));
3625 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3626 DAG.getIntPtrConstant(NumElts/2));
3627 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3628 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3629 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3632 /// ExpandBITCAST - If the target supports VFP, this function is called to
3633 /// expand a bit convert where either the source or destination type is i64 to
3634 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3635 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3636 /// vectors), since the legalizer won't know what to do with that.
3637 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3640 SDValue Op = N->getOperand(0);
3642 // This function is only supposed to be called for i64 types, either as the
3643 // source or destination of the bit convert.
3644 EVT SrcVT = Op.getValueType();
3645 EVT DstVT = N->getValueType(0);
3646 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3647 "ExpandBITCAST called for non-i64 type");
3649 // Turn i64->f64 into VMOVDRR.
3650 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3651 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3652 DAG.getConstant(0, MVT::i32));
3653 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3654 DAG.getConstant(1, MVT::i32));
3655 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3656 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3659 // Turn f64->i64 into VMOVRRD.
3660 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3661 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3662 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3663 // Merge the pieces into a single i64 value.
3664 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3670 /// getZeroVector - Returns a vector of specified type with all zero elements.
3671 /// Zero vectors are used to represent vector negation and in those cases
3672 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3673 /// not support i64 elements, so sometimes the zero vectors will need to be
3674 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3676 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3677 assert(VT.isVector() && "Expected a vector type");
3678 // The canonical modified immediate encoding of a zero vector is....0!
3679 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3680 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3681 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3682 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3685 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3686 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3687 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3688 SelectionDAG &DAG) const {
3689 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3690 EVT VT = Op.getValueType();
3691 unsigned VTBits = VT.getSizeInBits();
3693 SDValue ShOpLo = Op.getOperand(0);
3694 SDValue ShOpHi = Op.getOperand(1);
3695 SDValue ShAmt = Op.getOperand(2);
3697 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3699 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3701 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3702 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3703 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3704 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3705 DAG.getConstant(VTBits, MVT::i32));
3706 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3707 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3708 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3710 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3711 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3713 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3714 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3717 SDValue Ops[2] = { Lo, Hi };
3718 return DAG.getMergeValues(Ops, 2, dl);
3721 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3722 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3723 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3724 SelectionDAG &DAG) const {
3725 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3726 EVT VT = Op.getValueType();
3727 unsigned VTBits = VT.getSizeInBits();
3729 SDValue ShOpLo = Op.getOperand(0);
3730 SDValue ShOpHi = Op.getOperand(1);
3731 SDValue ShAmt = Op.getOperand(2);
3734 assert(Op.getOpcode() == ISD::SHL_PARTS);
3735 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3736 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3737 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3738 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3739 DAG.getConstant(VTBits, MVT::i32));
3740 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3741 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3743 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3744 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3745 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3747 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3748 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3751 SDValue Ops[2] = { Lo, Hi };
3752 return DAG.getMergeValues(Ops, 2, dl);
3755 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3756 SelectionDAG &DAG) const {
3757 // The rounding mode is in bits 23:22 of the FPSCR.
3758 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3759 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3760 // so that the shift + and get folded into a bitfield extract.
3762 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3763 DAG.getConstant(Intrinsic::arm_get_fpscr,
3765 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3766 DAG.getConstant(1U << 22, MVT::i32));
3767 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3768 DAG.getConstant(22, MVT::i32));
3769 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3770 DAG.getConstant(3, MVT::i32));
3773 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3774 const ARMSubtarget *ST) {
3775 EVT VT = N->getValueType(0);
3778 if (!ST->hasV6T2Ops())
3781 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3782 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3785 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3786 /// for each 16-bit element from operand, repeated. The basic idea is to
3787 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3789 /// Trace for v4i16:
3790 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3791 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3792 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3793 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3794 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3795 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3796 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3797 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3798 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3799 EVT VT = N->getValueType(0);
3802 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3803 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3804 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3805 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3806 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3807 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3810 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3811 /// bit-count for each 16-bit element from the operand. We need slightly
3812 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3813 /// 64/128-bit registers.
3815 /// Trace for v4i16:
3816 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3817 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3818 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3819 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3820 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3821 EVT VT = N->getValueType(0);
3824 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3825 if (VT.is64BitVector()) {
3826 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3827 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3828 DAG.getIntPtrConstant(0));
3830 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3831 BitCounts, DAG.getIntPtrConstant(0));
3832 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3836 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3837 /// bit-count for each 32-bit element from the operand. The idea here is
3838 /// to split the vector into 16-bit elements, leverage the 16-bit count
3839 /// routine, and then combine the results.
3841 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3842 /// input = [v0 v1 ] (vi: 32-bit elements)
3843 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3844 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3845 /// vrev: N0 = [k1 k0 k3 k2 ]
3847 /// N1 =+[k1 k0 k3 k2 ]
3849 /// N2 =+[k1 k3 k0 k2 ]
3851 /// Extended =+[k1 k3 k0 k2 ]
3853 /// Extracted=+[k1 k3 ]
3855 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3856 EVT VT = N->getValueType(0);
3859 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3861 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3862 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3863 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3864 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3865 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3867 if (VT.is64BitVector()) {
3868 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3869 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3870 DAG.getIntPtrConstant(0));
3872 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3873 DAG.getIntPtrConstant(0));
3874 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3878 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3879 const ARMSubtarget *ST) {
3880 EVT VT = N->getValueType(0);
3882 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3883 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3884 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3885 "Unexpected type for custom ctpop lowering");
3887 if (VT.getVectorElementType() == MVT::i32)
3888 return lowerCTPOP32BitElements(N, DAG);
3890 return lowerCTPOP16BitElements(N, DAG);
3893 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3894 const ARMSubtarget *ST) {
3895 EVT VT = N->getValueType(0);
3901 // Lower vector shifts on NEON to use VSHL.
3902 assert(ST->hasNEON() && "unexpected vector shift");
3904 // Left shifts translate directly to the vshiftu intrinsic.
3905 if (N->getOpcode() == ISD::SHL)
3906 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3907 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3908 N->getOperand(0), N->getOperand(1));
3910 assert((N->getOpcode() == ISD::SRA ||
3911 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3913 // NEON uses the same intrinsics for both left and right shifts. For
3914 // right shifts, the shift amounts are negative, so negate the vector of
3916 EVT ShiftVT = N->getOperand(1).getValueType();
3917 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3918 getZeroVector(ShiftVT, DAG, dl),
3920 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3921 Intrinsic::arm_neon_vshifts :
3922 Intrinsic::arm_neon_vshiftu);
3923 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3924 DAG.getConstant(vshiftInt, MVT::i32),
3925 N->getOperand(0), NegatedCount);
3928 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3929 const ARMSubtarget *ST) {
3930 EVT VT = N->getValueType(0);
3933 // We can get here for a node like i32 = ISD::SHL i32, i64
3937 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3938 "Unknown shift to lower!");
3940 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3941 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3942 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3945 // If we are in thumb mode, we don't have RRX.
3946 if (ST->isThumb1Only()) return SDValue();
3948 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3949 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3950 DAG.getConstant(0, MVT::i32));
3951 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3952 DAG.getConstant(1, MVT::i32));
3954 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3955 // captures the result into a carry flag.
3956 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3957 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3959 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3960 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3962 // Merge the pieces into a single i64 value.
3963 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3966 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3967 SDValue TmpOp0, TmpOp1;
3968 bool Invert = false;
3972 SDValue Op0 = Op.getOperand(0);
3973 SDValue Op1 = Op.getOperand(1);
3974 SDValue CC = Op.getOperand(2);
3975 EVT VT = Op.getValueType();
3976 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3979 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3980 switch (SetCCOpcode) {
3981 default: llvm_unreachable("Illegal FP comparison");
3983 case ISD::SETNE: Invert = true; // Fallthrough
3985 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3987 case ISD::SETLT: Swap = true; // Fallthrough
3989 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3991 case ISD::SETLE: Swap = true; // Fallthrough
3993 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3994 case ISD::SETUGE: Swap = true; // Fallthrough
3995 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3996 case ISD::SETUGT: Swap = true; // Fallthrough
3997 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3998 case ISD::SETUEQ: Invert = true; // Fallthrough
4000 // Expand this to (OLT | OGT).
4004 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4005 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4007 case ISD::SETUO: Invert = true; // Fallthrough
4009 // Expand this to (OLT | OGE).
4013 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4014 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4018 // Integer comparisons.
4019 switch (SetCCOpcode) {
4020 default: llvm_unreachable("Illegal integer comparison");
4021 case ISD::SETNE: Invert = true;
4022 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4023 case ISD::SETLT: Swap = true;
4024 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4025 case ISD::SETLE: Swap = true;
4026 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4027 case ISD::SETULT: Swap = true;
4028 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4029 case ISD::SETULE: Swap = true;
4030 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4033 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4034 if (Opc == ARMISD::VCEQ) {
4037 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4039 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4042 // Ignore bitconvert.
4043 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4044 AndOp = AndOp.getOperand(0);
4046 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4048 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4049 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4056 std::swap(Op0, Op1);
4058 // If one of the operands is a constant vector zero, attempt to fold the
4059 // comparison to a specialized compare-against-zero form.
4061 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4063 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4064 if (Opc == ARMISD::VCGE)
4065 Opc = ARMISD::VCLEZ;
4066 else if (Opc == ARMISD::VCGT)
4067 Opc = ARMISD::VCLTZ;
4072 if (SingleOp.getNode()) {
4075 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4077 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4079 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4081 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4083 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4085 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4088 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4092 Result = DAG.getNOT(dl, Result, VT);
4097 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4098 /// valid vector constant for a NEON instruction with a "modified immediate"
4099 /// operand (e.g., VMOV). If so, return the encoded value.
4100 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4101 unsigned SplatBitSize, SelectionDAG &DAG,
4102 EVT &VT, bool is128Bits, NEONModImmType type) {
4103 unsigned OpCmode, Imm;
4105 // SplatBitSize is set to the smallest size that splats the vector, so a
4106 // zero vector will always have SplatBitSize == 8. However, NEON modified
4107 // immediate instructions others than VMOV do not support the 8-bit encoding
4108 // of a zero vector, and the default encoding of zero is supposed to be the
4113 switch (SplatBitSize) {
4115 if (type != VMOVModImm)
4117 // Any 1-byte value is OK. Op=0, Cmode=1110.
4118 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4121 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4125 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4126 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4127 if ((SplatBits & ~0xff) == 0) {
4128 // Value = 0x00nn: Op=x, Cmode=100x.
4133 if ((SplatBits & ~0xff00) == 0) {
4134 // Value = 0xnn00: Op=x, Cmode=101x.
4136 Imm = SplatBits >> 8;
4142 // NEON's 32-bit VMOV supports splat values where:
4143 // * only one byte is nonzero, or
4144 // * the least significant byte is 0xff and the second byte is nonzero, or
4145 // * the least significant 2 bytes are 0xff and the third is nonzero.
4146 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4147 if ((SplatBits & ~0xff) == 0) {
4148 // Value = 0x000000nn: Op=x, Cmode=000x.
4153 if ((SplatBits & ~0xff00) == 0) {
4154 // Value = 0x0000nn00: Op=x, Cmode=001x.
4156 Imm = SplatBits >> 8;
4159 if ((SplatBits & ~0xff0000) == 0) {
4160 // Value = 0x00nn0000: Op=x, Cmode=010x.
4162 Imm = SplatBits >> 16;
4165 if ((SplatBits & ~0xff000000) == 0) {
4166 // Value = 0xnn000000: Op=x, Cmode=011x.
4168 Imm = SplatBits >> 24;
4172 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4173 if (type == OtherModImm) return SDValue();
4175 if ((SplatBits & ~0xffff) == 0 &&
4176 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4177 // Value = 0x0000nnff: Op=x, Cmode=1100.
4179 Imm = SplatBits >> 8;
4184 if ((SplatBits & ~0xffffff) == 0 &&
4185 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4186 // Value = 0x00nnffff: Op=x, Cmode=1101.
4188 Imm = SplatBits >> 16;
4189 SplatBits |= 0xffff;
4193 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4194 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4195 // VMOV.I32. A (very) minor optimization would be to replicate the value
4196 // and fall through here to test for a valid 64-bit splat. But, then the
4197 // caller would also need to check and handle the change in size.
4201 if (type != VMOVModImm)
4203 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4204 uint64_t BitMask = 0xff;
4206 unsigned ImmMask = 1;
4208 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4209 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4212 } else if ((SplatBits & BitMask) != 0) {
4218 // Op=1, Cmode=1110.
4221 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4226 llvm_unreachable("unexpected size for isNEONModifiedImm");
4229 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4230 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4233 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4234 const ARMSubtarget *ST) const {
4235 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4238 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4239 assert(Op.getValueType() == MVT::f32 &&
4240 "ConstantFP custom lowering should only occur for f32.");
4242 // Try splatting with a VMOV.f32...
4243 APFloat FPVal = CFP->getValueAPF();
4244 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4247 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4248 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4250 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4251 DAG.getConstant(0, MVT::i32));
4254 // If that fails, try a VMOV.i32
4256 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4257 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4259 if (NewVal != SDValue()) {
4261 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4263 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4265 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4266 DAG.getConstant(0, MVT::i32));
4269 // Finally, try a VMVN.i32
4270 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4272 if (NewVal != SDValue()) {
4274 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4275 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4277 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4278 DAG.getConstant(0, MVT::i32));
4284 // check if an VEXT instruction can handle the shuffle mask when the
4285 // vector sources of the shuffle are the same.
4286 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4287 unsigned NumElts = VT.getVectorNumElements();
4289 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4295 // If this is a VEXT shuffle, the immediate value is the index of the first
4296 // element. The other shuffle indices must be the successive elements after
4298 unsigned ExpectedElt = Imm;
4299 for (unsigned i = 1; i < NumElts; ++i) {
4300 // Increment the expected index. If it wraps around, just follow it
4301 // back to index zero and keep going.
4303 if (ExpectedElt == NumElts)
4306 if (M[i] < 0) continue; // ignore UNDEF indices
4307 if (ExpectedElt != static_cast<unsigned>(M[i]))
4315 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4316 bool &ReverseVEXT, unsigned &Imm) {
4317 unsigned NumElts = VT.getVectorNumElements();
4318 ReverseVEXT = false;
4320 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4326 // If this is a VEXT shuffle, the immediate value is the index of the first
4327 // element. The other shuffle indices must be the successive elements after
4329 unsigned ExpectedElt = Imm;
4330 for (unsigned i = 1; i < NumElts; ++i) {
4331 // Increment the expected index. If it wraps around, it may still be
4332 // a VEXT but the source vectors must be swapped.
4334 if (ExpectedElt == NumElts * 2) {
4339 if (M[i] < 0) continue; // ignore UNDEF indices
4340 if (ExpectedElt != static_cast<unsigned>(M[i]))
4344 // Adjust the index value if the source operands will be swapped.
4351 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4352 /// instruction with the specified blocksize. (The order of the elements
4353 /// within each block of the vector is reversed.)
4354 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4355 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4356 "Only possible block sizes for VREV are: 16, 32, 64");
4358 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4362 unsigned NumElts = VT.getVectorNumElements();
4363 unsigned BlockElts = M[0] + 1;
4364 // If the first shuffle index is UNDEF, be optimistic.
4366 BlockElts = BlockSize / EltSz;
4368 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4371 for (unsigned i = 0; i < NumElts; ++i) {
4372 if (M[i] < 0) continue; // ignore UNDEF indices
4373 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4380 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4381 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4382 // range, then 0 is placed into the resulting vector. So pretty much any mask
4383 // of 8 elements can work here.
4384 return VT == MVT::v8i8 && M.size() == 8;
4387 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4388 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4392 unsigned NumElts = VT.getVectorNumElements();
4393 WhichResult = (M[0] == 0 ? 0 : 1);
4394 for (unsigned i = 0; i < NumElts; i += 2) {
4395 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4396 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4402 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4403 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4404 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4405 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4406 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4410 unsigned NumElts = VT.getVectorNumElements();
4411 WhichResult = (M[0] == 0 ? 0 : 1);
4412 for (unsigned i = 0; i < NumElts; i += 2) {
4413 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4414 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4420 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4421 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4425 unsigned NumElts = VT.getVectorNumElements();
4426 WhichResult = (M[0] == 0 ? 0 : 1);
4427 for (unsigned i = 0; i != NumElts; ++i) {
4428 if (M[i] < 0) continue; // ignore UNDEF indices
4429 if ((unsigned) M[i] != 2 * i + WhichResult)
4433 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4434 if (VT.is64BitVector() && EltSz == 32)
4440 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4441 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4442 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4443 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4444 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4448 unsigned Half = VT.getVectorNumElements() / 2;
4449 WhichResult = (M[0] == 0 ? 0 : 1);
4450 for (unsigned j = 0; j != 2; ++j) {
4451 unsigned Idx = WhichResult;
4452 for (unsigned i = 0; i != Half; ++i) {
4453 int MIdx = M[i + j * Half];
4454 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4460 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4461 if (VT.is64BitVector() && EltSz == 32)
4467 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4468 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4472 unsigned NumElts = VT.getVectorNumElements();
4473 WhichResult = (M[0] == 0 ? 0 : 1);
4474 unsigned Idx = WhichResult * NumElts / 2;
4475 for (unsigned i = 0; i != NumElts; i += 2) {
4476 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4477 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4482 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4483 if (VT.is64BitVector() && EltSz == 32)
4489 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4490 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4491 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4492 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4493 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4497 unsigned NumElts = VT.getVectorNumElements();
4498 WhichResult = (M[0] == 0 ? 0 : 1);
4499 unsigned Idx = WhichResult * NumElts / 2;
4500 for (unsigned i = 0; i != NumElts; i += 2) {
4501 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4502 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4507 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4508 if (VT.is64BitVector() && EltSz == 32)
4514 /// \return true if this is a reverse operation on an vector.
4515 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4516 unsigned NumElts = VT.getVectorNumElements();
4517 // Make sure the mask has the right size.
4518 if (NumElts != M.size())
4521 // Look for <15, ..., 3, -1, 1, 0>.
4522 for (unsigned i = 0; i != NumElts; ++i)
4523 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4529 // If N is an integer constant that can be moved into a register in one
4530 // instruction, return an SDValue of such a constant (will become a MOV
4531 // instruction). Otherwise return null.
4532 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4533 const ARMSubtarget *ST, SDLoc dl) {
4535 if (!isa<ConstantSDNode>(N))
4537 Val = cast<ConstantSDNode>(N)->getZExtValue();
4539 if (ST->isThumb1Only()) {
4540 if (Val <= 255 || ~Val <= 255)
4541 return DAG.getConstant(Val, MVT::i32);
4543 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4544 return DAG.getConstant(Val, MVT::i32);
4549 // If this is a case we can't handle, return null and let the default
4550 // expansion code take care of it.
4551 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4552 const ARMSubtarget *ST) const {
4553 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4555 EVT VT = Op.getValueType();
4557 APInt SplatBits, SplatUndef;
4558 unsigned SplatBitSize;
4560 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4561 if (SplatBitSize <= 64) {
4562 // Check if an immediate VMOV works.
4564 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4565 SplatUndef.getZExtValue(), SplatBitSize,
4566 DAG, VmovVT, VT.is128BitVector(),
4568 if (Val.getNode()) {
4569 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4570 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4573 // Try an immediate VMVN.
4574 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4575 Val = isNEONModifiedImm(NegatedImm,
4576 SplatUndef.getZExtValue(), SplatBitSize,
4577 DAG, VmovVT, VT.is128BitVector(),
4579 if (Val.getNode()) {
4580 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4581 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4584 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4585 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4586 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4588 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4589 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4595 // Scan through the operands to see if only one value is used.
4597 // As an optimisation, even if more than one value is used it may be more
4598 // profitable to splat with one value then change some lanes.
4600 // Heuristically we decide to do this if the vector has a "dominant" value,
4601 // defined as splatted to more than half of the lanes.
4602 unsigned NumElts = VT.getVectorNumElements();
4603 bool isOnlyLowElement = true;
4604 bool usesOnlyOneValue = true;
4605 bool hasDominantValue = false;
4606 bool isConstant = true;
4608 // Map of the number of times a particular SDValue appears in the
4610 DenseMap<SDValue, unsigned> ValueCounts;
4612 for (unsigned i = 0; i < NumElts; ++i) {
4613 SDValue V = Op.getOperand(i);
4614 if (V.getOpcode() == ISD::UNDEF)
4617 isOnlyLowElement = false;
4618 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4621 ValueCounts.insert(std::make_pair(V, 0));
4622 unsigned &Count = ValueCounts[V];
4624 // Is this value dominant? (takes up more than half of the lanes)
4625 if (++Count > (NumElts / 2)) {
4626 hasDominantValue = true;
4630 if (ValueCounts.size() != 1)
4631 usesOnlyOneValue = false;
4632 if (!Value.getNode() && ValueCounts.size() > 0)
4633 Value = ValueCounts.begin()->first;
4635 if (ValueCounts.size() == 0)
4636 return DAG.getUNDEF(VT);
4638 if (isOnlyLowElement)
4639 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4641 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4643 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4644 // i32 and try again.
4645 if (hasDominantValue && EltSize <= 32) {
4649 // If we are VDUPing a value that comes directly from a vector, that will
4650 // cause an unnecessary move to and from a GPR, where instead we could
4651 // just use VDUPLANE. We can only do this if the lane being extracted
4652 // is at a constant index, as the VDUP from lane instructions only have
4653 // constant-index forms.
4654 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4655 isa<ConstantSDNode>(Value->getOperand(1))) {
4656 // We need to create a new undef vector to use for the VDUPLANE if the
4657 // size of the vector from which we get the value is different than the
4658 // size of the vector that we need to create. We will insert the element
4659 // such that the register coalescer will remove unnecessary copies.
4660 if (VT != Value->getOperand(0).getValueType()) {
4661 ConstantSDNode *constIndex;
4662 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4663 assert(constIndex && "The index is not a constant!");
4664 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4665 VT.getVectorNumElements();
4666 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4667 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4668 Value, DAG.getConstant(index, MVT::i32)),
4669 DAG.getConstant(index, MVT::i32));
4671 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4672 Value->getOperand(0), Value->getOperand(1));
4674 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4676 if (!usesOnlyOneValue) {
4677 // The dominant value was splatted as 'N', but we now have to insert
4678 // all differing elements.
4679 for (unsigned I = 0; I < NumElts; ++I) {
4680 if (Op.getOperand(I) == Value)
4682 SmallVector<SDValue, 3> Ops;
4684 Ops.push_back(Op.getOperand(I));
4685 Ops.push_back(DAG.getConstant(I, MVT::i32));
4686 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4691 if (VT.getVectorElementType().isFloatingPoint()) {
4692 SmallVector<SDValue, 8> Ops;
4693 for (unsigned i = 0; i < NumElts; ++i)
4694 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4696 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4697 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4698 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4700 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4702 if (usesOnlyOneValue) {
4703 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4704 if (isConstant && Val.getNode())
4705 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4709 // If all elements are constants and the case above didn't get hit, fall back
4710 // to the default expansion, which will generate a load from the constant
4715 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4717 SDValue shuffle = ReconstructShuffle(Op, DAG);
4718 if (shuffle != SDValue())
4722 // Vectors with 32- or 64-bit elements can be built by directly assigning
4723 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4724 // will be legalized.
4725 if (EltSize >= 32) {
4726 // Do the expansion with floating-point types, since that is what the VFP
4727 // registers are defined to use, and since i64 is not legal.
4728 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4729 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4730 SmallVector<SDValue, 8> Ops;
4731 for (unsigned i = 0; i < NumElts; ++i)
4732 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4733 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4734 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4740 // Gather data to see if the operation can be modelled as a
4741 // shuffle in combination with VEXTs.
4742 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4743 SelectionDAG &DAG) const {
4745 EVT VT = Op.getValueType();
4746 unsigned NumElts = VT.getVectorNumElements();
4748 SmallVector<SDValue, 2> SourceVecs;
4749 SmallVector<unsigned, 2> MinElts;
4750 SmallVector<unsigned, 2> MaxElts;
4752 for (unsigned i = 0; i < NumElts; ++i) {
4753 SDValue V = Op.getOperand(i);
4754 if (V.getOpcode() == ISD::UNDEF)
4756 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4757 // A shuffle can only come from building a vector from various
4758 // elements of other vectors.
4760 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4761 VT.getVectorElementType()) {
4762 // This code doesn't know how to handle shuffles where the vector
4763 // element types do not match (this happens because type legalization
4764 // promotes the return type of EXTRACT_VECTOR_ELT).
4765 // FIXME: It might be appropriate to extend this code to handle
4766 // mismatched types.
4770 // Record this extraction against the appropriate vector if possible...
4771 SDValue SourceVec = V.getOperand(0);
4772 // If the element number isn't a constant, we can't effectively
4773 // analyze what's going on.
4774 if (!isa<ConstantSDNode>(V.getOperand(1)))
4776 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4777 bool FoundSource = false;
4778 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4779 if (SourceVecs[j] == SourceVec) {
4780 if (MinElts[j] > EltNo)
4782 if (MaxElts[j] < EltNo)
4789 // Or record a new source if not...
4791 SourceVecs.push_back(SourceVec);
4792 MinElts.push_back(EltNo);
4793 MaxElts.push_back(EltNo);
4797 // Currently only do something sane when at most two source vectors
4799 if (SourceVecs.size() > 2)
4802 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4803 int VEXTOffsets[2] = {0, 0};
4805 // This loop extracts the usage patterns of the source vectors
4806 // and prepares appropriate SDValues for a shuffle if possible.
4807 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4808 if (SourceVecs[i].getValueType() == VT) {
4809 // No VEXT necessary
4810 ShuffleSrcs[i] = SourceVecs[i];
4813 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4814 // It probably isn't worth padding out a smaller vector just to
4815 // break it down again in a shuffle.
4819 // Since only 64-bit and 128-bit vectors are legal on ARM and
4820 // we've eliminated the other cases...
4821 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4822 "unexpected vector sizes in ReconstructShuffle");
4824 if (MaxElts[i] - MinElts[i] >= NumElts) {
4825 // Span too large for a VEXT to cope
4829 if (MinElts[i] >= NumElts) {
4830 // The extraction can just take the second half
4831 VEXTOffsets[i] = NumElts;
4832 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4834 DAG.getIntPtrConstant(NumElts));
4835 } else if (MaxElts[i] < NumElts) {
4836 // The extraction can just take the first half
4838 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4840 DAG.getIntPtrConstant(0));
4842 // An actual VEXT is needed
4843 VEXTOffsets[i] = MinElts[i];
4844 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4846 DAG.getIntPtrConstant(0));
4847 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4849 DAG.getIntPtrConstant(NumElts));
4850 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4851 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4855 SmallVector<int, 8> Mask;
4857 for (unsigned i = 0; i < NumElts; ++i) {
4858 SDValue Entry = Op.getOperand(i);
4859 if (Entry.getOpcode() == ISD::UNDEF) {
4864 SDValue ExtractVec = Entry.getOperand(0);
4865 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4866 .getOperand(1))->getSExtValue();
4867 if (ExtractVec == SourceVecs[0]) {
4868 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4870 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4874 // Final check before we try to produce nonsense...
4875 if (isShuffleMaskLegal(Mask, VT))
4876 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4882 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4883 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4884 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4885 /// are assumed to be legal.
4887 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4889 if (VT.getVectorNumElements() == 4 &&
4890 (VT.is128BitVector() || VT.is64BitVector())) {
4891 unsigned PFIndexes[4];
4892 for (unsigned i = 0; i != 4; ++i) {
4896 PFIndexes[i] = M[i];
4899 // Compute the index in the perfect shuffle table.
4900 unsigned PFTableIndex =
4901 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4902 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4903 unsigned Cost = (PFEntry >> 30);
4910 unsigned Imm, WhichResult;
4912 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4913 return (EltSize >= 32 ||
4914 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4915 isVREVMask(M, VT, 64) ||
4916 isVREVMask(M, VT, 32) ||
4917 isVREVMask(M, VT, 16) ||
4918 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4919 isVTBLMask(M, VT) ||
4920 isVTRNMask(M, VT, WhichResult) ||
4921 isVUZPMask(M, VT, WhichResult) ||
4922 isVZIPMask(M, VT, WhichResult) ||
4923 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4924 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4925 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4926 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4929 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4930 /// the specified operations to build the shuffle.
4931 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4932 SDValue RHS, SelectionDAG &DAG,
4934 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4935 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4936 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4939 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4948 OP_VUZPL, // VUZP, left result
4949 OP_VUZPR, // VUZP, right result
4950 OP_VZIPL, // VZIP, left result
4951 OP_VZIPR, // VZIP, right result
4952 OP_VTRNL, // VTRN, left result
4953 OP_VTRNR // VTRN, right result
4956 if (OpNum == OP_COPY) {
4957 if (LHSID == (1*9+2)*9+3) return LHS;
4958 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4962 SDValue OpLHS, OpRHS;
4963 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4964 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4965 EVT VT = OpLHS.getValueType();
4968 default: llvm_unreachable("Unknown shuffle opcode!");
4970 // VREV divides the vector in half and swaps within the half.
4971 if (VT.getVectorElementType() == MVT::i32 ||
4972 VT.getVectorElementType() == MVT::f32)
4973 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4974 // vrev <4 x i16> -> VREV32
4975 if (VT.getVectorElementType() == MVT::i16)
4976 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4977 // vrev <4 x i8> -> VREV16
4978 assert(VT.getVectorElementType() == MVT::i8);
4979 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4984 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4985 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4989 return DAG.getNode(ARMISD::VEXT, dl, VT,
4991 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4994 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4995 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4998 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4999 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5002 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5003 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5007 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5008 ArrayRef<int> ShuffleMask,
5009 SelectionDAG &DAG) {
5010 // Check to see if we can use the VTBL instruction.
5011 SDValue V1 = Op.getOperand(0);
5012 SDValue V2 = Op.getOperand(1);
5015 SmallVector<SDValue, 8> VTBLMask;
5016 for (ArrayRef<int>::iterator
5017 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5018 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5020 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5021 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5022 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5025 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5026 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5030 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5031 SelectionDAG &DAG) {
5033 SDValue OpLHS = Op.getOperand(0);
5034 EVT VT = OpLHS.getValueType();
5036 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5037 "Expect an v8i16/v16i8 type");
5038 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5039 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5040 // extract the first 8 bytes into the top double word and the last 8 bytes
5041 // into the bottom double word. The v8i16 case is similar.
5042 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5043 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5044 DAG.getConstant(ExtractNum, MVT::i32));
5047 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5048 SDValue V1 = Op.getOperand(0);
5049 SDValue V2 = Op.getOperand(1);
5051 EVT VT = Op.getValueType();
5052 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5054 // Convert shuffles that are directly supported on NEON to target-specific
5055 // DAG nodes, instead of keeping them as shuffles and matching them again
5056 // during code selection. This is more efficient and avoids the possibility
5057 // of inconsistencies between legalization and selection.
5058 // FIXME: floating-point vectors should be canonicalized to integer vectors
5059 // of the same time so that they get CSEd properly.
5060 ArrayRef<int> ShuffleMask = SVN->getMask();
5062 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5063 if (EltSize <= 32) {
5064 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5065 int Lane = SVN->getSplatIndex();
5066 // If this is undef splat, generate it via "just" vdup, if possible.
5067 if (Lane == -1) Lane = 0;
5069 // Test if V1 is a SCALAR_TO_VECTOR.
5070 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5071 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5073 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5074 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5076 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5077 !isa<ConstantSDNode>(V1.getOperand(0))) {
5078 bool IsScalarToVector = true;
5079 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5080 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5081 IsScalarToVector = false;
5084 if (IsScalarToVector)
5085 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5087 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5088 DAG.getConstant(Lane, MVT::i32));
5093 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5096 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5097 DAG.getConstant(Imm, MVT::i32));
5100 if (isVREVMask(ShuffleMask, VT, 64))
5101 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5102 if (isVREVMask(ShuffleMask, VT, 32))
5103 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5104 if (isVREVMask(ShuffleMask, VT, 16))
5105 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5107 if (V2->getOpcode() == ISD::UNDEF &&
5108 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5109 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5110 DAG.getConstant(Imm, MVT::i32));
5113 // Check for Neon shuffles that modify both input vectors in place.
5114 // If both results are used, i.e., if there are two shuffles with the same
5115 // source operands and with masks corresponding to both results of one of
5116 // these operations, DAG memoization will ensure that a single node is
5117 // used for both shuffles.
5118 unsigned WhichResult;
5119 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5120 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5121 V1, V2).getValue(WhichResult);
5122 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5123 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5124 V1, V2).getValue(WhichResult);
5125 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5126 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5127 V1, V2).getValue(WhichResult);
5129 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5130 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5131 V1, V1).getValue(WhichResult);
5132 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5133 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5134 V1, V1).getValue(WhichResult);
5135 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5136 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5137 V1, V1).getValue(WhichResult);
5140 // If the shuffle is not directly supported and it has 4 elements, use
5141 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5142 unsigned NumElts = VT.getVectorNumElements();
5144 unsigned PFIndexes[4];
5145 for (unsigned i = 0; i != 4; ++i) {
5146 if (ShuffleMask[i] < 0)
5149 PFIndexes[i] = ShuffleMask[i];
5152 // Compute the index in the perfect shuffle table.
5153 unsigned PFTableIndex =
5154 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5155 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5156 unsigned Cost = (PFEntry >> 30);
5159 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5162 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5163 if (EltSize >= 32) {
5164 // Do the expansion with floating-point types, since that is what the VFP
5165 // registers are defined to use, and since i64 is not legal.
5166 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5167 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5168 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5169 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5170 SmallVector<SDValue, 8> Ops;
5171 for (unsigned i = 0; i < NumElts; ++i) {
5172 if (ShuffleMask[i] < 0)
5173 Ops.push_back(DAG.getUNDEF(EltVT));
5175 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5176 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5177 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5180 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5181 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5184 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5185 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5187 if (VT == MVT::v8i8) {
5188 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5189 if (NewOp.getNode())
5196 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5197 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5198 SDValue Lane = Op.getOperand(2);
5199 if (!isa<ConstantSDNode>(Lane))
5205 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5206 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5207 SDValue Lane = Op.getOperand(1);
5208 if (!isa<ConstantSDNode>(Lane))
5211 SDValue Vec = Op.getOperand(0);
5212 if (Op.getValueType() == MVT::i32 &&
5213 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5215 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5221 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5222 // The only time a CONCAT_VECTORS operation can have legal types is when
5223 // two 64-bit vectors are concatenated to a 128-bit vector.
5224 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5225 "unexpected CONCAT_VECTORS");
5227 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5228 SDValue Op0 = Op.getOperand(0);
5229 SDValue Op1 = Op.getOperand(1);
5230 if (Op0.getOpcode() != ISD::UNDEF)
5231 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5232 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5233 DAG.getIntPtrConstant(0));
5234 if (Op1.getOpcode() != ISD::UNDEF)
5235 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5236 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5237 DAG.getIntPtrConstant(1));
5238 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5241 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5242 /// element has been zero/sign-extended, depending on the isSigned parameter,
5243 /// from an integer type half its size.
5244 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5246 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5247 EVT VT = N->getValueType(0);
5248 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5249 SDNode *BVN = N->getOperand(0).getNode();
5250 if (BVN->getValueType(0) != MVT::v4i32 ||
5251 BVN->getOpcode() != ISD::BUILD_VECTOR)
5253 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5254 unsigned HiElt = 1 - LoElt;
5255 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5256 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5257 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5258 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5259 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5262 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5263 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5266 if (Hi0->isNullValue() && Hi1->isNullValue())
5272 if (N->getOpcode() != ISD::BUILD_VECTOR)
5275 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5276 SDNode *Elt = N->getOperand(i).getNode();
5277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5278 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5279 unsigned HalfSize = EltSize / 2;
5281 if (!isIntN(HalfSize, C->getSExtValue()))
5284 if (!isUIntN(HalfSize, C->getZExtValue()))
5295 /// isSignExtended - Check if a node is a vector value that is sign-extended
5296 /// or a constant BUILD_VECTOR with sign-extended elements.
5297 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5298 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5300 if (isExtendedBUILD_VECTOR(N, DAG, true))
5305 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5306 /// or a constant BUILD_VECTOR with zero-extended elements.
5307 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5308 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5310 if (isExtendedBUILD_VECTOR(N, DAG, false))
5315 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5316 if (OrigVT.getSizeInBits() >= 64)
5319 assert(OrigVT.isSimple() && "Expecting a simple value type");
5321 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5322 switch (OrigSimpleTy) {
5323 default: llvm_unreachable("Unexpected Vector Type");
5332 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5333 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5334 /// We insert the required extension here to get the vector to fill a D register.
5335 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5338 unsigned ExtOpcode) {
5339 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5340 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5341 // 64-bits we need to insert a new extension so that it will be 64-bits.
5342 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5343 if (OrigTy.getSizeInBits() >= 64)
5346 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5347 EVT NewVT = getExtensionTo64Bits(OrigTy);
5349 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5352 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5353 /// does not do any sign/zero extension. If the original vector is less
5354 /// than 64 bits, an appropriate extension will be added after the load to
5355 /// reach a total size of 64 bits. We have to add the extension separately
5356 /// because ARM does not have a sign/zero extending load for vectors.
5357 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5358 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5360 // The load already has the right type.
5361 if (ExtendedTy == LD->getMemoryVT())
5362 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5363 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5364 LD->isNonTemporal(), LD->isInvariant(),
5365 LD->getAlignment());
5367 // We need to create a zextload/sextload. We cannot just create a load
5368 // followed by a zext/zext node because LowerMUL is also run during normal
5369 // operation legalization where we can't create illegal types.
5370 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5371 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5372 LD->getMemoryVT(), LD->isVolatile(),
5373 LD->isNonTemporal(), LD->getAlignment());
5376 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5377 /// extending load, or BUILD_VECTOR with extended elements, return the
5378 /// unextended value. The unextended vector should be 64 bits so that it can
5379 /// be used as an operand to a VMULL instruction. If the original vector size
5380 /// before extension is less than 64 bits we add a an extension to resize
5381 /// the vector to 64 bits.
5382 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5383 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5384 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5385 N->getOperand(0)->getValueType(0),
5389 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5390 return SkipLoadExtensionForVMULL(LD, DAG);
5392 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5393 // have been legalized as a BITCAST from v4i32.
5394 if (N->getOpcode() == ISD::BITCAST) {
5395 SDNode *BVN = N->getOperand(0).getNode();
5396 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5397 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5398 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5399 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5400 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5402 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5403 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5404 EVT VT = N->getValueType(0);
5405 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5406 unsigned NumElts = VT.getVectorNumElements();
5407 MVT TruncVT = MVT::getIntegerVT(EltSize);
5408 SmallVector<SDValue, 8> Ops;
5409 for (unsigned i = 0; i != NumElts; ++i) {
5410 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5411 const APInt &CInt = C->getAPIntValue();
5412 // Element types smaller than 32 bits are not legal, so use i32 elements.
5413 // The values are implicitly truncated so sext vs. zext doesn't matter.
5414 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5416 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5417 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5420 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5421 unsigned Opcode = N->getOpcode();
5422 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5423 SDNode *N0 = N->getOperand(0).getNode();
5424 SDNode *N1 = N->getOperand(1).getNode();
5425 return N0->hasOneUse() && N1->hasOneUse() &&
5426 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5431 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5432 unsigned Opcode = N->getOpcode();
5433 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5434 SDNode *N0 = N->getOperand(0).getNode();
5435 SDNode *N1 = N->getOperand(1).getNode();
5436 return N0->hasOneUse() && N1->hasOneUse() &&
5437 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5442 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5443 // Multiplications are only custom-lowered for 128-bit vectors so that
5444 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5445 EVT VT = Op.getValueType();
5446 assert(VT.is128BitVector() && VT.isInteger() &&
5447 "unexpected type for custom-lowering ISD::MUL");
5448 SDNode *N0 = Op.getOperand(0).getNode();
5449 SDNode *N1 = Op.getOperand(1).getNode();
5450 unsigned NewOpc = 0;
5452 bool isN0SExt = isSignExtended(N0, DAG);
5453 bool isN1SExt = isSignExtended(N1, DAG);
5454 if (isN0SExt && isN1SExt)
5455 NewOpc = ARMISD::VMULLs;
5457 bool isN0ZExt = isZeroExtended(N0, DAG);
5458 bool isN1ZExt = isZeroExtended(N1, DAG);
5459 if (isN0ZExt && isN1ZExt)
5460 NewOpc = ARMISD::VMULLu;
5461 else if (isN1SExt || isN1ZExt) {
5462 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5463 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5464 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5465 NewOpc = ARMISD::VMULLs;
5467 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5468 NewOpc = ARMISD::VMULLu;
5470 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5472 NewOpc = ARMISD::VMULLu;
5478 if (VT == MVT::v2i64)
5479 // Fall through to expand this. It is not legal.
5482 // Other vector multiplications are legal.
5487 // Legalize to a VMULL instruction.
5490 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5492 Op0 = SkipExtensionForVMULL(N0, DAG);
5493 assert(Op0.getValueType().is64BitVector() &&
5494 Op1.getValueType().is64BitVector() &&
5495 "unexpected types for extended operands to VMULL");
5496 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5499 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5500 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5507 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5508 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5509 EVT Op1VT = Op1.getValueType();
5510 return DAG.getNode(N0->getOpcode(), DL, VT,
5511 DAG.getNode(NewOpc, DL, VT,
5512 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5513 DAG.getNode(NewOpc, DL, VT,
5514 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5518 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5520 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5521 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5522 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5523 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5524 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5525 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5526 // Get reciprocal estimate.
5527 // float4 recip = vrecpeq_f32(yf);
5528 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5529 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5530 // Because char has a smaller range than uchar, we can actually get away
5531 // without any newton steps. This requires that we use a weird bias
5532 // of 0xb000, however (again, this has been exhaustively tested).
5533 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5534 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5535 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5536 Y = DAG.getConstant(0xb000, MVT::i32);
5537 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5538 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5539 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5540 // Convert back to short.
5541 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5542 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5547 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5549 // Convert to float.
5550 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5551 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5552 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5553 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5554 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5555 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5557 // Use reciprocal estimate and one refinement step.
5558 // float4 recip = vrecpeq_f32(yf);
5559 // recip *= vrecpsq_f32(yf, recip);
5560 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5561 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5562 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5563 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5565 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5566 // Because short has a smaller range than ushort, we can actually get away
5567 // with only a single newton step. This requires that we use a weird bias
5568 // of 89, however (again, this has been exhaustively tested).
5569 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5570 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5571 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5572 N1 = DAG.getConstant(0x89, MVT::i32);
5573 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5574 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5575 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5576 // Convert back to integer and return.
5577 // return vmovn_s32(vcvt_s32_f32(result));
5578 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5579 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5583 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5584 EVT VT = Op.getValueType();
5585 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5586 "unexpected type for custom-lowering ISD::SDIV");
5589 SDValue N0 = Op.getOperand(0);
5590 SDValue N1 = Op.getOperand(1);
5593 if (VT == MVT::v8i8) {
5594 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5595 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5597 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5598 DAG.getIntPtrConstant(4));
5599 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5600 DAG.getIntPtrConstant(4));
5601 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5602 DAG.getIntPtrConstant(0));
5603 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5604 DAG.getIntPtrConstant(0));
5606 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5607 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5609 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5610 N0 = LowerCONCAT_VECTORS(N0, DAG);
5612 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5615 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5618 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5619 EVT VT = Op.getValueType();
5620 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5621 "unexpected type for custom-lowering ISD::UDIV");
5624 SDValue N0 = Op.getOperand(0);
5625 SDValue N1 = Op.getOperand(1);
5628 if (VT == MVT::v8i8) {
5629 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5630 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5632 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5633 DAG.getIntPtrConstant(4));
5634 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5635 DAG.getIntPtrConstant(4));
5636 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5637 DAG.getIntPtrConstant(0));
5638 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5639 DAG.getIntPtrConstant(0));
5641 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5642 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5644 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5645 N0 = LowerCONCAT_VECTORS(N0, DAG);
5647 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5648 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5653 // v4i16 sdiv ... Convert to float.
5654 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5655 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5656 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5657 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5658 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5659 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5661 // Use reciprocal estimate and two refinement steps.
5662 // float4 recip = vrecpeq_f32(yf);
5663 // recip *= vrecpsq_f32(yf, recip);
5664 // recip *= vrecpsq_f32(yf, recip);
5665 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5666 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5667 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5668 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5670 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5671 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5672 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5674 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5675 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5676 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5677 // and that it will never cause us to return an answer too large).
5678 // float4 result = as_float4(as_int4(xf*recip) + 2);
5679 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5680 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5681 N1 = DAG.getConstant(2, MVT::i32);
5682 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5683 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5684 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5685 // Convert back to integer and return.
5686 // return vmovn_u32(vcvt_s32_f32(result));
5687 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5688 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5692 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5693 EVT VT = Op.getNode()->getValueType(0);
5694 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5697 bool ExtraOp = false;
5698 switch (Op.getOpcode()) {
5699 default: llvm_unreachable("Invalid code");
5700 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5701 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5702 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5703 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5707 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5709 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5710 Op.getOperand(1), Op.getOperand(2));
5713 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5714 // Monotonic load/store is legal for all targets
5715 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5718 // Aquire/Release load/store is not legal for targets without a
5719 // dmb or equivalent available.
5724 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5725 SelectionDAG &DAG, unsigned NewOp) {
5727 assert (Node->getValueType(0) == MVT::i64 &&
5728 "Only know how to expand i64 atomics");
5730 SmallVector<SDValue, 6> Ops;
5731 Ops.push_back(Node->getOperand(0)); // Chain
5732 Ops.push_back(Node->getOperand(1)); // Ptr
5734 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5735 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5736 // High part of Val1
5737 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5738 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5739 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5740 // High part of Val1
5741 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5742 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5743 // High part of Val2
5744 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5745 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5747 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5749 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5750 cast<MemSDNode>(Node)->getMemOperand());
5751 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5752 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5753 Results.push_back(Result.getValue(2));
5756 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5757 SmallVectorImpl<SDValue> &Results,
5759 const ARMSubtarget *Subtarget) {
5761 SDValue Cycles32, OutChain;
5763 if (Subtarget->hasPerfMon()) {
5764 // Under Power Management extensions, the cycle-count is:
5765 // mrc p15, #0, <Rt>, c9, c13, #0
5766 SDValue Ops[] = { N->getOperand(0), // Chain
5767 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5768 DAG.getConstant(15, MVT::i32),
5769 DAG.getConstant(0, MVT::i32),
5770 DAG.getConstant(9, MVT::i32),
5771 DAG.getConstant(13, MVT::i32),
5772 DAG.getConstant(0, MVT::i32)
5775 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
5776 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
5777 array_lengthof(Ops));
5778 OutChain = Cycles32.getValue(1);
5780 // Intrinsic is defined to return 0 on unsupported platforms. Technically
5781 // there are older ARM CPUs that have implementation-specific ways of
5782 // obtaining this information (FIXME!).
5783 Cycles32 = DAG.getConstant(0, MVT::i32);
5784 OutChain = DAG.getEntryNode();
5788 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
5789 Cycles32, DAG.getConstant(0, MVT::i32));
5790 Results.push_back(Cycles64);
5791 Results.push_back(OutChain);
5794 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5795 switch (Op.getOpcode()) {
5796 default: llvm_unreachable("Don't know how to custom lower this!");
5797 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5798 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5799 case ISD::GlobalAddress:
5800 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5801 LowerGlobalAddressELF(Op, DAG);
5802 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5803 case ISD::SELECT: return LowerSELECT(Op, DAG);
5804 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5805 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5806 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5807 case ISD::VASTART: return LowerVASTART(Op, DAG);
5808 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5809 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5810 case ISD::SINT_TO_FP:
5811 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5812 case ISD::FP_TO_SINT:
5813 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5814 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5815 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5816 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5817 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5818 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5819 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5820 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5822 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5825 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5826 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5827 case ISD::SRL_PARTS:
5828 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5829 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5830 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5831 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5832 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5833 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5834 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5835 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5836 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5837 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5838 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5839 case ISD::MUL: return LowerMUL(Op, DAG);
5840 case ISD::SDIV: return LowerSDIV(Op, DAG);
5841 case ISD::UDIV: return LowerUDIV(Op, DAG);
5845 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5846 case ISD::ATOMIC_LOAD:
5847 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5851 /// ReplaceNodeResults - Replace the results of node with an illegal result
5852 /// type with new values built out of custom code.
5853 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5854 SmallVectorImpl<SDValue>&Results,
5855 SelectionDAG &DAG) const {
5857 switch (N->getOpcode()) {
5859 llvm_unreachable("Don't know how to custom expand this!");
5861 Res = ExpandBITCAST(N, DAG);
5863 case ISD::SIGN_EXTEND:
5864 case ISD::ZERO_EXTEND:
5865 Res = ExpandVectorExtension(N, DAG);
5869 Res = Expand64BitShift(N, DAG, Subtarget);
5871 case ISD::READCYCLECOUNTER:
5872 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
5874 case ISD::ATOMIC_LOAD_ADD:
5875 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5877 case ISD::ATOMIC_LOAD_AND:
5878 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5880 case ISD::ATOMIC_LOAD_NAND:
5881 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5883 case ISD::ATOMIC_LOAD_OR:
5884 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5886 case ISD::ATOMIC_LOAD_SUB:
5887 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5889 case ISD::ATOMIC_LOAD_XOR:
5890 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5892 case ISD::ATOMIC_SWAP:
5893 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5895 case ISD::ATOMIC_CMP_SWAP:
5896 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5898 case ISD::ATOMIC_LOAD_MIN:
5899 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5901 case ISD::ATOMIC_LOAD_UMIN:
5902 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5904 case ISD::ATOMIC_LOAD_MAX:
5905 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5907 case ISD::ATOMIC_LOAD_UMAX:
5908 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5912 Results.push_back(Res);
5915 //===----------------------------------------------------------------------===//
5916 // ARM Scheduler Hooks
5917 //===----------------------------------------------------------------------===//
5920 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5921 MachineBasicBlock *BB,
5922 unsigned Size) const {
5923 unsigned dest = MI->getOperand(0).getReg();
5924 unsigned ptr = MI->getOperand(1).getReg();
5925 unsigned oldval = MI->getOperand(2).getReg();
5926 unsigned newval = MI->getOperand(3).getReg();
5927 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5928 DebugLoc dl = MI->getDebugLoc();
5929 bool isThumb2 = Subtarget->isThumb2();
5931 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5932 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5933 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5934 (const TargetRegisterClass*)&ARM::GPRRegClass);
5937 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5938 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5939 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5942 unsigned ldrOpc, strOpc;
5944 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5946 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5947 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5950 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5951 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5954 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5955 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5959 MachineFunction *MF = BB->getParent();
5960 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5961 MachineFunction::iterator It = BB;
5962 ++It; // insert the new blocks after the current block
5964 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5965 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5966 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5967 MF->insert(It, loop1MBB);
5968 MF->insert(It, loop2MBB);
5969 MF->insert(It, exitMBB);
5971 // Transfer the remainder of BB and its successor edges to exitMBB.
5972 exitMBB->splice(exitMBB->begin(), BB,
5973 llvm::next(MachineBasicBlock::iterator(MI)),
5975 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5979 // fallthrough --> loop1MBB
5980 BB->addSuccessor(loop1MBB);
5983 // ldrex dest, [ptr]
5987 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5988 if (ldrOpc == ARM::t2LDREX)
5990 AddDefaultPred(MIB);
5991 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5992 .addReg(dest).addReg(oldval));
5993 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5994 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5995 BB->addSuccessor(loop2MBB);
5996 BB->addSuccessor(exitMBB);
5999 // strex scratch, newval, [ptr]
6003 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6004 if (strOpc == ARM::t2STREX)
6006 AddDefaultPred(MIB);
6007 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6008 .addReg(scratch).addImm(0));
6009 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6010 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6011 BB->addSuccessor(loop1MBB);
6012 BB->addSuccessor(exitMBB);
6018 MI->eraseFromParent(); // The instruction is gone now.
6024 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6025 unsigned Size, unsigned BinOpcode) const {
6026 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6027 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6029 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6030 MachineFunction *MF = BB->getParent();
6031 MachineFunction::iterator It = BB;
6034 unsigned dest = MI->getOperand(0).getReg();
6035 unsigned ptr = MI->getOperand(1).getReg();
6036 unsigned incr = MI->getOperand(2).getReg();
6037 DebugLoc dl = MI->getDebugLoc();
6038 bool isThumb2 = Subtarget->isThumb2();
6040 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6042 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6043 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6046 unsigned ldrOpc, strOpc;
6048 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6050 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6051 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6054 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6055 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6058 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6059 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6063 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6064 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6065 MF->insert(It, loopMBB);
6066 MF->insert(It, exitMBB);
6068 // Transfer the remainder of BB and its successor edges to exitMBB.
6069 exitMBB->splice(exitMBB->begin(), BB,
6070 llvm::next(MachineBasicBlock::iterator(MI)),
6072 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6074 const TargetRegisterClass *TRC = isThumb2 ?
6075 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6076 (const TargetRegisterClass*)&ARM::GPRRegClass;
6077 unsigned scratch = MRI.createVirtualRegister(TRC);
6078 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6082 // fallthrough --> loopMBB
6083 BB->addSuccessor(loopMBB);
6087 // <binop> scratch2, dest, incr
6088 // strex scratch, scratch2, ptr
6091 // fallthrough --> exitMBB
6093 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6094 if (ldrOpc == ARM::t2LDREX)
6096 AddDefaultPred(MIB);
6098 // operand order needs to go the other way for NAND
6099 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6100 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6101 addReg(incr).addReg(dest)).addReg(0);
6103 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6104 addReg(dest).addReg(incr)).addReg(0);
6107 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6108 if (strOpc == ARM::t2STREX)
6110 AddDefaultPred(MIB);
6111 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6112 .addReg(scratch).addImm(0));
6113 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6114 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6116 BB->addSuccessor(loopMBB);
6117 BB->addSuccessor(exitMBB);
6123 MI->eraseFromParent(); // The instruction is gone now.
6129 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6130 MachineBasicBlock *BB,
6133 ARMCC::CondCodes Cond) const {
6134 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6136 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6137 MachineFunction *MF = BB->getParent();
6138 MachineFunction::iterator It = BB;
6141 unsigned dest = MI->getOperand(0).getReg();
6142 unsigned ptr = MI->getOperand(1).getReg();
6143 unsigned incr = MI->getOperand(2).getReg();
6144 unsigned oldval = dest;
6145 DebugLoc dl = MI->getDebugLoc();
6146 bool isThumb2 = Subtarget->isThumb2();
6148 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6150 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6151 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6154 unsigned ldrOpc, strOpc, extendOpc;
6156 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6158 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6159 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6160 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6163 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6164 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6165 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6168 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6169 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6174 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6175 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6176 MF->insert(It, loopMBB);
6177 MF->insert(It, exitMBB);
6179 // Transfer the remainder of BB and its successor edges to exitMBB.
6180 exitMBB->splice(exitMBB->begin(), BB,
6181 llvm::next(MachineBasicBlock::iterator(MI)),
6183 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6185 const TargetRegisterClass *TRC = isThumb2 ?
6186 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6187 (const TargetRegisterClass*)&ARM::GPRRegClass;
6188 unsigned scratch = MRI.createVirtualRegister(TRC);
6189 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6193 // fallthrough --> loopMBB
6194 BB->addSuccessor(loopMBB);
6198 // (sign extend dest, if required)
6200 // cmov.cond scratch2, incr, dest
6201 // strex scratch, scratch2, ptr
6204 // fallthrough --> exitMBB
6206 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6207 if (ldrOpc == ARM::t2LDREX)
6209 AddDefaultPred(MIB);
6211 // Sign extend the value, if necessary.
6212 if (signExtend && extendOpc) {
6213 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6214 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6219 // Build compare and cmov instructions.
6220 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6221 .addReg(oldval).addReg(incr));
6222 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6223 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6225 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6226 if (strOpc == ARM::t2STREX)
6228 AddDefaultPred(MIB);
6229 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6230 .addReg(scratch).addImm(0));
6231 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6232 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6234 BB->addSuccessor(loopMBB);
6235 BB->addSuccessor(exitMBB);
6241 MI->eraseFromParent(); // The instruction is gone now.
6247 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6248 unsigned Op1, unsigned Op2,
6249 bool NeedsCarry, bool IsCmpxchg,
6250 bool IsMinMax, ARMCC::CondCodes CC) const {
6251 // This also handles ATOMIC_SWAP, indicated by Op1==0.
6252 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6254 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6255 MachineFunction *MF = BB->getParent();
6256 MachineFunction::iterator It = BB;
6259 unsigned destlo = MI->getOperand(0).getReg();
6260 unsigned desthi = MI->getOperand(1).getReg();
6261 unsigned ptr = MI->getOperand(2).getReg();
6262 unsigned vallo = MI->getOperand(3).getReg();
6263 unsigned valhi = MI->getOperand(4).getReg();
6264 DebugLoc dl = MI->getDebugLoc();
6265 bool isThumb2 = Subtarget->isThumb2();
6267 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6269 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6270 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6271 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6274 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6275 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6276 if (IsCmpxchg || IsMinMax)
6277 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6279 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6280 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6282 MF->insert(It, loopMBB);
6283 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6284 if (IsCmpxchg) MF->insert(It, cont2BB);
6285 MF->insert(It, exitMBB);
6287 // Transfer the remainder of BB and its successor edges to exitMBB.
6288 exitMBB->splice(exitMBB->begin(), BB,
6289 llvm::next(MachineBasicBlock::iterator(MI)),
6291 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6293 const TargetRegisterClass *TRC = isThumb2 ?
6294 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6295 (const TargetRegisterClass*)&ARM::GPRRegClass;
6296 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6300 // fallthrough --> loopMBB
6301 BB->addSuccessor(loopMBB);
6304 // ldrexd r2, r3, ptr
6305 // <binopa> r0, r2, incr
6306 // <binopb> r1, r3, incr
6307 // strexd storesuccess, r0, r1, ptr
6308 // cmp storesuccess, #0
6310 // fallthrough --> exitMBB
6315 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6316 .addReg(destlo, RegState::Define)
6317 .addReg(desthi, RegState::Define)
6320 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6321 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6322 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6323 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6324 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6325 .addReg(GPRPair0, 0, ARM::gsub_0);
6326 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6327 .addReg(GPRPair0, 0, ARM::gsub_1);
6330 unsigned StoreLo, StoreHi;
6333 for (unsigned i = 0; i < 2; i++) {
6334 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6336 .addReg(i == 0 ? destlo : desthi)
6337 .addReg(i == 0 ? vallo : valhi));
6338 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6339 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6340 BB->addSuccessor(exitMBB);
6341 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6342 BB = (i == 0 ? contBB : cont2BB);
6345 // Copy to physregs for strexd
6346 StoreLo = MI->getOperand(5).getReg();
6347 StoreHi = MI->getOperand(6).getReg();
6349 // Perform binary operation
6350 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6351 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6352 .addReg(destlo).addReg(vallo))
6353 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6354 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6355 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6356 .addReg(desthi).addReg(valhi))
6357 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6362 // Copy to physregs for strexd
6367 // Compare and branch to exit block.
6368 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6369 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6370 BB->addSuccessor(exitMBB);
6371 BB->addSuccessor(contBB);
6379 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6380 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6382 // Marshal a pair...
6383 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6384 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6385 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6386 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6387 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6390 .addImm(ARM::gsub_0);
6391 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6394 .addImm(ARM::gsub_1);
6397 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6398 .addReg(StorePair).addReg(ptr));
6401 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6402 .addReg(storesuccess).addImm(0));
6403 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6404 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6406 BB->addSuccessor(loopMBB);
6407 BB->addSuccessor(exitMBB);
6413 MI->eraseFromParent(); // The instruction is gone now.
6418 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6419 /// registers the function context.
6420 void ARMTargetLowering::
6421 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6422 MachineBasicBlock *DispatchBB, int FI) const {
6423 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6424 DebugLoc dl = MI->getDebugLoc();
6425 MachineFunction *MF = MBB->getParent();
6426 MachineRegisterInfo *MRI = &MF->getRegInfo();
6427 MachineConstantPool *MCP = MF->getConstantPool();
6428 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6429 const Function *F = MF->getFunction();
6431 bool isThumb = Subtarget->isThumb();
6432 bool isThumb2 = Subtarget->isThumb2();
6434 unsigned PCLabelId = AFI->createPICLabelUId();
6435 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6436 ARMConstantPoolValue *CPV =
6437 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6438 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6440 const TargetRegisterClass *TRC = isThumb ?
6441 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6442 (const TargetRegisterClass*)&ARM::GPRRegClass;
6444 // Grab constant pool and fixed stack memory operands.
6445 MachineMemOperand *CPMMO =
6446 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6447 MachineMemOperand::MOLoad, 4, 4);
6449 MachineMemOperand *FIMMOSt =
6450 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6451 MachineMemOperand::MOStore, 4, 4);
6453 // Load the address of the dispatch MBB into the jump buffer.
6455 // Incoming value: jbuf
6456 // ldr.n r5, LCPI1_1
6459 // str r5, [$jbuf, #+4] ; &jbuf[1]
6460 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6461 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6462 .addConstantPoolIndex(CPI)
6463 .addMemOperand(CPMMO));
6464 // Set the low bit because of thumb mode.
6465 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6467 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6468 .addReg(NewVReg1, RegState::Kill)
6470 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6471 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6472 .addReg(NewVReg2, RegState::Kill)
6474 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6475 .addReg(NewVReg3, RegState::Kill)
6477 .addImm(36) // &jbuf[1] :: pc
6478 .addMemOperand(FIMMOSt));
6479 } else if (isThumb) {
6480 // Incoming value: jbuf
6481 // ldr.n r1, LCPI1_4
6485 // add r2, $jbuf, #+4 ; &jbuf[1]
6487 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6488 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6489 .addConstantPoolIndex(CPI)
6490 .addMemOperand(CPMMO));
6491 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6492 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6493 .addReg(NewVReg1, RegState::Kill)
6495 // Set the low bit because of thumb mode.
6496 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6497 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6498 .addReg(ARM::CPSR, RegState::Define)
6500 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6501 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6502 .addReg(ARM::CPSR, RegState::Define)
6503 .addReg(NewVReg2, RegState::Kill)
6504 .addReg(NewVReg3, RegState::Kill));
6505 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6506 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6508 .addImm(36)); // &jbuf[1] :: pc
6509 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6510 .addReg(NewVReg4, RegState::Kill)
6511 .addReg(NewVReg5, RegState::Kill)
6513 .addMemOperand(FIMMOSt));
6515 // Incoming value: jbuf
6518 // str r1, [$jbuf, #+4] ; &jbuf[1]
6519 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6520 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6521 .addConstantPoolIndex(CPI)
6523 .addMemOperand(CPMMO));
6524 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6525 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6526 .addReg(NewVReg1, RegState::Kill)
6527 .addImm(PCLabelId));
6528 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6529 .addReg(NewVReg2, RegState::Kill)
6531 .addImm(36) // &jbuf[1] :: pc
6532 .addMemOperand(FIMMOSt));
6536 MachineBasicBlock *ARMTargetLowering::
6537 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6538 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6539 DebugLoc dl = MI->getDebugLoc();
6540 MachineFunction *MF = MBB->getParent();
6541 MachineRegisterInfo *MRI = &MF->getRegInfo();
6542 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6543 MachineFrameInfo *MFI = MF->getFrameInfo();
6544 int FI = MFI->getFunctionContextIndex();
6546 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6547 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6548 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6550 // Get a mapping of the call site numbers to all of the landing pads they're
6552 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6553 unsigned MaxCSNum = 0;
6554 MachineModuleInfo &MMI = MF->getMMI();
6555 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6557 if (!BB->isLandingPad()) continue;
6559 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6561 for (MachineBasicBlock::iterator
6562 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6563 if (!II->isEHLabel()) continue;
6565 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6566 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6568 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6569 for (SmallVectorImpl<unsigned>::iterator
6570 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6571 CSI != CSE; ++CSI) {
6572 CallSiteNumToLPad[*CSI].push_back(BB);
6573 MaxCSNum = std::max(MaxCSNum, *CSI);
6579 // Get an ordered list of the machine basic blocks for the jump table.
6580 std::vector<MachineBasicBlock*> LPadList;
6581 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6582 LPadList.reserve(CallSiteNumToLPad.size());
6583 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6584 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6585 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6586 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6587 LPadList.push_back(*II);
6588 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6592 assert(!LPadList.empty() &&
6593 "No landing pad destinations for the dispatch jump table!");
6595 // Create the jump table and associated information.
6596 MachineJumpTableInfo *JTI =
6597 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6598 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6599 unsigned UId = AFI->createJumpTableUId();
6600 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6602 // Create the MBBs for the dispatch code.
6604 // Shove the dispatch's address into the return slot in the function context.
6605 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6606 DispatchBB->setIsLandingPad();
6608 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6609 unsigned trap_opcode;
6610 if (Subtarget->isThumb())
6611 trap_opcode = ARM::tTRAP;
6613 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6615 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6616 DispatchBB->addSuccessor(TrapBB);
6618 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6619 DispatchBB->addSuccessor(DispContBB);
6622 MF->insert(MF->end(), DispatchBB);
6623 MF->insert(MF->end(), DispContBB);
6624 MF->insert(MF->end(), TrapBB);
6626 // Insert code into the entry block that creates and registers the function
6628 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6630 MachineMemOperand *FIMMOLd =
6631 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6632 MachineMemOperand::MOLoad |
6633 MachineMemOperand::MOVolatile, 4, 4);
6635 MachineInstrBuilder MIB;
6636 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6638 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6639 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6641 // Add a register mask with no preserved registers. This results in all
6642 // registers being marked as clobbered.
6643 MIB.addRegMask(RI.getNoPreservedMask());
6645 unsigned NumLPads = LPadList.size();
6646 if (Subtarget->isThumb2()) {
6647 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6648 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6651 .addMemOperand(FIMMOLd));
6653 if (NumLPads < 256) {
6654 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6656 .addImm(LPadList.size()));
6658 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6659 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6660 .addImm(NumLPads & 0xFFFF));
6662 unsigned VReg2 = VReg1;
6663 if ((NumLPads & 0xFFFF0000) != 0) {
6664 VReg2 = MRI->createVirtualRegister(TRC);
6665 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6667 .addImm(NumLPads >> 16));
6670 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6675 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6680 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6681 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6682 .addJumpTableIndex(MJTI)
6685 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6688 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6689 .addReg(NewVReg3, RegState::Kill)
6691 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6693 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6694 .addReg(NewVReg4, RegState::Kill)
6696 .addJumpTableIndex(MJTI)
6698 } else if (Subtarget->isThumb()) {
6699 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6700 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6703 .addMemOperand(FIMMOLd));
6705 if (NumLPads < 256) {
6706 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6710 MachineConstantPool *ConstantPool = MF->getConstantPool();
6711 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6712 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6714 // MachineConstantPool wants an explicit alignment.
6715 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6717 Align = getDataLayout()->getTypeAllocSize(C->getType());
6718 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6720 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6721 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6722 .addReg(VReg1, RegState::Define)
6723 .addConstantPoolIndex(Idx));
6724 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6729 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6734 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6735 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6736 .addReg(ARM::CPSR, RegState::Define)
6740 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6741 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6742 .addJumpTableIndex(MJTI)
6745 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6746 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6747 .addReg(ARM::CPSR, RegState::Define)
6748 .addReg(NewVReg2, RegState::Kill)
6751 MachineMemOperand *JTMMOLd =
6752 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6753 MachineMemOperand::MOLoad, 4, 4);
6755 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6756 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6757 .addReg(NewVReg4, RegState::Kill)
6759 .addMemOperand(JTMMOLd));
6761 unsigned NewVReg6 = NewVReg5;
6762 if (RelocM == Reloc::PIC_) {
6763 NewVReg6 = MRI->createVirtualRegister(TRC);
6764 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6765 .addReg(ARM::CPSR, RegState::Define)
6766 .addReg(NewVReg5, RegState::Kill)
6770 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6771 .addReg(NewVReg6, RegState::Kill)
6772 .addJumpTableIndex(MJTI)
6775 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6776 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6779 .addMemOperand(FIMMOLd));
6781 if (NumLPads < 256) {
6782 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6785 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6786 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6787 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6788 .addImm(NumLPads & 0xFFFF));
6790 unsigned VReg2 = VReg1;
6791 if ((NumLPads & 0xFFFF0000) != 0) {
6792 VReg2 = MRI->createVirtualRegister(TRC);
6793 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6795 .addImm(NumLPads >> 16));
6798 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6802 MachineConstantPool *ConstantPool = MF->getConstantPool();
6803 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6804 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6806 // MachineConstantPool wants an explicit alignment.
6807 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6809 Align = getDataLayout()->getTypeAllocSize(C->getType());
6810 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6812 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6813 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6814 .addReg(VReg1, RegState::Define)
6815 .addConstantPoolIndex(Idx)
6817 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6819 .addReg(VReg1, RegState::Kill));
6822 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6827 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6829 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6831 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6832 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6833 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6834 .addJumpTableIndex(MJTI)
6837 MachineMemOperand *JTMMOLd =
6838 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6839 MachineMemOperand::MOLoad, 4, 4);
6840 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6842 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6843 .addReg(NewVReg3, RegState::Kill)
6846 .addMemOperand(JTMMOLd));
6848 if (RelocM == Reloc::PIC_) {
6849 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6850 .addReg(NewVReg5, RegState::Kill)
6852 .addJumpTableIndex(MJTI)
6855 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6856 .addReg(NewVReg5, RegState::Kill)
6857 .addJumpTableIndex(MJTI)
6862 // Add the jump table entries as successors to the MBB.
6863 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6864 for (std::vector<MachineBasicBlock*>::iterator
6865 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6866 MachineBasicBlock *CurMBB = *I;
6867 if (SeenMBBs.insert(CurMBB))
6868 DispContBB->addSuccessor(CurMBB);
6871 // N.B. the order the invoke BBs are processed in doesn't matter here.
6872 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6873 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6874 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6875 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6876 MachineBasicBlock *BB = *I;
6878 // Remove the landing pad successor from the invoke block and replace it
6879 // with the new dispatch block.
6880 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6882 while (!Successors.empty()) {
6883 MachineBasicBlock *SMBB = Successors.pop_back_val();
6884 if (SMBB->isLandingPad()) {
6885 BB->removeSuccessor(SMBB);
6886 MBBLPads.push_back(SMBB);
6890 BB->addSuccessor(DispatchBB);
6892 // Find the invoke call and mark all of the callee-saved registers as
6893 // 'implicit defined' so that they're spilled. This prevents code from
6894 // moving instructions to before the EH block, where they will never be
6896 for (MachineBasicBlock::reverse_iterator
6897 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6898 if (!II->isCall()) continue;
6900 DenseMap<unsigned, bool> DefRegs;
6901 for (MachineInstr::mop_iterator
6902 OI = II->operands_begin(), OE = II->operands_end();
6904 if (!OI->isReg()) continue;
6905 DefRegs[OI->getReg()] = true;
6908 MachineInstrBuilder MIB(*MF, &*II);
6910 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6911 unsigned Reg = SavedRegs[i];
6912 if (Subtarget->isThumb2() &&
6913 !ARM::tGPRRegClass.contains(Reg) &&
6914 !ARM::hGPRRegClass.contains(Reg))
6916 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6918 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6921 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6928 // Mark all former landing pads as non-landing pads. The dispatch is the only
6930 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6931 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6932 (*I)->setIsLandingPad(false);
6934 // The instruction is gone now.
6935 MI->eraseFromParent();
6941 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6942 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6943 E = MBB->succ_end(); I != E; ++I)
6946 llvm_unreachable("Expecting a BB with two successors!");
6949 MachineBasicBlock *ARMTargetLowering::
6950 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6951 // This pseudo instruction has 3 operands: dst, src, size
6952 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6953 // Otherwise, we will generate unrolled scalar copies.
6954 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6955 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6956 MachineFunction::iterator It = BB;
6959 unsigned dest = MI->getOperand(0).getReg();
6960 unsigned src = MI->getOperand(1).getReg();
6961 unsigned SizeVal = MI->getOperand(2).getImm();
6962 unsigned Align = MI->getOperand(3).getImm();
6963 DebugLoc dl = MI->getDebugLoc();
6965 bool isThumb2 = Subtarget->isThumb2();
6966 MachineFunction *MF = BB->getParent();
6967 MachineRegisterInfo &MRI = MF->getRegInfo();
6968 unsigned ldrOpc, strOpc, UnitSize = 0;
6970 const TargetRegisterClass *TRC = isThumb2 ?
6971 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6972 (const TargetRegisterClass*)&ARM::GPRRegClass;
6973 const TargetRegisterClass *TRC_Vec = 0;
6976 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6977 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6979 } else if (Align & 2) {
6980 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6981 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6984 // Check whether we can use NEON instructions.
6985 if (!MF->getFunction()->getAttributes().
6986 hasAttribute(AttributeSet::FunctionIndex,
6987 Attribute::NoImplicitFloat) &&
6988 Subtarget->hasNEON()) {
6989 if ((Align % 16 == 0) && SizeVal >= 16) {
6990 ldrOpc = ARM::VLD1q32wb_fixed;
6991 strOpc = ARM::VST1q32wb_fixed;
6993 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6995 else if ((Align % 8 == 0) && SizeVal >= 8) {
6996 ldrOpc = ARM::VLD1d32wb_fixed;
6997 strOpc = ARM::VST1d32wb_fixed;
6999 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
7002 // Can't use NEON instructions.
7003 if (UnitSize == 0) {
7004 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
7005 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
7010 unsigned BytesLeft = SizeVal % UnitSize;
7011 unsigned LoopSize = SizeVal - BytesLeft;
7013 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7014 // Use LDR and STR to copy.
7015 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7016 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7017 unsigned srcIn = src;
7018 unsigned destIn = dest;
7019 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7020 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7021 unsigned srcOut = MRI.createVirtualRegister(TRC);
7022 unsigned destOut = MRI.createVirtualRegister(TRC);
7023 if (UnitSize >= 8) {
7024 AddDefaultPred(BuildMI(*BB, MI, dl,
7025 TII->get(ldrOpc), scratch)
7026 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7028 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7029 .addReg(destIn).addImm(0).addReg(scratch));
7030 } else if (isThumb2) {
7031 AddDefaultPred(BuildMI(*BB, MI, dl,
7032 TII->get(ldrOpc), scratch)
7033 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7035 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7036 .addReg(scratch).addReg(destIn)
7039 AddDefaultPred(BuildMI(*BB, MI, dl,
7040 TII->get(ldrOpc), scratch)
7041 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7044 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7045 .addReg(scratch).addReg(destIn)
7046 .addReg(0).addImm(UnitSize));
7052 // Handle the leftover bytes with LDRB and STRB.
7053 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7054 // [destOut] = STRB_POST(scratch, destIn, 1)
7055 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7056 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7057 for (unsigned i = 0; i < BytesLeft; i++) {
7058 unsigned scratch = MRI.createVirtualRegister(TRC);
7059 unsigned srcOut = MRI.createVirtualRegister(TRC);
7060 unsigned destOut = MRI.createVirtualRegister(TRC);
7062 AddDefaultPred(BuildMI(*BB, MI, dl,
7063 TII->get(ldrOpc),scratch)
7064 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7066 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7067 .addReg(scratch).addReg(destIn)
7068 .addReg(0).addImm(1));
7070 AddDefaultPred(BuildMI(*BB, MI, dl,
7071 TII->get(ldrOpc),scratch)
7072 .addReg(srcOut, RegState::Define).addReg(srcIn)
7073 .addReg(0).addImm(1));
7075 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7076 .addReg(scratch).addReg(destIn)
7077 .addReg(0).addImm(1));
7082 MI->eraseFromParent(); // The instruction is gone now.
7086 // Expand the pseudo op to a loop.
7089 // movw varEnd, # --> with thumb2
7091 // ldrcp varEnd, idx --> without thumb2
7092 // fallthrough --> loopMBB
7094 // PHI varPhi, varEnd, varLoop
7095 // PHI srcPhi, src, srcLoop
7096 // PHI destPhi, dst, destLoop
7097 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7098 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7099 // subs varLoop, varPhi, #UnitSize
7101 // fallthrough --> exitMBB
7103 // epilogue to handle left-over bytes
7104 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7105 // [destOut] = STRB_POST(scratch, destLoop, 1)
7106 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7107 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7108 MF->insert(It, loopMBB);
7109 MF->insert(It, exitMBB);
7111 // Transfer the remainder of BB and its successor edges to exitMBB.
7112 exitMBB->splice(exitMBB->begin(), BB,
7113 llvm::next(MachineBasicBlock::iterator(MI)),
7115 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7117 // Load an immediate to varEnd.
7118 unsigned varEnd = MRI.createVirtualRegister(TRC);
7120 unsigned VReg1 = varEnd;
7121 if ((LoopSize & 0xFFFF0000) != 0)
7122 VReg1 = MRI.createVirtualRegister(TRC);
7123 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7124 .addImm(LoopSize & 0xFFFF));
7126 if ((LoopSize & 0xFFFF0000) != 0)
7127 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7129 .addImm(LoopSize >> 16));
7131 MachineConstantPool *ConstantPool = MF->getConstantPool();
7132 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7133 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7135 // MachineConstantPool wants an explicit alignment.
7136 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7138 Align = getDataLayout()->getTypeAllocSize(C->getType());
7139 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7141 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7142 .addReg(varEnd, RegState::Define)
7143 .addConstantPoolIndex(Idx)
7146 BB->addSuccessor(loopMBB);
7148 // Generate the loop body:
7149 // varPhi = PHI(varLoop, varEnd)
7150 // srcPhi = PHI(srcLoop, src)
7151 // destPhi = PHI(destLoop, dst)
7152 MachineBasicBlock *entryBB = BB;
7154 unsigned varLoop = MRI.createVirtualRegister(TRC);
7155 unsigned varPhi = MRI.createVirtualRegister(TRC);
7156 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7157 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7158 unsigned destLoop = MRI.createVirtualRegister(TRC);
7159 unsigned destPhi = MRI.createVirtualRegister(TRC);
7161 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7162 .addReg(varLoop).addMBB(loopMBB)
7163 .addReg(varEnd).addMBB(entryBB);
7164 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7165 .addReg(srcLoop).addMBB(loopMBB)
7166 .addReg(src).addMBB(entryBB);
7167 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7168 .addReg(destLoop).addMBB(loopMBB)
7169 .addReg(dest).addMBB(entryBB);
7171 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7172 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7173 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7174 if (UnitSize >= 8) {
7175 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7176 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7178 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7179 .addReg(destPhi).addImm(0).addReg(scratch));
7180 } else if (isThumb2) {
7181 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7182 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7184 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7185 .addReg(scratch).addReg(destPhi)
7188 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7189 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7192 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7193 .addReg(scratch).addReg(destPhi)
7194 .addReg(0).addImm(UnitSize));
7197 // Decrement loop variable by UnitSize.
7198 MachineInstrBuilder MIB = BuildMI(BB, dl,
7199 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7200 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7201 MIB->getOperand(5).setReg(ARM::CPSR);
7202 MIB->getOperand(5).setIsDef(true);
7204 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7205 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7207 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7208 BB->addSuccessor(loopMBB);
7209 BB->addSuccessor(exitMBB);
7211 // Add epilogue to handle BytesLeft.
7213 MachineInstr *StartOfExit = exitMBB->begin();
7214 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7215 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7217 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7218 // [destOut] = STRB_POST(scratch, destLoop, 1)
7219 unsigned srcIn = srcLoop;
7220 unsigned destIn = destLoop;
7221 for (unsigned i = 0; i < BytesLeft; i++) {
7222 unsigned scratch = MRI.createVirtualRegister(TRC);
7223 unsigned srcOut = MRI.createVirtualRegister(TRC);
7224 unsigned destOut = MRI.createVirtualRegister(TRC);
7226 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7227 TII->get(ldrOpc),scratch)
7228 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7230 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7231 .addReg(scratch).addReg(destIn)
7234 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7235 TII->get(ldrOpc),scratch)
7236 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7238 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7239 .addReg(scratch).addReg(destIn)
7240 .addReg(0).addImm(1));
7246 MI->eraseFromParent(); // The instruction is gone now.
7251 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7252 MachineBasicBlock *BB) const {
7253 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7254 DebugLoc dl = MI->getDebugLoc();
7255 bool isThumb2 = Subtarget->isThumb2();
7256 switch (MI->getOpcode()) {
7259 llvm_unreachable("Unexpected instr type to insert");
7261 // The Thumb2 pre-indexed stores have the same MI operands, they just
7262 // define them differently in the .td files from the isel patterns, so
7263 // they need pseudos.
7264 case ARM::t2STR_preidx:
7265 MI->setDesc(TII->get(ARM::t2STR_PRE));
7267 case ARM::t2STRB_preidx:
7268 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7270 case ARM::t2STRH_preidx:
7271 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7274 case ARM::STRi_preidx:
7275 case ARM::STRBi_preidx: {
7276 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7277 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7278 // Decode the offset.
7279 unsigned Offset = MI->getOperand(4).getImm();
7280 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7281 Offset = ARM_AM::getAM2Offset(Offset);
7285 MachineMemOperand *MMO = *MI->memoperands_begin();
7286 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7287 .addOperand(MI->getOperand(0)) // Rn_wb
7288 .addOperand(MI->getOperand(1)) // Rt
7289 .addOperand(MI->getOperand(2)) // Rn
7290 .addImm(Offset) // offset (skip GPR==zero_reg)
7291 .addOperand(MI->getOperand(5)) // pred
7292 .addOperand(MI->getOperand(6))
7293 .addMemOperand(MMO);
7294 MI->eraseFromParent();
7297 case ARM::STRr_preidx:
7298 case ARM::STRBr_preidx:
7299 case ARM::STRH_preidx: {
7301 switch (MI->getOpcode()) {
7302 default: llvm_unreachable("unexpected opcode!");
7303 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7304 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7305 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7307 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7308 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7309 MIB.addOperand(MI->getOperand(i));
7310 MI->eraseFromParent();
7313 case ARM::ATOMIC_LOAD_ADD_I8:
7314 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7315 case ARM::ATOMIC_LOAD_ADD_I16:
7316 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7317 case ARM::ATOMIC_LOAD_ADD_I32:
7318 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7320 case ARM::ATOMIC_LOAD_AND_I8:
7321 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7322 case ARM::ATOMIC_LOAD_AND_I16:
7323 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7324 case ARM::ATOMIC_LOAD_AND_I32:
7325 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7327 case ARM::ATOMIC_LOAD_OR_I8:
7328 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7329 case ARM::ATOMIC_LOAD_OR_I16:
7330 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7331 case ARM::ATOMIC_LOAD_OR_I32:
7332 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7334 case ARM::ATOMIC_LOAD_XOR_I8:
7335 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7336 case ARM::ATOMIC_LOAD_XOR_I16:
7337 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7338 case ARM::ATOMIC_LOAD_XOR_I32:
7339 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7341 case ARM::ATOMIC_LOAD_NAND_I8:
7342 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7343 case ARM::ATOMIC_LOAD_NAND_I16:
7344 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7345 case ARM::ATOMIC_LOAD_NAND_I32:
7346 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7348 case ARM::ATOMIC_LOAD_SUB_I8:
7349 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7350 case ARM::ATOMIC_LOAD_SUB_I16:
7351 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7352 case ARM::ATOMIC_LOAD_SUB_I32:
7353 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7355 case ARM::ATOMIC_LOAD_MIN_I8:
7356 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7357 case ARM::ATOMIC_LOAD_MIN_I16:
7358 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7359 case ARM::ATOMIC_LOAD_MIN_I32:
7360 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7362 case ARM::ATOMIC_LOAD_MAX_I8:
7363 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7364 case ARM::ATOMIC_LOAD_MAX_I16:
7365 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7366 case ARM::ATOMIC_LOAD_MAX_I32:
7367 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7369 case ARM::ATOMIC_LOAD_UMIN_I8:
7370 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7371 case ARM::ATOMIC_LOAD_UMIN_I16:
7372 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7373 case ARM::ATOMIC_LOAD_UMIN_I32:
7374 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7376 case ARM::ATOMIC_LOAD_UMAX_I8:
7377 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7378 case ARM::ATOMIC_LOAD_UMAX_I16:
7379 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7380 case ARM::ATOMIC_LOAD_UMAX_I32:
7381 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7383 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7384 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7385 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7387 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7388 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7389 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7392 case ARM::ATOMADD6432:
7393 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7394 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7395 /*NeedsCarry*/ true);
7396 case ARM::ATOMSUB6432:
7397 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7398 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7399 /*NeedsCarry*/ true);
7400 case ARM::ATOMOR6432:
7401 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7402 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7403 case ARM::ATOMXOR6432:
7404 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7405 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7406 case ARM::ATOMAND6432:
7407 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7408 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7409 case ARM::ATOMSWAP6432:
7410 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7411 case ARM::ATOMCMPXCHG6432:
7412 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7413 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7414 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7415 case ARM::ATOMMIN6432:
7416 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7417 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7418 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7419 /*IsMinMax*/ true, ARMCC::LT);
7420 case ARM::ATOMMAX6432:
7421 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7422 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7423 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7424 /*IsMinMax*/ true, ARMCC::GE);
7425 case ARM::ATOMUMIN6432:
7426 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7427 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7428 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7429 /*IsMinMax*/ true, ARMCC::LO);
7430 case ARM::ATOMUMAX6432:
7431 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7432 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7433 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7434 /*IsMinMax*/ true, ARMCC::HS);
7436 case ARM::tMOVCCr_pseudo: {
7437 // To "insert" a SELECT_CC instruction, we actually have to insert the
7438 // diamond control-flow pattern. The incoming instruction knows the
7439 // destination vreg to set, the condition code register to branch on, the
7440 // true/false values to select between, and a branch opcode to use.
7441 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7442 MachineFunction::iterator It = BB;
7448 // cmpTY ccX, r1, r2
7450 // fallthrough --> copy0MBB
7451 MachineBasicBlock *thisMBB = BB;
7452 MachineFunction *F = BB->getParent();
7453 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7454 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7455 F->insert(It, copy0MBB);
7456 F->insert(It, sinkMBB);
7458 // Transfer the remainder of BB and its successor edges to sinkMBB.
7459 sinkMBB->splice(sinkMBB->begin(), BB,
7460 llvm::next(MachineBasicBlock::iterator(MI)),
7462 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7464 BB->addSuccessor(copy0MBB);
7465 BB->addSuccessor(sinkMBB);
7467 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7468 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7471 // %FalseValue = ...
7472 // # fallthrough to sinkMBB
7475 // Update machine-CFG edges
7476 BB->addSuccessor(sinkMBB);
7479 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7482 BuildMI(*BB, BB->begin(), dl,
7483 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7484 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7485 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7487 MI->eraseFromParent(); // The pseudo instruction is gone now.
7492 case ARM::BCCZi64: {
7493 // If there is an unconditional branch to the other successor, remove it.
7494 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7496 // Compare both parts that make up the double comparison separately for
7498 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7500 unsigned LHS1 = MI->getOperand(1).getReg();
7501 unsigned LHS2 = MI->getOperand(2).getReg();
7503 AddDefaultPred(BuildMI(BB, dl,
7504 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7505 .addReg(LHS1).addImm(0));
7506 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7507 .addReg(LHS2).addImm(0)
7508 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7510 unsigned RHS1 = MI->getOperand(3).getReg();
7511 unsigned RHS2 = MI->getOperand(4).getReg();
7512 AddDefaultPred(BuildMI(BB, dl,
7513 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7514 .addReg(LHS1).addReg(RHS1));
7515 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7516 .addReg(LHS2).addReg(RHS2)
7517 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7520 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7521 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7522 if (MI->getOperand(0).getImm() == ARMCC::NE)
7523 std::swap(destMBB, exitMBB);
7525 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7526 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7528 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7530 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7532 MI->eraseFromParent(); // The pseudo instruction is gone now.
7536 case ARM::Int_eh_sjlj_setjmp:
7537 case ARM::Int_eh_sjlj_setjmp_nofp:
7538 case ARM::tInt_eh_sjlj_setjmp:
7539 case ARM::t2Int_eh_sjlj_setjmp:
7540 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7541 EmitSjLjDispatchBlock(MI, BB);
7546 // To insert an ABS instruction, we have to insert the
7547 // diamond control-flow pattern. The incoming instruction knows the
7548 // source vreg to test against 0, the destination vreg to set,
7549 // the condition code register to branch on, the
7550 // true/false values to select between, and a branch opcode to use.
7555 // BCC (branch to SinkBB if V0 >= 0)
7556 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7557 // SinkBB: V1 = PHI(V2, V3)
7558 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7559 MachineFunction::iterator BBI = BB;
7561 MachineFunction *Fn = BB->getParent();
7562 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7563 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7564 Fn->insert(BBI, RSBBB);
7565 Fn->insert(BBI, SinkBB);
7567 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7568 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7569 bool isThumb2 = Subtarget->isThumb2();
7570 MachineRegisterInfo &MRI = Fn->getRegInfo();
7571 // In Thumb mode S must not be specified if source register is the SP or
7572 // PC and if destination register is the SP, so restrict register class
7573 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7574 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7575 (const TargetRegisterClass*)&ARM::GPRRegClass);
7577 // Transfer the remainder of BB and its successor edges to sinkMBB.
7578 SinkBB->splice(SinkBB->begin(), BB,
7579 llvm::next(MachineBasicBlock::iterator(MI)),
7581 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7583 BB->addSuccessor(RSBBB);
7584 BB->addSuccessor(SinkBB);
7586 // fall through to SinkMBB
7587 RSBBB->addSuccessor(SinkBB);
7589 // insert a cmp at the end of BB
7590 AddDefaultPred(BuildMI(BB, dl,
7591 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7592 .addReg(ABSSrcReg).addImm(0));
7594 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7596 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7597 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7599 // insert rsbri in RSBBB
7600 // Note: BCC and rsbri will be converted into predicated rsbmi
7601 // by if-conversion pass
7602 BuildMI(*RSBBB, RSBBB->begin(), dl,
7603 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7604 .addReg(ABSSrcReg, RegState::Kill)
7605 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7607 // insert PHI in SinkBB,
7608 // reuse ABSDstReg to not change uses of ABS instruction
7609 BuildMI(*SinkBB, SinkBB->begin(), dl,
7610 TII->get(ARM::PHI), ABSDstReg)
7611 .addReg(NewRsbDstReg).addMBB(RSBBB)
7612 .addReg(ABSSrcReg).addMBB(BB);
7614 // remove ABS instruction
7615 MI->eraseFromParent();
7617 // return last added BB
7620 case ARM::COPY_STRUCT_BYVAL_I32:
7622 return EmitStructByval(MI, BB);
7626 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7627 SDNode *Node) const {
7628 if (!MI->hasPostISelHook()) {
7629 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7630 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7634 const MCInstrDesc *MCID = &MI->getDesc();
7635 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7636 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7637 // operand is still set to noreg. If needed, set the optional operand's
7638 // register to CPSR, and remove the redundant implicit def.
7640 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7642 // Rename pseudo opcodes.
7643 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7645 const ARMBaseInstrInfo *TII =
7646 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7647 MCID = &TII->get(NewOpc);
7649 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7650 "converted opcode should be the same except for cc_out");
7654 // Add the optional cc_out operand
7655 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7657 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7659 // Any ARM instruction that sets the 's' bit should specify an optional
7660 // "cc_out" operand in the last operand position.
7661 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7662 assert(!NewOpc && "Optional cc_out operand required");
7665 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7666 // since we already have an optional CPSR def.
7667 bool definesCPSR = false;
7668 bool deadCPSR = false;
7669 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7671 const MachineOperand &MO = MI->getOperand(i);
7672 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7676 MI->RemoveOperand(i);
7681 assert(!NewOpc && "Optional cc_out operand required");
7684 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7686 assert(!MI->getOperand(ccOutIdx).getReg() &&
7687 "expect uninitialized optional cc_out operand");
7691 // If this instruction was defined with an optional CPSR def and its dag node
7692 // had a live implicit CPSR def, then activate the optional CPSR def.
7693 MachineOperand &MO = MI->getOperand(ccOutIdx);
7694 MO.setReg(ARM::CPSR);
7698 //===----------------------------------------------------------------------===//
7699 // ARM Optimization Hooks
7700 //===----------------------------------------------------------------------===//
7702 // Helper function that checks if N is a null or all ones constant.
7703 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7704 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7707 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7710 // Return true if N is conditionally 0 or all ones.
7711 // Detects these expressions where cc is an i1 value:
7713 // (select cc 0, y) [AllOnes=0]
7714 // (select cc y, 0) [AllOnes=0]
7715 // (zext cc) [AllOnes=0]
7716 // (sext cc) [AllOnes=0/1]
7717 // (select cc -1, y) [AllOnes=1]
7718 // (select cc y, -1) [AllOnes=1]
7720 // Invert is set when N is the null/all ones constant when CC is false.
7721 // OtherOp is set to the alternative value of N.
7722 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7723 SDValue &CC, bool &Invert,
7725 SelectionDAG &DAG) {
7726 switch (N->getOpcode()) {
7727 default: return false;
7729 CC = N->getOperand(0);
7730 SDValue N1 = N->getOperand(1);
7731 SDValue N2 = N->getOperand(2);
7732 if (isZeroOrAllOnes(N1, AllOnes)) {
7737 if (isZeroOrAllOnes(N2, AllOnes)) {
7744 case ISD::ZERO_EXTEND:
7745 // (zext cc) can never be the all ones value.
7749 case ISD::SIGN_EXTEND: {
7750 EVT VT = N->getValueType(0);
7751 CC = N->getOperand(0);
7752 if (CC.getValueType() != MVT::i1)
7756 // When looking for an AllOnes constant, N is an sext, and the 'other'
7758 OtherOp = DAG.getConstant(0, VT);
7759 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7760 // When looking for a 0 constant, N can be zext or sext.
7761 OtherOp = DAG.getConstant(1, VT);
7763 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7769 // Combine a constant select operand into its use:
7771 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7772 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7773 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7774 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7775 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7777 // The transform is rejected if the select doesn't have a constant operand that
7778 // is null, or all ones when AllOnes is set.
7780 // Also recognize sext/zext from i1:
7782 // (add (zext cc), x) -> (select cc (add x, 1), x)
7783 // (add (sext cc), x) -> (select cc (add x, -1), x)
7785 // These transformations eventually create predicated instructions.
7787 // @param N The node to transform.
7788 // @param Slct The N operand that is a select.
7789 // @param OtherOp The other N operand (x above).
7790 // @param DCI Context.
7791 // @param AllOnes Require the select constant to be all ones instead of null.
7792 // @returns The new node, or SDValue() on failure.
7794 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7795 TargetLowering::DAGCombinerInfo &DCI,
7796 bool AllOnes = false) {
7797 SelectionDAG &DAG = DCI.DAG;
7798 EVT VT = N->getValueType(0);
7799 SDValue NonConstantVal;
7802 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7803 NonConstantVal, DAG))
7806 // Slct is now know to be the desired identity constant when CC is true.
7807 SDValue TrueVal = OtherOp;
7808 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7809 OtherOp, NonConstantVal);
7810 // Unless SwapSelectOps says CC should be false.
7812 std::swap(TrueVal, FalseVal);
7814 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7815 CCOp, TrueVal, FalseVal);
7818 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7820 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7821 TargetLowering::DAGCombinerInfo &DCI) {
7822 SDValue N0 = N->getOperand(0);
7823 SDValue N1 = N->getOperand(1);
7824 if (N0.getNode()->hasOneUse()) {
7825 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7826 if (Result.getNode())
7829 if (N1.getNode()->hasOneUse()) {
7830 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7831 if (Result.getNode())
7837 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7838 // (only after legalization).
7839 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7840 TargetLowering::DAGCombinerInfo &DCI,
7841 const ARMSubtarget *Subtarget) {
7843 // Only perform optimization if after legalize, and if NEON is available. We
7844 // also expected both operands to be BUILD_VECTORs.
7845 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7846 || N0.getOpcode() != ISD::BUILD_VECTOR
7847 || N1.getOpcode() != ISD::BUILD_VECTOR)
7850 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7851 EVT VT = N->getValueType(0);
7852 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7855 // Check that the vector operands are of the right form.
7856 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7857 // operands, where N is the size of the formed vector.
7858 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7859 // index such that we have a pair wise add pattern.
7861 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7862 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7864 SDValue Vec = N0->getOperand(0)->getOperand(0);
7865 SDNode *V = Vec.getNode();
7866 unsigned nextIndex = 0;
7868 // For each operands to the ADD which are BUILD_VECTORs,
7869 // check to see if each of their operands are an EXTRACT_VECTOR with
7870 // the same vector and appropriate index.
7871 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7872 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7873 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7875 SDValue ExtVec0 = N0->getOperand(i);
7876 SDValue ExtVec1 = N1->getOperand(i);
7878 // First operand is the vector, verify its the same.
7879 if (V != ExtVec0->getOperand(0).getNode() ||
7880 V != ExtVec1->getOperand(0).getNode())
7883 // Second is the constant, verify its correct.
7884 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7885 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7887 // For the constant, we want to see all the even or all the odd.
7888 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7889 || C1->getZExtValue() != nextIndex+1)
7898 // Create VPADDL node.
7899 SelectionDAG &DAG = DCI.DAG;
7900 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7902 // Build operand list.
7903 SmallVector<SDValue, 8> Ops;
7904 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7905 TLI.getPointerTy()));
7907 // Input is the vector.
7910 // Get widened type and narrowed type.
7912 unsigned numElem = VT.getVectorNumElements();
7913 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7914 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7915 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7916 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7918 llvm_unreachable("Invalid vector element type for padd optimization.");
7921 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
7922 widenType, &Ops[0], Ops.size());
7923 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
7926 static SDValue findMUL_LOHI(SDValue V) {
7927 if (V->getOpcode() == ISD::UMUL_LOHI ||
7928 V->getOpcode() == ISD::SMUL_LOHI)
7933 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7934 TargetLowering::DAGCombinerInfo &DCI,
7935 const ARMSubtarget *Subtarget) {
7937 if (Subtarget->isThumb1Only()) return SDValue();
7939 // Only perform the checks after legalize when the pattern is available.
7940 if (DCI.isBeforeLegalize()) return SDValue();
7942 // Look for multiply add opportunities.
7943 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7944 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7945 // a glue link from the first add to the second add.
7946 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7947 // a S/UMLAL instruction.
7950 // \ / \ [no multiline comment]
7956 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7957 SDValue AddcOp0 = AddcNode->getOperand(0);
7958 SDValue AddcOp1 = AddcNode->getOperand(1);
7960 // Check if the two operands are from the same mul_lohi node.
7961 if (AddcOp0.getNode() == AddcOp1.getNode())
7964 assert(AddcNode->getNumValues() == 2 &&
7965 AddcNode->getValueType(0) == MVT::i32 &&
7966 "Expect ADDC with two result values. First: i32");
7968 // Check that we have a glued ADDC node.
7969 if (AddcNode->getValueType(1) != MVT::Glue)
7972 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7973 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7974 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7975 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7976 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7979 // Look for the glued ADDE.
7980 SDNode* AddeNode = AddcNode->getGluedUser();
7981 if (AddeNode == NULL)
7984 // Make sure it is really an ADDE.
7985 if (AddeNode->getOpcode() != ISD::ADDE)
7988 assert(AddeNode->getNumOperands() == 3 &&
7989 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7990 "ADDE node has the wrong inputs");
7992 // Check for the triangle shape.
7993 SDValue AddeOp0 = AddeNode->getOperand(0);
7994 SDValue AddeOp1 = AddeNode->getOperand(1);
7996 // Make sure that the ADDE operands are not coming from the same node.
7997 if (AddeOp0.getNode() == AddeOp1.getNode())
8000 // Find the MUL_LOHI node walking up ADDE's operands.
8001 bool IsLeftOperandMUL = false;
8002 SDValue MULOp = findMUL_LOHI(AddeOp0);
8003 if (MULOp == SDValue())
8004 MULOp = findMUL_LOHI(AddeOp1);
8006 IsLeftOperandMUL = true;
8007 if (MULOp == SDValue())
8010 // Figure out the right opcode.
8011 unsigned Opc = MULOp->getOpcode();
8012 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8014 // Figure out the high and low input values to the MLAL node.
8015 SDValue* HiMul = &MULOp;
8016 SDValue* HiAdd = NULL;
8017 SDValue* LoMul = NULL;
8018 SDValue* LowAdd = NULL;
8020 if (IsLeftOperandMUL)
8026 if (AddcOp0->getOpcode() == Opc) {
8030 if (AddcOp1->getOpcode() == Opc) {
8038 if (LoMul->getNode() != HiMul->getNode())
8041 // Create the merged node.
8042 SelectionDAG &DAG = DCI.DAG;
8044 // Build operand list.
8045 SmallVector<SDValue, 8> Ops;
8046 Ops.push_back(LoMul->getOperand(0));
8047 Ops.push_back(LoMul->getOperand(1));
8048 Ops.push_back(*LowAdd);
8049 Ops.push_back(*HiAdd);
8051 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8052 DAG.getVTList(MVT::i32, MVT::i32),
8053 &Ops[0], Ops.size());
8055 // Replace the ADDs' nodes uses by the MLA node's values.
8056 SDValue HiMLALResult(MLALNode.getNode(), 1);
8057 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8059 SDValue LoMLALResult(MLALNode.getNode(), 0);
8060 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8062 // Return original node to notify the driver to stop replacing.
8063 SDValue resNode(AddcNode, 0);
8067 /// PerformADDCCombine - Target-specific dag combine transform from
8068 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8069 static SDValue PerformADDCCombine(SDNode *N,
8070 TargetLowering::DAGCombinerInfo &DCI,
8071 const ARMSubtarget *Subtarget) {
8073 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8077 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8078 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8079 /// called with the default operands, and if that fails, with commuted
8081 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8082 TargetLowering::DAGCombinerInfo &DCI,
8083 const ARMSubtarget *Subtarget){
8085 // Attempt to create vpaddl for this add.
8086 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8087 if (Result.getNode())
8090 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8091 if (N0.getNode()->hasOneUse()) {
8092 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8093 if (Result.getNode()) return Result;
8098 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8100 static SDValue PerformADDCombine(SDNode *N,
8101 TargetLowering::DAGCombinerInfo &DCI,
8102 const ARMSubtarget *Subtarget) {
8103 SDValue N0 = N->getOperand(0);
8104 SDValue N1 = N->getOperand(1);
8106 // First try with the default operand order.
8107 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8108 if (Result.getNode())
8111 // If that didn't work, try again with the operands commuted.
8112 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8115 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8117 static SDValue PerformSUBCombine(SDNode *N,
8118 TargetLowering::DAGCombinerInfo &DCI) {
8119 SDValue N0 = N->getOperand(0);
8120 SDValue N1 = N->getOperand(1);
8122 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8123 if (N1.getNode()->hasOneUse()) {
8124 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8125 if (Result.getNode()) return Result;
8131 /// PerformVMULCombine
8132 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8133 /// special multiplier accumulator forwarding.
8139 static SDValue PerformVMULCombine(SDNode *N,
8140 TargetLowering::DAGCombinerInfo &DCI,
8141 const ARMSubtarget *Subtarget) {
8142 if (!Subtarget->hasVMLxForwarding())
8145 SelectionDAG &DAG = DCI.DAG;
8146 SDValue N0 = N->getOperand(0);
8147 SDValue N1 = N->getOperand(1);
8148 unsigned Opcode = N0.getOpcode();
8149 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8150 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8151 Opcode = N1.getOpcode();
8152 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8153 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8158 EVT VT = N->getValueType(0);
8160 SDValue N00 = N0->getOperand(0);
8161 SDValue N01 = N0->getOperand(1);
8162 return DAG.getNode(Opcode, DL, VT,
8163 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8164 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8167 static SDValue PerformMULCombine(SDNode *N,
8168 TargetLowering::DAGCombinerInfo &DCI,
8169 const ARMSubtarget *Subtarget) {
8170 SelectionDAG &DAG = DCI.DAG;
8172 if (Subtarget->isThumb1Only())
8175 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8178 EVT VT = N->getValueType(0);
8179 if (VT.is64BitVector() || VT.is128BitVector())
8180 return PerformVMULCombine(N, DCI, Subtarget);
8184 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8188 int64_t MulAmt = C->getSExtValue();
8189 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8191 ShiftAmt = ShiftAmt & (32 - 1);
8192 SDValue V = N->getOperand(0);
8196 MulAmt >>= ShiftAmt;
8199 if (isPowerOf2_32(MulAmt - 1)) {
8200 // (mul x, 2^N + 1) => (add (shl x, N), x)
8201 Res = DAG.getNode(ISD::ADD, DL, VT,
8203 DAG.getNode(ISD::SHL, DL, VT,
8205 DAG.getConstant(Log2_32(MulAmt - 1),
8207 } else if (isPowerOf2_32(MulAmt + 1)) {
8208 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8209 Res = DAG.getNode(ISD::SUB, DL, VT,
8210 DAG.getNode(ISD::SHL, DL, VT,
8212 DAG.getConstant(Log2_32(MulAmt + 1),
8218 uint64_t MulAmtAbs = -MulAmt;
8219 if (isPowerOf2_32(MulAmtAbs + 1)) {
8220 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8221 Res = DAG.getNode(ISD::SUB, DL, VT,
8223 DAG.getNode(ISD::SHL, DL, VT,
8225 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8227 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8228 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8229 Res = DAG.getNode(ISD::ADD, DL, VT,
8231 DAG.getNode(ISD::SHL, DL, VT,
8233 DAG.getConstant(Log2_32(MulAmtAbs-1),
8235 Res = DAG.getNode(ISD::SUB, DL, VT,
8236 DAG.getConstant(0, MVT::i32),Res);
8243 Res = DAG.getNode(ISD::SHL, DL, VT,
8244 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8246 // Do not add new nodes to DAG combiner worklist.
8247 DCI.CombineTo(N, Res, false);
8251 static SDValue PerformANDCombine(SDNode *N,
8252 TargetLowering::DAGCombinerInfo &DCI,
8253 const ARMSubtarget *Subtarget) {
8255 // Attempt to use immediate-form VBIC
8256 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8258 EVT VT = N->getValueType(0);
8259 SelectionDAG &DAG = DCI.DAG;
8261 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8264 APInt SplatBits, SplatUndef;
8265 unsigned SplatBitSize;
8268 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8269 if (SplatBitSize <= 64) {
8271 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8272 SplatUndef.getZExtValue(), SplatBitSize,
8273 DAG, VbicVT, VT.is128BitVector(),
8275 if (Val.getNode()) {
8277 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8278 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8279 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8284 if (!Subtarget->isThumb1Only()) {
8285 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8286 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8287 if (Result.getNode())
8294 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8295 static SDValue PerformORCombine(SDNode *N,
8296 TargetLowering::DAGCombinerInfo &DCI,
8297 const ARMSubtarget *Subtarget) {
8298 // Attempt to use immediate-form VORR
8299 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8301 EVT VT = N->getValueType(0);
8302 SelectionDAG &DAG = DCI.DAG;
8304 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8307 APInt SplatBits, SplatUndef;
8308 unsigned SplatBitSize;
8310 if (BVN && Subtarget->hasNEON() &&
8311 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8312 if (SplatBitSize <= 64) {
8314 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8315 SplatUndef.getZExtValue(), SplatBitSize,
8316 DAG, VorrVT, VT.is128BitVector(),
8318 if (Val.getNode()) {
8320 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8321 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8322 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8327 if (!Subtarget->isThumb1Only()) {
8328 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8329 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8330 if (Result.getNode())
8334 // The code below optimizes (or (and X, Y), Z).
8335 // The AND operand needs to have a single user to make these optimizations
8337 SDValue N0 = N->getOperand(0);
8338 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8340 SDValue N1 = N->getOperand(1);
8342 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8343 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8344 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8346 unsigned SplatBitSize;
8349 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8351 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8352 HasAnyUndefs) && !HasAnyUndefs) {
8353 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8355 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8356 HasAnyUndefs) && !HasAnyUndefs &&
8357 SplatBits0 == ~SplatBits1) {
8358 // Canonicalize the vector type to make instruction selection simpler.
8359 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8360 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8361 N0->getOperand(1), N0->getOperand(0),
8363 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8368 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8371 // BFI is only available on V6T2+
8372 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8376 // 1) or (and A, mask), val => ARMbfi A, val, mask
8377 // iff (val & mask) == val
8379 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8380 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8381 // && mask == ~mask2
8382 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8383 // && ~mask == mask2
8384 // (i.e., copy a bitfield value into another bitfield of the same width)
8389 SDValue N00 = N0.getOperand(0);
8391 // The value and the mask need to be constants so we can verify this is
8392 // actually a bitfield set. If the mask is 0xffff, we can do better
8393 // via a movt instruction, so don't use BFI in that case.
8394 SDValue MaskOp = N0.getOperand(1);
8395 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8398 unsigned Mask = MaskC->getZExtValue();
8402 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8403 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8405 unsigned Val = N1C->getZExtValue();
8406 if ((Val & ~Mask) != Val)
8409 if (ARM::isBitFieldInvertedMask(Mask)) {
8410 Val >>= countTrailingZeros(~Mask);
8412 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8413 DAG.getConstant(Val, MVT::i32),
8414 DAG.getConstant(Mask, MVT::i32));
8416 // Do not add new nodes to DAG combiner worklist.
8417 DCI.CombineTo(N, Res, false);
8420 } else if (N1.getOpcode() == ISD::AND) {
8421 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8422 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8425 unsigned Mask2 = N11C->getZExtValue();
8427 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8429 if (ARM::isBitFieldInvertedMask(Mask) &&
8431 // The pack halfword instruction works better for masks that fit it,
8432 // so use that when it's available.
8433 if (Subtarget->hasT2ExtractPack() &&
8434 (Mask == 0xffff || Mask == 0xffff0000))
8437 unsigned amt = countTrailingZeros(Mask2);
8438 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8439 DAG.getConstant(amt, MVT::i32));
8440 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8441 DAG.getConstant(Mask, MVT::i32));
8442 // Do not add new nodes to DAG combiner worklist.
8443 DCI.CombineTo(N, Res, false);
8445 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8447 // The pack halfword instruction works better for masks that fit it,
8448 // so use that when it's available.
8449 if (Subtarget->hasT2ExtractPack() &&
8450 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8453 unsigned lsb = countTrailingZeros(Mask);
8454 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8455 DAG.getConstant(lsb, MVT::i32));
8456 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8457 DAG.getConstant(Mask2, MVT::i32));
8458 // Do not add new nodes to DAG combiner worklist.
8459 DCI.CombineTo(N, Res, false);
8464 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8465 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8466 ARM::isBitFieldInvertedMask(~Mask)) {
8467 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8468 // where lsb(mask) == #shamt and masked bits of B are known zero.
8469 SDValue ShAmt = N00.getOperand(1);
8470 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8471 unsigned LSB = countTrailingZeros(Mask);
8475 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8476 DAG.getConstant(~Mask, MVT::i32));
8478 // Do not add new nodes to DAG combiner worklist.
8479 DCI.CombineTo(N, Res, false);
8485 static SDValue PerformXORCombine(SDNode *N,
8486 TargetLowering::DAGCombinerInfo &DCI,
8487 const ARMSubtarget *Subtarget) {
8488 EVT VT = N->getValueType(0);
8489 SelectionDAG &DAG = DCI.DAG;
8491 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8494 if (!Subtarget->isThumb1Only()) {
8495 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8496 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8497 if (Result.getNode())
8504 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8505 /// the bits being cleared by the AND are not demanded by the BFI.
8506 static SDValue PerformBFICombine(SDNode *N,
8507 TargetLowering::DAGCombinerInfo &DCI) {
8508 SDValue N1 = N->getOperand(1);
8509 if (N1.getOpcode() == ISD::AND) {
8510 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8513 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8514 unsigned LSB = countTrailingZeros(~InvMask);
8515 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8516 unsigned Mask = (1 << Width)-1;
8517 unsigned Mask2 = N11C->getZExtValue();
8518 if ((Mask & (~Mask2)) == 0)
8519 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8520 N->getOperand(0), N1.getOperand(0),
8526 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8527 /// ARMISD::VMOVRRD.
8528 static SDValue PerformVMOVRRDCombine(SDNode *N,
8529 TargetLowering::DAGCombinerInfo &DCI) {
8530 // vmovrrd(vmovdrr x, y) -> x,y
8531 SDValue InDouble = N->getOperand(0);
8532 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8533 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8535 // vmovrrd(load f64) -> (load i32), (load i32)
8536 SDNode *InNode = InDouble.getNode();
8537 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8538 InNode->getValueType(0) == MVT::f64 &&
8539 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8540 !cast<LoadSDNode>(InNode)->isVolatile()) {
8541 // TODO: Should this be done for non-FrameIndex operands?
8542 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8544 SelectionDAG &DAG = DCI.DAG;
8546 SDValue BasePtr = LD->getBasePtr();
8547 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8548 LD->getPointerInfo(), LD->isVolatile(),
8549 LD->isNonTemporal(), LD->isInvariant(),
8550 LD->getAlignment());
8552 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8553 DAG.getConstant(4, MVT::i32));
8554 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8555 LD->getPointerInfo(), LD->isVolatile(),
8556 LD->isNonTemporal(), LD->isInvariant(),
8557 std::min(4U, LD->getAlignment() / 2));
8559 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8560 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8561 DCI.RemoveFromWorklist(LD);
8569 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8570 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8571 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8572 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8573 SDValue Op0 = N->getOperand(0);
8574 SDValue Op1 = N->getOperand(1);
8575 if (Op0.getOpcode() == ISD::BITCAST)
8576 Op0 = Op0.getOperand(0);
8577 if (Op1.getOpcode() == ISD::BITCAST)
8578 Op1 = Op1.getOperand(0);
8579 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8580 Op0.getNode() == Op1.getNode() &&
8581 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8582 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8583 N->getValueType(0), Op0.getOperand(0));
8587 /// PerformSTORECombine - Target-specific dag combine xforms for
8589 static SDValue PerformSTORECombine(SDNode *N,
8590 TargetLowering::DAGCombinerInfo &DCI) {
8591 StoreSDNode *St = cast<StoreSDNode>(N);
8592 if (St->isVolatile())
8595 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8596 // pack all of the elements in one place. Next, store to memory in fewer
8598 SDValue StVal = St->getValue();
8599 EVT VT = StVal.getValueType();
8600 if (St->isTruncatingStore() && VT.isVector()) {
8601 SelectionDAG &DAG = DCI.DAG;
8602 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8603 EVT StVT = St->getMemoryVT();
8604 unsigned NumElems = VT.getVectorNumElements();
8605 assert(StVT != VT && "Cannot truncate to the same type");
8606 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8607 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8609 // From, To sizes and ElemCount must be pow of two
8610 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8612 // We are going to use the original vector elt for storing.
8613 // Accumulated smaller vector elements must be a multiple of the store size.
8614 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8616 unsigned SizeRatio = FromEltSz / ToEltSz;
8617 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8619 // Create a type on which we perform the shuffle.
8620 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8621 NumElems*SizeRatio);
8622 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8625 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8626 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8627 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8629 // Can't shuffle using an illegal type.
8630 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8632 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8633 DAG.getUNDEF(WideVec.getValueType()),
8635 // At this point all of the data is stored at the bottom of the
8636 // register. We now need to save it to mem.
8638 // Find the largest store unit
8639 MVT StoreType = MVT::i8;
8640 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8641 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8642 MVT Tp = (MVT::SimpleValueType)tp;
8643 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8646 // Didn't find a legal store type.
8647 if (!TLI.isTypeLegal(StoreType))
8650 // Bitcast the original vector into a vector of store-size units
8651 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8652 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8653 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8654 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8655 SmallVector<SDValue, 8> Chains;
8656 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8657 TLI.getPointerTy());
8658 SDValue BasePtr = St->getBasePtr();
8660 // Perform one or more big stores into memory.
8661 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8662 for (unsigned I = 0; I < E; I++) {
8663 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8664 StoreType, ShuffWide,
8665 DAG.getIntPtrConstant(I));
8666 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8667 St->getPointerInfo(), St->isVolatile(),
8668 St->isNonTemporal(), St->getAlignment());
8669 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8671 Chains.push_back(Ch);
8673 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8677 if (!ISD::isNormalStore(St))
8680 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8681 // ARM stores of arguments in the same cache line.
8682 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8683 StVal.getNode()->hasOneUse()) {
8684 SelectionDAG &DAG = DCI.DAG;
8686 SDValue BasePtr = St->getBasePtr();
8687 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8688 StVal.getNode()->getOperand(0), BasePtr,
8689 St->getPointerInfo(), St->isVolatile(),
8690 St->isNonTemporal(), St->getAlignment());
8692 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8693 DAG.getConstant(4, MVT::i32));
8694 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8695 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8696 St->isNonTemporal(),
8697 std::min(4U, St->getAlignment() / 2));
8700 if (StVal.getValueType() != MVT::i64 ||
8701 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8704 // Bitcast an i64 store extracted from a vector to f64.
8705 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8706 SelectionDAG &DAG = DCI.DAG;
8708 SDValue IntVec = StVal.getOperand(0);
8709 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8710 IntVec.getValueType().getVectorNumElements());
8711 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8712 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8713 Vec, StVal.getOperand(1));
8715 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8716 // Make the DAGCombiner fold the bitcasts.
8717 DCI.AddToWorklist(Vec.getNode());
8718 DCI.AddToWorklist(ExtElt.getNode());
8719 DCI.AddToWorklist(V.getNode());
8720 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8721 St->getPointerInfo(), St->isVolatile(),
8722 St->isNonTemporal(), St->getAlignment(),
8726 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8727 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8728 /// i64 vector to have f64 elements, since the value can then be loaded
8729 /// directly into a VFP register.
8730 static bool hasNormalLoadOperand(SDNode *N) {
8731 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8732 for (unsigned i = 0; i < NumElts; ++i) {
8733 SDNode *Elt = N->getOperand(i).getNode();
8734 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8740 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8741 /// ISD::BUILD_VECTOR.
8742 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8743 TargetLowering::DAGCombinerInfo &DCI){
8744 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8745 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8746 // into a pair of GPRs, which is fine when the value is used as a scalar,
8747 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8748 SelectionDAG &DAG = DCI.DAG;
8749 if (N->getNumOperands() == 2) {
8750 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8755 // Load i64 elements as f64 values so that type legalization does not split
8756 // them up into i32 values.
8757 EVT VT = N->getValueType(0);
8758 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8761 SmallVector<SDValue, 8> Ops;
8762 unsigned NumElts = VT.getVectorNumElements();
8763 for (unsigned i = 0; i < NumElts; ++i) {
8764 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8766 // Make the DAGCombiner fold the bitcast.
8767 DCI.AddToWorklist(V.getNode());
8769 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8770 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8771 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8774 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8776 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8777 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8778 // At that time, we may have inserted bitcasts from integer to float.
8779 // If these bitcasts have survived DAGCombine, change the lowering of this
8780 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8781 // force to use floating point types.
8783 // Make sure we can change the type of the vector.
8784 // This is possible iff:
8785 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8786 // 1.1. Vector is used only once.
8787 // 1.2. Use is a bit convert to an integer type.
8788 // 2. The size of its operands are 32-bits (64-bits are not legal).
8789 EVT VT = N->getValueType(0);
8790 EVT EltVT = VT.getVectorElementType();
8792 // Check 1.1. and 2.
8793 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8796 // By construction, the input type must be float.
8797 assert(EltVT == MVT::f32 && "Unexpected type!");
8800 SDNode *Use = *N->use_begin();
8801 if (Use->getOpcode() != ISD::BITCAST ||
8802 Use->getValueType(0).isFloatingPoint())
8805 // Check profitability.
8806 // Model is, if more than half of the relevant operands are bitcast from
8807 // i32, turn the build_vector into a sequence of insert_vector_elt.
8808 // Relevant operands are everything that is not statically
8809 // (i.e., at compile time) bitcasted.
8810 unsigned NumOfBitCastedElts = 0;
8811 unsigned NumElts = VT.getVectorNumElements();
8812 unsigned NumOfRelevantElts = NumElts;
8813 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8814 SDValue Elt = N->getOperand(Idx);
8815 if (Elt->getOpcode() == ISD::BITCAST) {
8816 // Assume only bit cast to i32 will go away.
8817 if (Elt->getOperand(0).getValueType() == MVT::i32)
8818 ++NumOfBitCastedElts;
8819 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8820 // Constants are statically casted, thus do not count them as
8821 // relevant operands.
8822 --NumOfRelevantElts;
8825 // Check if more than half of the elements require a non-free bitcast.
8826 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8829 SelectionDAG &DAG = DCI.DAG;
8830 // Create the new vector type.
8831 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8832 // Check if the type is legal.
8833 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8834 if (!TLI.isTypeLegal(VecVT))
8838 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8839 // => BITCAST INSERT_VECTOR_ELT
8840 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8842 SDValue Vec = DAG.getUNDEF(VecVT);
8844 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8845 SDValue V = N->getOperand(Idx);
8846 if (V.getOpcode() == ISD::UNDEF)
8848 if (V.getOpcode() == ISD::BITCAST &&
8849 V->getOperand(0).getValueType() == MVT::i32)
8850 // Fold obvious case.
8851 V = V.getOperand(0);
8853 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8854 // Make the DAGCombiner fold the bitcasts.
8855 DCI.AddToWorklist(V.getNode());
8857 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8858 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8860 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8861 // Make the DAGCombiner fold the bitcasts.
8862 DCI.AddToWorklist(Vec.getNode());
8866 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8867 /// ISD::INSERT_VECTOR_ELT.
8868 static SDValue PerformInsertEltCombine(SDNode *N,
8869 TargetLowering::DAGCombinerInfo &DCI) {
8870 // Bitcast an i64 load inserted into a vector to f64.
8871 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8872 EVT VT = N->getValueType(0);
8873 SDNode *Elt = N->getOperand(1).getNode();
8874 if (VT.getVectorElementType() != MVT::i64 ||
8875 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8878 SelectionDAG &DAG = DCI.DAG;
8880 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8881 VT.getVectorNumElements());
8882 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8883 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8884 // Make the DAGCombiner fold the bitcasts.
8885 DCI.AddToWorklist(Vec.getNode());
8886 DCI.AddToWorklist(V.getNode());
8887 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8888 Vec, V, N->getOperand(2));
8889 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8892 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8893 /// ISD::VECTOR_SHUFFLE.
8894 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8895 // The LLVM shufflevector instruction does not require the shuffle mask
8896 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8897 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8898 // operands do not match the mask length, they are extended by concatenating
8899 // them with undef vectors. That is probably the right thing for other
8900 // targets, but for NEON it is better to concatenate two double-register
8901 // size vector operands into a single quad-register size vector. Do that
8902 // transformation here:
8903 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8904 // shuffle(concat(v1, v2), undef)
8905 SDValue Op0 = N->getOperand(0);
8906 SDValue Op1 = N->getOperand(1);
8907 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8908 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8909 Op0.getNumOperands() != 2 ||
8910 Op1.getNumOperands() != 2)
8912 SDValue Concat0Op1 = Op0.getOperand(1);
8913 SDValue Concat1Op1 = Op1.getOperand(1);
8914 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8915 Concat1Op1.getOpcode() != ISD::UNDEF)
8917 // Skip the transformation if any of the types are illegal.
8918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8919 EVT VT = N->getValueType(0);
8920 if (!TLI.isTypeLegal(VT) ||
8921 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8922 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8925 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8926 Op0.getOperand(0), Op1.getOperand(0));
8927 // Translate the shuffle mask.
8928 SmallVector<int, 16> NewMask;
8929 unsigned NumElts = VT.getVectorNumElements();
8930 unsigned HalfElts = NumElts/2;
8931 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8932 for (unsigned n = 0; n < NumElts; ++n) {
8933 int MaskElt = SVN->getMaskElt(n);
8935 if (MaskElt < (int)HalfElts)
8937 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8938 NewElt = HalfElts + MaskElt - NumElts;
8939 NewMask.push_back(NewElt);
8941 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8942 DAG.getUNDEF(VT), NewMask.data());
8945 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8946 /// NEON load/store intrinsics to merge base address updates.
8947 static SDValue CombineBaseUpdate(SDNode *N,
8948 TargetLowering::DAGCombinerInfo &DCI) {
8949 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8952 SelectionDAG &DAG = DCI.DAG;
8953 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8954 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8955 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8956 SDValue Addr = N->getOperand(AddrOpIdx);
8958 // Search for a use of the address operand that is an increment.
8959 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8960 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8962 if (User->getOpcode() != ISD::ADD ||
8963 UI.getUse().getResNo() != Addr.getResNo())
8966 // Check that the add is independent of the load/store. Otherwise, folding
8967 // it would create a cycle.
8968 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8971 // Find the new opcode for the updating load/store.
8973 bool isLaneOp = false;
8974 unsigned NewOpc = 0;
8975 unsigned NumVecs = 0;
8977 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8979 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8980 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8982 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8984 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8986 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8988 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8989 NumVecs = 2; isLaneOp = true; break;
8990 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8991 NumVecs = 3; isLaneOp = true; break;
8992 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8993 NumVecs = 4; isLaneOp = true; break;
8994 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8995 NumVecs = 1; isLoad = false; break;
8996 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8997 NumVecs = 2; isLoad = false; break;
8998 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8999 NumVecs = 3; isLoad = false; break;
9000 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9001 NumVecs = 4; isLoad = false; break;
9002 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9003 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9004 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9005 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9006 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9007 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9011 switch (N->getOpcode()) {
9012 default: llvm_unreachable("unexpected opcode for Neon base update");
9013 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9014 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9015 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9019 // Find the size of memory referenced by the load/store.
9022 VecTy = N->getValueType(0);
9024 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9025 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9027 NumBytes /= VecTy.getVectorNumElements();
9029 // If the increment is a constant, it must match the memory ref size.
9030 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9031 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9032 uint64_t IncVal = CInc->getZExtValue();
9033 if (IncVal != NumBytes)
9035 } else if (NumBytes >= 3 * 16) {
9036 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9037 // separate instructions that make it harder to use a non-constant update.
9041 // Create the new updating load/store node.
9043 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9045 for (n = 0; n < NumResultVecs; ++n)
9047 Tys[n++] = MVT::i32;
9048 Tys[n] = MVT::Other;
9049 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9050 SmallVector<SDValue, 8> Ops;
9051 Ops.push_back(N->getOperand(0)); // incoming chain
9052 Ops.push_back(N->getOperand(AddrOpIdx));
9054 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9055 Ops.push_back(N->getOperand(i));
9057 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9058 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9059 Ops.data(), Ops.size(),
9060 MemInt->getMemoryVT(),
9061 MemInt->getMemOperand());
9064 std::vector<SDValue> NewResults;
9065 for (unsigned i = 0; i < NumResultVecs; ++i) {
9066 NewResults.push_back(SDValue(UpdN.getNode(), i));
9068 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9069 DCI.CombineTo(N, NewResults);
9070 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9077 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9078 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9079 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9081 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9082 SelectionDAG &DAG = DCI.DAG;
9083 EVT VT = N->getValueType(0);
9084 // vldN-dup instructions only support 64-bit vectors for N > 1.
9085 if (!VT.is64BitVector())
9088 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9089 SDNode *VLD = N->getOperand(0).getNode();
9090 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9092 unsigned NumVecs = 0;
9093 unsigned NewOpc = 0;
9094 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9095 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9097 NewOpc = ARMISD::VLD2DUP;
9098 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9100 NewOpc = ARMISD::VLD3DUP;
9101 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9103 NewOpc = ARMISD::VLD4DUP;
9108 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9109 // numbers match the load.
9110 unsigned VLDLaneNo =
9111 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9112 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9114 // Ignore uses of the chain result.
9115 if (UI.getUse().getResNo() == NumVecs)
9118 if (User->getOpcode() != ARMISD::VDUPLANE ||
9119 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9123 // Create the vldN-dup node.
9126 for (n = 0; n < NumVecs; ++n)
9128 Tys[n] = MVT::Other;
9129 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9130 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9131 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9132 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9133 Ops, 2, VLDMemInt->getMemoryVT(),
9134 VLDMemInt->getMemOperand());
9137 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9139 unsigned ResNo = UI.getUse().getResNo();
9140 // Ignore uses of the chain result.
9141 if (ResNo == NumVecs)
9144 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9147 // Now the vldN-lane intrinsic is dead except for its chain result.
9148 // Update uses of the chain.
9149 std::vector<SDValue> VLDDupResults;
9150 for (unsigned n = 0; n < NumVecs; ++n)
9151 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9152 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9153 DCI.CombineTo(VLD, VLDDupResults);
9158 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9159 /// ARMISD::VDUPLANE.
9160 static SDValue PerformVDUPLANECombine(SDNode *N,
9161 TargetLowering::DAGCombinerInfo &DCI) {
9162 SDValue Op = N->getOperand(0);
9164 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9165 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9166 if (CombineVLDDUP(N, DCI))
9167 return SDValue(N, 0);
9169 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9170 // redundant. Ignore bit_converts for now; element sizes are checked below.
9171 while (Op.getOpcode() == ISD::BITCAST)
9172 Op = Op.getOperand(0);
9173 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9176 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9177 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9178 // The canonical VMOV for a zero vector uses a 32-bit element size.
9179 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9181 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9183 EVT VT = N->getValueType(0);
9184 if (EltSize > VT.getVectorElementType().getSizeInBits())
9187 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9190 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9191 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9192 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9196 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9198 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9203 APFloat APF = C->getValueAPF();
9204 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9205 != APFloat::opOK || !isExact)
9208 c0 = (I == 0) ? cN : c0;
9209 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9216 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9217 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9218 /// when the VMUL has a constant operand that is a power of 2.
9220 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9221 /// vmul.f32 d16, d17, d16
9222 /// vcvt.s32.f32 d16, d16
9224 /// vcvt.s32.f32 d16, d16, #3
9225 static SDValue PerformVCVTCombine(SDNode *N,
9226 TargetLowering::DAGCombinerInfo &DCI,
9227 const ARMSubtarget *Subtarget) {
9228 SelectionDAG &DAG = DCI.DAG;
9229 SDValue Op = N->getOperand(0);
9231 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9232 Op.getOpcode() != ISD::FMUL)
9236 SDValue N0 = Op->getOperand(0);
9237 SDValue ConstVec = Op->getOperand(1);
9238 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9240 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9241 !isConstVecPow2(ConstVec, isSigned, C))
9244 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9245 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9246 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9247 // These instructions only exist converting from f32 to i32. We can handle
9248 // smaller integers by generating an extra truncate, but larger ones would
9253 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9254 Intrinsic::arm_neon_vcvtfp2fxu;
9255 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9256 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9257 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9258 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9259 DAG.getConstant(Log2_64(C), MVT::i32));
9261 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9262 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9267 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9268 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9269 /// when the VDIV has a constant operand that is a power of 2.
9271 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9272 /// vcvt.f32.s32 d16, d16
9273 /// vdiv.f32 d16, d17, d16
9275 /// vcvt.f32.s32 d16, d16, #3
9276 static SDValue PerformVDIVCombine(SDNode *N,
9277 TargetLowering::DAGCombinerInfo &DCI,
9278 const ARMSubtarget *Subtarget) {
9279 SelectionDAG &DAG = DCI.DAG;
9280 SDValue Op = N->getOperand(0);
9281 unsigned OpOpcode = Op.getNode()->getOpcode();
9283 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9284 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9288 SDValue ConstVec = N->getOperand(1);
9289 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9291 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9292 !isConstVecPow2(ConstVec, isSigned, C))
9295 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9296 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9297 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9298 // These instructions only exist converting from i32 to f32. We can handle
9299 // smaller integers by generating an extra extend, but larger ones would
9304 SDValue ConvInput = Op.getOperand(0);
9305 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9306 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9307 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9308 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9311 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9312 Intrinsic::arm_neon_vcvtfxu2fp;
9313 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9315 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9316 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9319 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9320 /// operand of a vector shift operation, where all the elements of the
9321 /// build_vector must have the same constant integer value.
9322 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9323 // Ignore bit_converts.
9324 while (Op.getOpcode() == ISD::BITCAST)
9325 Op = Op.getOperand(0);
9326 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9327 APInt SplatBits, SplatUndef;
9328 unsigned SplatBitSize;
9330 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9331 HasAnyUndefs, ElementBits) ||
9332 SplatBitSize > ElementBits)
9334 Cnt = SplatBits.getSExtValue();
9338 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9339 /// operand of a vector shift left operation. That value must be in the range:
9340 /// 0 <= Value < ElementBits for a left shift; or
9341 /// 0 <= Value <= ElementBits for a long left shift.
9342 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9343 assert(VT.isVector() && "vector shift count is not a vector type");
9344 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9345 if (! getVShiftImm(Op, ElementBits, Cnt))
9347 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9350 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9351 /// operand of a vector shift right operation. For a shift opcode, the value
9352 /// is positive, but for an intrinsic the value count must be negative. The
9353 /// absolute value must be in the range:
9354 /// 1 <= |Value| <= ElementBits for a right shift; or
9355 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9356 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9358 assert(VT.isVector() && "vector shift count is not a vector type");
9359 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9360 if (! getVShiftImm(Op, ElementBits, Cnt))
9364 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9367 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9368 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9369 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9372 // Don't do anything for most intrinsics.
9375 // Vector shifts: check for immediate versions and lower them.
9376 // Note: This is done during DAG combining instead of DAG legalizing because
9377 // the build_vectors for 64-bit vector element shift counts are generally
9378 // not legal, and it is hard to see their values after they get legalized to
9379 // loads from a constant pool.
9380 case Intrinsic::arm_neon_vshifts:
9381 case Intrinsic::arm_neon_vshiftu:
9382 case Intrinsic::arm_neon_vshiftls:
9383 case Intrinsic::arm_neon_vshiftlu:
9384 case Intrinsic::arm_neon_vshiftn:
9385 case Intrinsic::arm_neon_vrshifts:
9386 case Intrinsic::arm_neon_vrshiftu:
9387 case Intrinsic::arm_neon_vrshiftn:
9388 case Intrinsic::arm_neon_vqshifts:
9389 case Intrinsic::arm_neon_vqshiftu:
9390 case Intrinsic::arm_neon_vqshiftsu:
9391 case Intrinsic::arm_neon_vqshiftns:
9392 case Intrinsic::arm_neon_vqshiftnu:
9393 case Intrinsic::arm_neon_vqshiftnsu:
9394 case Intrinsic::arm_neon_vqrshiftns:
9395 case Intrinsic::arm_neon_vqrshiftnu:
9396 case Intrinsic::arm_neon_vqrshiftnsu: {
9397 EVT VT = N->getOperand(1).getValueType();
9399 unsigned VShiftOpc = 0;
9402 case Intrinsic::arm_neon_vshifts:
9403 case Intrinsic::arm_neon_vshiftu:
9404 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9405 VShiftOpc = ARMISD::VSHL;
9408 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9409 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9410 ARMISD::VSHRs : ARMISD::VSHRu);
9415 case Intrinsic::arm_neon_vshiftls:
9416 case Intrinsic::arm_neon_vshiftlu:
9417 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9419 llvm_unreachable("invalid shift count for vshll intrinsic");
9421 case Intrinsic::arm_neon_vrshifts:
9422 case Intrinsic::arm_neon_vrshiftu:
9423 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9427 case Intrinsic::arm_neon_vqshifts:
9428 case Intrinsic::arm_neon_vqshiftu:
9429 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9433 case Intrinsic::arm_neon_vqshiftsu:
9434 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9436 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9438 case Intrinsic::arm_neon_vshiftn:
9439 case Intrinsic::arm_neon_vrshiftn:
9440 case Intrinsic::arm_neon_vqshiftns:
9441 case Intrinsic::arm_neon_vqshiftnu:
9442 case Intrinsic::arm_neon_vqshiftnsu:
9443 case Intrinsic::arm_neon_vqrshiftns:
9444 case Intrinsic::arm_neon_vqrshiftnu:
9445 case Intrinsic::arm_neon_vqrshiftnsu:
9446 // Narrowing shifts require an immediate right shift.
9447 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9449 llvm_unreachable("invalid shift count for narrowing vector shift "
9453 llvm_unreachable("unhandled vector shift");
9457 case Intrinsic::arm_neon_vshifts:
9458 case Intrinsic::arm_neon_vshiftu:
9459 // Opcode already set above.
9461 case Intrinsic::arm_neon_vshiftls:
9462 case Intrinsic::arm_neon_vshiftlu:
9463 if (Cnt == VT.getVectorElementType().getSizeInBits())
9464 VShiftOpc = ARMISD::VSHLLi;
9466 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9467 ARMISD::VSHLLs : ARMISD::VSHLLu);
9469 case Intrinsic::arm_neon_vshiftn:
9470 VShiftOpc = ARMISD::VSHRN; break;
9471 case Intrinsic::arm_neon_vrshifts:
9472 VShiftOpc = ARMISD::VRSHRs; break;
9473 case Intrinsic::arm_neon_vrshiftu:
9474 VShiftOpc = ARMISD::VRSHRu; break;
9475 case Intrinsic::arm_neon_vrshiftn:
9476 VShiftOpc = ARMISD::VRSHRN; break;
9477 case Intrinsic::arm_neon_vqshifts:
9478 VShiftOpc = ARMISD::VQSHLs; break;
9479 case Intrinsic::arm_neon_vqshiftu:
9480 VShiftOpc = ARMISD::VQSHLu; break;
9481 case Intrinsic::arm_neon_vqshiftsu:
9482 VShiftOpc = ARMISD::VQSHLsu; break;
9483 case Intrinsic::arm_neon_vqshiftns:
9484 VShiftOpc = ARMISD::VQSHRNs; break;
9485 case Intrinsic::arm_neon_vqshiftnu:
9486 VShiftOpc = ARMISD::VQSHRNu; break;
9487 case Intrinsic::arm_neon_vqshiftnsu:
9488 VShiftOpc = ARMISD::VQSHRNsu; break;
9489 case Intrinsic::arm_neon_vqrshiftns:
9490 VShiftOpc = ARMISD::VQRSHRNs; break;
9491 case Intrinsic::arm_neon_vqrshiftnu:
9492 VShiftOpc = ARMISD::VQRSHRNu; break;
9493 case Intrinsic::arm_neon_vqrshiftnsu:
9494 VShiftOpc = ARMISD::VQRSHRNsu; break;
9497 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9498 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9501 case Intrinsic::arm_neon_vshiftins: {
9502 EVT VT = N->getOperand(1).getValueType();
9504 unsigned VShiftOpc = 0;
9506 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9507 VShiftOpc = ARMISD::VSLI;
9508 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9509 VShiftOpc = ARMISD::VSRI;
9511 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9514 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9515 N->getOperand(1), N->getOperand(2),
9516 DAG.getConstant(Cnt, MVT::i32));
9519 case Intrinsic::arm_neon_vqrshifts:
9520 case Intrinsic::arm_neon_vqrshiftu:
9521 // No immediate versions of these to check for.
9528 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9529 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9530 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9531 /// vector element shift counts are generally not legal, and it is hard to see
9532 /// their values after they get legalized to loads from a constant pool.
9533 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9534 const ARMSubtarget *ST) {
9535 EVT VT = N->getValueType(0);
9536 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9537 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9538 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9539 SDValue N1 = N->getOperand(1);
9540 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9541 SDValue N0 = N->getOperand(0);
9542 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9543 DAG.MaskedValueIsZero(N0.getOperand(0),
9544 APInt::getHighBitsSet(32, 16)))
9545 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9549 // Nothing to be done for scalar shifts.
9550 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9551 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9554 assert(ST->hasNEON() && "unexpected vector shift");
9557 switch (N->getOpcode()) {
9558 default: llvm_unreachable("unexpected shift opcode");
9561 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9562 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9563 DAG.getConstant(Cnt, MVT::i32));
9568 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9569 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9570 ARMISD::VSHRs : ARMISD::VSHRu);
9571 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9572 DAG.getConstant(Cnt, MVT::i32));
9578 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9579 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9580 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9581 const ARMSubtarget *ST) {
9582 SDValue N0 = N->getOperand(0);
9584 // Check for sign- and zero-extensions of vector extract operations of 8-
9585 // and 16-bit vector elements. NEON supports these directly. They are
9586 // handled during DAG combining because type legalization will promote them
9587 // to 32-bit types and it is messy to recognize the operations after that.
9588 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9589 SDValue Vec = N0.getOperand(0);
9590 SDValue Lane = N0.getOperand(1);
9591 EVT VT = N->getValueType(0);
9592 EVT EltVT = N0.getValueType();
9593 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9595 if (VT == MVT::i32 &&
9596 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9597 TLI.isTypeLegal(Vec.getValueType()) &&
9598 isa<ConstantSDNode>(Lane)) {
9601 switch (N->getOpcode()) {
9602 default: llvm_unreachable("unexpected opcode");
9603 case ISD::SIGN_EXTEND:
9604 Opc = ARMISD::VGETLANEs;
9606 case ISD::ZERO_EXTEND:
9607 case ISD::ANY_EXTEND:
9608 Opc = ARMISD::VGETLANEu;
9611 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9618 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9619 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9620 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9621 const ARMSubtarget *ST) {
9622 // If the target supports NEON, try to use vmax/vmin instructions for f32
9623 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9624 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9625 // a NaN; only do the transformation when it matches that behavior.
9627 // For now only do this when using NEON for FP operations; if using VFP, it
9628 // is not obvious that the benefit outweighs the cost of switching to the
9630 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9631 N->getValueType(0) != MVT::f32)
9634 SDValue CondLHS = N->getOperand(0);
9635 SDValue CondRHS = N->getOperand(1);
9636 SDValue LHS = N->getOperand(2);
9637 SDValue RHS = N->getOperand(3);
9638 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9640 unsigned Opcode = 0;
9642 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9643 IsReversed = false; // x CC y ? x : y
9644 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9645 IsReversed = true ; // x CC y ? y : x
9659 // If LHS is NaN, an ordered comparison will be false and the result will
9660 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9661 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9662 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9663 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9665 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9666 // will return -0, so vmin can only be used for unsafe math or if one of
9667 // the operands is known to be nonzero.
9668 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9669 !DAG.getTarget().Options.UnsafeFPMath &&
9670 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9672 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9681 // If LHS is NaN, an ordered comparison will be false and the result will
9682 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9683 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9684 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9685 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9687 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9688 // will return +0, so vmax can only be used for unsafe math or if one of
9689 // the operands is known to be nonzero.
9690 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9691 !DAG.getTarget().Options.UnsafeFPMath &&
9692 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9694 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9700 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9703 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9705 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9706 SDValue Cmp = N->getOperand(4);
9707 if (Cmp.getOpcode() != ARMISD::CMPZ)
9708 // Only looking at EQ and NE cases.
9711 EVT VT = N->getValueType(0);
9713 SDValue LHS = Cmp.getOperand(0);
9714 SDValue RHS = Cmp.getOperand(1);
9715 SDValue FalseVal = N->getOperand(0);
9716 SDValue TrueVal = N->getOperand(1);
9717 SDValue ARMcc = N->getOperand(2);
9718 ARMCC::CondCodes CC =
9719 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9737 /// FIXME: Turn this into a target neutral optimization?
9739 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9740 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9741 N->getOperand(3), Cmp);
9742 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9744 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9745 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9746 N->getOperand(3), NewCmp);
9749 if (Res.getNode()) {
9750 APInt KnownZero, KnownOne;
9751 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9752 // Capture demanded bits information that would be otherwise lost.
9753 if (KnownZero == 0xfffffffe)
9754 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9755 DAG.getValueType(MVT::i1));
9756 else if (KnownZero == 0xffffff00)
9757 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9758 DAG.getValueType(MVT::i8));
9759 else if (KnownZero == 0xffff0000)
9760 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9761 DAG.getValueType(MVT::i16));
9767 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9768 DAGCombinerInfo &DCI) const {
9769 switch (N->getOpcode()) {
9771 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9772 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9773 case ISD::SUB: return PerformSUBCombine(N, DCI);
9774 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9775 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9776 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9777 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9778 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9779 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9780 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9781 case ISD::STORE: return PerformSTORECombine(N, DCI);
9782 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9783 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9784 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9785 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9786 case ISD::FP_TO_SINT:
9787 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9788 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9789 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9792 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9793 case ISD::SIGN_EXTEND:
9794 case ISD::ZERO_EXTEND:
9795 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9796 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9797 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9798 case ARMISD::VLD2DUP:
9799 case ARMISD::VLD3DUP:
9800 case ARMISD::VLD4DUP:
9801 return CombineBaseUpdate(N, DCI);
9802 case ARMISD::BUILD_VECTOR:
9803 return PerformARMBUILD_VECTORCombine(N, DCI);
9804 case ISD::INTRINSIC_VOID:
9805 case ISD::INTRINSIC_W_CHAIN:
9806 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9807 case Intrinsic::arm_neon_vld1:
9808 case Intrinsic::arm_neon_vld2:
9809 case Intrinsic::arm_neon_vld3:
9810 case Intrinsic::arm_neon_vld4:
9811 case Intrinsic::arm_neon_vld2lane:
9812 case Intrinsic::arm_neon_vld3lane:
9813 case Intrinsic::arm_neon_vld4lane:
9814 case Intrinsic::arm_neon_vst1:
9815 case Intrinsic::arm_neon_vst2:
9816 case Intrinsic::arm_neon_vst3:
9817 case Intrinsic::arm_neon_vst4:
9818 case Intrinsic::arm_neon_vst2lane:
9819 case Intrinsic::arm_neon_vst3lane:
9820 case Intrinsic::arm_neon_vst4lane:
9821 return CombineBaseUpdate(N, DCI);
9829 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9831 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9834 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9835 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9836 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9838 switch (VT.getSimpleVT().SimpleTy) {
9844 // Unaligned access can use (for example) LRDB, LRDH, LDR
9845 if (AllowsUnaligned) {
9847 *Fast = Subtarget->hasV7Ops();
9854 // For any little-endian targets with neon, we can support unaligned ld/st
9855 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9856 // A big-endian target may also explictly support unaligned accesses
9857 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9867 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9868 unsigned AlignCheck) {
9869 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9870 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9873 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9874 unsigned DstAlign, unsigned SrcAlign,
9875 bool IsMemset, bool ZeroMemset,
9877 MachineFunction &MF) const {
9878 const Function *F = MF.getFunction();
9880 // See if we can use NEON instructions for this...
9881 if ((!IsMemset || ZeroMemset) &&
9882 Subtarget->hasNEON() &&
9883 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9884 Attribute::NoImplicitFloat)) {
9887 (memOpAlign(SrcAlign, DstAlign, 16) ||
9888 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9890 } else if (Size >= 8 &&
9891 (memOpAlign(SrcAlign, DstAlign, 8) ||
9892 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9897 // Lowering to i32/i16 if the size permits.
9903 // Let the target-independent logic figure it out.
9907 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9908 if (Val.getOpcode() != ISD::LOAD)
9911 EVT VT1 = Val.getValueType();
9912 if (!VT1.isSimple() || !VT1.isInteger() ||
9913 !VT2.isSimple() || !VT2.isInteger())
9916 switch (VT1.getSimpleVT().SimpleTy) {
9921 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9928 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9933 switch (VT.getSimpleVT().SimpleTy) {
9934 default: return false;
9949 if ((V & (Scale - 1)) != 0)
9952 return V == (V & ((1LL << 5) - 1));
9955 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9956 const ARMSubtarget *Subtarget) {
9963 switch (VT.getSimpleVT().SimpleTy) {
9964 default: return false;
9969 // + imm12 or - imm8
9971 return V == (V & ((1LL << 8) - 1));
9972 return V == (V & ((1LL << 12) - 1));
9975 // Same as ARM mode. FIXME: NEON?
9976 if (!Subtarget->hasVFP2())
9981 return V == (V & ((1LL << 8) - 1));
9985 /// isLegalAddressImmediate - Return true if the integer value can be used
9986 /// as the offset of the target addressing mode for load / store of the
9988 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9989 const ARMSubtarget *Subtarget) {
9996 if (Subtarget->isThumb1Only())
9997 return isLegalT1AddressImmediate(V, VT);
9998 else if (Subtarget->isThumb2())
9999 return isLegalT2AddressImmediate(V, VT, Subtarget);
10004 switch (VT.getSimpleVT().SimpleTy) {
10005 default: return false;
10010 return V == (V & ((1LL << 12) - 1));
10013 return V == (V & ((1LL << 8) - 1));
10016 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10021 return V == (V & ((1LL << 8) - 1));
10025 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10027 int Scale = AM.Scale;
10031 switch (VT.getSimpleVT().SimpleTy) {
10032 default: return false;
10040 Scale = Scale & ~1;
10041 return Scale == 2 || Scale == 4 || Scale == 8;
10044 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10048 // Note, we allow "void" uses (basically, uses that aren't loads or
10049 // stores), because arm allows folding a scale into many arithmetic
10050 // operations. This should be made more precise and revisited later.
10052 // Allow r << imm, but the imm has to be a multiple of two.
10053 if (Scale & 1) return false;
10054 return isPowerOf2_32(Scale);
10058 /// isLegalAddressingMode - Return true if the addressing mode represented
10059 /// by AM is legal for this target, for a load/store of the specified type.
10060 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10062 EVT VT = getValueType(Ty, true);
10063 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10066 // Can never fold addr of global into load/store.
10070 switch (AM.Scale) {
10071 case 0: // no scale reg, must be "r+i" or "r", or "i".
10074 if (Subtarget->isThumb1Only())
10078 // ARM doesn't support any R+R*scale+imm addr modes.
10082 if (!VT.isSimple())
10085 if (Subtarget->isThumb2())
10086 return isLegalT2ScaledAddressingMode(AM, VT);
10088 int Scale = AM.Scale;
10089 switch (VT.getSimpleVT().SimpleTy) {
10090 default: return false;
10094 if (Scale < 0) Scale = -Scale;
10098 return isPowerOf2_32(Scale & ~1);
10102 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10107 // Note, we allow "void" uses (basically, uses that aren't loads or
10108 // stores), because arm allows folding a scale into many arithmetic
10109 // operations. This should be made more precise and revisited later.
10111 // Allow r << imm, but the imm has to be a multiple of two.
10112 if (Scale & 1) return false;
10113 return isPowerOf2_32(Scale);
10119 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10120 /// icmp immediate, that is the target has icmp instructions which can compare
10121 /// a register against the immediate without having to materialize the
10122 /// immediate into a register.
10123 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10124 // Thumb2 and ARM modes can use cmn for negative immediates.
10125 if (!Subtarget->isThumb())
10126 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10127 if (Subtarget->isThumb2())
10128 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10129 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10130 return Imm >= 0 && Imm <= 255;
10133 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10134 /// *or sub* immediate, that is the target has add or sub instructions which can
10135 /// add a register with the immediate without having to materialize the
10136 /// immediate into a register.
10137 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10138 // Same encoding for add/sub, just flip the sign.
10139 int64_t AbsImm = llvm::abs64(Imm);
10140 if (!Subtarget->isThumb())
10141 return ARM_AM::getSOImmVal(AbsImm) != -1;
10142 if (Subtarget->isThumb2())
10143 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10144 // Thumb1 only has 8-bit unsigned immediate.
10145 return AbsImm >= 0 && AbsImm <= 255;
10148 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10149 bool isSEXTLoad, SDValue &Base,
10150 SDValue &Offset, bool &isInc,
10151 SelectionDAG &DAG) {
10152 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10155 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10156 // AddressingMode 3
10157 Base = Ptr->getOperand(0);
10158 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10159 int RHSC = (int)RHS->getZExtValue();
10160 if (RHSC < 0 && RHSC > -256) {
10161 assert(Ptr->getOpcode() == ISD::ADD);
10163 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10167 isInc = (Ptr->getOpcode() == ISD::ADD);
10168 Offset = Ptr->getOperand(1);
10170 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10171 // AddressingMode 2
10172 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10173 int RHSC = (int)RHS->getZExtValue();
10174 if (RHSC < 0 && RHSC > -0x1000) {
10175 assert(Ptr->getOpcode() == ISD::ADD);
10177 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10178 Base = Ptr->getOperand(0);
10183 if (Ptr->getOpcode() == ISD::ADD) {
10185 ARM_AM::ShiftOpc ShOpcVal=
10186 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10187 if (ShOpcVal != ARM_AM::no_shift) {
10188 Base = Ptr->getOperand(1);
10189 Offset = Ptr->getOperand(0);
10191 Base = Ptr->getOperand(0);
10192 Offset = Ptr->getOperand(1);
10197 isInc = (Ptr->getOpcode() == ISD::ADD);
10198 Base = Ptr->getOperand(0);
10199 Offset = Ptr->getOperand(1);
10203 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10207 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10208 bool isSEXTLoad, SDValue &Base,
10209 SDValue &Offset, bool &isInc,
10210 SelectionDAG &DAG) {
10211 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10214 Base = Ptr->getOperand(0);
10215 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10216 int RHSC = (int)RHS->getZExtValue();
10217 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10218 assert(Ptr->getOpcode() == ISD::ADD);
10220 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10222 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10223 isInc = Ptr->getOpcode() == ISD::ADD;
10224 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10232 /// getPreIndexedAddressParts - returns true by value, base pointer and
10233 /// offset pointer and addressing mode by reference if the node's address
10234 /// can be legally represented as pre-indexed load / store address.
10236 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10238 ISD::MemIndexedMode &AM,
10239 SelectionDAG &DAG) const {
10240 if (Subtarget->isThumb1Only())
10245 bool isSEXTLoad = false;
10246 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10247 Ptr = LD->getBasePtr();
10248 VT = LD->getMemoryVT();
10249 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10250 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10251 Ptr = ST->getBasePtr();
10252 VT = ST->getMemoryVT();
10257 bool isLegal = false;
10258 if (Subtarget->isThumb2())
10259 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10260 Offset, isInc, DAG);
10262 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10263 Offset, isInc, DAG);
10267 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10271 /// getPostIndexedAddressParts - returns true by value, base pointer and
10272 /// offset pointer and addressing mode by reference if this node can be
10273 /// combined with a load / store to form a post-indexed load / store.
10274 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10277 ISD::MemIndexedMode &AM,
10278 SelectionDAG &DAG) const {
10279 if (Subtarget->isThumb1Only())
10284 bool isSEXTLoad = false;
10285 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10286 VT = LD->getMemoryVT();
10287 Ptr = LD->getBasePtr();
10288 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10289 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10290 VT = ST->getMemoryVT();
10291 Ptr = ST->getBasePtr();
10296 bool isLegal = false;
10297 if (Subtarget->isThumb2())
10298 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10301 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10307 // Swap base ptr and offset to catch more post-index load / store when
10308 // it's legal. In Thumb2 mode, offset must be an immediate.
10309 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10310 !Subtarget->isThumb2())
10311 std::swap(Base, Offset);
10313 // Post-indexed load / store update the base pointer.
10318 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10322 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10325 const SelectionDAG &DAG,
10326 unsigned Depth) const {
10327 unsigned BitWidth = KnownOne.getBitWidth();
10328 KnownZero = KnownOne = APInt(BitWidth, 0);
10329 switch (Op.getOpcode()) {
10335 // These nodes' second result is a boolean
10336 if (Op.getResNo() == 0)
10338 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10340 case ARMISD::CMOV: {
10341 // Bits are known zero/one if known on the LHS and RHS.
10342 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10343 if (KnownZero == 0 && KnownOne == 0) return;
10345 APInt KnownZeroRHS, KnownOneRHS;
10346 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10347 KnownZero &= KnownZeroRHS;
10348 KnownOne &= KnownOneRHS;
10354 //===----------------------------------------------------------------------===//
10355 // ARM Inline Assembly Support
10356 //===----------------------------------------------------------------------===//
10358 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10359 // Looking for "rev" which is V6+.
10360 if (!Subtarget->hasV6Ops())
10363 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10364 std::string AsmStr = IA->getAsmString();
10365 SmallVector<StringRef, 4> AsmPieces;
10366 SplitString(AsmStr, AsmPieces, ";\n");
10368 switch (AsmPieces.size()) {
10369 default: return false;
10371 AsmStr = AsmPieces[0];
10373 SplitString(AsmStr, AsmPieces, " \t,");
10376 if (AsmPieces.size() == 3 &&
10377 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10378 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10379 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10380 if (Ty && Ty->getBitWidth() == 32)
10381 return IntrinsicLowering::LowerToByteSwap(CI);
10389 /// getConstraintType - Given a constraint letter, return the type of
10390 /// constraint it is for this target.
10391 ARMTargetLowering::ConstraintType
10392 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10393 if (Constraint.size() == 1) {
10394 switch (Constraint[0]) {
10396 case 'l': return C_RegisterClass;
10397 case 'w': return C_RegisterClass;
10398 case 'h': return C_RegisterClass;
10399 case 'x': return C_RegisterClass;
10400 case 't': return C_RegisterClass;
10401 case 'j': return C_Other; // Constant for movw.
10402 // An address with a single base register. Due to the way we
10403 // currently handle addresses it is the same as an 'r' memory constraint.
10404 case 'Q': return C_Memory;
10406 } else if (Constraint.size() == 2) {
10407 switch (Constraint[0]) {
10409 // All 'U+' constraints are addresses.
10410 case 'U': return C_Memory;
10413 return TargetLowering::getConstraintType(Constraint);
10416 /// Examine constraint type and operand type and determine a weight value.
10417 /// This object must already have been set up with the operand type
10418 /// and the current alternative constraint selected.
10419 TargetLowering::ConstraintWeight
10420 ARMTargetLowering::getSingleConstraintMatchWeight(
10421 AsmOperandInfo &info, const char *constraint) const {
10422 ConstraintWeight weight = CW_Invalid;
10423 Value *CallOperandVal = info.CallOperandVal;
10424 // If we don't have a value, we can't do a match,
10425 // but allow it at the lowest weight.
10426 if (CallOperandVal == NULL)
10428 Type *type = CallOperandVal->getType();
10429 // Look at the constraint type.
10430 switch (*constraint) {
10432 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10435 if (type->isIntegerTy()) {
10436 if (Subtarget->isThumb())
10437 weight = CW_SpecificReg;
10439 weight = CW_Register;
10443 if (type->isFloatingPointTy())
10444 weight = CW_Register;
10450 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10452 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10454 if (Constraint.size() == 1) {
10455 // GCC ARM Constraint Letters
10456 switch (Constraint[0]) {
10457 case 'l': // Low regs or general regs.
10458 if (Subtarget->isThumb())
10459 return RCPair(0U, &ARM::tGPRRegClass);
10460 return RCPair(0U, &ARM::GPRRegClass);
10461 case 'h': // High regs or no regs.
10462 if (Subtarget->isThumb())
10463 return RCPair(0U, &ARM::hGPRRegClass);
10466 return RCPair(0U, &ARM::GPRRegClass);
10468 if (VT == MVT::f32)
10469 return RCPair(0U, &ARM::SPRRegClass);
10470 if (VT.getSizeInBits() == 64)
10471 return RCPair(0U, &ARM::DPRRegClass);
10472 if (VT.getSizeInBits() == 128)
10473 return RCPair(0U, &ARM::QPRRegClass);
10476 if (VT == MVT::f32)
10477 return RCPair(0U, &ARM::SPR_8RegClass);
10478 if (VT.getSizeInBits() == 64)
10479 return RCPair(0U, &ARM::DPR_8RegClass);
10480 if (VT.getSizeInBits() == 128)
10481 return RCPair(0U, &ARM::QPR_8RegClass);
10484 if (VT == MVT::f32)
10485 return RCPair(0U, &ARM::SPRRegClass);
10489 if (StringRef("{cc}").equals_lower(Constraint))
10490 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10492 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10495 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10496 /// vector. If it is invalid, don't add anything to Ops.
10497 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10498 std::string &Constraint,
10499 std::vector<SDValue>&Ops,
10500 SelectionDAG &DAG) const {
10501 SDValue Result(0, 0);
10503 // Currently only support length 1 constraints.
10504 if (Constraint.length() != 1) return;
10506 char ConstraintLetter = Constraint[0];
10507 switch (ConstraintLetter) {
10510 case 'I': case 'J': case 'K': case 'L':
10511 case 'M': case 'N': case 'O':
10512 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10516 int64_t CVal64 = C->getSExtValue();
10517 int CVal = (int) CVal64;
10518 // None of these constraints allow values larger than 32 bits. Check
10519 // that the value fits in an int.
10520 if (CVal != CVal64)
10523 switch (ConstraintLetter) {
10525 // Constant suitable for movw, must be between 0 and
10527 if (Subtarget->hasV6T2Ops())
10528 if (CVal >= 0 && CVal <= 65535)
10532 if (Subtarget->isThumb1Only()) {
10533 // This must be a constant between 0 and 255, for ADD
10535 if (CVal >= 0 && CVal <= 255)
10537 } else if (Subtarget->isThumb2()) {
10538 // A constant that can be used as an immediate value in a
10539 // data-processing instruction.
10540 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10543 // A constant that can be used as an immediate value in a
10544 // data-processing instruction.
10545 if (ARM_AM::getSOImmVal(CVal) != -1)
10551 if (Subtarget->isThumb()) { // FIXME thumb2
10552 // This must be a constant between -255 and -1, for negated ADD
10553 // immediates. This can be used in GCC with an "n" modifier that
10554 // prints the negated value, for use with SUB instructions. It is
10555 // not useful otherwise but is implemented for compatibility.
10556 if (CVal >= -255 && CVal <= -1)
10559 // This must be a constant between -4095 and 4095. It is not clear
10560 // what this constraint is intended for. Implemented for
10561 // compatibility with GCC.
10562 if (CVal >= -4095 && CVal <= 4095)
10568 if (Subtarget->isThumb1Only()) {
10569 // A 32-bit value where only one byte has a nonzero value. Exclude
10570 // zero to match GCC. This constraint is used by GCC internally for
10571 // constants that can be loaded with a move/shift combination.
10572 // It is not useful otherwise but is implemented for compatibility.
10573 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10575 } else if (Subtarget->isThumb2()) {
10576 // A constant whose bitwise inverse can be used as an immediate
10577 // value in a data-processing instruction. This can be used in GCC
10578 // with a "B" modifier that prints the inverted value, for use with
10579 // BIC and MVN instructions. It is not useful otherwise but is
10580 // implemented for compatibility.
10581 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10584 // A constant whose bitwise inverse can be used as an immediate
10585 // value in a data-processing instruction. This can be used in GCC
10586 // with a "B" modifier that prints the inverted value, for use with
10587 // BIC and MVN instructions. It is not useful otherwise but is
10588 // implemented for compatibility.
10589 if (ARM_AM::getSOImmVal(~CVal) != -1)
10595 if (Subtarget->isThumb1Only()) {
10596 // This must be a constant between -7 and 7,
10597 // for 3-operand ADD/SUB immediate instructions.
10598 if (CVal >= -7 && CVal < 7)
10600 } else if (Subtarget->isThumb2()) {
10601 // A constant whose negation can be used as an immediate value in a
10602 // data-processing instruction. This can be used in GCC with an "n"
10603 // modifier that prints the negated value, for use with SUB
10604 // instructions. It is not useful otherwise but is implemented for
10606 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10609 // A constant whose negation can be used as an immediate value in a
10610 // data-processing instruction. This can be used in GCC with an "n"
10611 // modifier that prints the negated value, for use with SUB
10612 // instructions. It is not useful otherwise but is implemented for
10614 if (ARM_AM::getSOImmVal(-CVal) != -1)
10620 if (Subtarget->isThumb()) { // FIXME thumb2
10621 // This must be a multiple of 4 between 0 and 1020, for
10622 // ADD sp + immediate.
10623 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10626 // A power of two or a constant between 0 and 32. This is used in
10627 // GCC for the shift amount on shifted register operands, but it is
10628 // useful in general for any shift amounts.
10629 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10635 if (Subtarget->isThumb()) { // FIXME thumb2
10636 // This must be a constant between 0 and 31, for shift amounts.
10637 if (CVal >= 0 && CVal <= 31)
10643 if (Subtarget->isThumb()) { // FIXME thumb2
10644 // This must be a multiple of 4 between -508 and 508, for
10645 // ADD/SUB sp = sp + immediate.
10646 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10651 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10655 if (Result.getNode()) {
10656 Ops.push_back(Result);
10659 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10663 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10664 // The ARM target isn't yet aware of offsets.
10668 bool ARM::isBitFieldInvertedMask(unsigned v) {
10669 if (v == 0xffffffff)
10672 // there can be 1's on either or both "outsides", all the "inside"
10673 // bits must be 0's
10674 unsigned TO = CountTrailingOnes_32(v);
10675 unsigned LO = CountLeadingOnes_32(v);
10676 v = (v >> TO) << TO;
10677 v = (v << LO) >> LO;
10681 /// isFPImmLegal - Returns true if the target can instruction select the
10682 /// specified FP immediate natively. If false, the legalizer will
10683 /// materialize the FP immediate as a load from a constant pool.
10684 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10685 if (!Subtarget->hasVFP3())
10687 if (VT == MVT::f32)
10688 return ARM_AM::getFP32Imm(Imm) != -1;
10689 if (VT == MVT::f64)
10690 return ARM_AM::getFP64Imm(Imm) != -1;
10694 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10695 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10696 /// specified in the intrinsic calls.
10697 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10699 unsigned Intrinsic) const {
10700 switch (Intrinsic) {
10701 case Intrinsic::arm_neon_vld1:
10702 case Intrinsic::arm_neon_vld2:
10703 case Intrinsic::arm_neon_vld3:
10704 case Intrinsic::arm_neon_vld4:
10705 case Intrinsic::arm_neon_vld2lane:
10706 case Intrinsic::arm_neon_vld3lane:
10707 case Intrinsic::arm_neon_vld4lane: {
10708 Info.opc = ISD::INTRINSIC_W_CHAIN;
10709 // Conservatively set memVT to the entire set of vectors loaded.
10710 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10711 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10712 Info.ptrVal = I.getArgOperand(0);
10714 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10715 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10716 Info.vol = false; // volatile loads with NEON intrinsics not supported
10717 Info.readMem = true;
10718 Info.writeMem = false;
10721 case Intrinsic::arm_neon_vst1:
10722 case Intrinsic::arm_neon_vst2:
10723 case Intrinsic::arm_neon_vst3:
10724 case Intrinsic::arm_neon_vst4:
10725 case Intrinsic::arm_neon_vst2lane:
10726 case Intrinsic::arm_neon_vst3lane:
10727 case Intrinsic::arm_neon_vst4lane: {
10728 Info.opc = ISD::INTRINSIC_VOID;
10729 // Conservatively set memVT to the entire set of vectors stored.
10730 unsigned NumElts = 0;
10731 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10732 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10733 if (!ArgTy->isVectorTy())
10735 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10737 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10738 Info.ptrVal = I.getArgOperand(0);
10740 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10741 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10742 Info.vol = false; // volatile stores with NEON intrinsics not supported
10743 Info.readMem = false;
10744 Info.writeMem = true;
10747 case Intrinsic::arm_strexd: {
10748 Info.opc = ISD::INTRINSIC_W_CHAIN;
10749 Info.memVT = MVT::i64;
10750 Info.ptrVal = I.getArgOperand(2);
10754 Info.readMem = false;
10755 Info.writeMem = true;
10758 case Intrinsic::arm_ldrexd: {
10759 Info.opc = ISD::INTRINSIC_W_CHAIN;
10760 Info.memVT = MVT::i64;
10761 Info.ptrVal = I.getArgOperand(0);
10765 Info.readMem = true;
10766 Info.writeMem = false;