1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57 // This option should go away when tail calls fully work.
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65 cl::desc("Generate calls via indirect call instructions"),
69 ARMInterworking("arm-interworking", cl::Hidden,
70 cl::desc("Enable / disable ARM interworking (for debugging only)"),
74 class ARMCCState : public CCState {
76 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77 const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78 LLVMContext &C, ParmContext PC)
79 : CCState(CC, isVarArg, MF, TM, locs, C) {
80 assert(((PC == Call) || (PC == Prologue)) &&
81 "ARMCCState users must specify whether their context is call"
82 "or prologue generation.");
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90 ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94 MVT PromotedBitwiseVT) {
95 if (VT != PromotedLdStVT) {
96 setOperationAction(ISD::LOAD, VT, Promote);
97 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99 setOperationAction(ISD::STORE, VT, Promote);
100 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103 MVT ElemTy = VT.getVectorElementType();
104 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105 setOperationAction(ISD::SETCC, VT, Custom);
106 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108 if (ElemTy == MVT::i32) {
109 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
120 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
121 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
122 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123 setOperationAction(ISD::SELECT, VT, Expand);
124 setOperationAction(ISD::SELECT_CC, VT, Expand);
125 setOperationAction(ISD::VSELECT, VT, Expand);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127 if (VT.isInteger()) {
128 setOperationAction(ISD::SHL, VT, Custom);
129 setOperationAction(ISD::SRA, VT, Custom);
130 setOperationAction(ISD::SRL, VT, Custom);
133 // Promote all bit-wise operations.
134 if (VT.isInteger() && VT != PromotedBitwiseVT) {
135 setOperationAction(ISD::AND, VT, Promote);
136 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137 setOperationAction(ISD::OR, VT, Promote);
138 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
139 setOperationAction(ISD::XOR, VT, Promote);
140 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
143 // Neon does not support vector divide/remainder operations.
144 setOperationAction(ISD::SDIV, VT, Expand);
145 setOperationAction(ISD::UDIV, VT, Expand);
146 setOperationAction(ISD::FDIV, VT, Expand);
147 setOperationAction(ISD::SREM, VT, Expand);
148 setOperationAction(ISD::UREM, VT, Expand);
149 setOperationAction(ISD::FREM, VT, Expand);
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPRRegClass);
154 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::QPRRegClass);
159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164 return new TargetLoweringObjectFileMachO();
166 return new ARMElfTargetObjectFile();
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170 : TargetLowering(TM, createTLOF(TM)) {
171 Subtarget = &TM.getSubtarget<ARMSubtarget>();
172 RegInfo = TM.getRegisterInfo();
173 Itins = TM.getInstrItineraryData();
175 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177 if (Subtarget->isTargetDarwin()) {
178 // Uses VFP for Thumb libfuncs if available.
179 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180 // Single-precision floating-point arithmetic.
181 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
186 // Double-precision floating-point arithmetic.
187 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
192 // Single-precision comparisons.
193 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
200 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
202 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
211 // Double-precision comparisons.
212 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
219 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
221 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
230 // Floating-point to integer conversions.
231 // i64 conversions are done via library routines even when generating VFP
232 // instructions, so use the same ones.
233 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
238 // Conversions between floating types.
239 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
242 // Integer to floating-point conversions.
243 // i64 conversions are done via library routines even when generating VFP
244 // instructions, so use the same ones.
245 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246 // e.g., __floatunsidf vs. __floatunssidfvfp.
247 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
254 // These libcalls are not available in 32-bit.
255 setLibcallName(RTLIB::SHL_I128, 0);
256 setLibcallName(RTLIB::SRL_I128, 0);
257 setLibcallName(RTLIB::SRA_I128, 0);
259 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260 // Double-precision floating-point arithmetic helper functions
261 // RTABI chapter 4.1.2, Table 2
262 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
271 // Double-precision floating-point comparison helper functions
272 // RTABI chapter 4.1.2, Table 3
273 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
286 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
287 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
288 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
289 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
298 // Single-precision floating-point arithmetic helper functions
299 // RTABI chapter 4.1.2, Table 4
300 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
309 // Single-precision floating-point comparison helper functions
310 // RTABI chapter 4.1.2, Table 5
311 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
324 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
325 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
326 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
327 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
336 // Floating-point to integer conversions.
337 // RTABI chapter 4.1.2, Table 6
338 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
355 // Conversions between floating types.
356 // RTABI chapter 4.1.2, Table 7
357 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
359 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
362 // Integer to floating-point conversions.
363 // RTABI chapter 4.1.2, Table 8
364 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381 // Long long helper functions
382 // RTABI chapter 4.2, Table 9
383 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
384 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
394 // Integer division functions
395 // RTABI chapter 4.3.1
396 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
397 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
401 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
414 // RTABI chapter 4.3.4
415 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
416 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
418 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
423 // Use divmod compiler-rt calls for iOS 5.0 and later.
424 if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
430 if (Subtarget->isThumb1Only())
431 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
433 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435 !Subtarget->isThumb1Only()) {
436 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437 if (!Subtarget->isFPOnlySP())
438 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
440 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
443 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447 setTruncStoreAction((MVT::SimpleValueType)VT,
448 (MVT::SimpleValueType)InnerVT, Expand);
449 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
454 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
456 if (Subtarget->hasNEON()) {
457 addDRTypeForNEON(MVT::v2f32);
458 addDRTypeForNEON(MVT::v8i8);
459 addDRTypeForNEON(MVT::v4i16);
460 addDRTypeForNEON(MVT::v2i32);
461 addDRTypeForNEON(MVT::v1i64);
463 addQRTypeForNEON(MVT::v4f32);
464 addQRTypeForNEON(MVT::v2f64);
465 addQRTypeForNEON(MVT::v16i8);
466 addQRTypeForNEON(MVT::v8i16);
467 addQRTypeForNEON(MVT::v4i32);
468 addQRTypeForNEON(MVT::v2i64);
470 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471 // neither Neon nor VFP support any arithmetic operations on it.
472 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473 // supported for v4f32.
474 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477 // FIXME: Code duplication: FDIV and FREM are expanded always, see
478 // ARMTargetLowering::addTypeForNEON method for details.
479 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481 // FIXME: Create unittest.
482 // In another words, find a way when "copysign" appears in DAG with vector
484 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485 // FIXME: Code duplication: SETCC has custom operation action, see
486 // ARMTargetLowering::addTypeForNEON method for details.
487 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488 // FIXME: Create unittest for FNEG and for FABS.
489 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
509 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
525 // Mark v2f32 intrinsics.
526 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
527 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
528 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
529 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
530 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
531 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
532 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
533 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
534 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
535 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
536 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
537 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
538 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
539 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
540 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
542 // Neon does not support some operations on v1i64 and v2i64 types.
543 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
544 // Custom handling for some quad-vector types to detect VMULL.
545 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
546 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
547 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
548 // Custom handling for some vector types to avoid expensive expansions
549 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
550 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
551 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
552 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
553 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
554 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
555 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
556 // a destination type that is wider than the source, and nor does
557 // it have a FP_TO_[SU]INT instruction with a narrower destination than
559 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
560 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
561 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
562 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
564 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
565 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
567 // Custom expand long extensions to vectors.
568 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
569 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
570 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
571 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
572 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
573 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
574 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
575 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
577 // NEON does not have single instruction CTPOP for vectors with element
578 // types wider than 8-bits. However, custom lowering can leverage the
579 // v8i8/v16i8 vcnt instruction.
580 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
581 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
582 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
583 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
585 // NEON only has FMA instructions as of VFP4.
586 if (!Subtarget->hasVFP4()) {
587 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
588 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
591 setTargetDAGCombine(ISD::INTRINSIC_VOID);
592 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
594 setTargetDAGCombine(ISD::SHL);
595 setTargetDAGCombine(ISD::SRL);
596 setTargetDAGCombine(ISD::SRA);
597 setTargetDAGCombine(ISD::SIGN_EXTEND);
598 setTargetDAGCombine(ISD::ZERO_EXTEND);
599 setTargetDAGCombine(ISD::ANY_EXTEND);
600 setTargetDAGCombine(ISD::SELECT_CC);
601 setTargetDAGCombine(ISD::BUILD_VECTOR);
602 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
603 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
604 setTargetDAGCombine(ISD::STORE);
605 setTargetDAGCombine(ISD::FP_TO_SINT);
606 setTargetDAGCombine(ISD::FP_TO_UINT);
607 setTargetDAGCombine(ISD::FDIV);
609 // It is legal to extload from v4i8 to v4i16 or v4i32.
610 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
611 MVT::v4i16, MVT::v2i16,
613 for (unsigned i = 0; i < 6; ++i) {
614 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
615 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
616 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
620 // ARM and Thumb2 support UMLAL/SMLAL.
621 if (!Subtarget->isThumb1Only())
622 setTargetDAGCombine(ISD::ADDC);
625 computeRegisterProperties();
627 // ARM does not have f32 extending load.
628 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
630 // ARM does not have i1 sign extending load.
631 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
633 // ARM supports all 4 flavors of integer indexed load / store.
634 if (!Subtarget->isThumb1Only()) {
635 for (unsigned im = (unsigned)ISD::PRE_INC;
636 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
637 setIndexedLoadAction(im, MVT::i1, Legal);
638 setIndexedLoadAction(im, MVT::i8, Legal);
639 setIndexedLoadAction(im, MVT::i16, Legal);
640 setIndexedLoadAction(im, MVT::i32, Legal);
641 setIndexedStoreAction(im, MVT::i1, Legal);
642 setIndexedStoreAction(im, MVT::i8, Legal);
643 setIndexedStoreAction(im, MVT::i16, Legal);
644 setIndexedStoreAction(im, MVT::i32, Legal);
648 // i64 operation support.
649 setOperationAction(ISD::MUL, MVT::i64, Expand);
650 setOperationAction(ISD::MULHU, MVT::i32, Expand);
651 if (Subtarget->isThumb1Only()) {
652 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
653 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
655 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
656 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
657 setOperationAction(ISD::MULHS, MVT::i32, Expand);
659 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662 setOperationAction(ISD::SRL, MVT::i64, Custom);
663 setOperationAction(ISD::SRA, MVT::i64, Custom);
665 if (!Subtarget->isThumb1Only()) {
666 // FIXME: We should do this for Thumb1 as well.
667 setOperationAction(ISD::ADDC, MVT::i32, Custom);
668 setOperationAction(ISD::ADDE, MVT::i32, Custom);
669 setOperationAction(ISD::SUBC, MVT::i32, Custom);
670 setOperationAction(ISD::SUBE, MVT::i32, Custom);
673 // ARM does not have ROTL.
674 setOperationAction(ISD::ROTL, MVT::i32, Expand);
675 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
676 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
677 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
678 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
680 // These just redirect to CTTZ and CTLZ on ARM.
681 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
682 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
684 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
686 // Only ARMv6 has BSWAP.
687 if (!Subtarget->hasV6Ops())
688 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
690 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
691 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
692 // These are expanded into libcalls if the cpu doesn't have HW divider.
693 setOperationAction(ISD::SDIV, MVT::i32, Expand);
694 setOperationAction(ISD::UDIV, MVT::i32, Expand);
696 setOperationAction(ISD::SREM, MVT::i32, Expand);
697 setOperationAction(ISD::UREM, MVT::i32, Expand);
698 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
699 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
701 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
702 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
703 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
704 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
705 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
707 setOperationAction(ISD::TRAP, MVT::Other, Legal);
709 // Use the default implementation.
710 setOperationAction(ISD::VASTART, MVT::Other, Custom);
711 setOperationAction(ISD::VAARG, MVT::Other, Expand);
712 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
713 setOperationAction(ISD::VAEND, MVT::Other, Expand);
714 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
715 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
717 if (!Subtarget->isTargetDarwin()) {
718 // Non-Darwin platforms may return values in these registers via the
719 // personality function.
720 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
721 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
722 setExceptionPointerRegister(ARM::R0);
723 setExceptionSelectorRegister(ARM::R1);
726 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
727 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
728 // the default expansion.
729 // FIXME: This should be checking for v6k, not just v6.
730 if (Subtarget->hasDataBarrier() ||
731 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
732 // membarrier needs custom lowering; the rest are legal and handled
734 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
735 // Custom lowering for 64-bit ops
736 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
737 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
738 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
739 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
740 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
741 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
742 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
743 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
744 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
745 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
746 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
747 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
748 setInsertFencesForAtomic(true);
750 // Set them all for expansion, which will force libcalls.
751 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
752 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
753 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
754 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
755 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
756 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
757 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
758 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
759 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
760 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
761 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
762 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
763 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
764 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
765 // Unordered/Monotonic case.
766 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
767 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
770 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
772 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
773 if (!Subtarget->hasV6Ops()) {
774 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
775 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
777 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
779 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
780 !Subtarget->isThumb1Only()) {
781 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
782 // iff target supports vfp2.
783 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
784 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
787 // We want to custom lower some of our intrinsics.
788 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
789 if (Subtarget->isTargetDarwin()) {
790 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
791 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
792 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
795 setOperationAction(ISD::SETCC, MVT::i32, Expand);
796 setOperationAction(ISD::SETCC, MVT::f32, Expand);
797 setOperationAction(ISD::SETCC, MVT::f64, Expand);
798 setOperationAction(ISD::SELECT, MVT::i32, Custom);
799 setOperationAction(ISD::SELECT, MVT::f32, Custom);
800 setOperationAction(ISD::SELECT, MVT::f64, Custom);
801 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
802 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
803 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
805 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
806 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
807 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
808 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
809 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
811 // We don't support sin/cos/fmod/copysign/pow
812 setOperationAction(ISD::FSIN, MVT::f64, Expand);
813 setOperationAction(ISD::FSIN, MVT::f32, Expand);
814 setOperationAction(ISD::FCOS, MVT::f32, Expand);
815 setOperationAction(ISD::FCOS, MVT::f64, Expand);
816 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
817 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
818 setOperationAction(ISD::FREM, MVT::f64, Expand);
819 setOperationAction(ISD::FREM, MVT::f32, Expand);
820 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821 !Subtarget->isThumb1Only()) {
822 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
823 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
825 setOperationAction(ISD::FPOW, MVT::f64, Expand);
826 setOperationAction(ISD::FPOW, MVT::f32, Expand);
828 if (!Subtarget->hasVFP4()) {
829 setOperationAction(ISD::FMA, MVT::f64, Expand);
830 setOperationAction(ISD::FMA, MVT::f32, Expand);
833 // Various VFP goodness
834 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
835 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
836 if (Subtarget->hasVFP2()) {
837 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
838 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
839 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
840 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
842 // Special handling for half-precision FP.
843 if (!Subtarget->hasFP16()) {
844 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
845 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
849 // We have target-specific dag combine patterns for the following nodes:
850 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
851 setTargetDAGCombine(ISD::ADD);
852 setTargetDAGCombine(ISD::SUB);
853 setTargetDAGCombine(ISD::MUL);
854 setTargetDAGCombine(ISD::AND);
855 setTargetDAGCombine(ISD::OR);
856 setTargetDAGCombine(ISD::XOR);
858 if (Subtarget->hasV6Ops())
859 setTargetDAGCombine(ISD::SRL);
861 setStackPointerRegisterToSaveRestore(ARM::SP);
863 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
864 !Subtarget->hasVFP2())
865 setSchedulingPreference(Sched::RegPressure);
867 setSchedulingPreference(Sched::Hybrid);
869 //// temporary - rewrite interface to use type
870 MaxStoresPerMemset = 8;
871 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
872 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
873 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
875 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
877 // On ARM arguments smaller than 4 bytes are extended, so all arguments
878 // are at least 4 bytes aligned.
879 setMinStackArgumentAlignment(4);
881 // Prefer likely predicted branches to selects on out-of-order cores.
882 PredictableSelectIsExpensive = Subtarget->isLikeA9();
884 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
887 // FIXME: It might make sense to define the representative register class as the
888 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
889 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
890 // SPR's representative would be DPR_VFP2. This should work well if register
891 // pressure tracking were modified such that a register use would increment the
892 // pressure of the register class's representative and all of it's super
893 // classes' representatives transitively. We have not implemented this because
894 // of the difficulty prior to coalescing of modeling operand register classes
895 // due to the common occurrence of cross class copies and subregister insertions
897 std::pair<const TargetRegisterClass*, uint8_t>
898 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
899 const TargetRegisterClass *RRC = 0;
901 switch (VT.SimpleTy) {
903 return TargetLowering::findRepresentativeClass(VT);
904 // Use DPR as representative register class for all floating point
905 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
906 // the cost is 1 for both f32 and f64.
907 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
908 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
909 RRC = &ARM::DPRRegClass;
910 // When NEON is used for SP, only half of the register file is available
911 // because operations that define both SP and DP results will be constrained
912 // to the VFP2 class (D0-D15). We currently model this constraint prior to
913 // coalescing by double-counting the SP regs. See the FIXME above.
914 if (Subtarget->useNEONForSinglePrecisionFP())
917 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
918 case MVT::v4f32: case MVT::v2f64:
919 RRC = &ARM::DPRRegClass;
923 RRC = &ARM::DPRRegClass;
927 RRC = &ARM::DPRRegClass;
931 return std::make_pair(RRC, Cost);
934 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
937 case ARMISD::Wrapper: return "ARMISD::Wrapper";
938 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
939 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
940 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
941 case ARMISD::CALL: return "ARMISD::CALL";
942 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
943 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
944 case ARMISD::tCALL: return "ARMISD::tCALL";
945 case ARMISD::BRCOND: return "ARMISD::BRCOND";
946 case ARMISD::BR_JT: return "ARMISD::BR_JT";
947 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
948 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
949 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
950 case ARMISD::CMP: return "ARMISD::CMP";
951 case ARMISD::CMN: return "ARMISD::CMN";
952 case ARMISD::CMPZ: return "ARMISD::CMPZ";
953 case ARMISD::CMPFP: return "ARMISD::CMPFP";
954 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
955 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
956 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
958 case ARMISD::CMOV: return "ARMISD::CMOV";
960 case ARMISD::RBIT: return "ARMISD::RBIT";
962 case ARMISD::FTOSI: return "ARMISD::FTOSI";
963 case ARMISD::FTOUI: return "ARMISD::FTOUI";
964 case ARMISD::SITOF: return "ARMISD::SITOF";
965 case ARMISD::UITOF: return "ARMISD::UITOF";
967 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
968 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
969 case ARMISD::RRX: return "ARMISD::RRX";
971 case ARMISD::ADDC: return "ARMISD::ADDC";
972 case ARMISD::ADDE: return "ARMISD::ADDE";
973 case ARMISD::SUBC: return "ARMISD::SUBC";
974 case ARMISD::SUBE: return "ARMISD::SUBE";
976 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
977 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
979 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
980 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
982 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
984 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
986 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
988 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
989 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
991 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
993 case ARMISD::VCEQ: return "ARMISD::VCEQ";
994 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
995 case ARMISD::VCGE: return "ARMISD::VCGE";
996 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
997 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
998 case ARMISD::VCGEU: return "ARMISD::VCGEU";
999 case ARMISD::VCGT: return "ARMISD::VCGT";
1000 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1001 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1002 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1003 case ARMISD::VTST: return "ARMISD::VTST";
1005 case ARMISD::VSHL: return "ARMISD::VSHL";
1006 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1007 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1008 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1009 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1010 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1011 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1012 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1013 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1014 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1015 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1016 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1017 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1018 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1019 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1020 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1021 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1022 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1023 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1024 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1025 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1026 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1027 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1028 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1029 case ARMISD::VDUP: return "ARMISD::VDUP";
1030 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1031 case ARMISD::VEXT: return "ARMISD::VEXT";
1032 case ARMISD::VREV64: return "ARMISD::VREV64";
1033 case ARMISD::VREV32: return "ARMISD::VREV32";
1034 case ARMISD::VREV16: return "ARMISD::VREV16";
1035 case ARMISD::VZIP: return "ARMISD::VZIP";
1036 case ARMISD::VUZP: return "ARMISD::VUZP";
1037 case ARMISD::VTRN: return "ARMISD::VTRN";
1038 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1039 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1040 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1041 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1042 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1043 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1044 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1045 case ARMISD::FMAX: return "ARMISD::FMAX";
1046 case ARMISD::FMIN: return "ARMISD::FMIN";
1047 case ARMISD::BFI: return "ARMISD::BFI";
1048 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1049 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1050 case ARMISD::VBSL: return "ARMISD::VBSL";
1051 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1052 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1053 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1054 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1055 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1056 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1057 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1058 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1059 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1060 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1061 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1062 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1063 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1064 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1065 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1066 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1067 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1068 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1069 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1070 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1074 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1075 if (!VT.isVector()) return getPointerTy();
1076 return VT.changeVectorElementTypeToInteger();
1079 /// getRegClassFor - Return the register class that should be used for the
1080 /// specified value type.
1081 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1082 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1083 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1084 // load / store 4 to 8 consecutive D registers.
1085 if (Subtarget->hasNEON()) {
1086 if (VT == MVT::v4i64)
1087 return &ARM::QQPRRegClass;
1088 if (VT == MVT::v8i64)
1089 return &ARM::QQQQPRRegClass;
1091 return TargetLowering::getRegClassFor(VT);
1094 // Create a fast isel object.
1096 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1097 const TargetLibraryInfo *libInfo) const {
1098 return ARM::createFastISel(funcInfo, libInfo);
1101 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1102 /// be used for loads / stores from the global.
1103 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1104 return (Subtarget->isThumb1Only() ? 127 : 4095);
1107 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1108 unsigned NumVals = N->getNumValues();
1110 return Sched::RegPressure;
1112 for (unsigned i = 0; i != NumVals; ++i) {
1113 EVT VT = N->getValueType(i);
1114 if (VT == MVT::Glue || VT == MVT::Other)
1116 if (VT.isFloatingPoint() || VT.isVector())
1120 if (!N->isMachineOpcode())
1121 return Sched::RegPressure;
1123 // Load are scheduled for latency even if there instruction itinerary
1124 // is not available.
1125 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1126 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1128 if (MCID.getNumDefs() == 0)
1129 return Sched::RegPressure;
1130 if (!Itins->isEmpty() &&
1131 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1134 return Sched::RegPressure;
1137 //===----------------------------------------------------------------------===//
1139 //===----------------------------------------------------------------------===//
1141 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1142 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1144 default: llvm_unreachable("Unknown condition code!");
1145 case ISD::SETNE: return ARMCC::NE;
1146 case ISD::SETEQ: return ARMCC::EQ;
1147 case ISD::SETGT: return ARMCC::GT;
1148 case ISD::SETGE: return ARMCC::GE;
1149 case ISD::SETLT: return ARMCC::LT;
1150 case ISD::SETLE: return ARMCC::LE;
1151 case ISD::SETUGT: return ARMCC::HI;
1152 case ISD::SETUGE: return ARMCC::HS;
1153 case ISD::SETULT: return ARMCC::LO;
1154 case ISD::SETULE: return ARMCC::LS;
1158 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1159 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1160 ARMCC::CondCodes &CondCode2) {
1161 CondCode2 = ARMCC::AL;
1163 default: llvm_unreachable("Unknown FP condition!");
1165 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1167 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1169 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1170 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1171 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1172 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1173 case ISD::SETO: CondCode = ARMCC::VC; break;
1174 case ISD::SETUO: CondCode = ARMCC::VS; break;
1175 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1176 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1177 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1179 case ISD::SETULT: CondCode = ARMCC::LT; break;
1181 case ISD::SETULE: CondCode = ARMCC::LE; break;
1183 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1187 //===----------------------------------------------------------------------===//
1188 // Calling Convention Implementation
1189 //===----------------------------------------------------------------------===//
1191 #include "ARMGenCallingConv.inc"
1193 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1194 /// given CallingConvention value.
1195 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1197 bool isVarArg) const {
1200 llvm_unreachable("Unsupported calling convention");
1201 case CallingConv::Fast:
1202 if (Subtarget->hasVFP2() && !isVarArg) {
1203 if (!Subtarget->isAAPCS_ABI())
1204 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1205 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1206 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1209 case CallingConv::C: {
1210 // Use target triple & subtarget features to do actual dispatch.
1211 if (!Subtarget->isAAPCS_ABI())
1212 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1213 else if (Subtarget->hasVFP2() &&
1214 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1216 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1217 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1219 case CallingConv::ARM_AAPCS_VFP:
1221 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1223 case CallingConv::ARM_AAPCS:
1224 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1225 case CallingConv::ARM_APCS:
1226 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1227 case CallingConv::GHC:
1228 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1232 /// LowerCallResult - Lower the result values of a call into the
1233 /// appropriate copies out of appropriate physical registers.
1235 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1236 CallingConv::ID CallConv, bool isVarArg,
1237 const SmallVectorImpl<ISD::InputArg> &Ins,
1238 SDLoc dl, SelectionDAG &DAG,
1239 SmallVectorImpl<SDValue> &InVals,
1240 bool isThisReturn, SDValue ThisVal) const {
1242 // Assign locations to each value returned by this call.
1243 SmallVector<CCValAssign, 16> RVLocs;
1244 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1245 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1246 CCInfo.AnalyzeCallResult(Ins,
1247 CCAssignFnForNode(CallConv, /* Return*/ true,
1250 // Copy all of the result registers out of their specified physreg.
1251 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1252 CCValAssign VA = RVLocs[i];
1254 // Pass 'this' value directly from the argument to return value, to avoid
1255 // reg unit interference
1256 if (i == 0 && isThisReturn) {
1257 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1258 "unexpected return calling convention register assignment");
1259 InVals.push_back(ThisVal);
1264 if (VA.needsCustom()) {
1265 // Handle f64 or half of a v2f64.
1266 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1268 Chain = Lo.getValue(1);
1269 InFlag = Lo.getValue(2);
1270 VA = RVLocs[++i]; // skip ahead to next loc
1271 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1273 Chain = Hi.getValue(1);
1274 InFlag = Hi.getValue(2);
1275 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1277 if (VA.getLocVT() == MVT::v2f64) {
1278 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1279 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1280 DAG.getConstant(0, MVT::i32));
1282 VA = RVLocs[++i]; // skip ahead to next loc
1283 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1284 Chain = Lo.getValue(1);
1285 InFlag = Lo.getValue(2);
1286 VA = RVLocs[++i]; // skip ahead to next loc
1287 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1288 Chain = Hi.getValue(1);
1289 InFlag = Hi.getValue(2);
1290 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1291 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1292 DAG.getConstant(1, MVT::i32));
1295 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1297 Chain = Val.getValue(1);
1298 InFlag = Val.getValue(2);
1301 switch (VA.getLocInfo()) {
1302 default: llvm_unreachable("Unknown loc info!");
1303 case CCValAssign::Full: break;
1304 case CCValAssign::BCvt:
1305 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1309 InVals.push_back(Val);
1315 /// LowerMemOpCallTo - Store the argument to the stack.
1317 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1318 SDValue StackPtr, SDValue Arg,
1319 SDLoc dl, SelectionDAG &DAG,
1320 const CCValAssign &VA,
1321 ISD::ArgFlagsTy Flags) const {
1322 unsigned LocMemOffset = VA.getLocMemOffset();
1323 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1324 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1325 return DAG.getStore(Chain, dl, Arg, PtrOff,
1326 MachinePointerInfo::getStack(LocMemOffset),
1330 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1331 SDValue Chain, SDValue &Arg,
1332 RegsToPassVector &RegsToPass,
1333 CCValAssign &VA, CCValAssign &NextVA,
1335 SmallVector<SDValue, 8> &MemOpChains,
1336 ISD::ArgFlagsTy Flags) const {
1338 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1339 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1340 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1342 if (NextVA.isRegLoc())
1343 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1345 assert(NextVA.isMemLoc());
1346 if (StackPtr.getNode() == 0)
1347 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1349 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1355 /// LowerCall - Lowering a call into a callseq_start <-
1356 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1359 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1360 SmallVectorImpl<SDValue> &InVals) const {
1361 SelectionDAG &DAG = CLI.DAG;
1363 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1364 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1365 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1366 SDValue Chain = CLI.Chain;
1367 SDValue Callee = CLI.Callee;
1368 bool &isTailCall = CLI.IsTailCall;
1369 CallingConv::ID CallConv = CLI.CallConv;
1370 bool doesNotRet = CLI.DoesNotReturn;
1371 bool isVarArg = CLI.IsVarArg;
1373 MachineFunction &MF = DAG.getMachineFunction();
1374 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1375 bool isThisReturn = false;
1376 bool isSibCall = false;
1377 // Disable tail calls if they're not supported.
1378 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1381 // Check if it's really possible to do a tail call.
1382 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1383 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1384 Outs, OutVals, Ins, DAG);
1385 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1386 // detected sibcalls.
1393 // Analyze operands of the call, assigning locations to each operand.
1394 SmallVector<CCValAssign, 16> ArgLocs;
1395 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1396 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1397 CCInfo.AnalyzeCallOperands(Outs,
1398 CCAssignFnForNode(CallConv, /* Return*/ false,
1401 // Get a count of how many bytes are to be pushed on the stack.
1402 unsigned NumBytes = CCInfo.getNextStackOffset();
1404 // For tail calls, memory operands are available in our caller's stack.
1408 // Adjust the stack pointer for the new arguments...
1409 // These operations are automatically eliminated by the prolog/epilog pass
1411 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1414 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1416 RegsToPassVector RegsToPass;
1417 SmallVector<SDValue, 8> MemOpChains;
1419 // Walk the register/memloc assignments, inserting copies/loads. In the case
1420 // of tail call optimization, arguments are handled later.
1421 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1423 ++i, ++realArgIdx) {
1424 CCValAssign &VA = ArgLocs[i];
1425 SDValue Arg = OutVals[realArgIdx];
1426 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1427 bool isByVal = Flags.isByVal();
1429 // Promote the value if needed.
1430 switch (VA.getLocInfo()) {
1431 default: llvm_unreachable("Unknown loc info!");
1432 case CCValAssign::Full: break;
1433 case CCValAssign::SExt:
1434 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1436 case CCValAssign::ZExt:
1437 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1439 case CCValAssign::AExt:
1440 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1442 case CCValAssign::BCvt:
1443 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1447 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1448 if (VA.needsCustom()) {
1449 if (VA.getLocVT() == MVT::v2f64) {
1450 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1451 DAG.getConstant(0, MVT::i32));
1452 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1453 DAG.getConstant(1, MVT::i32));
1455 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1456 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1458 VA = ArgLocs[++i]; // skip ahead to next loc
1459 if (VA.isRegLoc()) {
1460 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1461 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1463 assert(VA.isMemLoc());
1465 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1466 dl, DAG, VA, Flags));
1469 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1470 StackPtr, MemOpChains, Flags);
1472 } else if (VA.isRegLoc()) {
1473 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1474 assert(VA.getLocVT() == MVT::i32 &&
1475 "unexpected calling convention register assignment");
1476 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1477 "unexpected use of 'returned'");
1478 isThisReturn = true;
1480 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1481 } else if (isByVal) {
1482 assert(VA.isMemLoc());
1483 unsigned offset = 0;
1485 // True if this byval aggregate will be split between registers
1487 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1488 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1490 if (CurByValIdx < ByValArgsCount) {
1492 unsigned RegBegin, RegEnd;
1493 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1495 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1497 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1498 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1499 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1500 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1501 MachinePointerInfo(),
1502 false, false, false, 0);
1503 MemOpChains.push_back(Load.getValue(1));
1504 RegsToPass.push_back(std::make_pair(j, Load));
1507 // If parameter size outsides register area, "offset" value
1508 // helps us to calculate stack slot for remained part properly.
1509 offset = RegEnd - RegBegin;
1511 CCInfo.nextInRegsParam();
1514 if (Flags.getByValSize() > 4*offset) {
1515 unsigned LocMemOffset = VA.getLocMemOffset();
1516 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1517 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1519 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1520 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1521 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1523 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1525 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1526 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1527 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1528 Ops, array_lengthof(Ops)));
1530 } else if (!isSibCall) {
1531 assert(VA.isMemLoc());
1533 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1534 dl, DAG, VA, Flags));
1538 if (!MemOpChains.empty())
1539 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1540 &MemOpChains[0], MemOpChains.size());
1542 // Build a sequence of copy-to-reg nodes chained together with token chain
1543 // and flag operands which copy the outgoing args into the appropriate regs.
1545 // Tail call byval lowering might overwrite argument registers so in case of
1546 // tail call optimization the copies to registers are lowered later.
1548 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1549 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1550 RegsToPass[i].second, InFlag);
1551 InFlag = Chain.getValue(1);
1554 // For tail calls lower the arguments to the 'real' stack slot.
1556 // Force all the incoming stack arguments to be loaded from the stack
1557 // before any new outgoing arguments are stored to the stack, because the
1558 // outgoing stack slots may alias the incoming argument stack slots, and
1559 // the alias isn't otherwise explicit. This is slightly more conservative
1560 // than necessary, because it means that each store effectively depends
1561 // on every argument instead of just those arguments it would clobber.
1563 // Do not flag preceding copytoreg stuff together with the following stuff.
1565 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1566 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1567 RegsToPass[i].second, InFlag);
1568 InFlag = Chain.getValue(1);
1573 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1574 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1575 // node so that legalize doesn't hack it.
1576 bool isDirect = false;
1577 bool isARMFunc = false;
1578 bool isLocalARMFunc = false;
1579 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1581 if (EnableARMLongCalls) {
1582 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1583 && "long-calls with non-static relocation model!");
1584 // Handle a global address or an external symbol. If it's not one of
1585 // those, the target's already in a register, so we don't need to do
1587 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1588 const GlobalValue *GV = G->getGlobal();
1589 // Create a constant pool entry for the callee address
1590 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1591 ARMConstantPoolValue *CPV =
1592 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1594 // Get the address of the callee into a register
1595 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1596 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1597 Callee = DAG.getLoad(getPointerTy(), dl,
1598 DAG.getEntryNode(), CPAddr,
1599 MachinePointerInfo::getConstantPool(),
1600 false, false, false, 0);
1601 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1602 const char *Sym = S->getSymbol();
1604 // Create a constant pool entry for the callee address
1605 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1606 ARMConstantPoolValue *CPV =
1607 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1608 ARMPCLabelIndex, 0);
1609 // Get the address of the callee into a register
1610 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1611 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1612 Callee = DAG.getLoad(getPointerTy(), dl,
1613 DAG.getEntryNode(), CPAddr,
1614 MachinePointerInfo::getConstantPool(),
1615 false, false, false, 0);
1617 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1618 const GlobalValue *GV = G->getGlobal();
1620 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1621 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1622 getTargetMachine().getRelocationModel() != Reloc::Static;
1623 isARMFunc = !Subtarget->isThumb() || isStub;
1624 // ARM call to a local ARM function is predicable.
1625 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1626 // tBX takes a register source operand.
1627 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1628 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1629 ARMConstantPoolValue *CPV =
1630 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1631 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1632 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1633 Callee = DAG.getLoad(getPointerTy(), dl,
1634 DAG.getEntryNode(), CPAddr,
1635 MachinePointerInfo::getConstantPool(),
1636 false, false, false, 0);
1637 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1638 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1639 getPointerTy(), Callee, PICLabel);
1641 // On ELF targets for PIC code, direct calls should go through the PLT
1642 unsigned OpFlags = 0;
1643 if (Subtarget->isTargetELF() &&
1644 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1645 OpFlags = ARMII::MO_PLT;
1646 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1648 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1650 bool isStub = Subtarget->isTargetDarwin() &&
1651 getTargetMachine().getRelocationModel() != Reloc::Static;
1652 isARMFunc = !Subtarget->isThumb() || isStub;
1653 // tBX takes a register source operand.
1654 const char *Sym = S->getSymbol();
1655 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1656 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1657 ARMConstantPoolValue *CPV =
1658 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1659 ARMPCLabelIndex, 4);
1660 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1661 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1662 Callee = DAG.getLoad(getPointerTy(), dl,
1663 DAG.getEntryNode(), CPAddr,
1664 MachinePointerInfo::getConstantPool(),
1665 false, false, false, 0);
1666 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1667 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1668 getPointerTy(), Callee, PICLabel);
1670 unsigned OpFlags = 0;
1671 // On ELF targets for PIC code, direct calls should go through the PLT
1672 if (Subtarget->isTargetELF() &&
1673 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1674 OpFlags = ARMII::MO_PLT;
1675 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1679 // FIXME: handle tail calls differently.
1681 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1682 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1683 if (Subtarget->isThumb()) {
1684 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1685 CallOpc = ARMISD::CALL_NOLINK;
1687 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1689 if (!isDirect && !Subtarget->hasV5TOps())
1690 CallOpc = ARMISD::CALL_NOLINK;
1691 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1692 // Emit regular call when code size is the priority
1694 // "mov lr, pc; b _foo" to avoid confusing the RSP
1695 CallOpc = ARMISD::CALL_NOLINK;
1697 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1700 std::vector<SDValue> Ops;
1701 Ops.push_back(Chain);
1702 Ops.push_back(Callee);
1704 // Add argument registers to the end of the list so that they are known live
1706 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1707 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1708 RegsToPass[i].second.getValueType()));
1710 // Add a register mask operand representing the call-preserved registers.
1711 const uint32_t *Mask;
1712 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1713 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1715 // For 'this' returns, use the R0-preserving mask
1716 Mask = ARI->getThisReturnPreservedMask(CallConv);
1718 Mask = ARI->getCallPreservedMask(CallConv);
1720 assert(Mask && "Missing call preserved mask for calling convention");
1721 Ops.push_back(DAG.getRegisterMask(Mask));
1723 if (InFlag.getNode())
1724 Ops.push_back(InFlag);
1726 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1728 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1730 // Returns a chain and a flag for retval copy to use.
1731 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1732 InFlag = Chain.getValue(1);
1734 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1735 DAG.getIntPtrConstant(0, true), InFlag, dl);
1737 InFlag = Chain.getValue(1);
1739 // Handle result values, copying them out of physregs into vregs that we
1741 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1742 InVals, isThisReturn,
1743 isThisReturn ? OutVals[0] : SDValue());
1746 /// HandleByVal - Every parameter *after* a byval parameter is passed
1747 /// on the stack. Remember the next parameter register to allocate,
1748 /// and then confiscate the rest of the parameter registers to insure
1751 ARMTargetLowering::HandleByVal(
1752 CCState *State, unsigned &size, unsigned Align) const {
1753 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1754 assert((State->getCallOrPrologue() == Prologue ||
1755 State->getCallOrPrologue() == Call) &&
1756 "unhandled ParmContext");
1758 // For in-prologue parameters handling, we also introduce stack offset
1759 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1760 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1761 // NSAA should be evaluted (NSAA means "next stacked argument address").
1762 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1763 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1764 unsigned NSAAOffset = State->getNextStackOffset();
1765 if (State->getCallOrPrologue() != Call) {
1766 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1768 State->getInRegsParamInfo(i, RB, RE);
1769 assert(NSAAOffset >= (RE-RB)*4 &&
1770 "Stack offset for byval regs doesn't introduced anymore?");
1771 NSAAOffset -= (RE-RB)*4;
1774 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1775 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1776 unsigned AlignInRegs = Align / 4;
1777 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1778 for (unsigned i = 0; i < Waste; ++i)
1779 reg = State->AllocateReg(GPRArgRegs, 4);
1782 unsigned excess = 4 * (ARM::R4 - reg);
1784 // Special case when NSAA != SP and parameter size greater than size of
1785 // all remained GPR regs. In that case we can't split parameter, we must
1786 // send it to stack. We also must set NCRN to R4, so waste all
1787 // remained registers.
1788 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1789 while (State->AllocateReg(GPRArgRegs, 4))
1794 // First register for byval parameter is the first register that wasn't
1795 // allocated before this method call, so it would be "reg".
1796 // If parameter is small enough to be saved in range [reg, r4), then
1797 // the end (first after last) register would be reg + param-size-in-regs,
1798 // else parameter would be splitted between registers and stack,
1799 // end register would be r4 in this case.
1800 unsigned ByValRegBegin = reg;
1801 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1802 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1803 // Note, first register is allocated in the beginning of function already,
1804 // allocate remained amount of registers we need.
1805 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1806 State->AllocateReg(GPRArgRegs, 4);
1807 // At a call site, a byval parameter that is split between
1808 // registers and memory needs its size truncated here. In a
1809 // function prologue, such byval parameters are reassembled in
1810 // memory, and are not truncated.
1811 if (State->getCallOrPrologue() == Call) {
1812 // Make remained size equal to 0 in case, when
1813 // the whole structure may be stored into registers.
1823 /// MatchingStackOffset - Return true if the given stack call argument is
1824 /// already available in the same position (relatively) of the caller's
1825 /// incoming argument stack.
1827 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1828 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1829 const TargetInstrInfo *TII) {
1830 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1832 if (Arg.getOpcode() == ISD::CopyFromReg) {
1833 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1834 if (!TargetRegisterInfo::isVirtualRegister(VR))
1836 MachineInstr *Def = MRI->getVRegDef(VR);
1839 if (!Flags.isByVal()) {
1840 if (!TII->isLoadFromStackSlot(Def, FI))
1845 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1846 if (Flags.isByVal())
1847 // ByVal argument is passed in as a pointer but it's now being
1848 // dereferenced. e.g.
1849 // define @foo(%struct.X* %A) {
1850 // tail call @bar(%struct.X* byval %A)
1853 SDValue Ptr = Ld->getBasePtr();
1854 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1857 FI = FINode->getIndex();
1861 assert(FI != INT_MAX);
1862 if (!MFI->isFixedObjectIndex(FI))
1864 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1867 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1868 /// for tail call optimization. Targets which want to do tail call
1869 /// optimization should implement this function.
1871 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1872 CallingConv::ID CalleeCC,
1874 bool isCalleeStructRet,
1875 bool isCallerStructRet,
1876 const SmallVectorImpl<ISD::OutputArg> &Outs,
1877 const SmallVectorImpl<SDValue> &OutVals,
1878 const SmallVectorImpl<ISD::InputArg> &Ins,
1879 SelectionDAG& DAG) const {
1880 const Function *CallerF = DAG.getMachineFunction().getFunction();
1881 CallingConv::ID CallerCC = CallerF->getCallingConv();
1882 bool CCMatch = CallerCC == CalleeCC;
1884 // Look for obvious safe cases to perform tail call optimization that do not
1885 // require ABI changes. This is what gcc calls sibcall.
1887 // Do not sibcall optimize vararg calls unless the call site is not passing
1889 if (isVarArg && !Outs.empty())
1892 // Also avoid sibcall optimization if either caller or callee uses struct
1893 // return semantics.
1894 if (isCalleeStructRet || isCallerStructRet)
1897 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1898 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1899 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1900 // support in the assembler and linker to be used. This would need to be
1901 // fixed to fully support tail calls in Thumb1.
1903 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1904 // LR. This means if we need to reload LR, it takes an extra instructions,
1905 // which outweighs the value of the tail call; but here we don't know yet
1906 // whether LR is going to be used. Probably the right approach is to
1907 // generate the tail call here and turn it back into CALL/RET in
1908 // emitEpilogue if LR is used.
1910 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1911 // but we need to make sure there are enough registers; the only valid
1912 // registers are the 4 used for parameters. We don't currently do this
1914 if (Subtarget->isThumb1Only())
1917 // If the calling conventions do not match, then we'd better make sure the
1918 // results are returned in the same way as what the caller expects.
1920 SmallVector<CCValAssign, 16> RVLocs1;
1921 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1922 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1923 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1925 SmallVector<CCValAssign, 16> RVLocs2;
1926 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1927 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1928 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1930 if (RVLocs1.size() != RVLocs2.size())
1932 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1933 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1935 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1937 if (RVLocs1[i].isRegLoc()) {
1938 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1941 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1947 // If Caller's vararg or byval argument has been split between registers and
1948 // stack, do not perform tail call, since part of the argument is in caller's
1950 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1951 getInfo<ARMFunctionInfo>();
1952 if (AFI_Caller->getArgRegsSaveSize())
1955 // If the callee takes no arguments then go on to check the results of the
1957 if (!Outs.empty()) {
1958 // Check if stack adjustment is needed. For now, do not do this if any
1959 // argument is passed on the stack.
1960 SmallVector<CCValAssign, 16> ArgLocs;
1961 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1962 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1963 CCInfo.AnalyzeCallOperands(Outs,
1964 CCAssignFnForNode(CalleeCC, false, isVarArg));
1965 if (CCInfo.getNextStackOffset()) {
1966 MachineFunction &MF = DAG.getMachineFunction();
1968 // Check if the arguments are already laid out in the right way as
1969 // the caller's fixed stack objects.
1970 MachineFrameInfo *MFI = MF.getFrameInfo();
1971 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1972 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1973 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1975 ++i, ++realArgIdx) {
1976 CCValAssign &VA = ArgLocs[i];
1977 EVT RegVT = VA.getLocVT();
1978 SDValue Arg = OutVals[realArgIdx];
1979 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1980 if (VA.getLocInfo() == CCValAssign::Indirect)
1982 if (VA.needsCustom()) {
1983 // f64 and vector types are split into multiple registers or
1984 // register/stack-slot combinations. The types will not match
1985 // the registers; give up on memory f64 refs until we figure
1986 // out what to do about this.
1989 if (!ArgLocs[++i].isRegLoc())
1991 if (RegVT == MVT::v2f64) {
1992 if (!ArgLocs[++i].isRegLoc())
1994 if (!ArgLocs[++i].isRegLoc())
1997 } else if (!VA.isRegLoc()) {
1998 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2010 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2011 MachineFunction &MF, bool isVarArg,
2012 const SmallVectorImpl<ISD::OutputArg> &Outs,
2013 LLVMContext &Context) const {
2014 SmallVector<CCValAssign, 16> RVLocs;
2015 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2016 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2021 ARMTargetLowering::LowerReturn(SDValue Chain,
2022 CallingConv::ID CallConv, bool isVarArg,
2023 const SmallVectorImpl<ISD::OutputArg> &Outs,
2024 const SmallVectorImpl<SDValue> &OutVals,
2025 SDLoc dl, SelectionDAG &DAG) const {
2027 // CCValAssign - represent the assignment of the return value to a location.
2028 SmallVector<CCValAssign, 16> RVLocs;
2030 // CCState - Info about the registers and stack slots.
2031 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2032 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2034 // Analyze outgoing return values.
2035 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2039 SmallVector<SDValue, 4> RetOps;
2040 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2042 // Copy the result values into the output registers.
2043 for (unsigned i = 0, realRVLocIdx = 0;
2045 ++i, ++realRVLocIdx) {
2046 CCValAssign &VA = RVLocs[i];
2047 assert(VA.isRegLoc() && "Can only return in registers!");
2049 SDValue Arg = OutVals[realRVLocIdx];
2051 switch (VA.getLocInfo()) {
2052 default: llvm_unreachable("Unknown loc info!");
2053 case CCValAssign::Full: break;
2054 case CCValAssign::BCvt:
2055 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2059 if (VA.needsCustom()) {
2060 if (VA.getLocVT() == MVT::v2f64) {
2061 // Extract the first half and return it in two registers.
2062 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2063 DAG.getConstant(0, MVT::i32));
2064 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2065 DAG.getVTList(MVT::i32, MVT::i32), Half);
2067 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2068 Flag = Chain.getValue(1);
2069 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2070 VA = RVLocs[++i]; // skip ahead to next loc
2071 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2072 HalfGPRs.getValue(1), 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
2077 // Extract the 2nd half and fall through to handle it as an f64 value.
2078 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2079 DAG.getConstant(1, MVT::i32));
2081 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2083 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2084 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2085 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2086 Flag = Chain.getValue(1);
2087 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2088 VA = RVLocs[++i]; // skip ahead to next loc
2089 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2092 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2094 // Guarantee that all emitted copies are
2095 // stuck together, avoiding something bad.
2096 Flag = Chain.getValue(1);
2097 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2100 // Update chain and glue.
2103 RetOps.push_back(Flag);
2105 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2106 RetOps.data(), RetOps.size());
2109 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2110 if (N->getNumValues() != 1)
2112 if (!N->hasNUsesOfValue(1, 0))
2115 SDValue TCChain = Chain;
2116 SDNode *Copy = *N->use_begin();
2117 if (Copy->getOpcode() == ISD::CopyToReg) {
2118 // If the copy has a glue operand, we conservatively assume it isn't safe to
2119 // perform a tail call.
2120 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2122 TCChain = Copy->getOperand(0);
2123 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2124 SDNode *VMov = Copy;
2125 // f64 returned in a pair of GPRs.
2126 SmallPtrSet<SDNode*, 2> Copies;
2127 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2129 if (UI->getOpcode() != ISD::CopyToReg)
2133 if (Copies.size() > 2)
2136 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2138 SDValue UseChain = UI->getOperand(0);
2139 if (Copies.count(UseChain.getNode()))
2146 } else if (Copy->getOpcode() == ISD::BITCAST) {
2147 // f32 returned in a single GPR.
2148 if (!Copy->hasOneUse())
2150 Copy = *Copy->use_begin();
2151 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2153 TCChain = Copy->getOperand(0);
2158 bool HasRet = false;
2159 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2161 if (UI->getOpcode() != ARMISD::RET_FLAG)
2173 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2174 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2177 if (!CI->isTailCall())
2180 return !Subtarget->isThumb1Only();
2183 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2184 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2185 // one of the above mentioned nodes. It has to be wrapped because otherwise
2186 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2187 // be used to form addressing mode. These wrapped nodes will be selected
2189 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2190 EVT PtrVT = Op.getValueType();
2191 // FIXME there is no actual debug info here
2193 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2195 if (CP->isMachineConstantPoolEntry())
2196 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2197 CP->getAlignment());
2199 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2200 CP->getAlignment());
2201 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2204 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2205 return MachineJumpTableInfo::EK_Inline;
2208 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2209 SelectionDAG &DAG) const {
2210 MachineFunction &MF = DAG.getMachineFunction();
2211 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2212 unsigned ARMPCLabelIndex = 0;
2214 EVT PtrVT = getPointerTy();
2215 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2216 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2218 if (RelocM == Reloc::Static) {
2219 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2221 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2222 ARMPCLabelIndex = AFI->createPICLabelUId();
2223 ARMConstantPoolValue *CPV =
2224 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2225 ARMCP::CPBlockAddress, PCAdj);
2226 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2228 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2229 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2230 MachinePointerInfo::getConstantPool(),
2231 false, false, false, 0);
2232 if (RelocM == Reloc::Static)
2234 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2235 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2238 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2240 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2241 SelectionDAG &DAG) const {
2243 EVT PtrVT = getPointerTy();
2244 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2245 MachineFunction &MF = DAG.getMachineFunction();
2246 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2247 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2248 ARMConstantPoolValue *CPV =
2249 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2250 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2251 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2252 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2253 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2254 MachinePointerInfo::getConstantPool(),
2255 false, false, false, 0);
2256 SDValue Chain = Argument.getValue(1);
2258 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2259 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2261 // call __tls_get_addr.
2264 Entry.Node = Argument;
2265 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2266 Args.push_back(Entry);
2267 // FIXME: is there useful debug info available here?
2268 TargetLowering::CallLoweringInfo CLI(Chain,
2269 (Type *) Type::getInt32Ty(*DAG.getContext()),
2270 false, false, false, false,
2271 0, CallingConv::C, /*isTailCall=*/false,
2272 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2273 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2274 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2275 return CallResult.first;
2278 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2279 // "local exec" model.
2281 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2283 TLSModel::Model model) const {
2284 const GlobalValue *GV = GA->getGlobal();
2287 SDValue Chain = DAG.getEntryNode();
2288 EVT PtrVT = getPointerTy();
2289 // Get the Thread Pointer
2290 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2292 if (model == TLSModel::InitialExec) {
2293 MachineFunction &MF = DAG.getMachineFunction();
2294 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2295 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2296 // Initial exec model.
2297 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2298 ARMConstantPoolValue *CPV =
2299 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2300 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2302 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2303 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2304 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2305 MachinePointerInfo::getConstantPool(),
2306 false, false, false, 0);
2307 Chain = Offset.getValue(1);
2309 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2310 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2312 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2313 MachinePointerInfo::getConstantPool(),
2314 false, false, false, 0);
2317 assert(model == TLSModel::LocalExec);
2318 ARMConstantPoolValue *CPV =
2319 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2320 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2321 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2322 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2323 MachinePointerInfo::getConstantPool(),
2324 false, false, false, 0);
2327 // The address of the thread local variable is the add of the thread
2328 // pointer with the offset of the variable.
2329 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2333 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2334 // TODO: implement the "local dynamic" model
2335 assert(Subtarget->isTargetELF() &&
2336 "TLS not implemented for non-ELF targets");
2337 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2339 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2342 case TLSModel::GeneralDynamic:
2343 case TLSModel::LocalDynamic:
2344 return LowerToTLSGeneralDynamicModel(GA, DAG);
2345 case TLSModel::InitialExec:
2346 case TLSModel::LocalExec:
2347 return LowerToTLSExecModels(GA, DAG, model);
2349 llvm_unreachable("bogus TLS model");
2352 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2353 SelectionDAG &DAG) const {
2354 EVT PtrVT = getPointerTy();
2356 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2357 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2358 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2359 ARMConstantPoolValue *CPV =
2360 ARMConstantPoolConstant::Create(GV,
2361 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2362 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2363 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2364 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2366 MachinePointerInfo::getConstantPool(),
2367 false, false, false, 0);
2368 SDValue Chain = Result.getValue(1);
2369 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2370 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2372 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2373 MachinePointerInfo::getGOT(),
2374 false, false, false, 0);
2378 // If we have T2 ops, we can materialize the address directly via movt/movw
2379 // pair. This is always cheaper.
2380 if (Subtarget->useMovt()) {
2382 // FIXME: Once remat is capable of dealing with instructions with register
2383 // operands, expand this into two nodes.
2384 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2385 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2387 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2388 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2389 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2390 MachinePointerInfo::getConstantPool(),
2391 false, false, false, 0);
2395 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2396 SelectionDAG &DAG) const {
2397 EVT PtrVT = getPointerTy();
2399 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2400 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2402 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2403 // update ARMFastISel::ARMMaterializeGV.
2404 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2406 // FIXME: Once remat is capable of dealing with instructions with register
2407 // operands, expand this into two nodes.
2408 if (RelocM == Reloc::Static)
2409 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2410 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2412 unsigned Wrapper = (RelocM == Reloc::PIC_)
2413 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2414 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2415 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2416 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2417 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2418 MachinePointerInfo::getGOT(),
2419 false, false, false, 0);
2423 unsigned ARMPCLabelIndex = 0;
2425 if (RelocM == Reloc::Static) {
2426 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2428 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2429 ARMPCLabelIndex = AFI->createPICLabelUId();
2430 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2431 ARMConstantPoolValue *CPV =
2432 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2434 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2436 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2438 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2439 MachinePointerInfo::getConstantPool(),
2440 false, false, false, 0);
2441 SDValue Chain = Result.getValue(1);
2443 if (RelocM == Reloc::PIC_) {
2444 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2445 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2448 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2449 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2450 false, false, false, 0);
2455 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2456 SelectionDAG &DAG) const {
2457 assert(Subtarget->isTargetELF() &&
2458 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2459 MachineFunction &MF = DAG.getMachineFunction();
2460 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2461 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2462 EVT PtrVT = getPointerTy();
2464 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2465 ARMConstantPoolValue *CPV =
2466 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2467 ARMPCLabelIndex, PCAdj);
2468 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2469 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2470 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2471 MachinePointerInfo::getConstantPool(),
2472 false, false, false, 0);
2473 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2474 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2478 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2480 SDValue Val = DAG.getConstant(0, MVT::i32);
2481 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2482 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2483 Op.getOperand(1), Val);
2487 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2489 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2490 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2494 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2495 const ARMSubtarget *Subtarget) const {
2496 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2499 default: return SDValue(); // Don't custom lower most intrinsics.
2500 case Intrinsic::arm_thread_pointer: {
2501 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2502 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2504 case Intrinsic::eh_sjlj_lsda: {
2505 MachineFunction &MF = DAG.getMachineFunction();
2506 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2507 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2508 EVT PtrVT = getPointerTy();
2509 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2511 unsigned PCAdj = (RelocM != Reloc::PIC_)
2512 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2513 ARMConstantPoolValue *CPV =
2514 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2515 ARMCP::CPLSDA, PCAdj);
2516 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2517 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2519 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2520 MachinePointerInfo::getConstantPool(),
2521 false, false, false, 0);
2523 if (RelocM == Reloc::PIC_) {
2524 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2525 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2529 case Intrinsic::arm_neon_vmulls:
2530 case Intrinsic::arm_neon_vmullu: {
2531 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2532 ? ARMISD::VMULLs : ARMISD::VMULLu;
2533 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2534 Op.getOperand(1), Op.getOperand(2));
2539 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2540 const ARMSubtarget *Subtarget) {
2541 // FIXME: handle "fence singlethread" more efficiently.
2543 if (!Subtarget->hasDataBarrier()) {
2544 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2545 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2547 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2548 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2549 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2550 DAG.getConstant(0, MVT::i32));
2553 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2554 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2557 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2558 const ARMSubtarget *Subtarget) {
2559 // ARM pre v5TE and Thumb1 does not have preload instructions.
2560 if (!(Subtarget->isThumb2() ||
2561 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2562 // Just preserve the chain.
2563 return Op.getOperand(0);
2566 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2568 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2569 // ARMv7 with MP extension has PLDW.
2570 return Op.getOperand(0);
2572 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2573 if (Subtarget->isThumb()) {
2575 isRead = ~isRead & 1;
2576 isData = ~isData & 1;
2579 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2580 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2581 DAG.getConstant(isData, MVT::i32));
2584 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2585 MachineFunction &MF = DAG.getMachineFunction();
2586 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2588 // vastart just stores the address of the VarArgsFrameIndex slot into the
2589 // memory location argument.
2591 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2592 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2593 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2594 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2595 MachinePointerInfo(SV), false, false, 0);
2599 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2600 SDValue &Root, SelectionDAG &DAG,
2602 MachineFunction &MF = DAG.getMachineFunction();
2603 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2605 const TargetRegisterClass *RC;
2606 if (AFI->isThumb1OnlyFunction())
2607 RC = &ARM::tGPRRegClass;
2609 RC = &ARM::GPRRegClass;
2611 // Transform the arguments stored in physical registers into virtual ones.
2612 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2613 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2616 if (NextVA.isMemLoc()) {
2617 MachineFrameInfo *MFI = MF.getFrameInfo();
2618 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2620 // Create load node to retrieve arguments from the stack.
2621 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2622 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2623 MachinePointerInfo::getFixedStack(FI),
2624 false, false, false, 0);
2626 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2627 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2630 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2634 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2635 unsigned InRegsParamRecordIdx,
2637 unsigned &ArgRegsSize,
2638 unsigned &ArgRegsSaveSize)
2641 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2642 unsigned RBegin, REnd;
2643 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2644 NumGPRs = REnd - RBegin;
2646 unsigned int firstUnalloced;
2647 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2648 sizeof(GPRArgRegs) /
2649 sizeof(GPRArgRegs[0]));
2650 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2653 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2654 ArgRegsSize = NumGPRs * 4;
2656 // If parameter is split between stack and GPRs...
2657 if (NumGPRs && Align == 8 &&
2658 (ArgRegsSize < ArgSize ||
2659 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2660 // Add padding for part of param recovered from GPRs, so
2661 // its last byte must be at address K*8 - 1.
2662 // We need to do it, since remained (stack) part of parameter has
2663 // stack alignment, and we need to "attach" "GPRs head" without gaps
2666 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2667 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2669 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2671 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2672 (ArgRegsSize + AFI->getArgRegsSaveSize());
2673 ArgRegsSaveSize = ArgRegsSize + Padding;
2675 // We don't need to extend regs save size for byval parameters if they
2676 // are passed via GPRs only.
2677 ArgRegsSaveSize = ArgRegsSize;
2680 // The remaining GPRs hold either the beginning of variable-argument
2681 // data, or the beginning of an aggregate passed by value (usually
2682 // byval). Either way, we allocate stack slots adjacent to the data
2683 // provided by our caller, and store the unallocated registers there.
2684 // If this is a variadic function, the va_list pointer will begin with
2685 // these values; otherwise, this reassembles a (byval) structure that
2686 // was split between registers and memory.
2687 // Return: The frame index registers were stored into.
2689 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2690 SDLoc dl, SDValue &Chain,
2691 const Value *OrigArg,
2692 unsigned InRegsParamRecordIdx,
2693 unsigned OffsetFromOrigArg,
2696 bool ForceMutable) const {
2698 // Currently, two use-cases possible:
2699 // Case #1. Non var-args function, and we meet first byval parameter.
2700 // Setup first unallocated register as first byval register;
2701 // eat all remained registers
2702 // (these two actions are performed by HandleByVal method).
2703 // Then, here, we initialize stack frame with
2704 // "store-reg" instructions.
2705 // Case #2. Var-args function, that doesn't contain byval parameters.
2706 // The same: eat all remained unallocated registers,
2707 // initialize stack frame.
2709 MachineFunction &MF = DAG.getMachineFunction();
2710 MachineFrameInfo *MFI = MF.getFrameInfo();
2711 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2712 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2713 unsigned RBegin, REnd;
2714 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2715 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2716 firstRegToSaveIndex = RBegin - ARM::R0;
2717 lastRegToSaveIndex = REnd - ARM::R0;
2719 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2720 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2721 lastRegToSaveIndex = 4;
2724 unsigned ArgRegsSize, ArgRegsSaveSize;
2725 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2726 ArgRegsSize, ArgRegsSaveSize);
2728 // Store any by-val regs to their spots on the stack so that they may be
2729 // loaded by deferencing the result of formal parameter pointer or va_next.
2730 // Note: once stack area for byval/varargs registers
2731 // was initialized, it can't be initialized again.
2732 if (ArgRegsSaveSize) {
2734 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2737 assert(AFI->getStoredByValParamsPadding() == 0 &&
2738 "The only parameter may be padded.");
2739 AFI->setStoredByValParamsPadding(Padding);
2742 int FrameIndex = MFI->CreateFixedObject(
2744 Padding + ArgOffset,
2746 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2748 SmallVector<SDValue, 4> MemOps;
2749 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2750 ++firstRegToSaveIndex, ++i) {
2751 const TargetRegisterClass *RC;
2752 if (AFI->isThumb1OnlyFunction())
2753 RC = &ARM::tGPRRegClass;
2755 RC = &ARM::GPRRegClass;
2757 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2758 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2760 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2761 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2763 MemOps.push_back(Store);
2764 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2765 DAG.getConstant(4, getPointerTy()));
2768 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2770 if (!MemOps.empty())
2771 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2772 &MemOps[0], MemOps.size());
2775 // This will point to the next argument passed via stack.
2776 return MFI->CreateFixedObject(
2777 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2780 // Setup stack frame, the va_list pointer will start from.
2782 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2783 SDLoc dl, SDValue &Chain,
2785 bool ForceMutable) const {
2786 MachineFunction &MF = DAG.getMachineFunction();
2787 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2789 // Try to store any remaining integer argument regs
2790 // to their spots on the stack so that they may be loaded by deferencing
2791 // the result of va_next.
2792 // If there is no regs to be stored, just point address after last
2793 // argument passed via stack.
2795 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2796 0, ArgOffset, 0, ForceMutable);
2798 AFI->setVarArgsFrameIndex(FrameIndex);
2802 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2803 CallingConv::ID CallConv, bool isVarArg,
2804 const SmallVectorImpl<ISD::InputArg>
2806 SDLoc dl, SelectionDAG &DAG,
2807 SmallVectorImpl<SDValue> &InVals)
2809 MachineFunction &MF = DAG.getMachineFunction();
2810 MachineFrameInfo *MFI = MF.getFrameInfo();
2812 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2814 // Assign locations to all of the incoming arguments.
2815 SmallVector<CCValAssign, 16> ArgLocs;
2816 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2817 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2818 CCInfo.AnalyzeFormalArguments(Ins,
2819 CCAssignFnForNode(CallConv, /* Return*/ false,
2822 SmallVector<SDValue, 16> ArgValues;
2823 int lastInsIndex = -1;
2825 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2826 unsigned CurArgIdx = 0;
2828 // Initially ArgRegsSaveSize is zero.
2829 // Then we increase this value each time we meet byval parameter.
2830 // We also increase this value in case of varargs function.
2831 AFI->setArgRegsSaveSize(0);
2833 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2834 CCValAssign &VA = ArgLocs[i];
2835 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2836 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2837 // Arguments stored in registers.
2838 if (VA.isRegLoc()) {
2839 EVT RegVT = VA.getLocVT();
2841 if (VA.needsCustom()) {
2842 // f64 and vector types are split up into multiple registers or
2843 // combinations of registers and stack slots.
2844 if (VA.getLocVT() == MVT::v2f64) {
2845 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2847 VA = ArgLocs[++i]; // skip ahead to next loc
2849 if (VA.isMemLoc()) {
2850 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2851 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2852 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2853 MachinePointerInfo::getFixedStack(FI),
2854 false, false, false, 0);
2856 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2859 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2860 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2861 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2862 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2863 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2865 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2868 const TargetRegisterClass *RC;
2870 if (RegVT == MVT::f32)
2871 RC = &ARM::SPRRegClass;
2872 else if (RegVT == MVT::f64)
2873 RC = &ARM::DPRRegClass;
2874 else if (RegVT == MVT::v2f64)
2875 RC = &ARM::QPRRegClass;
2876 else if (RegVT == MVT::i32)
2877 RC = AFI->isThumb1OnlyFunction() ?
2878 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2879 (const TargetRegisterClass*)&ARM::GPRRegClass;
2881 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2883 // Transform the arguments in physical registers into virtual ones.
2884 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2885 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2888 // If this is an 8 or 16-bit value, it is really passed promoted
2889 // to 32 bits. Insert an assert[sz]ext to capture this, then
2890 // truncate to the right size.
2891 switch (VA.getLocInfo()) {
2892 default: llvm_unreachable("Unknown loc info!");
2893 case CCValAssign::Full: break;
2894 case CCValAssign::BCvt:
2895 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2897 case CCValAssign::SExt:
2898 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2899 DAG.getValueType(VA.getValVT()));
2900 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2902 case CCValAssign::ZExt:
2903 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2904 DAG.getValueType(VA.getValVT()));
2905 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2909 InVals.push_back(ArgValue);
2911 } else { // VA.isRegLoc()
2914 assert(VA.isMemLoc());
2915 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2917 int index = ArgLocs[i].getValNo();
2919 // Some Ins[] entries become multiple ArgLoc[] entries.
2920 // Process them only once.
2921 if (index != lastInsIndex)
2923 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2924 // FIXME: For now, all byval parameter objects are marked mutable.
2925 // This can be changed with more analysis.
2926 // In case of tail call optimization mark all arguments mutable.
2927 // Since they could be overwritten by lowering of arguments in case of
2929 if (Flags.isByVal()) {
2930 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2931 int FrameIndex = StoreByValRegs(
2932 CCInfo, DAG, dl, Chain, CurOrigArg,
2934 Ins[VA.getValNo()].PartOffset,
2935 VA.getLocMemOffset(),
2936 Flags.getByValSize(),
2937 true /*force mutable frames*/);
2938 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2939 CCInfo.nextInRegsParam();
2941 unsigned FIOffset = VA.getLocMemOffset() +
2942 AFI->getStoredByValParamsPadding();
2943 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2946 // Create load nodes to retrieve arguments from the stack.
2947 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2948 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2949 MachinePointerInfo::getFixedStack(FI),
2950 false, false, false, 0));
2952 lastInsIndex = index;
2959 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2960 CCInfo.getNextStackOffset());
2965 /// isFloatingPointZero - Return true if this is +0.0.
2966 static bool isFloatingPointZero(SDValue Op) {
2967 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2968 return CFP->getValueAPF().isPosZero();
2969 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2970 // Maybe this has already been legalized into the constant pool?
2971 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2972 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2973 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2974 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2975 return CFP->getValueAPF().isPosZero();
2981 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2982 /// the given operands.
2984 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2985 SDValue &ARMcc, SelectionDAG &DAG,
2987 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2988 unsigned C = RHSC->getZExtValue();
2989 if (!isLegalICmpImmediate(C)) {
2990 // Constant does not fit, try adjusting it by one?
2995 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2996 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2997 RHS = DAG.getConstant(C-1, MVT::i32);
3002 if (C != 0 && isLegalICmpImmediate(C-1)) {
3003 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3004 RHS = DAG.getConstant(C-1, MVT::i32);
3009 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3010 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3011 RHS = DAG.getConstant(C+1, MVT::i32);
3016 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3017 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3018 RHS = DAG.getConstant(C+1, MVT::i32);
3025 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3026 ARMISD::NodeType CompareType;
3029 CompareType = ARMISD::CMP;
3034 CompareType = ARMISD::CMPZ;
3037 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3038 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3041 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3043 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3046 if (!isFloatingPointZero(RHS))
3047 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3049 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3050 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3053 /// duplicateCmp - Glue values can have only one use, so this function
3054 /// duplicates a comparison node.
3056 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3057 unsigned Opc = Cmp.getOpcode();
3059 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3060 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3062 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3063 Cmp = Cmp.getOperand(0);
3064 Opc = Cmp.getOpcode();
3065 if (Opc == ARMISD::CMPFP)
3066 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3068 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3069 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3071 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3074 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3075 SDValue Cond = Op.getOperand(0);
3076 SDValue SelectTrue = Op.getOperand(1);
3077 SDValue SelectFalse = Op.getOperand(2);
3082 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3083 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3085 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3086 const ConstantSDNode *CMOVTrue =
3087 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3088 const ConstantSDNode *CMOVFalse =
3089 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3091 if (CMOVTrue && CMOVFalse) {
3092 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3093 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3097 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3099 False = SelectFalse;
3100 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3105 if (True.getNode() && False.getNode()) {
3106 EVT VT = Op.getValueType();
3107 SDValue ARMcc = Cond.getOperand(2);
3108 SDValue CCR = Cond.getOperand(3);
3109 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3110 assert(True.getValueType() == VT);
3111 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3116 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3117 // undefined bits before doing a full-word comparison with zero.
3118 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3119 DAG.getConstant(1, Cond.getValueType()));
3121 return DAG.getSelectCC(dl, Cond,
3122 DAG.getConstant(0, Cond.getValueType()),
3123 SelectTrue, SelectFalse, ISD::SETNE);
3126 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3127 EVT VT = Op.getValueType();
3128 SDValue LHS = Op.getOperand(0);
3129 SDValue RHS = Op.getOperand(1);
3130 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3131 SDValue TrueVal = Op.getOperand(2);
3132 SDValue FalseVal = Op.getOperand(3);
3135 if (LHS.getValueType() == MVT::i32) {
3137 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3138 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3139 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3142 ARMCC::CondCodes CondCode, CondCode2;
3143 FPCCToARMCC(CC, CondCode, CondCode2);
3145 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3146 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3147 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3148 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3150 if (CondCode2 != ARMCC::AL) {
3151 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3152 // FIXME: Needs another CMP because flag can have but one use.
3153 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3154 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3155 Result, TrueVal, ARMcc2, CCR, Cmp2);
3160 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3161 /// to morph to an integer compare sequence.
3162 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3163 const ARMSubtarget *Subtarget) {
3164 SDNode *N = Op.getNode();
3165 if (!N->hasOneUse())
3166 // Otherwise it requires moving the value from fp to integer registers.
3168 if (!N->getNumValues())
3170 EVT VT = Op.getValueType();
3171 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3172 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3173 // vmrs are very slow, e.g. cortex-a8.
3176 if (isFloatingPointZero(Op)) {
3180 return ISD::isNormalLoad(N);
3183 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3184 if (isFloatingPointZero(Op))
3185 return DAG.getConstant(0, MVT::i32);
3187 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3188 return DAG.getLoad(MVT::i32, SDLoc(Op),
3189 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3190 Ld->isVolatile(), Ld->isNonTemporal(),
3191 Ld->isInvariant(), Ld->getAlignment());
3193 llvm_unreachable("Unknown VFP cmp argument!");
3196 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3197 SDValue &RetVal1, SDValue &RetVal2) {
3198 if (isFloatingPointZero(Op)) {
3199 RetVal1 = DAG.getConstant(0, MVT::i32);
3200 RetVal2 = DAG.getConstant(0, MVT::i32);
3204 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3205 SDValue Ptr = Ld->getBasePtr();
3206 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3207 Ld->getChain(), Ptr,
3208 Ld->getPointerInfo(),
3209 Ld->isVolatile(), Ld->isNonTemporal(),
3210 Ld->isInvariant(), Ld->getAlignment());
3212 EVT PtrType = Ptr.getValueType();
3213 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3214 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3215 PtrType, Ptr, DAG.getConstant(4, PtrType));
3216 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3217 Ld->getChain(), NewPtr,
3218 Ld->getPointerInfo().getWithOffset(4),
3219 Ld->isVolatile(), Ld->isNonTemporal(),
3220 Ld->isInvariant(), NewAlign);
3224 llvm_unreachable("Unknown VFP cmp argument!");
3227 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3228 /// f32 and even f64 comparisons to integer ones.
3230 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3231 SDValue Chain = Op.getOperand(0);
3232 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3233 SDValue LHS = Op.getOperand(2);
3234 SDValue RHS = Op.getOperand(3);
3235 SDValue Dest = Op.getOperand(4);
3238 bool LHSSeenZero = false;
3239 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3240 bool RHSSeenZero = false;
3241 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3242 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3243 // If unsafe fp math optimization is enabled and there are no other uses of
3244 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3245 // to an integer comparison.
3246 if (CC == ISD::SETOEQ)
3248 else if (CC == ISD::SETUNE)
3251 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3253 if (LHS.getValueType() == MVT::f32) {
3254 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3255 bitcastf32Toi32(LHS, DAG), Mask);
3256 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3257 bitcastf32Toi32(RHS, DAG), Mask);
3258 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3259 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3260 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3261 Chain, Dest, ARMcc, CCR, Cmp);
3266 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3267 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3268 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3269 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3270 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3271 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3272 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3273 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3274 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3280 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3281 SDValue Chain = Op.getOperand(0);
3282 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3283 SDValue LHS = Op.getOperand(2);
3284 SDValue RHS = Op.getOperand(3);
3285 SDValue Dest = Op.getOperand(4);
3288 if (LHS.getValueType() == MVT::i32) {
3290 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3291 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3292 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3293 Chain, Dest, ARMcc, CCR, Cmp);
3296 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3298 if (getTargetMachine().Options.UnsafeFPMath &&
3299 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3300 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3301 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3302 if (Result.getNode())
3306 ARMCC::CondCodes CondCode, CondCode2;
3307 FPCCToARMCC(CC, CondCode, CondCode2);
3309 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3310 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3311 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3312 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3313 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3314 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3315 if (CondCode2 != ARMCC::AL) {
3316 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3317 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3318 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3323 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3324 SDValue Chain = Op.getOperand(0);
3325 SDValue Table = Op.getOperand(1);
3326 SDValue Index = Op.getOperand(2);
3329 EVT PTy = getPointerTy();
3330 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3331 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3332 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3333 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3334 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3335 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3336 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3337 if (Subtarget->isThumb2()) {
3338 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3339 // which does another jump to the destination. This also makes it easier
3340 // to translate it to TBB / TBH later.
3341 // FIXME: This might not work if the function is extremely large.
3342 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3343 Addr, Op.getOperand(2), JTI, UId);
3345 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3346 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3347 MachinePointerInfo::getJumpTable(),
3348 false, false, false, 0);
3349 Chain = Addr.getValue(1);
3350 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3351 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3353 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3354 MachinePointerInfo::getJumpTable(),
3355 false, false, false, 0);
3356 Chain = Addr.getValue(1);
3357 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3361 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3362 EVT VT = Op.getValueType();
3365 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3366 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3368 return DAG.UnrollVectorOp(Op.getNode());
3371 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3372 "Invalid type for custom lowering!");
3373 if (VT != MVT::v4i16)
3374 return DAG.UnrollVectorOp(Op.getNode());
3376 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3377 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3380 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3381 EVT VT = Op.getValueType();
3383 return LowerVectorFP_TO_INT(Op, DAG);
3388 switch (Op.getOpcode()) {
3389 default: llvm_unreachable("Invalid opcode!");
3390 case ISD::FP_TO_SINT:
3391 Opc = ARMISD::FTOSI;
3393 case ISD::FP_TO_UINT:
3394 Opc = ARMISD::FTOUI;
3397 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3398 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3401 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3402 EVT VT = Op.getValueType();
3405 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3406 if (VT.getVectorElementType() == MVT::f32)
3408 return DAG.UnrollVectorOp(Op.getNode());
3411 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3412 "Invalid type for custom lowering!");
3413 if (VT != MVT::v4f32)
3414 return DAG.UnrollVectorOp(Op.getNode());
3418 switch (Op.getOpcode()) {
3419 default: llvm_unreachable("Invalid opcode!");
3420 case ISD::SINT_TO_FP:
3421 CastOpc = ISD::SIGN_EXTEND;
3422 Opc = ISD::SINT_TO_FP;
3424 case ISD::UINT_TO_FP:
3425 CastOpc = ISD::ZERO_EXTEND;
3426 Opc = ISD::UINT_TO_FP;
3430 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3431 return DAG.getNode(Opc, dl, VT, Op);
3434 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3435 EVT VT = Op.getValueType();
3437 return LowerVectorINT_TO_FP(Op, DAG);
3442 switch (Op.getOpcode()) {
3443 default: llvm_unreachable("Invalid opcode!");
3444 case ISD::SINT_TO_FP:
3445 Opc = ARMISD::SITOF;
3447 case ISD::UINT_TO_FP:
3448 Opc = ARMISD::UITOF;
3452 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3453 return DAG.getNode(Opc, dl, VT, Op);
3456 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3457 // Implement fcopysign with a fabs and a conditional fneg.
3458 SDValue Tmp0 = Op.getOperand(0);
3459 SDValue Tmp1 = Op.getOperand(1);
3461 EVT VT = Op.getValueType();
3462 EVT SrcVT = Tmp1.getValueType();
3463 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3464 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3465 bool UseNEON = !InGPR && Subtarget->hasNEON();
3468 // Use VBSL to copy the sign bit.
3469 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3470 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3471 DAG.getTargetConstant(EncodedVal, MVT::i32));
3472 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3474 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3475 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3476 DAG.getConstant(32, MVT::i32));
3477 else /*if (VT == MVT::f32)*/
3478 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3479 if (SrcVT == MVT::f32) {
3480 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3482 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3483 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3484 DAG.getConstant(32, MVT::i32));
3485 } else if (VT == MVT::f32)
3486 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3487 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3488 DAG.getConstant(32, MVT::i32));
3489 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3490 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3492 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3494 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3495 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3496 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3498 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3499 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3500 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3501 if (VT == MVT::f32) {
3502 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3503 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3504 DAG.getConstant(0, MVT::i32));
3506 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3512 // Bitcast operand 1 to i32.
3513 if (SrcVT == MVT::f64)
3514 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3515 &Tmp1, 1).getValue(1);
3516 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3518 // Or in the signbit with integer operations.
3519 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3520 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3521 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3522 if (VT == MVT::f32) {
3523 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3524 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3525 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3526 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3529 // f64: Or the high part with signbit and then combine two parts.
3530 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3532 SDValue Lo = Tmp0.getValue(0);
3533 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3534 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3535 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3538 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3539 MachineFunction &MF = DAG.getMachineFunction();
3540 MachineFrameInfo *MFI = MF.getFrameInfo();
3541 MFI->setReturnAddressIsTaken(true);
3543 EVT VT = Op.getValueType();
3545 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3547 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3548 SDValue Offset = DAG.getConstant(4, MVT::i32);
3549 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3550 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3551 MachinePointerInfo(), false, false, false, 0);
3554 // Return LR, which contains the return address. Mark it an implicit live-in.
3555 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3556 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3559 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3560 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3561 MFI->setFrameAddressIsTaken(true);
3563 EVT VT = Op.getValueType();
3564 SDLoc dl(Op); // FIXME probably not meaningful
3565 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3566 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3567 ? ARM::R7 : ARM::R11;
3568 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3570 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3571 MachinePointerInfo(),
3572 false, false, false, 0);
3576 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3577 /// and size(DestVec) > 128-bits.
3578 /// This is achieved by doing the one extension from the SrcVec, splitting the
3579 /// result, extending these parts, and then concatenating these into the
3581 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3582 SDValue Op = N->getOperand(0);
3583 EVT SrcVT = Op.getValueType();
3584 EVT DestVT = N->getValueType(0);
3586 assert(DestVT.getSizeInBits() > 128 &&
3587 "Custom sext/zext expansion needs >128-bit vector.");
3588 // If this is a normal length extension, use the default expansion.
3589 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3590 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3594 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3595 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3596 unsigned NumElts = SrcVT.getVectorNumElements();
3597 LLVMContext &Ctx = *DAG.getContext();
3598 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3600 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3602 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3604 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3607 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3608 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3609 DAG.getIntPtrConstant(0));
3610 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3611 DAG.getIntPtrConstant(NumElts/2));
3612 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3613 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3614 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3617 /// ExpandBITCAST - If the target supports VFP, this function is called to
3618 /// expand a bit convert where either the source or destination type is i64 to
3619 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3620 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3621 /// vectors), since the legalizer won't know what to do with that.
3622 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3623 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3625 SDValue Op = N->getOperand(0);
3627 // This function is only supposed to be called for i64 types, either as the
3628 // source or destination of the bit convert.
3629 EVT SrcVT = Op.getValueType();
3630 EVT DstVT = N->getValueType(0);
3631 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3632 "ExpandBITCAST called for non-i64 type");
3634 // Turn i64->f64 into VMOVDRR.
3635 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3636 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3637 DAG.getConstant(0, MVT::i32));
3638 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3639 DAG.getConstant(1, MVT::i32));
3640 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3641 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3644 // Turn f64->i64 into VMOVRRD.
3645 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3646 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3647 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3648 // Merge the pieces into a single i64 value.
3649 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3655 /// getZeroVector - Returns a vector of specified type with all zero elements.
3656 /// Zero vectors are used to represent vector negation and in those cases
3657 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3658 /// not support i64 elements, so sometimes the zero vectors will need to be
3659 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3661 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3662 assert(VT.isVector() && "Expected a vector type");
3663 // The canonical modified immediate encoding of a zero vector is....0!
3664 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3665 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3666 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3667 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3670 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3671 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3672 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3673 SelectionDAG &DAG) const {
3674 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3675 EVT VT = Op.getValueType();
3676 unsigned VTBits = VT.getSizeInBits();
3678 SDValue ShOpLo = Op.getOperand(0);
3679 SDValue ShOpHi = Op.getOperand(1);
3680 SDValue ShAmt = Op.getOperand(2);
3682 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3684 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3686 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3687 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3688 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3689 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3690 DAG.getConstant(VTBits, MVT::i32));
3691 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3692 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3693 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3695 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3696 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3698 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3699 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3702 SDValue Ops[2] = { Lo, Hi };
3703 return DAG.getMergeValues(Ops, 2, dl);
3706 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3707 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3708 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3709 SelectionDAG &DAG) const {
3710 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3711 EVT VT = Op.getValueType();
3712 unsigned VTBits = VT.getSizeInBits();
3714 SDValue ShOpLo = Op.getOperand(0);
3715 SDValue ShOpHi = Op.getOperand(1);
3716 SDValue ShAmt = Op.getOperand(2);
3719 assert(Op.getOpcode() == ISD::SHL_PARTS);
3720 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3721 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3722 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3723 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3724 DAG.getConstant(VTBits, MVT::i32));
3725 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3726 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3728 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3729 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3730 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3732 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3733 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3736 SDValue Ops[2] = { Lo, Hi };
3737 return DAG.getMergeValues(Ops, 2, dl);
3740 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3741 SelectionDAG &DAG) const {
3742 // The rounding mode is in bits 23:22 of the FPSCR.
3743 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3744 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3745 // so that the shift + and get folded into a bitfield extract.
3747 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3748 DAG.getConstant(Intrinsic::arm_get_fpscr,
3750 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3751 DAG.getConstant(1U << 22, MVT::i32));
3752 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3753 DAG.getConstant(22, MVT::i32));
3754 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3755 DAG.getConstant(3, MVT::i32));
3758 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3759 const ARMSubtarget *ST) {
3760 EVT VT = N->getValueType(0);
3763 if (!ST->hasV6T2Ops())
3766 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3767 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3770 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3771 /// for each 16-bit element from operand, repeated. The basic idea is to
3772 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3774 /// Trace for v4i16:
3775 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3776 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3777 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3778 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3779 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3780 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3781 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3782 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3783 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3784 EVT VT = N->getValueType(0);
3787 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3788 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3789 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3790 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3791 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3792 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3795 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3796 /// bit-count for each 16-bit element from the operand. We need slightly
3797 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3798 /// 64/128-bit registers.
3800 /// Trace for v4i16:
3801 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3802 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3803 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3804 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3805 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3806 EVT VT = N->getValueType(0);
3809 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3810 if (VT.is64BitVector()) {
3811 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3812 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3813 DAG.getIntPtrConstant(0));
3815 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3816 BitCounts, DAG.getIntPtrConstant(0));
3817 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3821 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3822 /// bit-count for each 32-bit element from the operand. The idea here is
3823 /// to split the vector into 16-bit elements, leverage the 16-bit count
3824 /// routine, and then combine the results.
3826 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3827 /// input = [v0 v1 ] (vi: 32-bit elements)
3828 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3829 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3830 /// vrev: N0 = [k1 k0 k3 k2 ]
3832 /// N1 =+[k1 k0 k3 k2 ]
3834 /// N2 =+[k1 k3 k0 k2 ]
3836 /// Extended =+[k1 k3 k0 k2 ]
3838 /// Extracted=+[k1 k3 ]
3840 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3841 EVT VT = N->getValueType(0);
3844 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3846 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3847 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3848 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3849 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3850 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3852 if (VT.is64BitVector()) {
3853 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3854 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3855 DAG.getIntPtrConstant(0));
3857 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3858 DAG.getIntPtrConstant(0));
3859 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3863 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3864 const ARMSubtarget *ST) {
3865 EVT VT = N->getValueType(0);
3867 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3868 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3869 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3870 "Unexpected type for custom ctpop lowering");
3872 if (VT.getVectorElementType() == MVT::i32)
3873 return lowerCTPOP32BitElements(N, DAG);
3875 return lowerCTPOP16BitElements(N, DAG);
3878 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3879 const ARMSubtarget *ST) {
3880 EVT VT = N->getValueType(0);
3886 // Lower vector shifts on NEON to use VSHL.
3887 assert(ST->hasNEON() && "unexpected vector shift");
3889 // Left shifts translate directly to the vshiftu intrinsic.
3890 if (N->getOpcode() == ISD::SHL)
3891 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3892 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3893 N->getOperand(0), N->getOperand(1));
3895 assert((N->getOpcode() == ISD::SRA ||
3896 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3898 // NEON uses the same intrinsics for both left and right shifts. For
3899 // right shifts, the shift amounts are negative, so negate the vector of
3901 EVT ShiftVT = N->getOperand(1).getValueType();
3902 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3903 getZeroVector(ShiftVT, DAG, dl),
3905 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3906 Intrinsic::arm_neon_vshifts :
3907 Intrinsic::arm_neon_vshiftu);
3908 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3909 DAG.getConstant(vshiftInt, MVT::i32),
3910 N->getOperand(0), NegatedCount);
3913 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3914 const ARMSubtarget *ST) {
3915 EVT VT = N->getValueType(0);
3918 // We can get here for a node like i32 = ISD::SHL i32, i64
3922 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3923 "Unknown shift to lower!");
3925 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3926 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3927 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3930 // If we are in thumb mode, we don't have RRX.
3931 if (ST->isThumb1Only()) return SDValue();
3933 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3934 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3935 DAG.getConstant(0, MVT::i32));
3936 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3937 DAG.getConstant(1, MVT::i32));
3939 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3940 // captures the result into a carry flag.
3941 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3942 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3944 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3945 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3947 // Merge the pieces into a single i64 value.
3948 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3951 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3952 SDValue TmpOp0, TmpOp1;
3953 bool Invert = false;
3957 SDValue Op0 = Op.getOperand(0);
3958 SDValue Op1 = Op.getOperand(1);
3959 SDValue CC = Op.getOperand(2);
3960 EVT VT = Op.getValueType();
3961 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3964 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3965 switch (SetCCOpcode) {
3966 default: llvm_unreachable("Illegal FP comparison");
3968 case ISD::SETNE: Invert = true; // Fallthrough
3970 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3972 case ISD::SETLT: Swap = true; // Fallthrough
3974 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3976 case ISD::SETLE: Swap = true; // Fallthrough
3978 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3979 case ISD::SETUGE: Swap = true; // Fallthrough
3980 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3981 case ISD::SETUGT: Swap = true; // Fallthrough
3982 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3983 case ISD::SETUEQ: Invert = true; // Fallthrough
3985 // Expand this to (OLT | OGT).
3989 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3990 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3992 case ISD::SETUO: Invert = true; // Fallthrough
3994 // Expand this to (OLT | OGE).
3998 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3999 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4003 // Integer comparisons.
4004 switch (SetCCOpcode) {
4005 default: llvm_unreachable("Illegal integer comparison");
4006 case ISD::SETNE: Invert = true;
4007 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4008 case ISD::SETLT: Swap = true;
4009 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4010 case ISD::SETLE: Swap = true;
4011 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4012 case ISD::SETULT: Swap = true;
4013 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4014 case ISD::SETULE: Swap = true;
4015 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4018 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4019 if (Opc == ARMISD::VCEQ) {
4022 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4024 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4027 // Ignore bitconvert.
4028 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4029 AndOp = AndOp.getOperand(0);
4031 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4033 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4034 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4041 std::swap(Op0, Op1);
4043 // If one of the operands is a constant vector zero, attempt to fold the
4044 // comparison to a specialized compare-against-zero form.
4046 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4048 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4049 if (Opc == ARMISD::VCGE)
4050 Opc = ARMISD::VCLEZ;
4051 else if (Opc == ARMISD::VCGT)
4052 Opc = ARMISD::VCLTZ;
4057 if (SingleOp.getNode()) {
4060 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4062 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4064 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4066 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4068 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4070 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4073 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4077 Result = DAG.getNOT(dl, Result, VT);
4082 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4083 /// valid vector constant for a NEON instruction with a "modified immediate"
4084 /// operand (e.g., VMOV). If so, return the encoded value.
4085 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4086 unsigned SplatBitSize, SelectionDAG &DAG,
4087 EVT &VT, bool is128Bits, NEONModImmType type) {
4088 unsigned OpCmode, Imm;
4090 // SplatBitSize is set to the smallest size that splats the vector, so a
4091 // zero vector will always have SplatBitSize == 8. However, NEON modified
4092 // immediate instructions others than VMOV do not support the 8-bit encoding
4093 // of a zero vector, and the default encoding of zero is supposed to be the
4098 switch (SplatBitSize) {
4100 if (type != VMOVModImm)
4102 // Any 1-byte value is OK. Op=0, Cmode=1110.
4103 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4106 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4110 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4111 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4112 if ((SplatBits & ~0xff) == 0) {
4113 // Value = 0x00nn: Op=x, Cmode=100x.
4118 if ((SplatBits & ~0xff00) == 0) {
4119 // Value = 0xnn00: Op=x, Cmode=101x.
4121 Imm = SplatBits >> 8;
4127 // NEON's 32-bit VMOV supports splat values where:
4128 // * only one byte is nonzero, or
4129 // * the least significant byte is 0xff and the second byte is nonzero, or
4130 // * the least significant 2 bytes are 0xff and the third is nonzero.
4131 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4132 if ((SplatBits & ~0xff) == 0) {
4133 // Value = 0x000000nn: Op=x, Cmode=000x.
4138 if ((SplatBits & ~0xff00) == 0) {
4139 // Value = 0x0000nn00: Op=x, Cmode=001x.
4141 Imm = SplatBits >> 8;
4144 if ((SplatBits & ~0xff0000) == 0) {
4145 // Value = 0x00nn0000: Op=x, Cmode=010x.
4147 Imm = SplatBits >> 16;
4150 if ((SplatBits & ~0xff000000) == 0) {
4151 // Value = 0xnn000000: Op=x, Cmode=011x.
4153 Imm = SplatBits >> 24;
4157 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4158 if (type == OtherModImm) return SDValue();
4160 if ((SplatBits & ~0xffff) == 0 &&
4161 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4162 // Value = 0x0000nnff: Op=x, Cmode=1100.
4164 Imm = SplatBits >> 8;
4169 if ((SplatBits & ~0xffffff) == 0 &&
4170 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4171 // Value = 0x00nnffff: Op=x, Cmode=1101.
4173 Imm = SplatBits >> 16;
4174 SplatBits |= 0xffff;
4178 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4179 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4180 // VMOV.I32. A (very) minor optimization would be to replicate the value
4181 // and fall through here to test for a valid 64-bit splat. But, then the
4182 // caller would also need to check and handle the change in size.
4186 if (type != VMOVModImm)
4188 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4189 uint64_t BitMask = 0xff;
4191 unsigned ImmMask = 1;
4193 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4194 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4197 } else if ((SplatBits & BitMask) != 0) {
4203 // Op=1, Cmode=1110.
4206 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4211 llvm_unreachable("unexpected size for isNEONModifiedImm");
4214 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4215 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4218 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4219 const ARMSubtarget *ST) const {
4220 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4223 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4224 assert(Op.getValueType() == MVT::f32 &&
4225 "ConstantFP custom lowering should only occur for f32.");
4227 // Try splatting with a VMOV.f32...
4228 APFloat FPVal = CFP->getValueAPF();
4229 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4232 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4233 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4235 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4236 DAG.getConstant(0, MVT::i32));
4239 // If that fails, try a VMOV.i32
4241 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4242 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4244 if (NewVal != SDValue()) {
4246 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4248 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4250 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4251 DAG.getConstant(0, MVT::i32));
4254 // Finally, try a VMVN.i32
4255 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4257 if (NewVal != SDValue()) {
4259 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4260 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4262 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4263 DAG.getConstant(0, MVT::i32));
4269 // check if an VEXT instruction can handle the shuffle mask when the
4270 // vector sources of the shuffle are the same.
4271 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4272 unsigned NumElts = VT.getVectorNumElements();
4274 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4280 // If this is a VEXT shuffle, the immediate value is the index of the first
4281 // element. The other shuffle indices must be the successive elements after
4283 unsigned ExpectedElt = Imm;
4284 for (unsigned i = 1; i < NumElts; ++i) {
4285 // Increment the expected index. If it wraps around, just follow it
4286 // back to index zero and keep going.
4288 if (ExpectedElt == NumElts)
4291 if (M[i] < 0) continue; // ignore UNDEF indices
4292 if (ExpectedElt != static_cast<unsigned>(M[i]))
4300 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4301 bool &ReverseVEXT, unsigned &Imm) {
4302 unsigned NumElts = VT.getVectorNumElements();
4303 ReverseVEXT = false;
4305 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4311 // If this is a VEXT shuffle, the immediate value is the index of the first
4312 // element. The other shuffle indices must be the successive elements after
4314 unsigned ExpectedElt = Imm;
4315 for (unsigned i = 1; i < NumElts; ++i) {
4316 // Increment the expected index. If it wraps around, it may still be
4317 // a VEXT but the source vectors must be swapped.
4319 if (ExpectedElt == NumElts * 2) {
4324 if (M[i] < 0) continue; // ignore UNDEF indices
4325 if (ExpectedElt != static_cast<unsigned>(M[i]))
4329 // Adjust the index value if the source operands will be swapped.
4336 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4337 /// instruction with the specified blocksize. (The order of the elements
4338 /// within each block of the vector is reversed.)
4339 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4340 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4341 "Only possible block sizes for VREV are: 16, 32, 64");
4343 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4347 unsigned NumElts = VT.getVectorNumElements();
4348 unsigned BlockElts = M[0] + 1;
4349 // If the first shuffle index is UNDEF, be optimistic.
4351 BlockElts = BlockSize / EltSz;
4353 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4356 for (unsigned i = 0; i < NumElts; ++i) {
4357 if (M[i] < 0) continue; // ignore UNDEF indices
4358 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4365 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4366 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4367 // range, then 0 is placed into the resulting vector. So pretty much any mask
4368 // of 8 elements can work here.
4369 return VT == MVT::v8i8 && M.size() == 8;
4372 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4373 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4377 unsigned NumElts = VT.getVectorNumElements();
4378 WhichResult = (M[0] == 0 ? 0 : 1);
4379 for (unsigned i = 0; i < NumElts; i += 2) {
4380 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4381 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4387 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4388 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4389 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4390 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4391 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4395 unsigned NumElts = VT.getVectorNumElements();
4396 WhichResult = (M[0] == 0 ? 0 : 1);
4397 for (unsigned i = 0; i < NumElts; i += 2) {
4398 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4399 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4405 static bool isVUZPMask(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) {
4413 if (M[i] < 0) continue; // ignore UNDEF indices
4414 if ((unsigned) M[i] != 2 * i + WhichResult)
4418 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4419 if (VT.is64BitVector() && EltSz == 32)
4425 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4426 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4427 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4428 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4429 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4433 unsigned Half = VT.getVectorNumElements() / 2;
4434 WhichResult = (M[0] == 0 ? 0 : 1);
4435 for (unsigned j = 0; j != 2; ++j) {
4436 unsigned Idx = WhichResult;
4437 for (unsigned i = 0; i != Half; ++i) {
4438 int MIdx = M[i + j * Half];
4439 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4445 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4446 if (VT.is64BitVector() && EltSz == 32)
4452 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4453 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4457 unsigned NumElts = VT.getVectorNumElements();
4458 WhichResult = (M[0] == 0 ? 0 : 1);
4459 unsigned Idx = WhichResult * NumElts / 2;
4460 for (unsigned i = 0; i != NumElts; i += 2) {
4461 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4462 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4467 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4468 if (VT.is64BitVector() && EltSz == 32)
4474 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4475 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4476 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4477 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4478 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4482 unsigned NumElts = VT.getVectorNumElements();
4483 WhichResult = (M[0] == 0 ? 0 : 1);
4484 unsigned Idx = WhichResult * NumElts / 2;
4485 for (unsigned i = 0; i != NumElts; i += 2) {
4486 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4487 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4492 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4493 if (VT.is64BitVector() && EltSz == 32)
4499 /// \return true if this is a reverse operation on an vector.
4500 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4501 unsigned NumElts = VT.getVectorNumElements();
4502 // Make sure the mask has the right size.
4503 if (NumElts != M.size())
4506 // Look for <15, ..., 3, -1, 1, 0>.
4507 for (unsigned i = 0; i != NumElts; ++i)
4508 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4514 // If N is an integer constant that can be moved into a register in one
4515 // instruction, return an SDValue of such a constant (will become a MOV
4516 // instruction). Otherwise return null.
4517 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4518 const ARMSubtarget *ST, SDLoc dl) {
4520 if (!isa<ConstantSDNode>(N))
4522 Val = cast<ConstantSDNode>(N)->getZExtValue();
4524 if (ST->isThumb1Only()) {
4525 if (Val <= 255 || ~Val <= 255)
4526 return DAG.getConstant(Val, MVT::i32);
4528 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4529 return DAG.getConstant(Val, MVT::i32);
4534 // If this is a case we can't handle, return null and let the default
4535 // expansion code take care of it.
4536 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4537 const ARMSubtarget *ST) const {
4538 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4540 EVT VT = Op.getValueType();
4542 APInt SplatBits, SplatUndef;
4543 unsigned SplatBitSize;
4545 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4546 if (SplatBitSize <= 64) {
4547 // Check if an immediate VMOV works.
4549 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4550 SplatUndef.getZExtValue(), SplatBitSize,
4551 DAG, VmovVT, VT.is128BitVector(),
4553 if (Val.getNode()) {
4554 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4555 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4558 // Try an immediate VMVN.
4559 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4560 Val = isNEONModifiedImm(NegatedImm,
4561 SplatUndef.getZExtValue(), SplatBitSize,
4562 DAG, VmovVT, VT.is128BitVector(),
4564 if (Val.getNode()) {
4565 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4566 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4569 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4570 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4571 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4573 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4574 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4580 // Scan through the operands to see if only one value is used.
4582 // As an optimisation, even if more than one value is used it may be more
4583 // profitable to splat with one value then change some lanes.
4585 // Heuristically we decide to do this if the vector has a "dominant" value,
4586 // defined as splatted to more than half of the lanes.
4587 unsigned NumElts = VT.getVectorNumElements();
4588 bool isOnlyLowElement = true;
4589 bool usesOnlyOneValue = true;
4590 bool hasDominantValue = false;
4591 bool isConstant = true;
4593 // Map of the number of times a particular SDValue appears in the
4595 DenseMap<SDValue, unsigned> ValueCounts;
4597 for (unsigned i = 0; i < NumElts; ++i) {
4598 SDValue V = Op.getOperand(i);
4599 if (V.getOpcode() == ISD::UNDEF)
4602 isOnlyLowElement = false;
4603 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4606 ValueCounts.insert(std::make_pair(V, 0));
4607 unsigned &Count = ValueCounts[V];
4609 // Is this value dominant? (takes up more than half of the lanes)
4610 if (++Count > (NumElts / 2)) {
4611 hasDominantValue = true;
4615 if (ValueCounts.size() != 1)
4616 usesOnlyOneValue = false;
4617 if (!Value.getNode() && ValueCounts.size() > 0)
4618 Value = ValueCounts.begin()->first;
4620 if (ValueCounts.size() == 0)
4621 return DAG.getUNDEF(VT);
4623 if (isOnlyLowElement)
4624 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4626 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4628 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4629 // i32 and try again.
4630 if (hasDominantValue && EltSize <= 32) {
4634 // If we are VDUPing a value that comes directly from a vector, that will
4635 // cause an unnecessary move to and from a GPR, where instead we could
4636 // just use VDUPLANE. We can only do this if the lane being extracted
4637 // is at a constant index, as the VDUP from lane instructions only have
4638 // constant-index forms.
4639 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4640 isa<ConstantSDNode>(Value->getOperand(1))) {
4641 // We need to create a new undef vector to use for the VDUPLANE if the
4642 // size of the vector from which we get the value is different than the
4643 // size of the vector that we need to create. We will insert the element
4644 // such that the register coalescer will remove unnecessary copies.
4645 if (VT != Value->getOperand(0).getValueType()) {
4646 ConstantSDNode *constIndex;
4647 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4648 assert(constIndex && "The index is not a constant!");
4649 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4650 VT.getVectorNumElements();
4651 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4652 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4653 Value, DAG.getConstant(index, MVT::i32)),
4654 DAG.getConstant(index, MVT::i32));
4656 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4657 Value->getOperand(0), Value->getOperand(1));
4659 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4661 if (!usesOnlyOneValue) {
4662 // The dominant value was splatted as 'N', but we now have to insert
4663 // all differing elements.
4664 for (unsigned I = 0; I < NumElts; ++I) {
4665 if (Op.getOperand(I) == Value)
4667 SmallVector<SDValue, 3> Ops;
4669 Ops.push_back(Op.getOperand(I));
4670 Ops.push_back(DAG.getConstant(I, MVT::i32));
4671 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4676 if (VT.getVectorElementType().isFloatingPoint()) {
4677 SmallVector<SDValue, 8> Ops;
4678 for (unsigned i = 0; i < NumElts; ++i)
4679 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4681 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4682 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4683 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4685 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4687 if (usesOnlyOneValue) {
4688 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4689 if (isConstant && Val.getNode())
4690 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4694 // If all elements are constants and the case above didn't get hit, fall back
4695 // to the default expansion, which will generate a load from the constant
4700 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4702 SDValue shuffle = ReconstructShuffle(Op, DAG);
4703 if (shuffle != SDValue())
4707 // Vectors with 32- or 64-bit elements can be built by directly assigning
4708 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4709 // will be legalized.
4710 if (EltSize >= 32) {
4711 // Do the expansion with floating-point types, since that is what the VFP
4712 // registers are defined to use, and since i64 is not legal.
4713 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4714 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4715 SmallVector<SDValue, 8> Ops;
4716 for (unsigned i = 0; i < NumElts; ++i)
4717 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4718 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4719 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4725 // Gather data to see if the operation can be modelled as a
4726 // shuffle in combination with VEXTs.
4727 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4728 SelectionDAG &DAG) const {
4730 EVT VT = Op.getValueType();
4731 unsigned NumElts = VT.getVectorNumElements();
4733 SmallVector<SDValue, 2> SourceVecs;
4734 SmallVector<unsigned, 2> MinElts;
4735 SmallVector<unsigned, 2> MaxElts;
4737 for (unsigned i = 0; i < NumElts; ++i) {
4738 SDValue V = Op.getOperand(i);
4739 if (V.getOpcode() == ISD::UNDEF)
4741 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4742 // A shuffle can only come from building a vector from various
4743 // elements of other vectors.
4745 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4746 VT.getVectorElementType()) {
4747 // This code doesn't know how to handle shuffles where the vector
4748 // element types do not match (this happens because type legalization
4749 // promotes the return type of EXTRACT_VECTOR_ELT).
4750 // FIXME: It might be appropriate to extend this code to handle
4751 // mismatched types.
4755 // Record this extraction against the appropriate vector if possible...
4756 SDValue SourceVec = V.getOperand(0);
4757 // If the element number isn't a constant, we can't effectively
4758 // analyze what's going on.
4759 if (!isa<ConstantSDNode>(V.getOperand(1)))
4761 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4762 bool FoundSource = false;
4763 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4764 if (SourceVecs[j] == SourceVec) {
4765 if (MinElts[j] > EltNo)
4767 if (MaxElts[j] < EltNo)
4774 // Or record a new source if not...
4776 SourceVecs.push_back(SourceVec);
4777 MinElts.push_back(EltNo);
4778 MaxElts.push_back(EltNo);
4782 // Currently only do something sane when at most two source vectors
4784 if (SourceVecs.size() > 2)
4787 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4788 int VEXTOffsets[2] = {0, 0};
4790 // This loop extracts the usage patterns of the source vectors
4791 // and prepares appropriate SDValues for a shuffle if possible.
4792 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4793 if (SourceVecs[i].getValueType() == VT) {
4794 // No VEXT necessary
4795 ShuffleSrcs[i] = SourceVecs[i];
4798 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4799 // It probably isn't worth padding out a smaller vector just to
4800 // break it down again in a shuffle.
4804 // Since only 64-bit and 128-bit vectors are legal on ARM and
4805 // we've eliminated the other cases...
4806 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4807 "unexpected vector sizes in ReconstructShuffle");
4809 if (MaxElts[i] - MinElts[i] >= NumElts) {
4810 // Span too large for a VEXT to cope
4814 if (MinElts[i] >= NumElts) {
4815 // The extraction can just take the second half
4816 VEXTOffsets[i] = NumElts;
4817 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4819 DAG.getIntPtrConstant(NumElts));
4820 } else if (MaxElts[i] < NumElts) {
4821 // The extraction can just take the first half
4823 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4825 DAG.getIntPtrConstant(0));
4827 // An actual VEXT is needed
4828 VEXTOffsets[i] = MinElts[i];
4829 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4831 DAG.getIntPtrConstant(0));
4832 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4834 DAG.getIntPtrConstant(NumElts));
4835 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4836 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4840 SmallVector<int, 8> Mask;
4842 for (unsigned i = 0; i < NumElts; ++i) {
4843 SDValue Entry = Op.getOperand(i);
4844 if (Entry.getOpcode() == ISD::UNDEF) {
4849 SDValue ExtractVec = Entry.getOperand(0);
4850 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4851 .getOperand(1))->getSExtValue();
4852 if (ExtractVec == SourceVecs[0]) {
4853 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4855 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4859 // Final check before we try to produce nonsense...
4860 if (isShuffleMaskLegal(Mask, VT))
4861 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4867 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4868 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4869 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4870 /// are assumed to be legal.
4872 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4874 if (VT.getVectorNumElements() == 4 &&
4875 (VT.is128BitVector() || VT.is64BitVector())) {
4876 unsigned PFIndexes[4];
4877 for (unsigned i = 0; i != 4; ++i) {
4881 PFIndexes[i] = M[i];
4884 // Compute the index in the perfect shuffle table.
4885 unsigned PFTableIndex =
4886 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4887 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4888 unsigned Cost = (PFEntry >> 30);
4895 unsigned Imm, WhichResult;
4897 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4898 return (EltSize >= 32 ||
4899 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4900 isVREVMask(M, VT, 64) ||
4901 isVREVMask(M, VT, 32) ||
4902 isVREVMask(M, VT, 16) ||
4903 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4904 isVTBLMask(M, VT) ||
4905 isVTRNMask(M, VT, WhichResult) ||
4906 isVUZPMask(M, VT, WhichResult) ||
4907 isVZIPMask(M, VT, WhichResult) ||
4908 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4909 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4910 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4911 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4914 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4915 /// the specified operations to build the shuffle.
4916 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4917 SDValue RHS, SelectionDAG &DAG,
4919 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4920 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4921 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4924 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4933 OP_VUZPL, // VUZP, left result
4934 OP_VUZPR, // VUZP, right result
4935 OP_VZIPL, // VZIP, left result
4936 OP_VZIPR, // VZIP, right result
4937 OP_VTRNL, // VTRN, left result
4938 OP_VTRNR // VTRN, right result
4941 if (OpNum == OP_COPY) {
4942 if (LHSID == (1*9+2)*9+3) return LHS;
4943 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4947 SDValue OpLHS, OpRHS;
4948 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4949 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4950 EVT VT = OpLHS.getValueType();
4953 default: llvm_unreachable("Unknown shuffle opcode!");
4955 // VREV divides the vector in half and swaps within the half.
4956 if (VT.getVectorElementType() == MVT::i32 ||
4957 VT.getVectorElementType() == MVT::f32)
4958 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4959 // vrev <4 x i16> -> VREV32
4960 if (VT.getVectorElementType() == MVT::i16)
4961 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4962 // vrev <4 x i8> -> VREV16
4963 assert(VT.getVectorElementType() == MVT::i8);
4964 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4969 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4970 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4974 return DAG.getNode(ARMISD::VEXT, dl, VT,
4976 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4979 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4980 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4983 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4984 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4987 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4988 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4992 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4993 ArrayRef<int> ShuffleMask,
4994 SelectionDAG &DAG) {
4995 // Check to see if we can use the VTBL instruction.
4996 SDValue V1 = Op.getOperand(0);
4997 SDValue V2 = Op.getOperand(1);
5000 SmallVector<SDValue, 8> VTBLMask;
5001 for (ArrayRef<int>::iterator
5002 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5003 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5005 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5006 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5007 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5010 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5011 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5015 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5016 SelectionDAG &DAG) {
5018 SDValue OpLHS = Op.getOperand(0);
5019 EVT VT = OpLHS.getValueType();
5021 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5022 "Expect an v8i16/v16i8 type");
5023 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5024 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5025 // extract the first 8 bytes into the top double word and the last 8 bytes
5026 // into the bottom double word. The v8i16 case is similar.
5027 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5028 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5029 DAG.getConstant(ExtractNum, MVT::i32));
5032 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5033 SDValue V1 = Op.getOperand(0);
5034 SDValue V2 = Op.getOperand(1);
5036 EVT VT = Op.getValueType();
5037 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5039 // Convert shuffles that are directly supported on NEON to target-specific
5040 // DAG nodes, instead of keeping them as shuffles and matching them again
5041 // during code selection. This is more efficient and avoids the possibility
5042 // of inconsistencies between legalization and selection.
5043 // FIXME: floating-point vectors should be canonicalized to integer vectors
5044 // of the same time so that they get CSEd properly.
5045 ArrayRef<int> ShuffleMask = SVN->getMask();
5047 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5048 if (EltSize <= 32) {
5049 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5050 int Lane = SVN->getSplatIndex();
5051 // If this is undef splat, generate it via "just" vdup, if possible.
5052 if (Lane == -1) Lane = 0;
5054 // Test if V1 is a SCALAR_TO_VECTOR.
5055 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5056 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5058 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5059 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5061 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5062 !isa<ConstantSDNode>(V1.getOperand(0))) {
5063 bool IsScalarToVector = true;
5064 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5065 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5066 IsScalarToVector = false;
5069 if (IsScalarToVector)
5070 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5072 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5073 DAG.getConstant(Lane, MVT::i32));
5078 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5081 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5082 DAG.getConstant(Imm, MVT::i32));
5085 if (isVREVMask(ShuffleMask, VT, 64))
5086 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5087 if (isVREVMask(ShuffleMask, VT, 32))
5088 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5089 if (isVREVMask(ShuffleMask, VT, 16))
5090 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5092 if (V2->getOpcode() == ISD::UNDEF &&
5093 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5094 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5095 DAG.getConstant(Imm, MVT::i32));
5098 // Check for Neon shuffles that modify both input vectors in place.
5099 // If both results are used, i.e., if there are two shuffles with the same
5100 // source operands and with masks corresponding to both results of one of
5101 // these operations, DAG memoization will ensure that a single node is
5102 // used for both shuffles.
5103 unsigned WhichResult;
5104 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5105 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5106 V1, V2).getValue(WhichResult);
5107 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5108 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5109 V1, V2).getValue(WhichResult);
5110 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5111 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5112 V1, V2).getValue(WhichResult);
5114 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5115 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5116 V1, V1).getValue(WhichResult);
5117 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5118 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5119 V1, V1).getValue(WhichResult);
5120 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5121 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5122 V1, V1).getValue(WhichResult);
5125 // If the shuffle is not directly supported and it has 4 elements, use
5126 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5127 unsigned NumElts = VT.getVectorNumElements();
5129 unsigned PFIndexes[4];
5130 for (unsigned i = 0; i != 4; ++i) {
5131 if (ShuffleMask[i] < 0)
5134 PFIndexes[i] = ShuffleMask[i];
5137 // Compute the index in the perfect shuffle table.
5138 unsigned PFTableIndex =
5139 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5140 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5141 unsigned Cost = (PFEntry >> 30);
5144 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5147 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5148 if (EltSize >= 32) {
5149 // Do the expansion with floating-point types, since that is what the VFP
5150 // registers are defined to use, and since i64 is not legal.
5151 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5152 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5153 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5154 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5155 SmallVector<SDValue, 8> Ops;
5156 for (unsigned i = 0; i < NumElts; ++i) {
5157 if (ShuffleMask[i] < 0)
5158 Ops.push_back(DAG.getUNDEF(EltVT));
5160 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5161 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5162 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5165 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5166 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5169 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5170 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5172 if (VT == MVT::v8i8) {
5173 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5174 if (NewOp.getNode())
5181 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5182 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5183 SDValue Lane = Op.getOperand(2);
5184 if (!isa<ConstantSDNode>(Lane))
5190 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5191 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5192 SDValue Lane = Op.getOperand(1);
5193 if (!isa<ConstantSDNode>(Lane))
5196 SDValue Vec = Op.getOperand(0);
5197 if (Op.getValueType() == MVT::i32 &&
5198 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5200 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5206 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5207 // The only time a CONCAT_VECTORS operation can have legal types is when
5208 // two 64-bit vectors are concatenated to a 128-bit vector.
5209 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5210 "unexpected CONCAT_VECTORS");
5212 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5213 SDValue Op0 = Op.getOperand(0);
5214 SDValue Op1 = Op.getOperand(1);
5215 if (Op0.getOpcode() != ISD::UNDEF)
5216 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5217 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5218 DAG.getIntPtrConstant(0));
5219 if (Op1.getOpcode() != ISD::UNDEF)
5220 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5221 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5222 DAG.getIntPtrConstant(1));
5223 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5226 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5227 /// element has been zero/sign-extended, depending on the isSigned parameter,
5228 /// from an integer type half its size.
5229 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5231 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5232 EVT VT = N->getValueType(0);
5233 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5234 SDNode *BVN = N->getOperand(0).getNode();
5235 if (BVN->getValueType(0) != MVT::v4i32 ||
5236 BVN->getOpcode() != ISD::BUILD_VECTOR)
5238 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5239 unsigned HiElt = 1 - LoElt;
5240 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5241 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5242 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5243 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5244 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5247 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5248 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5251 if (Hi0->isNullValue() && Hi1->isNullValue())
5257 if (N->getOpcode() != ISD::BUILD_VECTOR)
5260 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5261 SDNode *Elt = N->getOperand(i).getNode();
5262 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5263 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5264 unsigned HalfSize = EltSize / 2;
5266 if (!isIntN(HalfSize, C->getSExtValue()))
5269 if (!isUIntN(HalfSize, C->getZExtValue()))
5280 /// isSignExtended - Check if a node is a vector value that is sign-extended
5281 /// or a constant BUILD_VECTOR with sign-extended elements.
5282 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5283 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5285 if (isExtendedBUILD_VECTOR(N, DAG, true))
5290 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5291 /// or a constant BUILD_VECTOR with zero-extended elements.
5292 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5293 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5295 if (isExtendedBUILD_VECTOR(N, DAG, false))
5300 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5301 if (OrigVT.getSizeInBits() >= 64)
5304 assert(OrigVT.isSimple() && "Expecting a simple value type");
5306 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5307 switch (OrigSimpleTy) {
5308 default: llvm_unreachable("Unexpected Vector Type");
5317 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5318 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5319 /// We insert the required extension here to get the vector to fill a D register.
5320 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5323 unsigned ExtOpcode) {
5324 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5325 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5326 // 64-bits we need to insert a new extension so that it will be 64-bits.
5327 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5328 if (OrigTy.getSizeInBits() >= 64)
5331 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5332 EVT NewVT = getExtensionTo64Bits(OrigTy);
5334 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5337 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5338 /// does not do any sign/zero extension. If the original vector is less
5339 /// than 64 bits, an appropriate extension will be added after the load to
5340 /// reach a total size of 64 bits. We have to add the extension separately
5341 /// because ARM does not have a sign/zero extending load for vectors.
5342 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5343 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5345 // The load already has the right type.
5346 if (ExtendedTy == LD->getMemoryVT())
5347 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5348 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5349 LD->isNonTemporal(), LD->isInvariant(),
5350 LD->getAlignment());
5352 // We need to create a zextload/sextload. We cannot just create a load
5353 // followed by a zext/zext node because LowerMUL is also run during normal
5354 // operation legalization where we can't create illegal types.
5355 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5356 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5357 LD->getMemoryVT(), LD->isVolatile(),
5358 LD->isNonTemporal(), LD->getAlignment());
5361 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5362 /// extending load, or BUILD_VECTOR with extended elements, return the
5363 /// unextended value. The unextended vector should be 64 bits so that it can
5364 /// be used as an operand to a VMULL instruction. If the original vector size
5365 /// before extension is less than 64 bits we add a an extension to resize
5366 /// the vector to 64 bits.
5367 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5368 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5369 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5370 N->getOperand(0)->getValueType(0),
5374 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5375 return SkipLoadExtensionForVMULL(LD, DAG);
5377 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5378 // have been legalized as a BITCAST from v4i32.
5379 if (N->getOpcode() == ISD::BITCAST) {
5380 SDNode *BVN = N->getOperand(0).getNode();
5381 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5382 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5383 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5384 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5385 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5387 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5388 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5389 EVT VT = N->getValueType(0);
5390 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5391 unsigned NumElts = VT.getVectorNumElements();
5392 MVT TruncVT = MVT::getIntegerVT(EltSize);
5393 SmallVector<SDValue, 8> Ops;
5394 for (unsigned i = 0; i != NumElts; ++i) {
5395 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5396 const APInt &CInt = C->getAPIntValue();
5397 // Element types smaller than 32 bits are not legal, so use i32 elements.
5398 // The values are implicitly truncated so sext vs. zext doesn't matter.
5399 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5401 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5402 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5405 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5406 unsigned Opcode = N->getOpcode();
5407 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5408 SDNode *N0 = N->getOperand(0).getNode();
5409 SDNode *N1 = N->getOperand(1).getNode();
5410 return N0->hasOneUse() && N1->hasOneUse() &&
5411 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5416 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5417 unsigned Opcode = N->getOpcode();
5418 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5419 SDNode *N0 = N->getOperand(0).getNode();
5420 SDNode *N1 = N->getOperand(1).getNode();
5421 return N0->hasOneUse() && N1->hasOneUse() &&
5422 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5427 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5428 // Multiplications are only custom-lowered for 128-bit vectors so that
5429 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5430 EVT VT = Op.getValueType();
5431 assert(VT.is128BitVector() && VT.isInteger() &&
5432 "unexpected type for custom-lowering ISD::MUL");
5433 SDNode *N0 = Op.getOperand(0).getNode();
5434 SDNode *N1 = Op.getOperand(1).getNode();
5435 unsigned NewOpc = 0;
5437 bool isN0SExt = isSignExtended(N0, DAG);
5438 bool isN1SExt = isSignExtended(N1, DAG);
5439 if (isN0SExt && isN1SExt)
5440 NewOpc = ARMISD::VMULLs;
5442 bool isN0ZExt = isZeroExtended(N0, DAG);
5443 bool isN1ZExt = isZeroExtended(N1, DAG);
5444 if (isN0ZExt && isN1ZExt)
5445 NewOpc = ARMISD::VMULLu;
5446 else if (isN1SExt || isN1ZExt) {
5447 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5448 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5449 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5450 NewOpc = ARMISD::VMULLs;
5452 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5453 NewOpc = ARMISD::VMULLu;
5455 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5457 NewOpc = ARMISD::VMULLu;
5463 if (VT == MVT::v2i64)
5464 // Fall through to expand this. It is not legal.
5467 // Other vector multiplications are legal.
5472 // Legalize to a VMULL instruction.
5475 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5477 Op0 = SkipExtensionForVMULL(N0, DAG);
5478 assert(Op0.getValueType().is64BitVector() &&
5479 Op1.getValueType().is64BitVector() &&
5480 "unexpected types for extended operands to VMULL");
5481 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5484 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5485 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5492 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5493 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5494 EVT Op1VT = Op1.getValueType();
5495 return DAG.getNode(N0->getOpcode(), DL, VT,
5496 DAG.getNode(NewOpc, DL, VT,
5497 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5498 DAG.getNode(NewOpc, DL, VT,
5499 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5503 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5505 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5506 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5507 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5508 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5509 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5510 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5511 // Get reciprocal estimate.
5512 // float4 recip = vrecpeq_f32(yf);
5513 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5514 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5515 // Because char has a smaller range than uchar, we can actually get away
5516 // without any newton steps. This requires that we use a weird bias
5517 // of 0xb000, however (again, this has been exhaustively tested).
5518 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5519 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5520 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5521 Y = DAG.getConstant(0xb000, MVT::i32);
5522 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5523 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5524 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5525 // Convert back to short.
5526 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5527 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5532 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5534 // Convert to float.
5535 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5536 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5537 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5538 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5539 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5540 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5542 // Use reciprocal estimate and one refinement step.
5543 // float4 recip = vrecpeq_f32(yf);
5544 // recip *= vrecpsq_f32(yf, recip);
5545 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5546 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5547 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5548 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5550 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5551 // Because short has a smaller range than ushort, we can actually get away
5552 // with only a single newton step. This requires that we use a weird bias
5553 // of 89, however (again, this has been exhaustively tested).
5554 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5555 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5556 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5557 N1 = DAG.getConstant(0x89, MVT::i32);
5558 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5559 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5560 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5561 // Convert back to integer and return.
5562 // return vmovn_s32(vcvt_s32_f32(result));
5563 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5564 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5568 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5569 EVT VT = Op.getValueType();
5570 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5571 "unexpected type for custom-lowering ISD::SDIV");
5574 SDValue N0 = Op.getOperand(0);
5575 SDValue N1 = Op.getOperand(1);
5578 if (VT == MVT::v8i8) {
5579 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5580 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5582 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5583 DAG.getIntPtrConstant(4));
5584 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5585 DAG.getIntPtrConstant(4));
5586 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5587 DAG.getIntPtrConstant(0));
5588 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5589 DAG.getIntPtrConstant(0));
5591 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5592 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5594 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5595 N0 = LowerCONCAT_VECTORS(N0, DAG);
5597 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5600 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5603 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5604 EVT VT = Op.getValueType();
5605 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5606 "unexpected type for custom-lowering ISD::UDIV");
5609 SDValue N0 = Op.getOperand(0);
5610 SDValue N1 = Op.getOperand(1);
5613 if (VT == MVT::v8i8) {
5614 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5615 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5617 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5618 DAG.getIntPtrConstant(4));
5619 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5620 DAG.getIntPtrConstant(4));
5621 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5622 DAG.getIntPtrConstant(0));
5623 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5624 DAG.getIntPtrConstant(0));
5626 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5627 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5629 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5630 N0 = LowerCONCAT_VECTORS(N0, DAG);
5632 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5633 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5638 // v4i16 sdiv ... Convert to float.
5639 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5640 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5641 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5642 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5643 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5644 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5646 // Use reciprocal estimate and two refinement steps.
5647 // float4 recip = vrecpeq_f32(yf);
5648 // recip *= vrecpsq_f32(yf, recip);
5649 // recip *= vrecpsq_f32(yf, recip);
5650 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5651 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5652 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5653 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5655 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5656 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5657 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5659 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5660 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5661 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5662 // and that it will never cause us to return an answer too large).
5663 // float4 result = as_float4(as_int4(xf*recip) + 2);
5664 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5665 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5666 N1 = DAG.getConstant(2, MVT::i32);
5667 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5668 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5669 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5670 // Convert back to integer and return.
5671 // return vmovn_u32(vcvt_s32_f32(result));
5672 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5673 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5677 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5678 EVT VT = Op.getNode()->getValueType(0);
5679 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5682 bool ExtraOp = false;
5683 switch (Op.getOpcode()) {
5684 default: llvm_unreachable("Invalid code");
5685 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5686 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5687 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5688 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5692 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5694 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5695 Op.getOperand(1), Op.getOperand(2));
5698 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5699 // Monotonic load/store is legal for all targets
5700 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5703 // Aquire/Release load/store is not legal for targets without a
5704 // dmb or equivalent available.
5709 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5710 SelectionDAG &DAG, unsigned NewOp) {
5712 assert (Node->getValueType(0) == MVT::i64 &&
5713 "Only know how to expand i64 atomics");
5715 SmallVector<SDValue, 6> Ops;
5716 Ops.push_back(Node->getOperand(0)); // Chain
5717 Ops.push_back(Node->getOperand(1)); // Ptr
5719 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5720 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5721 // High part of Val1
5722 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5723 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5724 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5725 // High part of Val1
5726 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5727 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5728 // High part of Val2
5729 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5730 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5732 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5734 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5735 cast<MemSDNode>(Node)->getMemOperand());
5736 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5737 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5738 Results.push_back(Result.getValue(2));
5741 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5742 SmallVectorImpl<SDValue> &Results,
5744 const ARMSubtarget *Subtarget) {
5746 SDValue Cycles32, OutChain;
5748 if (Subtarget->hasPerfMon()) {
5749 // Under Power Management extensions, the cycle-count is:
5750 // mrc p15, #0, <Rt>, c9, c13, #0
5751 SDValue Ops[] = { N->getOperand(0), // Chain
5752 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5753 DAG.getConstant(15, MVT::i32),
5754 DAG.getConstant(0, MVT::i32),
5755 DAG.getConstant(9, MVT::i32),
5756 DAG.getConstant(13, MVT::i32),
5757 DAG.getConstant(0, MVT::i32)
5760 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
5761 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
5762 array_lengthof(Ops));
5763 OutChain = Cycles32.getValue(1);
5765 // Intrinsic is defined to return 0 on unsupported platforms. Technically
5766 // there are older ARM CPUs that have implementation-specific ways of
5767 // obtaining this information (FIXME!).
5768 Cycles32 = DAG.getConstant(0, MVT::i32);
5769 OutChain = DAG.getEntryNode();
5773 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
5774 Cycles32, DAG.getConstant(0, MVT::i32));
5775 Results.push_back(Cycles64);
5776 Results.push_back(OutChain);
5779 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5780 switch (Op.getOpcode()) {
5781 default: llvm_unreachable("Don't know how to custom lower this!");
5782 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5783 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5784 case ISD::GlobalAddress:
5785 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5786 LowerGlobalAddressELF(Op, DAG);
5787 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5788 case ISD::SELECT: return LowerSELECT(Op, DAG);
5789 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5790 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5791 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5792 case ISD::VASTART: return LowerVASTART(Op, DAG);
5793 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5794 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5795 case ISD::SINT_TO_FP:
5796 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5797 case ISD::FP_TO_SINT:
5798 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5799 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5800 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5801 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5802 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5803 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5804 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5805 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5807 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5810 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5811 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5812 case ISD::SRL_PARTS:
5813 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5814 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5815 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5816 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5817 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5818 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5819 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5820 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5821 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5822 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5823 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5824 case ISD::MUL: return LowerMUL(Op, DAG);
5825 case ISD::SDIV: return LowerSDIV(Op, DAG);
5826 case ISD::UDIV: return LowerUDIV(Op, DAG);
5830 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5831 case ISD::ATOMIC_LOAD:
5832 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5836 /// ReplaceNodeResults - Replace the results of node with an illegal result
5837 /// type with new values built out of custom code.
5838 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5839 SmallVectorImpl<SDValue>&Results,
5840 SelectionDAG &DAG) const {
5842 switch (N->getOpcode()) {
5844 llvm_unreachable("Don't know how to custom expand this!");
5846 Res = ExpandBITCAST(N, DAG);
5848 case ISD::SIGN_EXTEND:
5849 case ISD::ZERO_EXTEND:
5850 Res = ExpandVectorExtension(N, DAG);
5854 Res = Expand64BitShift(N, DAG, Subtarget);
5856 case ISD::READCYCLECOUNTER:
5857 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
5859 case ISD::ATOMIC_LOAD_ADD:
5860 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5862 case ISD::ATOMIC_LOAD_AND:
5863 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5865 case ISD::ATOMIC_LOAD_NAND:
5866 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5868 case ISD::ATOMIC_LOAD_OR:
5869 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5871 case ISD::ATOMIC_LOAD_SUB:
5872 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5874 case ISD::ATOMIC_LOAD_XOR:
5875 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5877 case ISD::ATOMIC_SWAP:
5878 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5880 case ISD::ATOMIC_CMP_SWAP:
5881 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5883 case ISD::ATOMIC_LOAD_MIN:
5884 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5886 case ISD::ATOMIC_LOAD_UMIN:
5887 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5889 case ISD::ATOMIC_LOAD_MAX:
5890 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5892 case ISD::ATOMIC_LOAD_UMAX:
5893 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5897 Results.push_back(Res);
5900 //===----------------------------------------------------------------------===//
5901 // ARM Scheduler Hooks
5902 //===----------------------------------------------------------------------===//
5905 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5906 MachineBasicBlock *BB,
5907 unsigned Size) const {
5908 unsigned dest = MI->getOperand(0).getReg();
5909 unsigned ptr = MI->getOperand(1).getReg();
5910 unsigned oldval = MI->getOperand(2).getReg();
5911 unsigned newval = MI->getOperand(3).getReg();
5912 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5913 DebugLoc dl = MI->getDebugLoc();
5914 bool isThumb2 = Subtarget->isThumb2();
5916 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5917 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5918 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5919 (const TargetRegisterClass*)&ARM::GPRRegClass);
5922 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5923 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5924 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5927 unsigned ldrOpc, strOpc;
5929 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5931 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5932 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5935 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5936 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5939 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5940 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5944 MachineFunction *MF = BB->getParent();
5945 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5946 MachineFunction::iterator It = BB;
5947 ++It; // insert the new blocks after the current block
5949 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5950 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5951 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5952 MF->insert(It, loop1MBB);
5953 MF->insert(It, loop2MBB);
5954 MF->insert(It, exitMBB);
5956 // Transfer the remainder of BB and its successor edges to exitMBB.
5957 exitMBB->splice(exitMBB->begin(), BB,
5958 llvm::next(MachineBasicBlock::iterator(MI)),
5960 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5964 // fallthrough --> loop1MBB
5965 BB->addSuccessor(loop1MBB);
5968 // ldrex dest, [ptr]
5972 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5973 if (ldrOpc == ARM::t2LDREX)
5975 AddDefaultPred(MIB);
5976 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5977 .addReg(dest).addReg(oldval));
5978 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5979 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5980 BB->addSuccessor(loop2MBB);
5981 BB->addSuccessor(exitMBB);
5984 // strex scratch, newval, [ptr]
5988 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5989 if (strOpc == ARM::t2STREX)
5991 AddDefaultPred(MIB);
5992 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5993 .addReg(scratch).addImm(0));
5994 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5995 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5996 BB->addSuccessor(loop1MBB);
5997 BB->addSuccessor(exitMBB);
6003 MI->eraseFromParent(); // The instruction is gone now.
6009 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6010 unsigned Size, unsigned BinOpcode) const {
6011 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6012 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6014 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6015 MachineFunction *MF = BB->getParent();
6016 MachineFunction::iterator It = BB;
6019 unsigned dest = MI->getOperand(0).getReg();
6020 unsigned ptr = MI->getOperand(1).getReg();
6021 unsigned incr = MI->getOperand(2).getReg();
6022 DebugLoc dl = MI->getDebugLoc();
6023 bool isThumb2 = Subtarget->isThumb2();
6025 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6027 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6028 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6031 unsigned ldrOpc, strOpc;
6033 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6035 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6036 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6039 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6040 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6043 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6044 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6048 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6049 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6050 MF->insert(It, loopMBB);
6051 MF->insert(It, exitMBB);
6053 // Transfer the remainder of BB and its successor edges to exitMBB.
6054 exitMBB->splice(exitMBB->begin(), BB,
6055 llvm::next(MachineBasicBlock::iterator(MI)),
6057 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6059 const TargetRegisterClass *TRC = isThumb2 ?
6060 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6061 (const TargetRegisterClass*)&ARM::GPRRegClass;
6062 unsigned scratch = MRI.createVirtualRegister(TRC);
6063 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6067 // fallthrough --> loopMBB
6068 BB->addSuccessor(loopMBB);
6072 // <binop> scratch2, dest, incr
6073 // strex scratch, scratch2, ptr
6076 // fallthrough --> exitMBB
6078 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6079 if (ldrOpc == ARM::t2LDREX)
6081 AddDefaultPred(MIB);
6083 // operand order needs to go the other way for NAND
6084 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6085 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6086 addReg(incr).addReg(dest)).addReg(0);
6088 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6089 addReg(dest).addReg(incr)).addReg(0);
6092 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6093 if (strOpc == ARM::t2STREX)
6095 AddDefaultPred(MIB);
6096 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6097 .addReg(scratch).addImm(0));
6098 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6099 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6101 BB->addSuccessor(loopMBB);
6102 BB->addSuccessor(exitMBB);
6108 MI->eraseFromParent(); // The instruction is gone now.
6114 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6115 MachineBasicBlock *BB,
6118 ARMCC::CondCodes Cond) const {
6119 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6121 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6122 MachineFunction *MF = BB->getParent();
6123 MachineFunction::iterator It = BB;
6126 unsigned dest = MI->getOperand(0).getReg();
6127 unsigned ptr = MI->getOperand(1).getReg();
6128 unsigned incr = MI->getOperand(2).getReg();
6129 unsigned oldval = dest;
6130 DebugLoc dl = MI->getDebugLoc();
6131 bool isThumb2 = Subtarget->isThumb2();
6133 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6135 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6136 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6139 unsigned ldrOpc, strOpc, extendOpc;
6141 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6143 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6144 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6145 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6148 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6149 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6150 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6153 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6154 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6159 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6160 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6161 MF->insert(It, loopMBB);
6162 MF->insert(It, exitMBB);
6164 // Transfer the remainder of BB and its successor edges to exitMBB.
6165 exitMBB->splice(exitMBB->begin(), BB,
6166 llvm::next(MachineBasicBlock::iterator(MI)),
6168 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6170 const TargetRegisterClass *TRC = isThumb2 ?
6171 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6172 (const TargetRegisterClass*)&ARM::GPRRegClass;
6173 unsigned scratch = MRI.createVirtualRegister(TRC);
6174 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6178 // fallthrough --> loopMBB
6179 BB->addSuccessor(loopMBB);
6183 // (sign extend dest, if required)
6185 // cmov.cond scratch2, incr, dest
6186 // strex scratch, scratch2, ptr
6189 // fallthrough --> exitMBB
6191 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6192 if (ldrOpc == ARM::t2LDREX)
6194 AddDefaultPred(MIB);
6196 // Sign extend the value, if necessary.
6197 if (signExtend && extendOpc) {
6198 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6199 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6204 // Build compare and cmov instructions.
6205 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6206 .addReg(oldval).addReg(incr));
6207 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6208 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6210 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6211 if (strOpc == ARM::t2STREX)
6213 AddDefaultPred(MIB);
6214 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6215 .addReg(scratch).addImm(0));
6216 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6217 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6219 BB->addSuccessor(loopMBB);
6220 BB->addSuccessor(exitMBB);
6226 MI->eraseFromParent(); // The instruction is gone now.
6232 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6233 unsigned Op1, unsigned Op2,
6234 bool NeedsCarry, bool IsCmpxchg,
6235 bool IsMinMax, ARMCC::CondCodes CC) const {
6236 // This also handles ATOMIC_SWAP, indicated by Op1==0.
6237 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6239 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6240 MachineFunction *MF = BB->getParent();
6241 MachineFunction::iterator It = BB;
6244 unsigned destlo = MI->getOperand(0).getReg();
6245 unsigned desthi = MI->getOperand(1).getReg();
6246 unsigned ptr = MI->getOperand(2).getReg();
6247 unsigned vallo = MI->getOperand(3).getReg();
6248 unsigned valhi = MI->getOperand(4).getReg();
6249 DebugLoc dl = MI->getDebugLoc();
6250 bool isThumb2 = Subtarget->isThumb2();
6252 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6254 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6255 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6256 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6259 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6260 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6261 if (IsCmpxchg || IsMinMax)
6262 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6264 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6265 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6267 MF->insert(It, loopMBB);
6268 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6269 if (IsCmpxchg) MF->insert(It, cont2BB);
6270 MF->insert(It, exitMBB);
6272 // Transfer the remainder of BB and its successor edges to exitMBB.
6273 exitMBB->splice(exitMBB->begin(), BB,
6274 llvm::next(MachineBasicBlock::iterator(MI)),
6276 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6278 const TargetRegisterClass *TRC = isThumb2 ?
6279 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6280 (const TargetRegisterClass*)&ARM::GPRRegClass;
6281 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6285 // fallthrough --> loopMBB
6286 BB->addSuccessor(loopMBB);
6289 // ldrexd r2, r3, ptr
6290 // <binopa> r0, r2, incr
6291 // <binopb> r1, r3, incr
6292 // strexd storesuccess, r0, r1, ptr
6293 // cmp storesuccess, #0
6295 // fallthrough --> exitMBB
6300 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6301 .addReg(destlo, RegState::Define)
6302 .addReg(desthi, RegState::Define)
6305 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6306 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6307 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6308 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6309 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6310 .addReg(GPRPair0, 0, ARM::gsub_0);
6311 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6312 .addReg(GPRPair0, 0, ARM::gsub_1);
6315 unsigned StoreLo, StoreHi;
6318 for (unsigned i = 0; i < 2; i++) {
6319 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6321 .addReg(i == 0 ? destlo : desthi)
6322 .addReg(i == 0 ? vallo : valhi));
6323 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6324 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6325 BB->addSuccessor(exitMBB);
6326 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6327 BB = (i == 0 ? contBB : cont2BB);
6330 // Copy to physregs for strexd
6331 StoreLo = MI->getOperand(5).getReg();
6332 StoreHi = MI->getOperand(6).getReg();
6334 // Perform binary operation
6335 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6336 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6337 .addReg(destlo).addReg(vallo))
6338 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6339 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6340 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6341 .addReg(desthi).addReg(valhi))
6342 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6347 // Copy to physregs for strexd
6352 // Compare and branch to exit block.
6353 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6354 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6355 BB->addSuccessor(exitMBB);
6356 BB->addSuccessor(contBB);
6364 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6365 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6367 // Marshal a pair...
6368 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6369 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6370 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6371 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6372 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6375 .addImm(ARM::gsub_0);
6376 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6379 .addImm(ARM::gsub_1);
6382 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6383 .addReg(StorePair).addReg(ptr));
6386 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6387 .addReg(storesuccess).addImm(0));
6388 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6389 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6391 BB->addSuccessor(loopMBB);
6392 BB->addSuccessor(exitMBB);
6398 MI->eraseFromParent(); // The instruction is gone now.
6403 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6404 /// registers the function context.
6405 void ARMTargetLowering::
6406 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6407 MachineBasicBlock *DispatchBB, int FI) const {
6408 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6409 DebugLoc dl = MI->getDebugLoc();
6410 MachineFunction *MF = MBB->getParent();
6411 MachineRegisterInfo *MRI = &MF->getRegInfo();
6412 MachineConstantPool *MCP = MF->getConstantPool();
6413 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6414 const Function *F = MF->getFunction();
6416 bool isThumb = Subtarget->isThumb();
6417 bool isThumb2 = Subtarget->isThumb2();
6419 unsigned PCLabelId = AFI->createPICLabelUId();
6420 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6421 ARMConstantPoolValue *CPV =
6422 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6423 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6425 const TargetRegisterClass *TRC = isThumb ?
6426 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6427 (const TargetRegisterClass*)&ARM::GPRRegClass;
6429 // Grab constant pool and fixed stack memory operands.
6430 MachineMemOperand *CPMMO =
6431 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6432 MachineMemOperand::MOLoad, 4, 4);
6434 MachineMemOperand *FIMMOSt =
6435 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6436 MachineMemOperand::MOStore, 4, 4);
6438 // Load the address of the dispatch MBB into the jump buffer.
6440 // Incoming value: jbuf
6441 // ldr.n r5, LCPI1_1
6444 // str r5, [$jbuf, #+4] ; &jbuf[1]
6445 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6446 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6447 .addConstantPoolIndex(CPI)
6448 .addMemOperand(CPMMO));
6449 // Set the low bit because of thumb mode.
6450 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6452 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6453 .addReg(NewVReg1, RegState::Kill)
6455 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6456 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6457 .addReg(NewVReg2, RegState::Kill)
6459 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6460 .addReg(NewVReg3, RegState::Kill)
6462 .addImm(36) // &jbuf[1] :: pc
6463 .addMemOperand(FIMMOSt));
6464 } else if (isThumb) {
6465 // Incoming value: jbuf
6466 // ldr.n r1, LCPI1_4
6470 // add r2, $jbuf, #+4 ; &jbuf[1]
6472 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6473 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6474 .addConstantPoolIndex(CPI)
6475 .addMemOperand(CPMMO));
6476 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6477 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6478 .addReg(NewVReg1, RegState::Kill)
6480 // Set the low bit because of thumb mode.
6481 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6482 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6483 .addReg(ARM::CPSR, RegState::Define)
6485 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6486 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6487 .addReg(ARM::CPSR, RegState::Define)
6488 .addReg(NewVReg2, RegState::Kill)
6489 .addReg(NewVReg3, RegState::Kill));
6490 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6491 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6493 .addImm(36)); // &jbuf[1] :: pc
6494 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6495 .addReg(NewVReg4, RegState::Kill)
6496 .addReg(NewVReg5, RegState::Kill)
6498 .addMemOperand(FIMMOSt));
6500 // Incoming value: jbuf
6503 // str r1, [$jbuf, #+4] ; &jbuf[1]
6504 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6505 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6506 .addConstantPoolIndex(CPI)
6508 .addMemOperand(CPMMO));
6509 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6510 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6511 .addReg(NewVReg1, RegState::Kill)
6512 .addImm(PCLabelId));
6513 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6514 .addReg(NewVReg2, RegState::Kill)
6516 .addImm(36) // &jbuf[1] :: pc
6517 .addMemOperand(FIMMOSt));
6521 MachineBasicBlock *ARMTargetLowering::
6522 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6523 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6524 DebugLoc dl = MI->getDebugLoc();
6525 MachineFunction *MF = MBB->getParent();
6526 MachineRegisterInfo *MRI = &MF->getRegInfo();
6527 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6528 MachineFrameInfo *MFI = MF->getFrameInfo();
6529 int FI = MFI->getFunctionContextIndex();
6531 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6532 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6533 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6535 // Get a mapping of the call site numbers to all of the landing pads they're
6537 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6538 unsigned MaxCSNum = 0;
6539 MachineModuleInfo &MMI = MF->getMMI();
6540 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6542 if (!BB->isLandingPad()) continue;
6544 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6546 for (MachineBasicBlock::iterator
6547 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6548 if (!II->isEHLabel()) continue;
6550 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6551 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6553 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6554 for (SmallVectorImpl<unsigned>::iterator
6555 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6556 CSI != CSE; ++CSI) {
6557 CallSiteNumToLPad[*CSI].push_back(BB);
6558 MaxCSNum = std::max(MaxCSNum, *CSI);
6564 // Get an ordered list of the machine basic blocks for the jump table.
6565 std::vector<MachineBasicBlock*> LPadList;
6566 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6567 LPadList.reserve(CallSiteNumToLPad.size());
6568 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6569 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6570 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6571 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6572 LPadList.push_back(*II);
6573 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6577 assert(!LPadList.empty() &&
6578 "No landing pad destinations for the dispatch jump table!");
6580 // Create the jump table and associated information.
6581 MachineJumpTableInfo *JTI =
6582 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6583 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6584 unsigned UId = AFI->createJumpTableUId();
6585 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6587 // Create the MBBs for the dispatch code.
6589 // Shove the dispatch's address into the return slot in the function context.
6590 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6591 DispatchBB->setIsLandingPad();
6593 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6594 unsigned trap_opcode;
6595 if (Subtarget->isThumb())
6596 trap_opcode = ARM::tTRAP;
6598 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6600 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6601 DispatchBB->addSuccessor(TrapBB);
6603 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6604 DispatchBB->addSuccessor(DispContBB);
6607 MF->insert(MF->end(), DispatchBB);
6608 MF->insert(MF->end(), DispContBB);
6609 MF->insert(MF->end(), TrapBB);
6611 // Insert code into the entry block that creates and registers the function
6613 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6615 MachineMemOperand *FIMMOLd =
6616 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6617 MachineMemOperand::MOLoad |
6618 MachineMemOperand::MOVolatile, 4, 4);
6620 MachineInstrBuilder MIB;
6621 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6623 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6624 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6626 // Add a register mask with no preserved registers. This results in all
6627 // registers being marked as clobbered.
6628 MIB.addRegMask(RI.getNoPreservedMask());
6630 unsigned NumLPads = LPadList.size();
6631 if (Subtarget->isThumb2()) {
6632 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6633 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6636 .addMemOperand(FIMMOLd));
6638 if (NumLPads < 256) {
6639 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6641 .addImm(LPadList.size()));
6643 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6644 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6645 .addImm(NumLPads & 0xFFFF));
6647 unsigned VReg2 = VReg1;
6648 if ((NumLPads & 0xFFFF0000) != 0) {
6649 VReg2 = MRI->createVirtualRegister(TRC);
6650 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6652 .addImm(NumLPads >> 16));
6655 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6660 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6665 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6666 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6667 .addJumpTableIndex(MJTI)
6670 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6673 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6674 .addReg(NewVReg3, RegState::Kill)
6676 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6678 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6679 .addReg(NewVReg4, RegState::Kill)
6681 .addJumpTableIndex(MJTI)
6683 } else if (Subtarget->isThumb()) {
6684 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6685 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6688 .addMemOperand(FIMMOLd));
6690 if (NumLPads < 256) {
6691 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6695 MachineConstantPool *ConstantPool = MF->getConstantPool();
6696 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6697 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6699 // MachineConstantPool wants an explicit alignment.
6700 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6702 Align = getDataLayout()->getTypeAllocSize(C->getType());
6703 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6705 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6706 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6707 .addReg(VReg1, RegState::Define)
6708 .addConstantPoolIndex(Idx));
6709 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6714 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6719 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6720 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6721 .addReg(ARM::CPSR, RegState::Define)
6725 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6726 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6727 .addJumpTableIndex(MJTI)
6730 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6731 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6732 .addReg(ARM::CPSR, RegState::Define)
6733 .addReg(NewVReg2, RegState::Kill)
6736 MachineMemOperand *JTMMOLd =
6737 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6738 MachineMemOperand::MOLoad, 4, 4);
6740 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6741 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6742 .addReg(NewVReg4, RegState::Kill)
6744 .addMemOperand(JTMMOLd));
6746 unsigned NewVReg6 = NewVReg5;
6747 if (RelocM == Reloc::PIC_) {
6748 NewVReg6 = MRI->createVirtualRegister(TRC);
6749 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6750 .addReg(ARM::CPSR, RegState::Define)
6751 .addReg(NewVReg5, RegState::Kill)
6755 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6756 .addReg(NewVReg6, RegState::Kill)
6757 .addJumpTableIndex(MJTI)
6760 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6761 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6764 .addMemOperand(FIMMOLd));
6766 if (NumLPads < 256) {
6767 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6770 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6771 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6772 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6773 .addImm(NumLPads & 0xFFFF));
6775 unsigned VReg2 = VReg1;
6776 if ((NumLPads & 0xFFFF0000) != 0) {
6777 VReg2 = MRI->createVirtualRegister(TRC);
6778 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6780 .addImm(NumLPads >> 16));
6783 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6787 MachineConstantPool *ConstantPool = MF->getConstantPool();
6788 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6789 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6791 // MachineConstantPool wants an explicit alignment.
6792 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6794 Align = getDataLayout()->getTypeAllocSize(C->getType());
6795 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6797 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6798 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6799 .addReg(VReg1, RegState::Define)
6800 .addConstantPoolIndex(Idx)
6802 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6804 .addReg(VReg1, RegState::Kill));
6807 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6812 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6814 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6816 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6817 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6818 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6819 .addJumpTableIndex(MJTI)
6822 MachineMemOperand *JTMMOLd =
6823 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6824 MachineMemOperand::MOLoad, 4, 4);
6825 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6827 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6828 .addReg(NewVReg3, RegState::Kill)
6831 .addMemOperand(JTMMOLd));
6833 if (RelocM == Reloc::PIC_) {
6834 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6835 .addReg(NewVReg5, RegState::Kill)
6837 .addJumpTableIndex(MJTI)
6840 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6841 .addReg(NewVReg5, RegState::Kill)
6842 .addJumpTableIndex(MJTI)
6847 // Add the jump table entries as successors to the MBB.
6848 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6849 for (std::vector<MachineBasicBlock*>::iterator
6850 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6851 MachineBasicBlock *CurMBB = *I;
6852 if (SeenMBBs.insert(CurMBB))
6853 DispContBB->addSuccessor(CurMBB);
6856 // N.B. the order the invoke BBs are processed in doesn't matter here.
6857 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6858 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6859 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6860 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6861 MachineBasicBlock *BB = *I;
6863 // Remove the landing pad successor from the invoke block and replace it
6864 // with the new dispatch block.
6865 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6867 while (!Successors.empty()) {
6868 MachineBasicBlock *SMBB = Successors.pop_back_val();
6869 if (SMBB->isLandingPad()) {
6870 BB->removeSuccessor(SMBB);
6871 MBBLPads.push_back(SMBB);
6875 BB->addSuccessor(DispatchBB);
6877 // Find the invoke call and mark all of the callee-saved registers as
6878 // 'implicit defined' so that they're spilled. This prevents code from
6879 // moving instructions to before the EH block, where they will never be
6881 for (MachineBasicBlock::reverse_iterator
6882 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6883 if (!II->isCall()) continue;
6885 DenseMap<unsigned, bool> DefRegs;
6886 for (MachineInstr::mop_iterator
6887 OI = II->operands_begin(), OE = II->operands_end();
6889 if (!OI->isReg()) continue;
6890 DefRegs[OI->getReg()] = true;
6893 MachineInstrBuilder MIB(*MF, &*II);
6895 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6896 unsigned Reg = SavedRegs[i];
6897 if (Subtarget->isThumb2() &&
6898 !ARM::tGPRRegClass.contains(Reg) &&
6899 !ARM::hGPRRegClass.contains(Reg))
6901 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6903 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6906 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6913 // Mark all former landing pads as non-landing pads. The dispatch is the only
6915 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6916 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6917 (*I)->setIsLandingPad(false);
6919 // The instruction is gone now.
6920 MI->eraseFromParent();
6926 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6927 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6928 E = MBB->succ_end(); I != E; ++I)
6931 llvm_unreachable("Expecting a BB with two successors!");
6934 MachineBasicBlock *ARMTargetLowering::
6935 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6936 // This pseudo instruction has 3 operands: dst, src, size
6937 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6938 // Otherwise, we will generate unrolled scalar copies.
6939 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6940 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6941 MachineFunction::iterator It = BB;
6944 unsigned dest = MI->getOperand(0).getReg();
6945 unsigned src = MI->getOperand(1).getReg();
6946 unsigned SizeVal = MI->getOperand(2).getImm();
6947 unsigned Align = MI->getOperand(3).getImm();
6948 DebugLoc dl = MI->getDebugLoc();
6950 bool isThumb2 = Subtarget->isThumb2();
6951 MachineFunction *MF = BB->getParent();
6952 MachineRegisterInfo &MRI = MF->getRegInfo();
6953 unsigned ldrOpc, strOpc, UnitSize = 0;
6955 const TargetRegisterClass *TRC = isThumb2 ?
6956 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6957 (const TargetRegisterClass*)&ARM::GPRRegClass;
6958 const TargetRegisterClass *TRC_Vec = 0;
6961 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6962 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6964 } else if (Align & 2) {
6965 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6966 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6969 // Check whether we can use NEON instructions.
6970 if (!MF->getFunction()->getAttributes().
6971 hasAttribute(AttributeSet::FunctionIndex,
6972 Attribute::NoImplicitFloat) &&
6973 Subtarget->hasNEON()) {
6974 if ((Align % 16 == 0) && SizeVal >= 16) {
6975 ldrOpc = ARM::VLD1q32wb_fixed;
6976 strOpc = ARM::VST1q32wb_fixed;
6978 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6980 else if ((Align % 8 == 0) && SizeVal >= 8) {
6981 ldrOpc = ARM::VLD1d32wb_fixed;
6982 strOpc = ARM::VST1d32wb_fixed;
6984 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6987 // Can't use NEON instructions.
6988 if (UnitSize == 0) {
6989 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6990 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6995 unsigned BytesLeft = SizeVal % UnitSize;
6996 unsigned LoopSize = SizeVal - BytesLeft;
6998 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6999 // Use LDR and STR to copy.
7000 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7001 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7002 unsigned srcIn = src;
7003 unsigned destIn = dest;
7004 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7005 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7006 unsigned srcOut = MRI.createVirtualRegister(TRC);
7007 unsigned destOut = MRI.createVirtualRegister(TRC);
7008 if (UnitSize >= 8) {
7009 AddDefaultPred(BuildMI(*BB, MI, dl,
7010 TII->get(ldrOpc), scratch)
7011 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7013 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7014 .addReg(destIn).addImm(0).addReg(scratch));
7015 } else if (isThumb2) {
7016 AddDefaultPred(BuildMI(*BB, MI, dl,
7017 TII->get(ldrOpc), scratch)
7018 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7020 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7021 .addReg(scratch).addReg(destIn)
7024 AddDefaultPred(BuildMI(*BB, MI, dl,
7025 TII->get(ldrOpc), scratch)
7026 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7029 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7030 .addReg(scratch).addReg(destIn)
7031 .addReg(0).addImm(UnitSize));
7037 // Handle the leftover bytes with LDRB and STRB.
7038 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7039 // [destOut] = STRB_POST(scratch, destIn, 1)
7040 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7041 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7042 for (unsigned i = 0; i < BytesLeft; i++) {
7043 unsigned scratch = MRI.createVirtualRegister(TRC);
7044 unsigned srcOut = MRI.createVirtualRegister(TRC);
7045 unsigned destOut = MRI.createVirtualRegister(TRC);
7047 AddDefaultPred(BuildMI(*BB, MI, dl,
7048 TII->get(ldrOpc),scratch)
7049 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7051 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7052 .addReg(scratch).addReg(destIn)
7053 .addReg(0).addImm(1));
7055 AddDefaultPred(BuildMI(*BB, MI, dl,
7056 TII->get(ldrOpc),scratch)
7057 .addReg(srcOut, RegState::Define).addReg(srcIn)
7058 .addReg(0).addImm(1));
7060 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7061 .addReg(scratch).addReg(destIn)
7062 .addReg(0).addImm(1));
7067 MI->eraseFromParent(); // The instruction is gone now.
7071 // Expand the pseudo op to a loop.
7074 // movw varEnd, # --> with thumb2
7076 // ldrcp varEnd, idx --> without thumb2
7077 // fallthrough --> loopMBB
7079 // PHI varPhi, varEnd, varLoop
7080 // PHI srcPhi, src, srcLoop
7081 // PHI destPhi, dst, destLoop
7082 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7083 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7084 // subs varLoop, varPhi, #UnitSize
7086 // fallthrough --> exitMBB
7088 // epilogue to handle left-over bytes
7089 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7090 // [destOut] = STRB_POST(scratch, destLoop, 1)
7091 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7092 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7093 MF->insert(It, loopMBB);
7094 MF->insert(It, exitMBB);
7096 // Transfer the remainder of BB and its successor edges to exitMBB.
7097 exitMBB->splice(exitMBB->begin(), BB,
7098 llvm::next(MachineBasicBlock::iterator(MI)),
7100 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7102 // Load an immediate to varEnd.
7103 unsigned varEnd = MRI.createVirtualRegister(TRC);
7105 unsigned VReg1 = varEnd;
7106 if ((LoopSize & 0xFFFF0000) != 0)
7107 VReg1 = MRI.createVirtualRegister(TRC);
7108 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7109 .addImm(LoopSize & 0xFFFF));
7111 if ((LoopSize & 0xFFFF0000) != 0)
7112 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7114 .addImm(LoopSize >> 16));
7116 MachineConstantPool *ConstantPool = MF->getConstantPool();
7117 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7118 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7120 // MachineConstantPool wants an explicit alignment.
7121 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7123 Align = getDataLayout()->getTypeAllocSize(C->getType());
7124 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7126 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7127 .addReg(varEnd, RegState::Define)
7128 .addConstantPoolIndex(Idx)
7131 BB->addSuccessor(loopMBB);
7133 // Generate the loop body:
7134 // varPhi = PHI(varLoop, varEnd)
7135 // srcPhi = PHI(srcLoop, src)
7136 // destPhi = PHI(destLoop, dst)
7137 MachineBasicBlock *entryBB = BB;
7139 unsigned varLoop = MRI.createVirtualRegister(TRC);
7140 unsigned varPhi = MRI.createVirtualRegister(TRC);
7141 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7142 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7143 unsigned destLoop = MRI.createVirtualRegister(TRC);
7144 unsigned destPhi = MRI.createVirtualRegister(TRC);
7146 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7147 .addReg(varLoop).addMBB(loopMBB)
7148 .addReg(varEnd).addMBB(entryBB);
7149 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7150 .addReg(srcLoop).addMBB(loopMBB)
7151 .addReg(src).addMBB(entryBB);
7152 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7153 .addReg(destLoop).addMBB(loopMBB)
7154 .addReg(dest).addMBB(entryBB);
7156 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7157 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7158 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7159 if (UnitSize >= 8) {
7160 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7161 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7163 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7164 .addReg(destPhi).addImm(0).addReg(scratch));
7165 } else if (isThumb2) {
7166 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7167 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7169 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7170 .addReg(scratch).addReg(destPhi)
7173 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7174 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7177 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7178 .addReg(scratch).addReg(destPhi)
7179 .addReg(0).addImm(UnitSize));
7182 // Decrement loop variable by UnitSize.
7183 MachineInstrBuilder MIB = BuildMI(BB, dl,
7184 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7185 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7186 MIB->getOperand(5).setReg(ARM::CPSR);
7187 MIB->getOperand(5).setIsDef(true);
7189 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7190 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7192 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7193 BB->addSuccessor(loopMBB);
7194 BB->addSuccessor(exitMBB);
7196 // Add epilogue to handle BytesLeft.
7198 MachineInstr *StartOfExit = exitMBB->begin();
7199 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7200 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7202 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7203 // [destOut] = STRB_POST(scratch, destLoop, 1)
7204 unsigned srcIn = srcLoop;
7205 unsigned destIn = destLoop;
7206 for (unsigned i = 0; i < BytesLeft; i++) {
7207 unsigned scratch = MRI.createVirtualRegister(TRC);
7208 unsigned srcOut = MRI.createVirtualRegister(TRC);
7209 unsigned destOut = MRI.createVirtualRegister(TRC);
7211 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7212 TII->get(ldrOpc),scratch)
7213 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7215 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7216 .addReg(scratch).addReg(destIn)
7219 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7220 TII->get(ldrOpc),scratch)
7221 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7223 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7224 .addReg(scratch).addReg(destIn)
7225 .addReg(0).addImm(1));
7231 MI->eraseFromParent(); // The instruction is gone now.
7236 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7237 MachineBasicBlock *BB) const {
7238 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7239 DebugLoc dl = MI->getDebugLoc();
7240 bool isThumb2 = Subtarget->isThumb2();
7241 switch (MI->getOpcode()) {
7244 llvm_unreachable("Unexpected instr type to insert");
7246 // The Thumb2 pre-indexed stores have the same MI operands, they just
7247 // define them differently in the .td files from the isel patterns, so
7248 // they need pseudos.
7249 case ARM::t2STR_preidx:
7250 MI->setDesc(TII->get(ARM::t2STR_PRE));
7252 case ARM::t2STRB_preidx:
7253 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7255 case ARM::t2STRH_preidx:
7256 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7259 case ARM::STRi_preidx:
7260 case ARM::STRBi_preidx: {
7261 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7262 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7263 // Decode the offset.
7264 unsigned Offset = MI->getOperand(4).getImm();
7265 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7266 Offset = ARM_AM::getAM2Offset(Offset);
7270 MachineMemOperand *MMO = *MI->memoperands_begin();
7271 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7272 .addOperand(MI->getOperand(0)) // Rn_wb
7273 .addOperand(MI->getOperand(1)) // Rt
7274 .addOperand(MI->getOperand(2)) // Rn
7275 .addImm(Offset) // offset (skip GPR==zero_reg)
7276 .addOperand(MI->getOperand(5)) // pred
7277 .addOperand(MI->getOperand(6))
7278 .addMemOperand(MMO);
7279 MI->eraseFromParent();
7282 case ARM::STRr_preidx:
7283 case ARM::STRBr_preidx:
7284 case ARM::STRH_preidx: {
7286 switch (MI->getOpcode()) {
7287 default: llvm_unreachable("unexpected opcode!");
7288 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7289 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7290 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7292 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7293 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7294 MIB.addOperand(MI->getOperand(i));
7295 MI->eraseFromParent();
7298 case ARM::ATOMIC_LOAD_ADD_I8:
7299 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7300 case ARM::ATOMIC_LOAD_ADD_I16:
7301 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7302 case ARM::ATOMIC_LOAD_ADD_I32:
7303 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7305 case ARM::ATOMIC_LOAD_AND_I8:
7306 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7307 case ARM::ATOMIC_LOAD_AND_I16:
7308 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7309 case ARM::ATOMIC_LOAD_AND_I32:
7310 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7312 case ARM::ATOMIC_LOAD_OR_I8:
7313 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7314 case ARM::ATOMIC_LOAD_OR_I16:
7315 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7316 case ARM::ATOMIC_LOAD_OR_I32:
7317 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7319 case ARM::ATOMIC_LOAD_XOR_I8:
7320 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7321 case ARM::ATOMIC_LOAD_XOR_I16:
7322 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7323 case ARM::ATOMIC_LOAD_XOR_I32:
7324 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7326 case ARM::ATOMIC_LOAD_NAND_I8:
7327 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7328 case ARM::ATOMIC_LOAD_NAND_I16:
7329 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7330 case ARM::ATOMIC_LOAD_NAND_I32:
7331 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7333 case ARM::ATOMIC_LOAD_SUB_I8:
7334 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7335 case ARM::ATOMIC_LOAD_SUB_I16:
7336 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7337 case ARM::ATOMIC_LOAD_SUB_I32:
7338 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7340 case ARM::ATOMIC_LOAD_MIN_I8:
7341 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7342 case ARM::ATOMIC_LOAD_MIN_I16:
7343 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7344 case ARM::ATOMIC_LOAD_MIN_I32:
7345 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7347 case ARM::ATOMIC_LOAD_MAX_I8:
7348 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7349 case ARM::ATOMIC_LOAD_MAX_I16:
7350 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7351 case ARM::ATOMIC_LOAD_MAX_I32:
7352 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7354 case ARM::ATOMIC_LOAD_UMIN_I8:
7355 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7356 case ARM::ATOMIC_LOAD_UMIN_I16:
7357 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7358 case ARM::ATOMIC_LOAD_UMIN_I32:
7359 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7361 case ARM::ATOMIC_LOAD_UMAX_I8:
7362 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7363 case ARM::ATOMIC_LOAD_UMAX_I16:
7364 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7365 case ARM::ATOMIC_LOAD_UMAX_I32:
7366 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7368 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7369 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7370 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7372 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7373 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7374 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7377 case ARM::ATOMADD6432:
7378 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7379 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7380 /*NeedsCarry*/ true);
7381 case ARM::ATOMSUB6432:
7382 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7383 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7384 /*NeedsCarry*/ true);
7385 case ARM::ATOMOR6432:
7386 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7387 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7388 case ARM::ATOMXOR6432:
7389 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7390 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7391 case ARM::ATOMAND6432:
7392 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7393 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7394 case ARM::ATOMSWAP6432:
7395 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7396 case ARM::ATOMCMPXCHG6432:
7397 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7398 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7399 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7400 case ARM::ATOMMIN6432:
7401 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7402 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7403 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7404 /*IsMinMax*/ true, ARMCC::LT);
7405 case ARM::ATOMMAX6432:
7406 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7407 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7408 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7409 /*IsMinMax*/ true, ARMCC::GE);
7410 case ARM::ATOMUMIN6432:
7411 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7412 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7413 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7414 /*IsMinMax*/ true, ARMCC::LO);
7415 case ARM::ATOMUMAX6432:
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::HS);
7421 case ARM::tMOVCCr_pseudo: {
7422 // To "insert" a SELECT_CC instruction, we actually have to insert the
7423 // diamond control-flow pattern. The incoming instruction knows the
7424 // destination vreg to set, the condition code register to branch on, the
7425 // true/false values to select between, and a branch opcode to use.
7426 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7427 MachineFunction::iterator It = BB;
7433 // cmpTY ccX, r1, r2
7435 // fallthrough --> copy0MBB
7436 MachineBasicBlock *thisMBB = BB;
7437 MachineFunction *F = BB->getParent();
7438 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7439 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7440 F->insert(It, copy0MBB);
7441 F->insert(It, sinkMBB);
7443 // Transfer the remainder of BB and its successor edges to sinkMBB.
7444 sinkMBB->splice(sinkMBB->begin(), BB,
7445 llvm::next(MachineBasicBlock::iterator(MI)),
7447 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7449 BB->addSuccessor(copy0MBB);
7450 BB->addSuccessor(sinkMBB);
7452 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7453 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7456 // %FalseValue = ...
7457 // # fallthrough to sinkMBB
7460 // Update machine-CFG edges
7461 BB->addSuccessor(sinkMBB);
7464 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7467 BuildMI(*BB, BB->begin(), dl,
7468 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7469 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7470 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7472 MI->eraseFromParent(); // The pseudo instruction is gone now.
7477 case ARM::BCCZi64: {
7478 // If there is an unconditional branch to the other successor, remove it.
7479 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7481 // Compare both parts that make up the double comparison separately for
7483 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7485 unsigned LHS1 = MI->getOperand(1).getReg();
7486 unsigned LHS2 = MI->getOperand(2).getReg();
7488 AddDefaultPred(BuildMI(BB, dl,
7489 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7490 .addReg(LHS1).addImm(0));
7491 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7492 .addReg(LHS2).addImm(0)
7493 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7495 unsigned RHS1 = MI->getOperand(3).getReg();
7496 unsigned RHS2 = MI->getOperand(4).getReg();
7497 AddDefaultPred(BuildMI(BB, dl,
7498 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7499 .addReg(LHS1).addReg(RHS1));
7500 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7501 .addReg(LHS2).addReg(RHS2)
7502 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7505 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7506 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7507 if (MI->getOperand(0).getImm() == ARMCC::NE)
7508 std::swap(destMBB, exitMBB);
7510 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7511 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7513 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7515 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7517 MI->eraseFromParent(); // The pseudo instruction is gone now.
7521 case ARM::Int_eh_sjlj_setjmp:
7522 case ARM::Int_eh_sjlj_setjmp_nofp:
7523 case ARM::tInt_eh_sjlj_setjmp:
7524 case ARM::t2Int_eh_sjlj_setjmp:
7525 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7526 EmitSjLjDispatchBlock(MI, BB);
7531 // To insert an ABS instruction, we have to insert the
7532 // diamond control-flow pattern. The incoming instruction knows the
7533 // source vreg to test against 0, the destination vreg to set,
7534 // the condition code register to branch on, the
7535 // true/false values to select between, and a branch opcode to use.
7540 // BCC (branch to SinkBB if V0 >= 0)
7541 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7542 // SinkBB: V1 = PHI(V2, V3)
7543 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7544 MachineFunction::iterator BBI = BB;
7546 MachineFunction *Fn = BB->getParent();
7547 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7548 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7549 Fn->insert(BBI, RSBBB);
7550 Fn->insert(BBI, SinkBB);
7552 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7553 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7554 bool isThumb2 = Subtarget->isThumb2();
7555 MachineRegisterInfo &MRI = Fn->getRegInfo();
7556 // In Thumb mode S must not be specified if source register is the SP or
7557 // PC and if destination register is the SP, so restrict register class
7558 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7559 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7560 (const TargetRegisterClass*)&ARM::GPRRegClass);
7562 // Transfer the remainder of BB and its successor edges to sinkMBB.
7563 SinkBB->splice(SinkBB->begin(), BB,
7564 llvm::next(MachineBasicBlock::iterator(MI)),
7566 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7568 BB->addSuccessor(RSBBB);
7569 BB->addSuccessor(SinkBB);
7571 // fall through to SinkMBB
7572 RSBBB->addSuccessor(SinkBB);
7574 // insert a cmp at the end of BB
7575 AddDefaultPred(BuildMI(BB, dl,
7576 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7577 .addReg(ABSSrcReg).addImm(0));
7579 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7581 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7582 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7584 // insert rsbri in RSBBB
7585 // Note: BCC and rsbri will be converted into predicated rsbmi
7586 // by if-conversion pass
7587 BuildMI(*RSBBB, RSBBB->begin(), dl,
7588 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7589 .addReg(ABSSrcReg, RegState::Kill)
7590 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7592 // insert PHI in SinkBB,
7593 // reuse ABSDstReg to not change uses of ABS instruction
7594 BuildMI(*SinkBB, SinkBB->begin(), dl,
7595 TII->get(ARM::PHI), ABSDstReg)
7596 .addReg(NewRsbDstReg).addMBB(RSBBB)
7597 .addReg(ABSSrcReg).addMBB(BB);
7599 // remove ABS instruction
7600 MI->eraseFromParent();
7602 // return last added BB
7605 case ARM::COPY_STRUCT_BYVAL_I32:
7607 return EmitStructByval(MI, BB);
7611 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7612 SDNode *Node) const {
7613 if (!MI->hasPostISelHook()) {
7614 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7615 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7619 const MCInstrDesc *MCID = &MI->getDesc();
7620 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7621 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7622 // operand is still set to noreg. If needed, set the optional operand's
7623 // register to CPSR, and remove the redundant implicit def.
7625 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7627 // Rename pseudo opcodes.
7628 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7630 const ARMBaseInstrInfo *TII =
7631 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7632 MCID = &TII->get(NewOpc);
7634 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7635 "converted opcode should be the same except for cc_out");
7639 // Add the optional cc_out operand
7640 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7642 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7644 // Any ARM instruction that sets the 's' bit should specify an optional
7645 // "cc_out" operand in the last operand position.
7646 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7647 assert(!NewOpc && "Optional cc_out operand required");
7650 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7651 // since we already have an optional CPSR def.
7652 bool definesCPSR = false;
7653 bool deadCPSR = false;
7654 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7656 const MachineOperand &MO = MI->getOperand(i);
7657 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7661 MI->RemoveOperand(i);
7666 assert(!NewOpc && "Optional cc_out operand required");
7669 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7671 assert(!MI->getOperand(ccOutIdx).getReg() &&
7672 "expect uninitialized optional cc_out operand");
7676 // If this instruction was defined with an optional CPSR def and its dag node
7677 // had a live implicit CPSR def, then activate the optional CPSR def.
7678 MachineOperand &MO = MI->getOperand(ccOutIdx);
7679 MO.setReg(ARM::CPSR);
7683 //===----------------------------------------------------------------------===//
7684 // ARM Optimization Hooks
7685 //===----------------------------------------------------------------------===//
7687 // Helper function that checks if N is a null or all ones constant.
7688 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7689 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7692 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7695 // Return true if N is conditionally 0 or all ones.
7696 // Detects these expressions where cc is an i1 value:
7698 // (select cc 0, y) [AllOnes=0]
7699 // (select cc y, 0) [AllOnes=0]
7700 // (zext cc) [AllOnes=0]
7701 // (sext cc) [AllOnes=0/1]
7702 // (select cc -1, y) [AllOnes=1]
7703 // (select cc y, -1) [AllOnes=1]
7705 // Invert is set when N is the null/all ones constant when CC is false.
7706 // OtherOp is set to the alternative value of N.
7707 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7708 SDValue &CC, bool &Invert,
7710 SelectionDAG &DAG) {
7711 switch (N->getOpcode()) {
7712 default: return false;
7714 CC = N->getOperand(0);
7715 SDValue N1 = N->getOperand(1);
7716 SDValue N2 = N->getOperand(2);
7717 if (isZeroOrAllOnes(N1, AllOnes)) {
7722 if (isZeroOrAllOnes(N2, AllOnes)) {
7729 case ISD::ZERO_EXTEND:
7730 // (zext cc) can never be the all ones value.
7734 case ISD::SIGN_EXTEND: {
7735 EVT VT = N->getValueType(0);
7736 CC = N->getOperand(0);
7737 if (CC.getValueType() != MVT::i1)
7741 // When looking for an AllOnes constant, N is an sext, and the 'other'
7743 OtherOp = DAG.getConstant(0, VT);
7744 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7745 // When looking for a 0 constant, N can be zext or sext.
7746 OtherOp = DAG.getConstant(1, VT);
7748 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7754 // Combine a constant select operand into its use:
7756 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7757 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7758 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7759 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7760 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7762 // The transform is rejected if the select doesn't have a constant operand that
7763 // is null, or all ones when AllOnes is set.
7765 // Also recognize sext/zext from i1:
7767 // (add (zext cc), x) -> (select cc (add x, 1), x)
7768 // (add (sext cc), x) -> (select cc (add x, -1), x)
7770 // These transformations eventually create predicated instructions.
7772 // @param N The node to transform.
7773 // @param Slct The N operand that is a select.
7774 // @param OtherOp The other N operand (x above).
7775 // @param DCI Context.
7776 // @param AllOnes Require the select constant to be all ones instead of null.
7777 // @returns The new node, or SDValue() on failure.
7779 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7780 TargetLowering::DAGCombinerInfo &DCI,
7781 bool AllOnes = false) {
7782 SelectionDAG &DAG = DCI.DAG;
7783 EVT VT = N->getValueType(0);
7784 SDValue NonConstantVal;
7787 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7788 NonConstantVal, DAG))
7791 // Slct is now know to be the desired identity constant when CC is true.
7792 SDValue TrueVal = OtherOp;
7793 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7794 OtherOp, NonConstantVal);
7795 // Unless SwapSelectOps says CC should be false.
7797 std::swap(TrueVal, FalseVal);
7799 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7800 CCOp, TrueVal, FalseVal);
7803 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7805 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7806 TargetLowering::DAGCombinerInfo &DCI) {
7807 SDValue N0 = N->getOperand(0);
7808 SDValue N1 = N->getOperand(1);
7809 if (N0.getNode()->hasOneUse()) {
7810 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7811 if (Result.getNode())
7814 if (N1.getNode()->hasOneUse()) {
7815 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7816 if (Result.getNode())
7822 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7823 // (only after legalization).
7824 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7825 TargetLowering::DAGCombinerInfo &DCI,
7826 const ARMSubtarget *Subtarget) {
7828 // Only perform optimization if after legalize, and if NEON is available. We
7829 // also expected both operands to be BUILD_VECTORs.
7830 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7831 || N0.getOpcode() != ISD::BUILD_VECTOR
7832 || N1.getOpcode() != ISD::BUILD_VECTOR)
7835 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7836 EVT VT = N->getValueType(0);
7837 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7840 // Check that the vector operands are of the right form.
7841 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7842 // operands, where N is the size of the formed vector.
7843 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7844 // index such that we have a pair wise add pattern.
7846 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7847 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7849 SDValue Vec = N0->getOperand(0)->getOperand(0);
7850 SDNode *V = Vec.getNode();
7851 unsigned nextIndex = 0;
7853 // For each operands to the ADD which are BUILD_VECTORs,
7854 // check to see if each of their operands are an EXTRACT_VECTOR with
7855 // the same vector and appropriate index.
7856 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7857 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7858 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7860 SDValue ExtVec0 = N0->getOperand(i);
7861 SDValue ExtVec1 = N1->getOperand(i);
7863 // First operand is the vector, verify its the same.
7864 if (V != ExtVec0->getOperand(0).getNode() ||
7865 V != ExtVec1->getOperand(0).getNode())
7868 // Second is the constant, verify its correct.
7869 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7870 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7872 // For the constant, we want to see all the even or all the odd.
7873 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7874 || C1->getZExtValue() != nextIndex+1)
7883 // Create VPADDL node.
7884 SelectionDAG &DAG = DCI.DAG;
7885 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7887 // Build operand list.
7888 SmallVector<SDValue, 8> Ops;
7889 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7890 TLI.getPointerTy()));
7892 // Input is the vector.
7895 // Get widened type and narrowed type.
7897 unsigned numElem = VT.getVectorNumElements();
7898 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7899 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7900 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7901 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7903 llvm_unreachable("Invalid vector element type for padd optimization.");
7906 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
7907 widenType, &Ops[0], Ops.size());
7908 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
7911 static SDValue findMUL_LOHI(SDValue V) {
7912 if (V->getOpcode() == ISD::UMUL_LOHI ||
7913 V->getOpcode() == ISD::SMUL_LOHI)
7918 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7919 TargetLowering::DAGCombinerInfo &DCI,
7920 const ARMSubtarget *Subtarget) {
7922 if (Subtarget->isThumb1Only()) return SDValue();
7924 // Only perform the checks after legalize when the pattern is available.
7925 if (DCI.isBeforeLegalize()) return SDValue();
7927 // Look for multiply add opportunities.
7928 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7929 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7930 // a glue link from the first add to the second add.
7931 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7932 // a S/UMLAL instruction.
7935 // \ / \ [no multiline comment]
7941 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7942 SDValue AddcOp0 = AddcNode->getOperand(0);
7943 SDValue AddcOp1 = AddcNode->getOperand(1);
7945 // Check if the two operands are from the same mul_lohi node.
7946 if (AddcOp0.getNode() == AddcOp1.getNode())
7949 assert(AddcNode->getNumValues() == 2 &&
7950 AddcNode->getValueType(0) == MVT::i32 &&
7951 AddcNode->getValueType(1) == MVT::Glue &&
7952 "Expect ADDC with two result values: i32, glue");
7954 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7955 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7956 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7957 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7958 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7961 // Look for the glued ADDE.
7962 SDNode* AddeNode = AddcNode->getGluedUser();
7963 if (AddeNode == NULL)
7966 // Make sure it is really an ADDE.
7967 if (AddeNode->getOpcode() != ISD::ADDE)
7970 assert(AddeNode->getNumOperands() == 3 &&
7971 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7972 "ADDE node has the wrong inputs");
7974 // Check for the triangle shape.
7975 SDValue AddeOp0 = AddeNode->getOperand(0);
7976 SDValue AddeOp1 = AddeNode->getOperand(1);
7978 // Make sure that the ADDE operands are not coming from the same node.
7979 if (AddeOp0.getNode() == AddeOp1.getNode())
7982 // Find the MUL_LOHI node walking up ADDE's operands.
7983 bool IsLeftOperandMUL = false;
7984 SDValue MULOp = findMUL_LOHI(AddeOp0);
7985 if (MULOp == SDValue())
7986 MULOp = findMUL_LOHI(AddeOp1);
7988 IsLeftOperandMUL = true;
7989 if (MULOp == SDValue())
7992 // Figure out the right opcode.
7993 unsigned Opc = MULOp->getOpcode();
7994 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7996 // Figure out the high and low input values to the MLAL node.
7997 SDValue* HiMul = &MULOp;
7998 SDValue* HiAdd = NULL;
7999 SDValue* LoMul = NULL;
8000 SDValue* LowAdd = NULL;
8002 if (IsLeftOperandMUL)
8008 if (AddcOp0->getOpcode() == Opc) {
8012 if (AddcOp1->getOpcode() == Opc) {
8020 if (LoMul->getNode() != HiMul->getNode())
8023 // Create the merged node.
8024 SelectionDAG &DAG = DCI.DAG;
8026 // Build operand list.
8027 SmallVector<SDValue, 8> Ops;
8028 Ops.push_back(LoMul->getOperand(0));
8029 Ops.push_back(LoMul->getOperand(1));
8030 Ops.push_back(*LowAdd);
8031 Ops.push_back(*HiAdd);
8033 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8034 DAG.getVTList(MVT::i32, MVT::i32),
8035 &Ops[0], Ops.size());
8037 // Replace the ADDs' nodes uses by the MLA node's values.
8038 SDValue HiMLALResult(MLALNode.getNode(), 1);
8039 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8041 SDValue LoMLALResult(MLALNode.getNode(), 0);
8042 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8044 // Return original node to notify the driver to stop replacing.
8045 SDValue resNode(AddcNode, 0);
8049 /// PerformADDCCombine - Target-specific dag combine transform from
8050 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8051 static SDValue PerformADDCCombine(SDNode *N,
8052 TargetLowering::DAGCombinerInfo &DCI,
8053 const ARMSubtarget *Subtarget) {
8055 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8059 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8060 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8061 /// called with the default operands, and if that fails, with commuted
8063 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8064 TargetLowering::DAGCombinerInfo &DCI,
8065 const ARMSubtarget *Subtarget){
8067 // Attempt to create vpaddl for this add.
8068 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8069 if (Result.getNode())
8072 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8073 if (N0.getNode()->hasOneUse()) {
8074 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8075 if (Result.getNode()) return Result;
8080 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8082 static SDValue PerformADDCombine(SDNode *N,
8083 TargetLowering::DAGCombinerInfo &DCI,
8084 const ARMSubtarget *Subtarget) {
8085 SDValue N0 = N->getOperand(0);
8086 SDValue N1 = N->getOperand(1);
8088 // First try with the default operand order.
8089 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8090 if (Result.getNode())
8093 // If that didn't work, try again with the operands commuted.
8094 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8097 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8099 static SDValue PerformSUBCombine(SDNode *N,
8100 TargetLowering::DAGCombinerInfo &DCI) {
8101 SDValue N0 = N->getOperand(0);
8102 SDValue N1 = N->getOperand(1);
8104 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8105 if (N1.getNode()->hasOneUse()) {
8106 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8107 if (Result.getNode()) return Result;
8113 /// PerformVMULCombine
8114 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8115 /// special multiplier accumulator forwarding.
8121 static SDValue PerformVMULCombine(SDNode *N,
8122 TargetLowering::DAGCombinerInfo &DCI,
8123 const ARMSubtarget *Subtarget) {
8124 if (!Subtarget->hasVMLxForwarding())
8127 SelectionDAG &DAG = DCI.DAG;
8128 SDValue N0 = N->getOperand(0);
8129 SDValue N1 = N->getOperand(1);
8130 unsigned Opcode = N0.getOpcode();
8131 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8132 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8133 Opcode = N1.getOpcode();
8134 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8135 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8140 EVT VT = N->getValueType(0);
8142 SDValue N00 = N0->getOperand(0);
8143 SDValue N01 = N0->getOperand(1);
8144 return DAG.getNode(Opcode, DL, VT,
8145 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8146 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8149 static SDValue PerformMULCombine(SDNode *N,
8150 TargetLowering::DAGCombinerInfo &DCI,
8151 const ARMSubtarget *Subtarget) {
8152 SelectionDAG &DAG = DCI.DAG;
8154 if (Subtarget->isThumb1Only())
8157 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8160 EVT VT = N->getValueType(0);
8161 if (VT.is64BitVector() || VT.is128BitVector())
8162 return PerformVMULCombine(N, DCI, Subtarget);
8166 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8170 int64_t MulAmt = C->getSExtValue();
8171 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8173 ShiftAmt = ShiftAmt & (32 - 1);
8174 SDValue V = N->getOperand(0);
8178 MulAmt >>= ShiftAmt;
8181 if (isPowerOf2_32(MulAmt - 1)) {
8182 // (mul x, 2^N + 1) => (add (shl x, N), x)
8183 Res = DAG.getNode(ISD::ADD, DL, VT,
8185 DAG.getNode(ISD::SHL, DL, VT,
8187 DAG.getConstant(Log2_32(MulAmt - 1),
8189 } else if (isPowerOf2_32(MulAmt + 1)) {
8190 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8191 Res = DAG.getNode(ISD::SUB, DL, VT,
8192 DAG.getNode(ISD::SHL, DL, VT,
8194 DAG.getConstant(Log2_32(MulAmt + 1),
8200 uint64_t MulAmtAbs = -MulAmt;
8201 if (isPowerOf2_32(MulAmtAbs + 1)) {
8202 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8203 Res = DAG.getNode(ISD::SUB, DL, VT,
8205 DAG.getNode(ISD::SHL, DL, VT,
8207 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8209 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8210 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8211 Res = DAG.getNode(ISD::ADD, DL, VT,
8213 DAG.getNode(ISD::SHL, DL, VT,
8215 DAG.getConstant(Log2_32(MulAmtAbs-1),
8217 Res = DAG.getNode(ISD::SUB, DL, VT,
8218 DAG.getConstant(0, MVT::i32),Res);
8225 Res = DAG.getNode(ISD::SHL, DL, VT,
8226 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8228 // Do not add new nodes to DAG combiner worklist.
8229 DCI.CombineTo(N, Res, false);
8233 static SDValue PerformANDCombine(SDNode *N,
8234 TargetLowering::DAGCombinerInfo &DCI,
8235 const ARMSubtarget *Subtarget) {
8237 // Attempt to use immediate-form VBIC
8238 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8240 EVT VT = N->getValueType(0);
8241 SelectionDAG &DAG = DCI.DAG;
8243 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8246 APInt SplatBits, SplatUndef;
8247 unsigned SplatBitSize;
8250 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8251 if (SplatBitSize <= 64) {
8253 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8254 SplatUndef.getZExtValue(), SplatBitSize,
8255 DAG, VbicVT, VT.is128BitVector(),
8257 if (Val.getNode()) {
8259 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8260 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8261 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8266 if (!Subtarget->isThumb1Only()) {
8267 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8268 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8269 if (Result.getNode())
8276 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8277 static SDValue PerformORCombine(SDNode *N,
8278 TargetLowering::DAGCombinerInfo &DCI,
8279 const ARMSubtarget *Subtarget) {
8280 // Attempt to use immediate-form VORR
8281 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8283 EVT VT = N->getValueType(0);
8284 SelectionDAG &DAG = DCI.DAG;
8286 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8289 APInt SplatBits, SplatUndef;
8290 unsigned SplatBitSize;
8292 if (BVN && Subtarget->hasNEON() &&
8293 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8294 if (SplatBitSize <= 64) {
8296 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8297 SplatUndef.getZExtValue(), SplatBitSize,
8298 DAG, VorrVT, VT.is128BitVector(),
8300 if (Val.getNode()) {
8302 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8303 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8304 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8309 if (!Subtarget->isThumb1Only()) {
8310 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8311 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8312 if (Result.getNode())
8316 // The code below optimizes (or (and X, Y), Z).
8317 // The AND operand needs to have a single user to make these optimizations
8319 SDValue N0 = N->getOperand(0);
8320 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8322 SDValue N1 = N->getOperand(1);
8324 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8325 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8326 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8328 unsigned SplatBitSize;
8331 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8333 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8334 HasAnyUndefs) && !HasAnyUndefs) {
8335 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8337 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8338 HasAnyUndefs) && !HasAnyUndefs &&
8339 SplatBits0 == ~SplatBits1) {
8340 // Canonicalize the vector type to make instruction selection simpler.
8341 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8342 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8343 N0->getOperand(1), N0->getOperand(0),
8345 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8350 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8353 // BFI is only available on V6T2+
8354 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8358 // 1) or (and A, mask), val => ARMbfi A, val, mask
8359 // iff (val & mask) == val
8361 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8362 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8363 // && mask == ~mask2
8364 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8365 // && ~mask == mask2
8366 // (i.e., copy a bitfield value into another bitfield of the same width)
8371 SDValue N00 = N0.getOperand(0);
8373 // The value and the mask need to be constants so we can verify this is
8374 // actually a bitfield set. If the mask is 0xffff, we can do better
8375 // via a movt instruction, so don't use BFI in that case.
8376 SDValue MaskOp = N0.getOperand(1);
8377 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8380 unsigned Mask = MaskC->getZExtValue();
8384 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8385 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8387 unsigned Val = N1C->getZExtValue();
8388 if ((Val & ~Mask) != Val)
8391 if (ARM::isBitFieldInvertedMask(Mask)) {
8392 Val >>= countTrailingZeros(~Mask);
8394 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8395 DAG.getConstant(Val, MVT::i32),
8396 DAG.getConstant(Mask, MVT::i32));
8398 // Do not add new nodes to DAG combiner worklist.
8399 DCI.CombineTo(N, Res, false);
8402 } else if (N1.getOpcode() == ISD::AND) {
8403 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8404 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8407 unsigned Mask2 = N11C->getZExtValue();
8409 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8411 if (ARM::isBitFieldInvertedMask(Mask) &&
8413 // The pack halfword instruction works better for masks that fit it,
8414 // so use that when it's available.
8415 if (Subtarget->hasT2ExtractPack() &&
8416 (Mask == 0xffff || Mask == 0xffff0000))
8419 unsigned amt = countTrailingZeros(Mask2);
8420 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8421 DAG.getConstant(amt, MVT::i32));
8422 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8423 DAG.getConstant(Mask, MVT::i32));
8424 // Do not add new nodes to DAG combiner worklist.
8425 DCI.CombineTo(N, Res, false);
8427 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8429 // The pack halfword instruction works better for masks that fit it,
8430 // so use that when it's available.
8431 if (Subtarget->hasT2ExtractPack() &&
8432 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8435 unsigned lsb = countTrailingZeros(Mask);
8436 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8437 DAG.getConstant(lsb, MVT::i32));
8438 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8439 DAG.getConstant(Mask2, MVT::i32));
8440 // Do not add new nodes to DAG combiner worklist.
8441 DCI.CombineTo(N, Res, false);
8446 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8447 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8448 ARM::isBitFieldInvertedMask(~Mask)) {
8449 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8450 // where lsb(mask) == #shamt and masked bits of B are known zero.
8451 SDValue ShAmt = N00.getOperand(1);
8452 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8453 unsigned LSB = countTrailingZeros(Mask);
8457 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8458 DAG.getConstant(~Mask, MVT::i32));
8460 // Do not add new nodes to DAG combiner worklist.
8461 DCI.CombineTo(N, Res, false);
8467 static SDValue PerformXORCombine(SDNode *N,
8468 TargetLowering::DAGCombinerInfo &DCI,
8469 const ARMSubtarget *Subtarget) {
8470 EVT VT = N->getValueType(0);
8471 SelectionDAG &DAG = DCI.DAG;
8473 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8476 if (!Subtarget->isThumb1Only()) {
8477 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8478 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8479 if (Result.getNode())
8486 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8487 /// the bits being cleared by the AND are not demanded by the BFI.
8488 static SDValue PerformBFICombine(SDNode *N,
8489 TargetLowering::DAGCombinerInfo &DCI) {
8490 SDValue N1 = N->getOperand(1);
8491 if (N1.getOpcode() == ISD::AND) {
8492 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8495 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8496 unsigned LSB = countTrailingZeros(~InvMask);
8497 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8498 unsigned Mask = (1 << Width)-1;
8499 unsigned Mask2 = N11C->getZExtValue();
8500 if ((Mask & (~Mask2)) == 0)
8501 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8502 N->getOperand(0), N1.getOperand(0),
8508 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8509 /// ARMISD::VMOVRRD.
8510 static SDValue PerformVMOVRRDCombine(SDNode *N,
8511 TargetLowering::DAGCombinerInfo &DCI) {
8512 // vmovrrd(vmovdrr x, y) -> x,y
8513 SDValue InDouble = N->getOperand(0);
8514 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8515 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8517 // vmovrrd(load f64) -> (load i32), (load i32)
8518 SDNode *InNode = InDouble.getNode();
8519 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8520 InNode->getValueType(0) == MVT::f64 &&
8521 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8522 !cast<LoadSDNode>(InNode)->isVolatile()) {
8523 // TODO: Should this be done for non-FrameIndex operands?
8524 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8526 SelectionDAG &DAG = DCI.DAG;
8528 SDValue BasePtr = LD->getBasePtr();
8529 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8530 LD->getPointerInfo(), LD->isVolatile(),
8531 LD->isNonTemporal(), LD->isInvariant(),
8532 LD->getAlignment());
8534 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8535 DAG.getConstant(4, MVT::i32));
8536 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8537 LD->getPointerInfo(), LD->isVolatile(),
8538 LD->isNonTemporal(), LD->isInvariant(),
8539 std::min(4U, LD->getAlignment() / 2));
8541 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8542 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8543 DCI.RemoveFromWorklist(LD);
8551 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8552 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8553 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8554 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8555 SDValue Op0 = N->getOperand(0);
8556 SDValue Op1 = N->getOperand(1);
8557 if (Op0.getOpcode() == ISD::BITCAST)
8558 Op0 = Op0.getOperand(0);
8559 if (Op1.getOpcode() == ISD::BITCAST)
8560 Op1 = Op1.getOperand(0);
8561 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8562 Op0.getNode() == Op1.getNode() &&
8563 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8564 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8565 N->getValueType(0), Op0.getOperand(0));
8569 /// PerformSTORECombine - Target-specific dag combine xforms for
8571 static SDValue PerformSTORECombine(SDNode *N,
8572 TargetLowering::DAGCombinerInfo &DCI) {
8573 StoreSDNode *St = cast<StoreSDNode>(N);
8574 if (St->isVolatile())
8577 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8578 // pack all of the elements in one place. Next, store to memory in fewer
8580 SDValue StVal = St->getValue();
8581 EVT VT = StVal.getValueType();
8582 if (St->isTruncatingStore() && VT.isVector()) {
8583 SelectionDAG &DAG = DCI.DAG;
8584 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8585 EVT StVT = St->getMemoryVT();
8586 unsigned NumElems = VT.getVectorNumElements();
8587 assert(StVT != VT && "Cannot truncate to the same type");
8588 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8589 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8591 // From, To sizes and ElemCount must be pow of two
8592 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8594 // We are going to use the original vector elt for storing.
8595 // Accumulated smaller vector elements must be a multiple of the store size.
8596 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8598 unsigned SizeRatio = FromEltSz / ToEltSz;
8599 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8601 // Create a type on which we perform the shuffle.
8602 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8603 NumElems*SizeRatio);
8604 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8607 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8608 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8609 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8611 // Can't shuffle using an illegal type.
8612 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8614 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8615 DAG.getUNDEF(WideVec.getValueType()),
8617 // At this point all of the data is stored at the bottom of the
8618 // register. We now need to save it to mem.
8620 // Find the largest store unit
8621 MVT StoreType = MVT::i8;
8622 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8623 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8624 MVT Tp = (MVT::SimpleValueType)tp;
8625 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8628 // Didn't find a legal store type.
8629 if (!TLI.isTypeLegal(StoreType))
8632 // Bitcast the original vector into a vector of store-size units
8633 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8634 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8635 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8636 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8637 SmallVector<SDValue, 8> Chains;
8638 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8639 TLI.getPointerTy());
8640 SDValue BasePtr = St->getBasePtr();
8642 // Perform one or more big stores into memory.
8643 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8644 for (unsigned I = 0; I < E; I++) {
8645 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8646 StoreType, ShuffWide,
8647 DAG.getIntPtrConstant(I));
8648 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8649 St->getPointerInfo(), St->isVolatile(),
8650 St->isNonTemporal(), St->getAlignment());
8651 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8653 Chains.push_back(Ch);
8655 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8659 if (!ISD::isNormalStore(St))
8662 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8663 // ARM stores of arguments in the same cache line.
8664 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8665 StVal.getNode()->hasOneUse()) {
8666 SelectionDAG &DAG = DCI.DAG;
8668 SDValue BasePtr = St->getBasePtr();
8669 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8670 StVal.getNode()->getOperand(0), BasePtr,
8671 St->getPointerInfo(), St->isVolatile(),
8672 St->isNonTemporal(), St->getAlignment());
8674 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8675 DAG.getConstant(4, MVT::i32));
8676 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8677 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8678 St->isNonTemporal(),
8679 std::min(4U, St->getAlignment() / 2));
8682 if (StVal.getValueType() != MVT::i64 ||
8683 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8686 // Bitcast an i64 store extracted from a vector to f64.
8687 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8688 SelectionDAG &DAG = DCI.DAG;
8690 SDValue IntVec = StVal.getOperand(0);
8691 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8692 IntVec.getValueType().getVectorNumElements());
8693 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8694 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8695 Vec, StVal.getOperand(1));
8697 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8698 // Make the DAGCombiner fold the bitcasts.
8699 DCI.AddToWorklist(Vec.getNode());
8700 DCI.AddToWorklist(ExtElt.getNode());
8701 DCI.AddToWorklist(V.getNode());
8702 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8703 St->getPointerInfo(), St->isVolatile(),
8704 St->isNonTemporal(), St->getAlignment(),
8708 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8709 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8710 /// i64 vector to have f64 elements, since the value can then be loaded
8711 /// directly into a VFP register.
8712 static bool hasNormalLoadOperand(SDNode *N) {
8713 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8714 for (unsigned i = 0; i < NumElts; ++i) {
8715 SDNode *Elt = N->getOperand(i).getNode();
8716 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8722 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8723 /// ISD::BUILD_VECTOR.
8724 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8725 TargetLowering::DAGCombinerInfo &DCI){
8726 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8727 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8728 // into a pair of GPRs, which is fine when the value is used as a scalar,
8729 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8730 SelectionDAG &DAG = DCI.DAG;
8731 if (N->getNumOperands() == 2) {
8732 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8737 // Load i64 elements as f64 values so that type legalization does not split
8738 // them up into i32 values.
8739 EVT VT = N->getValueType(0);
8740 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8743 SmallVector<SDValue, 8> Ops;
8744 unsigned NumElts = VT.getVectorNumElements();
8745 for (unsigned i = 0; i < NumElts; ++i) {
8746 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8748 // Make the DAGCombiner fold the bitcast.
8749 DCI.AddToWorklist(V.getNode());
8751 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8752 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8753 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8756 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8757 /// ISD::INSERT_VECTOR_ELT.
8758 static SDValue PerformInsertEltCombine(SDNode *N,
8759 TargetLowering::DAGCombinerInfo &DCI) {
8760 // Bitcast an i64 load inserted into a vector to f64.
8761 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8762 EVT VT = N->getValueType(0);
8763 SDNode *Elt = N->getOperand(1).getNode();
8764 if (VT.getVectorElementType() != MVT::i64 ||
8765 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8768 SelectionDAG &DAG = DCI.DAG;
8770 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8771 VT.getVectorNumElements());
8772 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8773 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8774 // Make the DAGCombiner fold the bitcasts.
8775 DCI.AddToWorklist(Vec.getNode());
8776 DCI.AddToWorklist(V.getNode());
8777 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8778 Vec, V, N->getOperand(2));
8779 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8782 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8783 /// ISD::VECTOR_SHUFFLE.
8784 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8785 // The LLVM shufflevector instruction does not require the shuffle mask
8786 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8787 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8788 // operands do not match the mask length, they are extended by concatenating
8789 // them with undef vectors. That is probably the right thing for other
8790 // targets, but for NEON it is better to concatenate two double-register
8791 // size vector operands into a single quad-register size vector. Do that
8792 // transformation here:
8793 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8794 // shuffle(concat(v1, v2), undef)
8795 SDValue Op0 = N->getOperand(0);
8796 SDValue Op1 = N->getOperand(1);
8797 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8798 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8799 Op0.getNumOperands() != 2 ||
8800 Op1.getNumOperands() != 2)
8802 SDValue Concat0Op1 = Op0.getOperand(1);
8803 SDValue Concat1Op1 = Op1.getOperand(1);
8804 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8805 Concat1Op1.getOpcode() != ISD::UNDEF)
8807 // Skip the transformation if any of the types are illegal.
8808 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8809 EVT VT = N->getValueType(0);
8810 if (!TLI.isTypeLegal(VT) ||
8811 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8812 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8815 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8816 Op0.getOperand(0), Op1.getOperand(0));
8817 // Translate the shuffle mask.
8818 SmallVector<int, 16> NewMask;
8819 unsigned NumElts = VT.getVectorNumElements();
8820 unsigned HalfElts = NumElts/2;
8821 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8822 for (unsigned n = 0; n < NumElts; ++n) {
8823 int MaskElt = SVN->getMaskElt(n);
8825 if (MaskElt < (int)HalfElts)
8827 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8828 NewElt = HalfElts + MaskElt - NumElts;
8829 NewMask.push_back(NewElt);
8831 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8832 DAG.getUNDEF(VT), NewMask.data());
8835 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8836 /// NEON load/store intrinsics to merge base address updates.
8837 static SDValue CombineBaseUpdate(SDNode *N,
8838 TargetLowering::DAGCombinerInfo &DCI) {
8839 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8842 SelectionDAG &DAG = DCI.DAG;
8843 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8844 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8845 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8846 SDValue Addr = N->getOperand(AddrOpIdx);
8848 // Search for a use of the address operand that is an increment.
8849 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8850 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8852 if (User->getOpcode() != ISD::ADD ||
8853 UI.getUse().getResNo() != Addr.getResNo())
8856 // Check that the add is independent of the load/store. Otherwise, folding
8857 // it would create a cycle.
8858 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8861 // Find the new opcode for the updating load/store.
8863 bool isLaneOp = false;
8864 unsigned NewOpc = 0;
8865 unsigned NumVecs = 0;
8867 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8869 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8870 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8872 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8874 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8876 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8878 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8879 NumVecs = 2; isLaneOp = true; break;
8880 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8881 NumVecs = 3; isLaneOp = true; break;
8882 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8883 NumVecs = 4; isLaneOp = true; break;
8884 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8885 NumVecs = 1; isLoad = false; break;
8886 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8887 NumVecs = 2; isLoad = false; break;
8888 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8889 NumVecs = 3; isLoad = false; break;
8890 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8891 NumVecs = 4; isLoad = false; break;
8892 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8893 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8894 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8895 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8896 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8897 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8901 switch (N->getOpcode()) {
8902 default: llvm_unreachable("unexpected opcode for Neon base update");
8903 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8904 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8905 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8909 // Find the size of memory referenced by the load/store.
8912 VecTy = N->getValueType(0);
8914 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8915 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8917 NumBytes /= VecTy.getVectorNumElements();
8919 // If the increment is a constant, it must match the memory ref size.
8920 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8921 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8922 uint64_t IncVal = CInc->getZExtValue();
8923 if (IncVal != NumBytes)
8925 } else if (NumBytes >= 3 * 16) {
8926 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8927 // separate instructions that make it harder to use a non-constant update.
8931 // Create the new updating load/store node.
8933 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8935 for (n = 0; n < NumResultVecs; ++n)
8937 Tys[n++] = MVT::i32;
8938 Tys[n] = MVT::Other;
8939 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8940 SmallVector<SDValue, 8> Ops;
8941 Ops.push_back(N->getOperand(0)); // incoming chain
8942 Ops.push_back(N->getOperand(AddrOpIdx));
8944 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8945 Ops.push_back(N->getOperand(i));
8947 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8948 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8949 Ops.data(), Ops.size(),
8950 MemInt->getMemoryVT(),
8951 MemInt->getMemOperand());
8954 std::vector<SDValue> NewResults;
8955 for (unsigned i = 0; i < NumResultVecs; ++i) {
8956 NewResults.push_back(SDValue(UpdN.getNode(), i));
8958 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8959 DCI.CombineTo(N, NewResults);
8960 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8967 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8968 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8969 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8971 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8972 SelectionDAG &DAG = DCI.DAG;
8973 EVT VT = N->getValueType(0);
8974 // vldN-dup instructions only support 64-bit vectors for N > 1.
8975 if (!VT.is64BitVector())
8978 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8979 SDNode *VLD = N->getOperand(0).getNode();
8980 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8982 unsigned NumVecs = 0;
8983 unsigned NewOpc = 0;
8984 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8985 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8987 NewOpc = ARMISD::VLD2DUP;
8988 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8990 NewOpc = ARMISD::VLD3DUP;
8991 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8993 NewOpc = ARMISD::VLD4DUP;
8998 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8999 // numbers match the load.
9000 unsigned VLDLaneNo =
9001 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9002 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9004 // Ignore uses of the chain result.
9005 if (UI.getUse().getResNo() == NumVecs)
9008 if (User->getOpcode() != ARMISD::VDUPLANE ||
9009 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9013 // Create the vldN-dup node.
9016 for (n = 0; n < NumVecs; ++n)
9018 Tys[n] = MVT::Other;
9019 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9020 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9021 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9022 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9023 Ops, 2, VLDMemInt->getMemoryVT(),
9024 VLDMemInt->getMemOperand());
9027 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9029 unsigned ResNo = UI.getUse().getResNo();
9030 // Ignore uses of the chain result.
9031 if (ResNo == NumVecs)
9034 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9037 // Now the vldN-lane intrinsic is dead except for its chain result.
9038 // Update uses of the chain.
9039 std::vector<SDValue> VLDDupResults;
9040 for (unsigned n = 0; n < NumVecs; ++n)
9041 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9042 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9043 DCI.CombineTo(VLD, VLDDupResults);
9048 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9049 /// ARMISD::VDUPLANE.
9050 static SDValue PerformVDUPLANECombine(SDNode *N,
9051 TargetLowering::DAGCombinerInfo &DCI) {
9052 SDValue Op = N->getOperand(0);
9054 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9055 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9056 if (CombineVLDDUP(N, DCI))
9057 return SDValue(N, 0);
9059 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9060 // redundant. Ignore bit_converts for now; element sizes are checked below.
9061 while (Op.getOpcode() == ISD::BITCAST)
9062 Op = Op.getOperand(0);
9063 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9066 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9067 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9068 // The canonical VMOV for a zero vector uses a 32-bit element size.
9069 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9071 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9073 EVT VT = N->getValueType(0);
9074 if (EltSize > VT.getVectorElementType().getSizeInBits())
9077 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9080 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9081 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9082 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9086 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9088 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9093 APFloat APF = C->getValueAPF();
9094 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9095 != APFloat::opOK || !isExact)
9098 c0 = (I == 0) ? cN : c0;
9099 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9106 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9107 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9108 /// when the VMUL has a constant operand that is a power of 2.
9110 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9111 /// vmul.f32 d16, d17, d16
9112 /// vcvt.s32.f32 d16, d16
9114 /// vcvt.s32.f32 d16, d16, #3
9115 static SDValue PerformVCVTCombine(SDNode *N,
9116 TargetLowering::DAGCombinerInfo &DCI,
9117 const ARMSubtarget *Subtarget) {
9118 SelectionDAG &DAG = DCI.DAG;
9119 SDValue Op = N->getOperand(0);
9121 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9122 Op.getOpcode() != ISD::FMUL)
9126 SDValue N0 = Op->getOperand(0);
9127 SDValue ConstVec = Op->getOperand(1);
9128 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9130 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9131 !isConstVecPow2(ConstVec, isSigned, C))
9134 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9135 Intrinsic::arm_neon_vcvtfp2fxu;
9136 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9138 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9139 DAG.getConstant(Log2_64(C), MVT::i32));
9142 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9143 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9144 /// when the VDIV has a constant operand that is a power of 2.
9146 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9147 /// vcvt.f32.s32 d16, d16
9148 /// vdiv.f32 d16, d17, d16
9150 /// vcvt.f32.s32 d16, d16, #3
9151 static SDValue PerformVDIVCombine(SDNode *N,
9152 TargetLowering::DAGCombinerInfo &DCI,
9153 const ARMSubtarget *Subtarget) {
9154 SelectionDAG &DAG = DCI.DAG;
9155 SDValue Op = N->getOperand(0);
9156 unsigned OpOpcode = Op.getNode()->getOpcode();
9158 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9159 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9163 SDValue ConstVec = N->getOperand(1);
9164 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9166 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9167 !isConstVecPow2(ConstVec, isSigned, C))
9170 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9171 Intrinsic::arm_neon_vcvtfxu2fp;
9172 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9174 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9175 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
9178 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9179 /// operand of a vector shift operation, where all the elements of the
9180 /// build_vector must have the same constant integer value.
9181 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9182 // Ignore bit_converts.
9183 while (Op.getOpcode() == ISD::BITCAST)
9184 Op = Op.getOperand(0);
9185 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9186 APInt SplatBits, SplatUndef;
9187 unsigned SplatBitSize;
9189 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9190 HasAnyUndefs, ElementBits) ||
9191 SplatBitSize > ElementBits)
9193 Cnt = SplatBits.getSExtValue();
9197 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9198 /// operand of a vector shift left operation. That value must be in the range:
9199 /// 0 <= Value < ElementBits for a left shift; or
9200 /// 0 <= Value <= ElementBits for a long left shift.
9201 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9202 assert(VT.isVector() && "vector shift count is not a vector type");
9203 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9204 if (! getVShiftImm(Op, ElementBits, Cnt))
9206 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9209 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9210 /// operand of a vector shift right operation. For a shift opcode, the value
9211 /// is positive, but for an intrinsic the value count must be negative. The
9212 /// absolute value must be in the range:
9213 /// 1 <= |Value| <= ElementBits for a right shift; or
9214 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9215 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9217 assert(VT.isVector() && "vector shift count is not a vector type");
9218 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9219 if (! getVShiftImm(Op, ElementBits, Cnt))
9223 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9226 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9227 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9228 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9231 // Don't do anything for most intrinsics.
9234 // Vector shifts: check for immediate versions and lower them.
9235 // Note: This is done during DAG combining instead of DAG legalizing because
9236 // the build_vectors for 64-bit vector element shift counts are generally
9237 // not legal, and it is hard to see their values after they get legalized to
9238 // loads from a constant pool.
9239 case Intrinsic::arm_neon_vshifts:
9240 case Intrinsic::arm_neon_vshiftu:
9241 case Intrinsic::arm_neon_vshiftls:
9242 case Intrinsic::arm_neon_vshiftlu:
9243 case Intrinsic::arm_neon_vshiftn:
9244 case Intrinsic::arm_neon_vrshifts:
9245 case Intrinsic::arm_neon_vrshiftu:
9246 case Intrinsic::arm_neon_vrshiftn:
9247 case Intrinsic::arm_neon_vqshifts:
9248 case Intrinsic::arm_neon_vqshiftu:
9249 case Intrinsic::arm_neon_vqshiftsu:
9250 case Intrinsic::arm_neon_vqshiftns:
9251 case Intrinsic::arm_neon_vqshiftnu:
9252 case Intrinsic::arm_neon_vqshiftnsu:
9253 case Intrinsic::arm_neon_vqrshiftns:
9254 case Intrinsic::arm_neon_vqrshiftnu:
9255 case Intrinsic::arm_neon_vqrshiftnsu: {
9256 EVT VT = N->getOperand(1).getValueType();
9258 unsigned VShiftOpc = 0;
9261 case Intrinsic::arm_neon_vshifts:
9262 case Intrinsic::arm_neon_vshiftu:
9263 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9264 VShiftOpc = ARMISD::VSHL;
9267 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9268 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9269 ARMISD::VSHRs : ARMISD::VSHRu);
9274 case Intrinsic::arm_neon_vshiftls:
9275 case Intrinsic::arm_neon_vshiftlu:
9276 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9278 llvm_unreachable("invalid shift count for vshll intrinsic");
9280 case Intrinsic::arm_neon_vrshifts:
9281 case Intrinsic::arm_neon_vrshiftu:
9282 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9286 case Intrinsic::arm_neon_vqshifts:
9287 case Intrinsic::arm_neon_vqshiftu:
9288 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9292 case Intrinsic::arm_neon_vqshiftsu:
9293 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9295 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9297 case Intrinsic::arm_neon_vshiftn:
9298 case Intrinsic::arm_neon_vrshiftn:
9299 case Intrinsic::arm_neon_vqshiftns:
9300 case Intrinsic::arm_neon_vqshiftnu:
9301 case Intrinsic::arm_neon_vqshiftnsu:
9302 case Intrinsic::arm_neon_vqrshiftns:
9303 case Intrinsic::arm_neon_vqrshiftnu:
9304 case Intrinsic::arm_neon_vqrshiftnsu:
9305 // Narrowing shifts require an immediate right shift.
9306 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9308 llvm_unreachable("invalid shift count for narrowing vector shift "
9312 llvm_unreachable("unhandled vector shift");
9316 case Intrinsic::arm_neon_vshifts:
9317 case Intrinsic::arm_neon_vshiftu:
9318 // Opcode already set above.
9320 case Intrinsic::arm_neon_vshiftls:
9321 case Intrinsic::arm_neon_vshiftlu:
9322 if (Cnt == VT.getVectorElementType().getSizeInBits())
9323 VShiftOpc = ARMISD::VSHLLi;
9325 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9326 ARMISD::VSHLLs : ARMISD::VSHLLu);
9328 case Intrinsic::arm_neon_vshiftn:
9329 VShiftOpc = ARMISD::VSHRN; break;
9330 case Intrinsic::arm_neon_vrshifts:
9331 VShiftOpc = ARMISD::VRSHRs; break;
9332 case Intrinsic::arm_neon_vrshiftu:
9333 VShiftOpc = ARMISD::VRSHRu; break;
9334 case Intrinsic::arm_neon_vrshiftn:
9335 VShiftOpc = ARMISD::VRSHRN; break;
9336 case Intrinsic::arm_neon_vqshifts:
9337 VShiftOpc = ARMISD::VQSHLs; break;
9338 case Intrinsic::arm_neon_vqshiftu:
9339 VShiftOpc = ARMISD::VQSHLu; break;
9340 case Intrinsic::arm_neon_vqshiftsu:
9341 VShiftOpc = ARMISD::VQSHLsu; break;
9342 case Intrinsic::arm_neon_vqshiftns:
9343 VShiftOpc = ARMISD::VQSHRNs; break;
9344 case Intrinsic::arm_neon_vqshiftnu:
9345 VShiftOpc = ARMISD::VQSHRNu; break;
9346 case Intrinsic::arm_neon_vqshiftnsu:
9347 VShiftOpc = ARMISD::VQSHRNsu; break;
9348 case Intrinsic::arm_neon_vqrshiftns:
9349 VShiftOpc = ARMISD::VQRSHRNs; break;
9350 case Intrinsic::arm_neon_vqrshiftnu:
9351 VShiftOpc = ARMISD::VQRSHRNu; break;
9352 case Intrinsic::arm_neon_vqrshiftnsu:
9353 VShiftOpc = ARMISD::VQRSHRNsu; break;
9356 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9357 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9360 case Intrinsic::arm_neon_vshiftins: {
9361 EVT VT = N->getOperand(1).getValueType();
9363 unsigned VShiftOpc = 0;
9365 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9366 VShiftOpc = ARMISD::VSLI;
9367 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9368 VShiftOpc = ARMISD::VSRI;
9370 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9373 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9374 N->getOperand(1), N->getOperand(2),
9375 DAG.getConstant(Cnt, MVT::i32));
9378 case Intrinsic::arm_neon_vqrshifts:
9379 case Intrinsic::arm_neon_vqrshiftu:
9380 // No immediate versions of these to check for.
9387 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9388 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9389 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9390 /// vector element shift counts are generally not legal, and it is hard to see
9391 /// their values after they get legalized to loads from a constant pool.
9392 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9393 const ARMSubtarget *ST) {
9394 EVT VT = N->getValueType(0);
9395 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9396 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9397 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9398 SDValue N1 = N->getOperand(1);
9399 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9400 SDValue N0 = N->getOperand(0);
9401 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9402 DAG.MaskedValueIsZero(N0.getOperand(0),
9403 APInt::getHighBitsSet(32, 16)))
9404 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9408 // Nothing to be done for scalar shifts.
9409 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9410 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9413 assert(ST->hasNEON() && "unexpected vector shift");
9416 switch (N->getOpcode()) {
9417 default: llvm_unreachable("unexpected shift opcode");
9420 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9421 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9422 DAG.getConstant(Cnt, MVT::i32));
9427 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9428 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9429 ARMISD::VSHRs : ARMISD::VSHRu);
9430 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9431 DAG.getConstant(Cnt, MVT::i32));
9437 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9438 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9439 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9440 const ARMSubtarget *ST) {
9441 SDValue N0 = N->getOperand(0);
9443 // Check for sign- and zero-extensions of vector extract operations of 8-
9444 // and 16-bit vector elements. NEON supports these directly. They are
9445 // handled during DAG combining because type legalization will promote them
9446 // to 32-bit types and it is messy to recognize the operations after that.
9447 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9448 SDValue Vec = N0.getOperand(0);
9449 SDValue Lane = N0.getOperand(1);
9450 EVT VT = N->getValueType(0);
9451 EVT EltVT = N0.getValueType();
9452 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9454 if (VT == MVT::i32 &&
9455 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9456 TLI.isTypeLegal(Vec.getValueType()) &&
9457 isa<ConstantSDNode>(Lane)) {
9460 switch (N->getOpcode()) {
9461 default: llvm_unreachable("unexpected opcode");
9462 case ISD::SIGN_EXTEND:
9463 Opc = ARMISD::VGETLANEs;
9465 case ISD::ZERO_EXTEND:
9466 case ISD::ANY_EXTEND:
9467 Opc = ARMISD::VGETLANEu;
9470 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9477 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9478 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9479 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9480 const ARMSubtarget *ST) {
9481 // If the target supports NEON, try to use vmax/vmin instructions for f32
9482 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9483 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9484 // a NaN; only do the transformation when it matches that behavior.
9486 // For now only do this when using NEON for FP operations; if using VFP, it
9487 // is not obvious that the benefit outweighs the cost of switching to the
9489 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9490 N->getValueType(0) != MVT::f32)
9493 SDValue CondLHS = N->getOperand(0);
9494 SDValue CondRHS = N->getOperand(1);
9495 SDValue LHS = N->getOperand(2);
9496 SDValue RHS = N->getOperand(3);
9497 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9499 unsigned Opcode = 0;
9501 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9502 IsReversed = false; // x CC y ? x : y
9503 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9504 IsReversed = true ; // x CC y ? y : x
9518 // If LHS is NaN, an ordered comparison will be false and the result will
9519 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9520 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9521 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9522 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9524 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9525 // will return -0, so vmin can only be used for unsafe math or if one of
9526 // the operands is known to be nonzero.
9527 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9528 !DAG.getTarget().Options.UnsafeFPMath &&
9529 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9531 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9540 // If LHS is NaN, an ordered comparison will be false and the result will
9541 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9542 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9543 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9544 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9546 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9547 // will return +0, so vmax can only be used for unsafe math or if one of
9548 // the operands is known to be nonzero.
9549 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9550 !DAG.getTarget().Options.UnsafeFPMath &&
9551 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9553 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9559 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9562 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9564 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9565 SDValue Cmp = N->getOperand(4);
9566 if (Cmp.getOpcode() != ARMISD::CMPZ)
9567 // Only looking at EQ and NE cases.
9570 EVT VT = N->getValueType(0);
9572 SDValue LHS = Cmp.getOperand(0);
9573 SDValue RHS = Cmp.getOperand(1);
9574 SDValue FalseVal = N->getOperand(0);
9575 SDValue TrueVal = N->getOperand(1);
9576 SDValue ARMcc = N->getOperand(2);
9577 ARMCC::CondCodes CC =
9578 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9596 /// FIXME: Turn this into a target neutral optimization?
9598 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9599 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9600 N->getOperand(3), Cmp);
9601 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9603 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9604 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9605 N->getOperand(3), NewCmp);
9608 if (Res.getNode()) {
9609 APInt KnownZero, KnownOne;
9610 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9611 // Capture demanded bits information that would be otherwise lost.
9612 if (KnownZero == 0xfffffffe)
9613 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9614 DAG.getValueType(MVT::i1));
9615 else if (KnownZero == 0xffffff00)
9616 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9617 DAG.getValueType(MVT::i8));
9618 else if (KnownZero == 0xffff0000)
9619 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9620 DAG.getValueType(MVT::i16));
9626 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9627 DAGCombinerInfo &DCI) const {
9628 switch (N->getOpcode()) {
9630 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9631 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9632 case ISD::SUB: return PerformSUBCombine(N, DCI);
9633 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9634 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9635 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9636 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9637 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9638 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9639 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9640 case ISD::STORE: return PerformSTORECombine(N, DCI);
9641 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9642 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9643 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9644 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9645 case ISD::FP_TO_SINT:
9646 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9647 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9648 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9651 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9652 case ISD::SIGN_EXTEND:
9653 case ISD::ZERO_EXTEND:
9654 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9655 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9656 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9657 case ARMISD::VLD2DUP:
9658 case ARMISD::VLD3DUP:
9659 case ARMISD::VLD4DUP:
9660 return CombineBaseUpdate(N, DCI);
9661 case ISD::INTRINSIC_VOID:
9662 case ISD::INTRINSIC_W_CHAIN:
9663 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9664 case Intrinsic::arm_neon_vld1:
9665 case Intrinsic::arm_neon_vld2:
9666 case Intrinsic::arm_neon_vld3:
9667 case Intrinsic::arm_neon_vld4:
9668 case Intrinsic::arm_neon_vld2lane:
9669 case Intrinsic::arm_neon_vld3lane:
9670 case Intrinsic::arm_neon_vld4lane:
9671 case Intrinsic::arm_neon_vst1:
9672 case Intrinsic::arm_neon_vst2:
9673 case Intrinsic::arm_neon_vst3:
9674 case Intrinsic::arm_neon_vst4:
9675 case Intrinsic::arm_neon_vst2lane:
9676 case Intrinsic::arm_neon_vst3lane:
9677 case Intrinsic::arm_neon_vst4lane:
9678 return CombineBaseUpdate(N, DCI);
9686 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9688 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9691 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9692 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9693 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9695 switch (VT.getSimpleVT().SimpleTy) {
9701 // Unaligned access can use (for example) LRDB, LRDH, LDR
9702 if (AllowsUnaligned) {
9704 *Fast = Subtarget->hasV7Ops();
9711 // For any little-endian targets with neon, we can support unaligned ld/st
9712 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9713 // A big-endian target may also explictly support unaligned accesses
9714 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9724 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9725 unsigned AlignCheck) {
9726 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9727 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9730 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9731 unsigned DstAlign, unsigned SrcAlign,
9732 bool IsMemset, bool ZeroMemset,
9734 MachineFunction &MF) const {
9735 const Function *F = MF.getFunction();
9737 // See if we can use NEON instructions for this...
9738 if ((!IsMemset || ZeroMemset) &&
9739 Subtarget->hasNEON() &&
9740 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9741 Attribute::NoImplicitFloat)) {
9744 (memOpAlign(SrcAlign, DstAlign, 16) ||
9745 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9747 } else if (Size >= 8 &&
9748 (memOpAlign(SrcAlign, DstAlign, 8) ||
9749 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9754 // Lowering to i32/i16 if the size permits.
9760 // Let the target-independent logic figure it out.
9764 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9765 if (Val.getOpcode() != ISD::LOAD)
9768 EVT VT1 = Val.getValueType();
9769 if (!VT1.isSimple() || !VT1.isInteger() ||
9770 !VT2.isSimple() || !VT2.isInteger())
9773 switch (VT1.getSimpleVT().SimpleTy) {
9778 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9785 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9790 switch (VT.getSimpleVT().SimpleTy) {
9791 default: return false;
9806 if ((V & (Scale - 1)) != 0)
9809 return V == (V & ((1LL << 5) - 1));
9812 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9813 const ARMSubtarget *Subtarget) {
9820 switch (VT.getSimpleVT().SimpleTy) {
9821 default: return false;
9826 // + imm12 or - imm8
9828 return V == (V & ((1LL << 8) - 1));
9829 return V == (V & ((1LL << 12) - 1));
9832 // Same as ARM mode. FIXME: NEON?
9833 if (!Subtarget->hasVFP2())
9838 return V == (V & ((1LL << 8) - 1));
9842 /// isLegalAddressImmediate - Return true if the integer value can be used
9843 /// as the offset of the target addressing mode for load / store of the
9845 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9846 const ARMSubtarget *Subtarget) {
9853 if (Subtarget->isThumb1Only())
9854 return isLegalT1AddressImmediate(V, VT);
9855 else if (Subtarget->isThumb2())
9856 return isLegalT2AddressImmediate(V, VT, Subtarget);
9861 switch (VT.getSimpleVT().SimpleTy) {
9862 default: return false;
9867 return V == (V & ((1LL << 12) - 1));
9870 return V == (V & ((1LL << 8) - 1));
9873 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9878 return V == (V & ((1LL << 8) - 1));
9882 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9884 int Scale = AM.Scale;
9888 switch (VT.getSimpleVT().SimpleTy) {
9889 default: return false;
9898 return Scale == 2 || Scale == 4 || Scale == 8;
9901 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9905 // Note, we allow "void" uses (basically, uses that aren't loads or
9906 // stores), because arm allows folding a scale into many arithmetic
9907 // operations. This should be made more precise and revisited later.
9909 // Allow r << imm, but the imm has to be a multiple of two.
9910 if (Scale & 1) return false;
9911 return isPowerOf2_32(Scale);
9915 /// isLegalAddressingMode - Return true if the addressing mode represented
9916 /// by AM is legal for this target, for a load/store of the specified type.
9917 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9919 EVT VT = getValueType(Ty, true);
9920 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9923 // Can never fold addr of global into load/store.
9928 case 0: // no scale reg, must be "r+i" or "r", or "i".
9931 if (Subtarget->isThumb1Only())
9935 // ARM doesn't support any R+R*scale+imm addr modes.
9942 if (Subtarget->isThumb2())
9943 return isLegalT2ScaledAddressingMode(AM, VT);
9945 int Scale = AM.Scale;
9946 switch (VT.getSimpleVT().SimpleTy) {
9947 default: return false;
9951 if (Scale < 0) Scale = -Scale;
9955 return isPowerOf2_32(Scale & ~1);
9959 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9964 // Note, we allow "void" uses (basically, uses that aren't loads or
9965 // stores), because arm allows folding a scale into many arithmetic
9966 // operations. This should be made more precise and revisited later.
9968 // Allow r << imm, but the imm has to be a multiple of two.
9969 if (Scale & 1) return false;
9970 return isPowerOf2_32(Scale);
9976 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9977 /// icmp immediate, that is the target has icmp instructions which can compare
9978 /// a register against the immediate without having to materialize the
9979 /// immediate into a register.
9980 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9981 // Thumb2 and ARM modes can use cmn for negative immediates.
9982 if (!Subtarget->isThumb())
9983 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9984 if (Subtarget->isThumb2())
9985 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9986 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9987 return Imm >= 0 && Imm <= 255;
9990 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9991 /// *or sub* immediate, that is the target has add or sub instructions which can
9992 /// add a register with the immediate without having to materialize the
9993 /// immediate into a register.
9994 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9995 // Same encoding for add/sub, just flip the sign.
9996 int64_t AbsImm = llvm::abs64(Imm);
9997 if (!Subtarget->isThumb())
9998 return ARM_AM::getSOImmVal(AbsImm) != -1;
9999 if (Subtarget->isThumb2())
10000 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10001 // Thumb1 only has 8-bit unsigned immediate.
10002 return AbsImm >= 0 && AbsImm <= 255;
10005 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10006 bool isSEXTLoad, SDValue &Base,
10007 SDValue &Offset, bool &isInc,
10008 SelectionDAG &DAG) {
10009 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10012 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10013 // AddressingMode 3
10014 Base = Ptr->getOperand(0);
10015 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10016 int RHSC = (int)RHS->getZExtValue();
10017 if (RHSC < 0 && RHSC > -256) {
10018 assert(Ptr->getOpcode() == ISD::ADD);
10020 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10024 isInc = (Ptr->getOpcode() == ISD::ADD);
10025 Offset = Ptr->getOperand(1);
10027 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10028 // AddressingMode 2
10029 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10030 int RHSC = (int)RHS->getZExtValue();
10031 if (RHSC < 0 && RHSC > -0x1000) {
10032 assert(Ptr->getOpcode() == ISD::ADD);
10034 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10035 Base = Ptr->getOperand(0);
10040 if (Ptr->getOpcode() == ISD::ADD) {
10042 ARM_AM::ShiftOpc ShOpcVal=
10043 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10044 if (ShOpcVal != ARM_AM::no_shift) {
10045 Base = Ptr->getOperand(1);
10046 Offset = Ptr->getOperand(0);
10048 Base = Ptr->getOperand(0);
10049 Offset = Ptr->getOperand(1);
10054 isInc = (Ptr->getOpcode() == ISD::ADD);
10055 Base = Ptr->getOperand(0);
10056 Offset = Ptr->getOperand(1);
10060 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10064 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10065 bool isSEXTLoad, SDValue &Base,
10066 SDValue &Offset, bool &isInc,
10067 SelectionDAG &DAG) {
10068 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10071 Base = Ptr->getOperand(0);
10072 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10073 int RHSC = (int)RHS->getZExtValue();
10074 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10075 assert(Ptr->getOpcode() == ISD::ADD);
10077 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10079 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10080 isInc = Ptr->getOpcode() == ISD::ADD;
10081 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10089 /// getPreIndexedAddressParts - returns true by value, base pointer and
10090 /// offset pointer and addressing mode by reference if the node's address
10091 /// can be legally represented as pre-indexed load / store address.
10093 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10095 ISD::MemIndexedMode &AM,
10096 SelectionDAG &DAG) const {
10097 if (Subtarget->isThumb1Only())
10102 bool isSEXTLoad = false;
10103 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10104 Ptr = LD->getBasePtr();
10105 VT = LD->getMemoryVT();
10106 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10107 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10108 Ptr = ST->getBasePtr();
10109 VT = ST->getMemoryVT();
10114 bool isLegal = false;
10115 if (Subtarget->isThumb2())
10116 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10117 Offset, isInc, DAG);
10119 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10120 Offset, isInc, DAG);
10124 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10128 /// getPostIndexedAddressParts - returns true by value, base pointer and
10129 /// offset pointer and addressing mode by reference if this node can be
10130 /// combined with a load / store to form a post-indexed load / store.
10131 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10134 ISD::MemIndexedMode &AM,
10135 SelectionDAG &DAG) const {
10136 if (Subtarget->isThumb1Only())
10141 bool isSEXTLoad = false;
10142 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10143 VT = LD->getMemoryVT();
10144 Ptr = LD->getBasePtr();
10145 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10146 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10147 VT = ST->getMemoryVT();
10148 Ptr = ST->getBasePtr();
10153 bool isLegal = false;
10154 if (Subtarget->isThumb2())
10155 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10158 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10164 // Swap base ptr and offset to catch more post-index load / store when
10165 // it's legal. In Thumb2 mode, offset must be an immediate.
10166 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10167 !Subtarget->isThumb2())
10168 std::swap(Base, Offset);
10170 // Post-indexed load / store update the base pointer.
10175 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10179 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10182 const SelectionDAG &DAG,
10183 unsigned Depth) const {
10184 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
10185 switch (Op.getOpcode()) {
10187 case ARMISD::CMOV: {
10188 // Bits are known zero/one if known on the LHS and RHS.
10189 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10190 if (KnownZero == 0 && KnownOne == 0) return;
10192 APInt KnownZeroRHS, KnownOneRHS;
10193 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10194 KnownZero &= KnownZeroRHS;
10195 KnownOne &= KnownOneRHS;
10201 //===----------------------------------------------------------------------===//
10202 // ARM Inline Assembly Support
10203 //===----------------------------------------------------------------------===//
10205 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10206 // Looking for "rev" which is V6+.
10207 if (!Subtarget->hasV6Ops())
10210 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10211 std::string AsmStr = IA->getAsmString();
10212 SmallVector<StringRef, 4> AsmPieces;
10213 SplitString(AsmStr, AsmPieces, ";\n");
10215 switch (AsmPieces.size()) {
10216 default: return false;
10218 AsmStr = AsmPieces[0];
10220 SplitString(AsmStr, AsmPieces, " \t,");
10223 if (AsmPieces.size() == 3 &&
10224 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10225 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10226 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10227 if (Ty && Ty->getBitWidth() == 32)
10228 return IntrinsicLowering::LowerToByteSwap(CI);
10236 /// getConstraintType - Given a constraint letter, return the type of
10237 /// constraint it is for this target.
10238 ARMTargetLowering::ConstraintType
10239 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10240 if (Constraint.size() == 1) {
10241 switch (Constraint[0]) {
10243 case 'l': return C_RegisterClass;
10244 case 'w': return C_RegisterClass;
10245 case 'h': return C_RegisterClass;
10246 case 'x': return C_RegisterClass;
10247 case 't': return C_RegisterClass;
10248 case 'j': return C_Other; // Constant for movw.
10249 // An address with a single base register. Due to the way we
10250 // currently handle addresses it is the same as an 'r' memory constraint.
10251 case 'Q': return C_Memory;
10253 } else if (Constraint.size() == 2) {
10254 switch (Constraint[0]) {
10256 // All 'U+' constraints are addresses.
10257 case 'U': return C_Memory;
10260 return TargetLowering::getConstraintType(Constraint);
10263 /// Examine constraint type and operand type and determine a weight value.
10264 /// This object must already have been set up with the operand type
10265 /// and the current alternative constraint selected.
10266 TargetLowering::ConstraintWeight
10267 ARMTargetLowering::getSingleConstraintMatchWeight(
10268 AsmOperandInfo &info, const char *constraint) const {
10269 ConstraintWeight weight = CW_Invalid;
10270 Value *CallOperandVal = info.CallOperandVal;
10271 // If we don't have a value, we can't do a match,
10272 // but allow it at the lowest weight.
10273 if (CallOperandVal == NULL)
10275 Type *type = CallOperandVal->getType();
10276 // Look at the constraint type.
10277 switch (*constraint) {
10279 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10282 if (type->isIntegerTy()) {
10283 if (Subtarget->isThumb())
10284 weight = CW_SpecificReg;
10286 weight = CW_Register;
10290 if (type->isFloatingPointTy())
10291 weight = CW_Register;
10297 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10299 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10301 if (Constraint.size() == 1) {
10302 // GCC ARM Constraint Letters
10303 switch (Constraint[0]) {
10304 case 'l': // Low regs or general regs.
10305 if (Subtarget->isThumb())
10306 return RCPair(0U, &ARM::tGPRRegClass);
10307 return RCPair(0U, &ARM::GPRRegClass);
10308 case 'h': // High regs or no regs.
10309 if (Subtarget->isThumb())
10310 return RCPair(0U, &ARM::hGPRRegClass);
10313 return RCPair(0U, &ARM::GPRRegClass);
10315 if (VT == MVT::f32)
10316 return RCPair(0U, &ARM::SPRRegClass);
10317 if (VT.getSizeInBits() == 64)
10318 return RCPair(0U, &ARM::DPRRegClass);
10319 if (VT.getSizeInBits() == 128)
10320 return RCPair(0U, &ARM::QPRRegClass);
10323 if (VT == MVT::f32)
10324 return RCPair(0U, &ARM::SPR_8RegClass);
10325 if (VT.getSizeInBits() == 64)
10326 return RCPair(0U, &ARM::DPR_8RegClass);
10327 if (VT.getSizeInBits() == 128)
10328 return RCPair(0U, &ARM::QPR_8RegClass);
10331 if (VT == MVT::f32)
10332 return RCPair(0U, &ARM::SPRRegClass);
10336 if (StringRef("{cc}").equals_lower(Constraint))
10337 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10339 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10342 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10343 /// vector. If it is invalid, don't add anything to Ops.
10344 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10345 std::string &Constraint,
10346 std::vector<SDValue>&Ops,
10347 SelectionDAG &DAG) const {
10348 SDValue Result(0, 0);
10350 // Currently only support length 1 constraints.
10351 if (Constraint.length() != 1) return;
10353 char ConstraintLetter = Constraint[0];
10354 switch (ConstraintLetter) {
10357 case 'I': case 'J': case 'K': case 'L':
10358 case 'M': case 'N': case 'O':
10359 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10363 int64_t CVal64 = C->getSExtValue();
10364 int CVal = (int) CVal64;
10365 // None of these constraints allow values larger than 32 bits. Check
10366 // that the value fits in an int.
10367 if (CVal != CVal64)
10370 switch (ConstraintLetter) {
10372 // Constant suitable for movw, must be between 0 and
10374 if (Subtarget->hasV6T2Ops())
10375 if (CVal >= 0 && CVal <= 65535)
10379 if (Subtarget->isThumb1Only()) {
10380 // This must be a constant between 0 and 255, for ADD
10382 if (CVal >= 0 && CVal <= 255)
10384 } else if (Subtarget->isThumb2()) {
10385 // A constant that can be used as an immediate value in a
10386 // data-processing instruction.
10387 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10390 // A constant that can be used as an immediate value in a
10391 // data-processing instruction.
10392 if (ARM_AM::getSOImmVal(CVal) != -1)
10398 if (Subtarget->isThumb()) { // FIXME thumb2
10399 // This must be a constant between -255 and -1, for negated ADD
10400 // immediates. This can be used in GCC with an "n" modifier that
10401 // prints the negated value, for use with SUB instructions. It is
10402 // not useful otherwise but is implemented for compatibility.
10403 if (CVal >= -255 && CVal <= -1)
10406 // This must be a constant between -4095 and 4095. It is not clear
10407 // what this constraint is intended for. Implemented for
10408 // compatibility with GCC.
10409 if (CVal >= -4095 && CVal <= 4095)
10415 if (Subtarget->isThumb1Only()) {
10416 // A 32-bit value where only one byte has a nonzero value. Exclude
10417 // zero to match GCC. This constraint is used by GCC internally for
10418 // constants that can be loaded with a move/shift combination.
10419 // It is not useful otherwise but is implemented for compatibility.
10420 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10422 } else if (Subtarget->isThumb2()) {
10423 // A constant whose bitwise inverse can be used as an immediate
10424 // value in a data-processing instruction. This can be used in GCC
10425 // with a "B" modifier that prints the inverted value, for use with
10426 // BIC and MVN instructions. It is not useful otherwise but is
10427 // implemented for compatibility.
10428 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10431 // A constant whose bitwise inverse can be used as an immediate
10432 // value in a data-processing instruction. This can be used in GCC
10433 // with a "B" modifier that prints the inverted value, for use with
10434 // BIC and MVN instructions. It is not useful otherwise but is
10435 // implemented for compatibility.
10436 if (ARM_AM::getSOImmVal(~CVal) != -1)
10442 if (Subtarget->isThumb1Only()) {
10443 // This must be a constant between -7 and 7,
10444 // for 3-operand ADD/SUB immediate instructions.
10445 if (CVal >= -7 && CVal < 7)
10447 } else if (Subtarget->isThumb2()) {
10448 // A constant whose negation can be used as an immediate value in a
10449 // data-processing instruction. This can be used in GCC with an "n"
10450 // modifier that prints the negated value, for use with SUB
10451 // instructions. It is not useful otherwise but is implemented for
10453 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10456 // A constant whose negation can be used as an immediate value in a
10457 // data-processing instruction. This can be used in GCC with an "n"
10458 // modifier that prints the negated value, for use with SUB
10459 // instructions. It is not useful otherwise but is implemented for
10461 if (ARM_AM::getSOImmVal(-CVal) != -1)
10467 if (Subtarget->isThumb()) { // FIXME thumb2
10468 // This must be a multiple of 4 between 0 and 1020, for
10469 // ADD sp + immediate.
10470 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10473 // A power of two or a constant between 0 and 32. This is used in
10474 // GCC for the shift amount on shifted register operands, but it is
10475 // useful in general for any shift amounts.
10476 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10482 if (Subtarget->isThumb()) { // FIXME thumb2
10483 // This must be a constant between 0 and 31, for shift amounts.
10484 if (CVal >= 0 && CVal <= 31)
10490 if (Subtarget->isThumb()) { // FIXME thumb2
10491 // This must be a multiple of 4 between -508 and 508, for
10492 // ADD/SUB sp = sp + immediate.
10493 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10498 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10502 if (Result.getNode()) {
10503 Ops.push_back(Result);
10506 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10510 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10511 // The ARM target isn't yet aware of offsets.
10515 bool ARM::isBitFieldInvertedMask(unsigned v) {
10516 if (v == 0xffffffff)
10519 // there can be 1's on either or both "outsides", all the "inside"
10520 // bits must be 0's
10521 unsigned TO = CountTrailingOnes_32(v);
10522 unsigned LO = CountLeadingOnes_32(v);
10523 v = (v >> TO) << TO;
10524 v = (v << LO) >> LO;
10528 /// isFPImmLegal - Returns true if the target can instruction select the
10529 /// specified FP immediate natively. If false, the legalizer will
10530 /// materialize the FP immediate as a load from a constant pool.
10531 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10532 if (!Subtarget->hasVFP3())
10534 if (VT == MVT::f32)
10535 return ARM_AM::getFP32Imm(Imm) != -1;
10536 if (VT == MVT::f64)
10537 return ARM_AM::getFP64Imm(Imm) != -1;
10541 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10542 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10543 /// specified in the intrinsic calls.
10544 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10546 unsigned Intrinsic) const {
10547 switch (Intrinsic) {
10548 case Intrinsic::arm_neon_vld1:
10549 case Intrinsic::arm_neon_vld2:
10550 case Intrinsic::arm_neon_vld3:
10551 case Intrinsic::arm_neon_vld4:
10552 case Intrinsic::arm_neon_vld2lane:
10553 case Intrinsic::arm_neon_vld3lane:
10554 case Intrinsic::arm_neon_vld4lane: {
10555 Info.opc = ISD::INTRINSIC_W_CHAIN;
10556 // Conservatively set memVT to the entire set of vectors loaded.
10557 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10558 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10559 Info.ptrVal = I.getArgOperand(0);
10561 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10562 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10563 Info.vol = false; // volatile loads with NEON intrinsics not supported
10564 Info.readMem = true;
10565 Info.writeMem = false;
10568 case Intrinsic::arm_neon_vst1:
10569 case Intrinsic::arm_neon_vst2:
10570 case Intrinsic::arm_neon_vst3:
10571 case Intrinsic::arm_neon_vst4:
10572 case Intrinsic::arm_neon_vst2lane:
10573 case Intrinsic::arm_neon_vst3lane:
10574 case Intrinsic::arm_neon_vst4lane: {
10575 Info.opc = ISD::INTRINSIC_VOID;
10576 // Conservatively set memVT to the entire set of vectors stored.
10577 unsigned NumElts = 0;
10578 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10579 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10580 if (!ArgTy->isVectorTy())
10582 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10584 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10585 Info.ptrVal = I.getArgOperand(0);
10587 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10588 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10589 Info.vol = false; // volatile stores with NEON intrinsics not supported
10590 Info.readMem = false;
10591 Info.writeMem = true;
10594 case Intrinsic::arm_strexd: {
10595 Info.opc = ISD::INTRINSIC_W_CHAIN;
10596 Info.memVT = MVT::i64;
10597 Info.ptrVal = I.getArgOperand(2);
10601 Info.readMem = false;
10602 Info.writeMem = true;
10605 case Intrinsic::arm_ldrexd: {
10606 Info.opc = ISD::INTRINSIC_W_CHAIN;
10607 Info.memVT = MVT::i64;
10608 Info.ptrVal = I.getArgOperand(0);
10612 Info.readMem = true;
10613 Info.writeMem = false;