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 // Only ARMv6 has BSWAP.
685 if (!Subtarget->hasV6Ops())
686 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
688 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
689 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
690 // These are expanded into libcalls if the cpu doesn't have HW divider.
691 setOperationAction(ISD::SDIV, MVT::i32, Expand);
692 setOperationAction(ISD::UDIV, MVT::i32, Expand);
694 setOperationAction(ISD::SREM, MVT::i32, Expand);
695 setOperationAction(ISD::UREM, MVT::i32, Expand);
696 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
697 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
699 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
700 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
701 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
702 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
703 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
705 setOperationAction(ISD::TRAP, MVT::Other, Legal);
707 // Use the default implementation.
708 setOperationAction(ISD::VASTART, MVT::Other, Custom);
709 setOperationAction(ISD::VAARG, MVT::Other, Expand);
710 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
711 setOperationAction(ISD::VAEND, MVT::Other, Expand);
712 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
713 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
715 if (!Subtarget->isTargetDarwin()) {
716 // Non-Darwin platforms may return values in these registers via the
717 // personality function.
718 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
719 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
720 setExceptionPointerRegister(ARM::R0);
721 setExceptionSelectorRegister(ARM::R1);
724 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
725 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
726 // the default expansion.
727 // FIXME: This should be checking for v6k, not just v6.
728 if (Subtarget->hasDataBarrier() ||
729 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
730 // membarrier needs custom lowering; the rest are legal and handled
732 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
733 // Custom lowering for 64-bit ops
734 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
735 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
736 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
737 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
738 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
739 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
740 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
741 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
742 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
743 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
744 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
745 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
746 setInsertFencesForAtomic(true);
748 // Set them all for expansion, which will force libcalls.
749 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
750 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
751 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
752 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
753 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
754 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
755 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
756 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
757 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
758 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
759 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
760 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
761 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
762 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
763 // Unordered/Monotonic case.
764 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
765 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
768 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
770 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
771 if (!Subtarget->hasV6Ops()) {
772 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
773 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
775 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
777 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
778 !Subtarget->isThumb1Only()) {
779 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
780 // iff target supports vfp2.
781 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
782 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
785 // We want to custom lower some of our intrinsics.
786 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
787 if (Subtarget->isTargetDarwin()) {
788 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
789 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
790 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
793 setOperationAction(ISD::SETCC, MVT::i32, Expand);
794 setOperationAction(ISD::SETCC, MVT::f32, Expand);
795 setOperationAction(ISD::SETCC, MVT::f64, Expand);
796 setOperationAction(ISD::SELECT, MVT::i32, Custom);
797 setOperationAction(ISD::SELECT, MVT::f32, Custom);
798 setOperationAction(ISD::SELECT, MVT::f64, Custom);
799 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
800 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
801 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
803 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
804 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
805 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
806 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
807 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
809 // We don't support sin/cos/fmod/copysign/pow
810 setOperationAction(ISD::FSIN, MVT::f64, Expand);
811 setOperationAction(ISD::FSIN, MVT::f32, Expand);
812 setOperationAction(ISD::FCOS, MVT::f32, Expand);
813 setOperationAction(ISD::FCOS, MVT::f64, Expand);
814 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
815 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
816 setOperationAction(ISD::FREM, MVT::f64, Expand);
817 setOperationAction(ISD::FREM, MVT::f32, Expand);
818 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
819 !Subtarget->isThumb1Only()) {
820 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
821 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
823 setOperationAction(ISD::FPOW, MVT::f64, Expand);
824 setOperationAction(ISD::FPOW, MVT::f32, Expand);
826 if (!Subtarget->hasVFP4()) {
827 setOperationAction(ISD::FMA, MVT::f64, Expand);
828 setOperationAction(ISD::FMA, MVT::f32, Expand);
831 // Various VFP goodness
832 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
833 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
834 if (Subtarget->hasVFP2()) {
835 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
836 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
837 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
838 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
840 // Special handling for half-precision FP.
841 if (!Subtarget->hasFP16()) {
842 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
843 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
847 // We have target-specific dag combine patterns for the following nodes:
848 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
849 setTargetDAGCombine(ISD::ADD);
850 setTargetDAGCombine(ISD::SUB);
851 setTargetDAGCombine(ISD::MUL);
852 setTargetDAGCombine(ISD::AND);
853 setTargetDAGCombine(ISD::OR);
854 setTargetDAGCombine(ISD::XOR);
856 if (Subtarget->hasV6Ops())
857 setTargetDAGCombine(ISD::SRL);
859 setStackPointerRegisterToSaveRestore(ARM::SP);
861 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
862 !Subtarget->hasVFP2())
863 setSchedulingPreference(Sched::RegPressure);
865 setSchedulingPreference(Sched::Hybrid);
867 //// temporary - rewrite interface to use type
868 MaxStoresPerMemset = 8;
869 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
870 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
871 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
872 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
873 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
875 // On ARM arguments smaller than 4 bytes are extended, so all arguments
876 // are at least 4 bytes aligned.
877 setMinStackArgumentAlignment(4);
879 // Prefer likely predicted branches to selects on out-of-order cores.
880 PredictableSelectIsExpensive = Subtarget->isLikeA9();
882 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
885 // FIXME: It might make sense to define the representative register class as the
886 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
887 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
888 // SPR's representative would be DPR_VFP2. This should work well if register
889 // pressure tracking were modified such that a register use would increment the
890 // pressure of the register class's representative and all of it's super
891 // classes' representatives transitively. We have not implemented this because
892 // of the difficulty prior to coalescing of modeling operand register classes
893 // due to the common occurrence of cross class copies and subregister insertions
895 std::pair<const TargetRegisterClass*, uint8_t>
896 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
897 const TargetRegisterClass *RRC = 0;
899 switch (VT.SimpleTy) {
901 return TargetLowering::findRepresentativeClass(VT);
902 // Use DPR as representative register class for all floating point
903 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
904 // the cost is 1 for both f32 and f64.
905 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
906 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
907 RRC = &ARM::DPRRegClass;
908 // When NEON is used for SP, only half of the register file is available
909 // because operations that define both SP and DP results will be constrained
910 // to the VFP2 class (D0-D15). We currently model this constraint prior to
911 // coalescing by double-counting the SP regs. See the FIXME above.
912 if (Subtarget->useNEONForSinglePrecisionFP())
915 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
916 case MVT::v4f32: case MVT::v2f64:
917 RRC = &ARM::DPRRegClass;
921 RRC = &ARM::DPRRegClass;
925 RRC = &ARM::DPRRegClass;
929 return std::make_pair(RRC, Cost);
932 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
935 case ARMISD::Wrapper: return "ARMISD::Wrapper";
936 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
937 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
938 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
939 case ARMISD::CALL: return "ARMISD::CALL";
940 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
941 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
942 case ARMISD::tCALL: return "ARMISD::tCALL";
943 case ARMISD::BRCOND: return "ARMISD::BRCOND";
944 case ARMISD::BR_JT: return "ARMISD::BR_JT";
945 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
946 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
947 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
948 case ARMISD::CMP: return "ARMISD::CMP";
949 case ARMISD::CMN: return "ARMISD::CMN";
950 case ARMISD::CMPZ: return "ARMISD::CMPZ";
951 case ARMISD::CMPFP: return "ARMISD::CMPFP";
952 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
953 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
954 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
956 case ARMISD::CMOV: return "ARMISD::CMOV";
958 case ARMISD::RBIT: return "ARMISD::RBIT";
960 case ARMISD::FTOSI: return "ARMISD::FTOSI";
961 case ARMISD::FTOUI: return "ARMISD::FTOUI";
962 case ARMISD::SITOF: return "ARMISD::SITOF";
963 case ARMISD::UITOF: return "ARMISD::UITOF";
965 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
966 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
967 case ARMISD::RRX: return "ARMISD::RRX";
969 case ARMISD::ADDC: return "ARMISD::ADDC";
970 case ARMISD::ADDE: return "ARMISD::ADDE";
971 case ARMISD::SUBC: return "ARMISD::SUBC";
972 case ARMISD::SUBE: return "ARMISD::SUBE";
974 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
975 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
977 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
978 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
980 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
982 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
984 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
986 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
987 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
989 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
991 case ARMISD::VCEQ: return "ARMISD::VCEQ";
992 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
993 case ARMISD::VCGE: return "ARMISD::VCGE";
994 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
995 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
996 case ARMISD::VCGEU: return "ARMISD::VCGEU";
997 case ARMISD::VCGT: return "ARMISD::VCGT";
998 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
999 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1000 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1001 case ARMISD::VTST: return "ARMISD::VTST";
1003 case ARMISD::VSHL: return "ARMISD::VSHL";
1004 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1005 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1006 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1007 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1008 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1009 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1010 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1011 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1012 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1013 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1014 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1015 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1016 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1017 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1018 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1019 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1020 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1021 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1022 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1023 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1024 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1025 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1026 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1027 case ARMISD::VDUP: return "ARMISD::VDUP";
1028 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1029 case ARMISD::VEXT: return "ARMISD::VEXT";
1030 case ARMISD::VREV64: return "ARMISD::VREV64";
1031 case ARMISD::VREV32: return "ARMISD::VREV32";
1032 case ARMISD::VREV16: return "ARMISD::VREV16";
1033 case ARMISD::VZIP: return "ARMISD::VZIP";
1034 case ARMISD::VUZP: return "ARMISD::VUZP";
1035 case ARMISD::VTRN: return "ARMISD::VTRN";
1036 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1037 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1038 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1039 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1040 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1041 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1042 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1043 case ARMISD::FMAX: return "ARMISD::FMAX";
1044 case ARMISD::FMIN: return "ARMISD::FMIN";
1045 case ARMISD::BFI: return "ARMISD::BFI";
1046 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1047 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1048 case ARMISD::VBSL: return "ARMISD::VBSL";
1049 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1050 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1051 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1052 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1053 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1054 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1055 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1056 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1057 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1058 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1059 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1060 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1061 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1062 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1063 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1064 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1065 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1066 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1067 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1068 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1072 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1073 if (!VT.isVector()) return getPointerTy();
1074 return VT.changeVectorElementTypeToInteger();
1077 /// getRegClassFor - Return the register class that should be used for the
1078 /// specified value type.
1079 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1080 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1081 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1082 // load / store 4 to 8 consecutive D registers.
1083 if (Subtarget->hasNEON()) {
1084 if (VT == MVT::v4i64)
1085 return &ARM::QQPRRegClass;
1086 if (VT == MVT::v8i64)
1087 return &ARM::QQQQPRRegClass;
1089 return TargetLowering::getRegClassFor(VT);
1092 // Create a fast isel object.
1094 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1095 const TargetLibraryInfo *libInfo) const {
1096 return ARM::createFastISel(funcInfo, libInfo);
1099 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1100 /// be used for loads / stores from the global.
1101 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1102 return (Subtarget->isThumb1Only() ? 127 : 4095);
1105 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1106 unsigned NumVals = N->getNumValues();
1108 return Sched::RegPressure;
1110 for (unsigned i = 0; i != NumVals; ++i) {
1111 EVT VT = N->getValueType(i);
1112 if (VT == MVT::Glue || VT == MVT::Other)
1114 if (VT.isFloatingPoint() || VT.isVector())
1118 if (!N->isMachineOpcode())
1119 return Sched::RegPressure;
1121 // Load are scheduled for latency even if there instruction itinerary
1122 // is not available.
1123 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1124 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1126 if (MCID.getNumDefs() == 0)
1127 return Sched::RegPressure;
1128 if (!Itins->isEmpty() &&
1129 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1132 return Sched::RegPressure;
1135 //===----------------------------------------------------------------------===//
1137 //===----------------------------------------------------------------------===//
1139 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1140 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1142 default: llvm_unreachable("Unknown condition code!");
1143 case ISD::SETNE: return ARMCC::NE;
1144 case ISD::SETEQ: return ARMCC::EQ;
1145 case ISD::SETGT: return ARMCC::GT;
1146 case ISD::SETGE: return ARMCC::GE;
1147 case ISD::SETLT: return ARMCC::LT;
1148 case ISD::SETLE: return ARMCC::LE;
1149 case ISD::SETUGT: return ARMCC::HI;
1150 case ISD::SETUGE: return ARMCC::HS;
1151 case ISD::SETULT: return ARMCC::LO;
1152 case ISD::SETULE: return ARMCC::LS;
1156 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1157 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1158 ARMCC::CondCodes &CondCode2) {
1159 CondCode2 = ARMCC::AL;
1161 default: llvm_unreachable("Unknown FP condition!");
1163 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1165 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1167 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1168 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1169 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1170 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1171 case ISD::SETO: CondCode = ARMCC::VC; break;
1172 case ISD::SETUO: CondCode = ARMCC::VS; break;
1173 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1174 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1175 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1177 case ISD::SETULT: CondCode = ARMCC::LT; break;
1179 case ISD::SETULE: CondCode = ARMCC::LE; break;
1181 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1185 //===----------------------------------------------------------------------===//
1186 // Calling Convention Implementation
1187 //===----------------------------------------------------------------------===//
1189 #include "ARMGenCallingConv.inc"
1191 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1192 /// given CallingConvention value.
1193 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1195 bool isVarArg) const {
1198 llvm_unreachable("Unsupported calling convention");
1199 case CallingConv::Fast:
1200 if (Subtarget->hasVFP2() && !isVarArg) {
1201 if (!Subtarget->isAAPCS_ABI())
1202 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1203 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1204 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1207 case CallingConv::C: {
1208 // Use target triple & subtarget features to do actual dispatch.
1209 if (!Subtarget->isAAPCS_ABI())
1210 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1211 else if (Subtarget->hasVFP2() &&
1212 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1214 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1215 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1217 case CallingConv::ARM_AAPCS_VFP:
1219 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1221 case CallingConv::ARM_AAPCS:
1222 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1223 case CallingConv::ARM_APCS:
1224 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1225 case CallingConv::GHC:
1226 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1230 /// LowerCallResult - Lower the result values of a call into the
1231 /// appropriate copies out of appropriate physical registers.
1233 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1234 CallingConv::ID CallConv, bool isVarArg,
1235 const SmallVectorImpl<ISD::InputArg> &Ins,
1236 DebugLoc dl, SelectionDAG &DAG,
1237 SmallVectorImpl<SDValue> &InVals,
1238 bool isThisReturn, SDValue ThisVal) const {
1240 // Assign locations to each value returned by this call.
1241 SmallVector<CCValAssign, 16> RVLocs;
1242 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1243 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1244 CCInfo.AnalyzeCallResult(Ins,
1245 CCAssignFnForNode(CallConv, /* Return*/ true,
1248 // Copy all of the result registers out of their specified physreg.
1249 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1250 CCValAssign VA = RVLocs[i];
1252 // Pass 'this' value directly from the argument to return value, to avoid
1253 // reg unit interference
1254 if (i == 0 && isThisReturn) {
1255 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1256 "unexpected return calling convention register assignment");
1257 InVals.push_back(ThisVal);
1262 if (VA.needsCustom()) {
1263 // Handle f64 or half of a v2f64.
1264 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1266 Chain = Lo.getValue(1);
1267 InFlag = Lo.getValue(2);
1268 VA = RVLocs[++i]; // skip ahead to next loc
1269 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1271 Chain = Hi.getValue(1);
1272 InFlag = Hi.getValue(2);
1273 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1275 if (VA.getLocVT() == MVT::v2f64) {
1276 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1277 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1278 DAG.getConstant(0, MVT::i32));
1280 VA = RVLocs[++i]; // skip ahead to next loc
1281 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1282 Chain = Lo.getValue(1);
1283 InFlag = Lo.getValue(2);
1284 VA = RVLocs[++i]; // skip ahead to next loc
1285 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1286 Chain = Hi.getValue(1);
1287 InFlag = Hi.getValue(2);
1288 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1289 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1290 DAG.getConstant(1, MVT::i32));
1293 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1295 Chain = Val.getValue(1);
1296 InFlag = Val.getValue(2);
1299 switch (VA.getLocInfo()) {
1300 default: llvm_unreachable("Unknown loc info!");
1301 case CCValAssign::Full: break;
1302 case CCValAssign::BCvt:
1303 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1307 InVals.push_back(Val);
1313 /// LowerMemOpCallTo - Store the argument to the stack.
1315 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1316 SDValue StackPtr, SDValue Arg,
1317 DebugLoc dl, SelectionDAG &DAG,
1318 const CCValAssign &VA,
1319 ISD::ArgFlagsTy Flags) const {
1320 unsigned LocMemOffset = VA.getLocMemOffset();
1321 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1322 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1323 return DAG.getStore(Chain, dl, Arg, PtrOff,
1324 MachinePointerInfo::getStack(LocMemOffset),
1328 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1329 SDValue Chain, SDValue &Arg,
1330 RegsToPassVector &RegsToPass,
1331 CCValAssign &VA, CCValAssign &NextVA,
1333 SmallVector<SDValue, 8> &MemOpChains,
1334 ISD::ArgFlagsTy Flags) const {
1336 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1337 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1338 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1340 if (NextVA.isRegLoc())
1341 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1343 assert(NextVA.isMemLoc());
1344 if (StackPtr.getNode() == 0)
1345 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1347 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1353 /// LowerCall - Lowering a call into a callseq_start <-
1354 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1357 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1358 SmallVectorImpl<SDValue> &InVals) const {
1359 SelectionDAG &DAG = CLI.DAG;
1360 DebugLoc &dl = CLI.DL;
1361 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1362 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1363 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1364 SDValue Chain = CLI.Chain;
1365 SDValue Callee = CLI.Callee;
1366 bool &isTailCall = CLI.IsTailCall;
1367 CallingConv::ID CallConv = CLI.CallConv;
1368 bool doesNotRet = CLI.DoesNotReturn;
1369 bool isVarArg = CLI.IsVarArg;
1371 MachineFunction &MF = DAG.getMachineFunction();
1372 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1373 bool isThisReturn = false;
1374 bool isSibCall = false;
1375 // Disable tail calls if they're not supported.
1376 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1379 // Check if it's really possible to do a tail call.
1380 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1381 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1382 Outs, OutVals, Ins, DAG);
1383 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1384 // detected sibcalls.
1391 // Analyze operands of the call, assigning locations to each operand.
1392 SmallVector<CCValAssign, 16> ArgLocs;
1393 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1394 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1395 CCInfo.AnalyzeCallOperands(Outs,
1396 CCAssignFnForNode(CallConv, /* Return*/ false,
1399 // Get a count of how many bytes are to be pushed on the stack.
1400 unsigned NumBytes = CCInfo.getNextStackOffset();
1402 // For tail calls, memory operands are available in our caller's stack.
1406 // Adjust the stack pointer for the new arguments...
1407 // These operations are automatically eliminated by the prolog/epilog pass
1409 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1411 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1413 RegsToPassVector RegsToPass;
1414 SmallVector<SDValue, 8> MemOpChains;
1416 // Walk the register/memloc assignments, inserting copies/loads. In the case
1417 // of tail call optimization, arguments are handled later.
1418 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1420 ++i, ++realArgIdx) {
1421 CCValAssign &VA = ArgLocs[i];
1422 SDValue Arg = OutVals[realArgIdx];
1423 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1424 bool isByVal = Flags.isByVal();
1426 // Promote the value if needed.
1427 switch (VA.getLocInfo()) {
1428 default: llvm_unreachable("Unknown loc info!");
1429 case CCValAssign::Full: break;
1430 case CCValAssign::SExt:
1431 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1433 case CCValAssign::ZExt:
1434 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1436 case CCValAssign::AExt:
1437 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1439 case CCValAssign::BCvt:
1440 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1444 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1445 if (VA.needsCustom()) {
1446 if (VA.getLocVT() == MVT::v2f64) {
1447 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1448 DAG.getConstant(0, MVT::i32));
1449 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1450 DAG.getConstant(1, MVT::i32));
1452 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1453 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1455 VA = ArgLocs[++i]; // skip ahead to next loc
1456 if (VA.isRegLoc()) {
1457 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1458 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1460 assert(VA.isMemLoc());
1462 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1463 dl, DAG, VA, Flags));
1466 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1467 StackPtr, MemOpChains, Flags);
1469 } else if (VA.isRegLoc()) {
1470 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1471 assert(VA.getLocVT() == MVT::i32 &&
1472 "unexpected calling convention register assignment");
1473 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1474 "unexpected use of 'returned'");
1475 isThisReturn = true;
1477 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1478 } else if (isByVal) {
1479 assert(VA.isMemLoc());
1480 unsigned offset = 0;
1482 // True if this byval aggregate will be split between registers
1484 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1485 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1487 if (CurByValIdx < ByValArgsCount) {
1489 unsigned RegBegin, RegEnd;
1490 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1492 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1494 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1495 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1496 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1497 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1498 MachinePointerInfo(),
1499 false, false, false, 0);
1500 MemOpChains.push_back(Load.getValue(1));
1501 RegsToPass.push_back(std::make_pair(j, Load));
1504 // If parameter size outsides register area, "offset" value
1505 // helps us to calculate stack slot for remained part properly.
1506 offset = RegEnd - RegBegin;
1508 CCInfo.nextInRegsParam();
1511 if (Flags.getByValSize() > 4*offset) {
1512 unsigned LocMemOffset = VA.getLocMemOffset();
1513 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1514 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1516 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1517 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1518 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1520 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1522 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1523 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1524 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1525 Ops, array_lengthof(Ops)));
1527 } else if (!isSibCall) {
1528 assert(VA.isMemLoc());
1530 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1531 dl, DAG, VA, Flags));
1535 if (!MemOpChains.empty())
1536 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1537 &MemOpChains[0], MemOpChains.size());
1539 // Build a sequence of copy-to-reg nodes chained together with token chain
1540 // and flag operands which copy the outgoing args into the appropriate regs.
1542 // Tail call byval lowering might overwrite argument registers so in case of
1543 // tail call optimization the copies to registers are lowered later.
1545 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1546 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1547 RegsToPass[i].second, InFlag);
1548 InFlag = Chain.getValue(1);
1551 // For tail calls lower the arguments to the 'real' stack slot.
1553 // Force all the incoming stack arguments to be loaded from the stack
1554 // before any new outgoing arguments are stored to the stack, because the
1555 // outgoing stack slots may alias the incoming argument stack slots, and
1556 // the alias isn't otherwise explicit. This is slightly more conservative
1557 // than necessary, because it means that each store effectively depends
1558 // on every argument instead of just those arguments it would clobber.
1560 // Do not flag preceding copytoreg stuff together with the following stuff.
1562 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1563 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1564 RegsToPass[i].second, InFlag);
1565 InFlag = Chain.getValue(1);
1570 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1571 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1572 // node so that legalize doesn't hack it.
1573 bool isDirect = false;
1574 bool isARMFunc = false;
1575 bool isLocalARMFunc = false;
1576 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1578 if (EnableARMLongCalls) {
1579 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1580 && "long-calls with non-static relocation model!");
1581 // Handle a global address or an external symbol. If it's not one of
1582 // those, the target's already in a register, so we don't need to do
1584 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1585 const GlobalValue *GV = G->getGlobal();
1586 // Create a constant pool entry for the callee address
1587 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1588 ARMConstantPoolValue *CPV =
1589 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1591 // Get the address of the callee into a register
1592 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1593 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1594 Callee = DAG.getLoad(getPointerTy(), dl,
1595 DAG.getEntryNode(), CPAddr,
1596 MachinePointerInfo::getConstantPool(),
1597 false, false, false, 0);
1598 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1599 const char *Sym = S->getSymbol();
1601 // Create a constant pool entry for the callee address
1602 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1603 ARMConstantPoolValue *CPV =
1604 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1605 ARMPCLabelIndex, 0);
1606 // Get the address of the callee into a register
1607 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1608 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1609 Callee = DAG.getLoad(getPointerTy(), dl,
1610 DAG.getEntryNode(), CPAddr,
1611 MachinePointerInfo::getConstantPool(),
1612 false, false, false, 0);
1614 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1615 const GlobalValue *GV = G->getGlobal();
1617 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1618 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1619 getTargetMachine().getRelocationModel() != Reloc::Static;
1620 isARMFunc = !Subtarget->isThumb() || isStub;
1621 // ARM call to a local ARM function is predicable.
1622 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1623 // tBX takes a register source operand.
1624 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1625 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1626 ARMConstantPoolValue *CPV =
1627 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1628 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1629 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1630 Callee = DAG.getLoad(getPointerTy(), dl,
1631 DAG.getEntryNode(), CPAddr,
1632 MachinePointerInfo::getConstantPool(),
1633 false, false, false, 0);
1634 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1635 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1636 getPointerTy(), Callee, PICLabel);
1638 // On ELF targets for PIC code, direct calls should go through the PLT
1639 unsigned OpFlags = 0;
1640 if (Subtarget->isTargetELF() &&
1641 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1642 OpFlags = ARMII::MO_PLT;
1643 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1645 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1647 bool isStub = Subtarget->isTargetDarwin() &&
1648 getTargetMachine().getRelocationModel() != Reloc::Static;
1649 isARMFunc = !Subtarget->isThumb() || isStub;
1650 // tBX takes a register source operand.
1651 const char *Sym = S->getSymbol();
1652 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1653 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1654 ARMConstantPoolValue *CPV =
1655 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1656 ARMPCLabelIndex, 4);
1657 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1658 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1659 Callee = DAG.getLoad(getPointerTy(), dl,
1660 DAG.getEntryNode(), CPAddr,
1661 MachinePointerInfo::getConstantPool(),
1662 false, false, false, 0);
1663 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1664 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1665 getPointerTy(), Callee, PICLabel);
1667 unsigned OpFlags = 0;
1668 // On ELF targets for PIC code, direct calls should go through the PLT
1669 if (Subtarget->isTargetELF() &&
1670 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1671 OpFlags = ARMII::MO_PLT;
1672 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1676 // FIXME: handle tail calls differently.
1678 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1679 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1680 if (Subtarget->isThumb()) {
1681 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1682 CallOpc = ARMISD::CALL_NOLINK;
1684 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1686 if (!isDirect && !Subtarget->hasV5TOps())
1687 CallOpc = ARMISD::CALL_NOLINK;
1688 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1689 // Emit regular call when code size is the priority
1691 // "mov lr, pc; b _foo" to avoid confusing the RSP
1692 CallOpc = ARMISD::CALL_NOLINK;
1694 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1697 std::vector<SDValue> Ops;
1698 Ops.push_back(Chain);
1699 Ops.push_back(Callee);
1701 // Add argument registers to the end of the list so that they are known live
1703 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1704 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1705 RegsToPass[i].second.getValueType()));
1707 // Add a register mask operand representing the call-preserved registers.
1708 const uint32_t *Mask;
1709 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1710 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1712 // For 'this' returns, use the R0-preserving mask
1713 Mask = ARI->getThisReturnPreservedMask(CallConv);
1715 Mask = ARI->getCallPreservedMask(CallConv);
1717 assert(Mask && "Missing call preserved mask for calling convention");
1718 Ops.push_back(DAG.getRegisterMask(Mask));
1720 if (InFlag.getNode())
1721 Ops.push_back(InFlag);
1723 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1725 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1727 // Returns a chain and a flag for retval copy to use.
1728 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1729 InFlag = Chain.getValue(1);
1731 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1732 DAG.getIntPtrConstant(0, true), InFlag);
1734 InFlag = Chain.getValue(1);
1736 // Handle result values, copying them out of physregs into vregs that we
1738 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1739 InVals, isThisReturn,
1740 isThisReturn ? OutVals[0] : SDValue());
1743 /// HandleByVal - Every parameter *after* a byval parameter is passed
1744 /// on the stack. Remember the next parameter register to allocate,
1745 /// and then confiscate the rest of the parameter registers to insure
1748 ARMTargetLowering::HandleByVal(
1749 CCState *State, unsigned &size, unsigned Align) const {
1750 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1751 assert((State->getCallOrPrologue() == Prologue ||
1752 State->getCallOrPrologue() == Call) &&
1753 "unhandled ParmContext");
1755 // For in-prologue parameters handling, we also introduce stack offset
1756 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1757 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1758 // NSAA should be evaluted (NSAA means "next stacked argument address").
1759 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1760 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1761 unsigned NSAAOffset = State->getNextStackOffset();
1762 if (State->getCallOrPrologue() != Call) {
1763 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1765 State->getInRegsParamInfo(i, RB, RE);
1766 assert(NSAAOffset >= (RE-RB)*4 &&
1767 "Stack offset for byval regs doesn't introduced anymore?");
1768 NSAAOffset -= (RE-RB)*4;
1771 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1772 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1773 unsigned AlignInRegs = Align / 4;
1774 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1775 for (unsigned i = 0; i < Waste; ++i)
1776 reg = State->AllocateReg(GPRArgRegs, 4);
1779 unsigned excess = 4 * (ARM::R4 - reg);
1781 // Special case when NSAA != SP and parameter size greater than size of
1782 // all remained GPR regs. In that case we can't split parameter, we must
1783 // send it to stack. We also must set NCRN to R4, so waste all
1784 // remained registers.
1785 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1786 while (State->AllocateReg(GPRArgRegs, 4))
1791 // First register for byval parameter is the first register that wasn't
1792 // allocated before this method call, so it would be "reg".
1793 // If parameter is small enough to be saved in range [reg, r4), then
1794 // the end (first after last) register would be reg + param-size-in-regs,
1795 // else parameter would be splitted between registers and stack,
1796 // end register would be r4 in this case.
1797 unsigned ByValRegBegin = reg;
1798 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1799 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1800 // Note, first register is allocated in the beginning of function already,
1801 // allocate remained amount of registers we need.
1802 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1803 State->AllocateReg(GPRArgRegs, 4);
1804 // At a call site, a byval parameter that is split between
1805 // registers and memory needs its size truncated here. In a
1806 // function prologue, such byval parameters are reassembled in
1807 // memory, and are not truncated.
1808 if (State->getCallOrPrologue() == Call) {
1809 // Make remained size equal to 0 in case, when
1810 // the whole structure may be stored into registers.
1820 /// MatchingStackOffset - Return true if the given stack call argument is
1821 /// already available in the same position (relatively) of the caller's
1822 /// incoming argument stack.
1824 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1825 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1826 const TargetInstrInfo *TII) {
1827 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1829 if (Arg.getOpcode() == ISD::CopyFromReg) {
1830 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1831 if (!TargetRegisterInfo::isVirtualRegister(VR))
1833 MachineInstr *Def = MRI->getVRegDef(VR);
1836 if (!Flags.isByVal()) {
1837 if (!TII->isLoadFromStackSlot(Def, FI))
1842 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1843 if (Flags.isByVal())
1844 // ByVal argument is passed in as a pointer but it's now being
1845 // dereferenced. e.g.
1846 // define @foo(%struct.X* %A) {
1847 // tail call @bar(%struct.X* byval %A)
1850 SDValue Ptr = Ld->getBasePtr();
1851 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1854 FI = FINode->getIndex();
1858 assert(FI != INT_MAX);
1859 if (!MFI->isFixedObjectIndex(FI))
1861 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1864 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1865 /// for tail call optimization. Targets which want to do tail call
1866 /// optimization should implement this function.
1868 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1869 CallingConv::ID CalleeCC,
1871 bool isCalleeStructRet,
1872 bool isCallerStructRet,
1873 const SmallVectorImpl<ISD::OutputArg> &Outs,
1874 const SmallVectorImpl<SDValue> &OutVals,
1875 const SmallVectorImpl<ISD::InputArg> &Ins,
1876 SelectionDAG& DAG) const {
1877 const Function *CallerF = DAG.getMachineFunction().getFunction();
1878 CallingConv::ID CallerCC = CallerF->getCallingConv();
1879 bool CCMatch = CallerCC == CalleeCC;
1881 // Look for obvious safe cases to perform tail call optimization that do not
1882 // require ABI changes. This is what gcc calls sibcall.
1884 // Do not sibcall optimize vararg calls unless the call site is not passing
1886 if (isVarArg && !Outs.empty())
1889 // Also avoid sibcall optimization if either caller or callee uses struct
1890 // return semantics.
1891 if (isCalleeStructRet || isCallerStructRet)
1894 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1895 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1896 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1897 // support in the assembler and linker to be used. This would need to be
1898 // fixed to fully support tail calls in Thumb1.
1900 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1901 // LR. This means if we need to reload LR, it takes an extra instructions,
1902 // which outweighs the value of the tail call; but here we don't know yet
1903 // whether LR is going to be used. Probably the right approach is to
1904 // generate the tail call here and turn it back into CALL/RET in
1905 // emitEpilogue if LR is used.
1907 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1908 // but we need to make sure there are enough registers; the only valid
1909 // registers are the 4 used for parameters. We don't currently do this
1911 if (Subtarget->isThumb1Only())
1914 // If the calling conventions do not match, then we'd better make sure the
1915 // results are returned in the same way as what the caller expects.
1917 SmallVector<CCValAssign, 16> RVLocs1;
1918 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1919 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1920 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1922 SmallVector<CCValAssign, 16> RVLocs2;
1923 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1924 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1925 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1927 if (RVLocs1.size() != RVLocs2.size())
1929 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1930 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1932 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1934 if (RVLocs1[i].isRegLoc()) {
1935 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1938 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1944 // If Caller's vararg or byval argument has been split between registers and
1945 // stack, do not perform tail call, since part of the argument is in caller's
1947 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1948 getInfo<ARMFunctionInfo>();
1949 if (AFI_Caller->getArgRegsSaveSize())
1952 // If the callee takes no arguments then go on to check the results of the
1954 if (!Outs.empty()) {
1955 // Check if stack adjustment is needed. For now, do not do this if any
1956 // argument is passed on the stack.
1957 SmallVector<CCValAssign, 16> ArgLocs;
1958 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1959 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1960 CCInfo.AnalyzeCallOperands(Outs,
1961 CCAssignFnForNode(CalleeCC, false, isVarArg));
1962 if (CCInfo.getNextStackOffset()) {
1963 MachineFunction &MF = DAG.getMachineFunction();
1965 // Check if the arguments are already laid out in the right way as
1966 // the caller's fixed stack objects.
1967 MachineFrameInfo *MFI = MF.getFrameInfo();
1968 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1969 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1970 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1972 ++i, ++realArgIdx) {
1973 CCValAssign &VA = ArgLocs[i];
1974 EVT RegVT = VA.getLocVT();
1975 SDValue Arg = OutVals[realArgIdx];
1976 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1977 if (VA.getLocInfo() == CCValAssign::Indirect)
1979 if (VA.needsCustom()) {
1980 // f64 and vector types are split into multiple registers or
1981 // register/stack-slot combinations. The types will not match
1982 // the registers; give up on memory f64 refs until we figure
1983 // out what to do about this.
1986 if (!ArgLocs[++i].isRegLoc())
1988 if (RegVT == MVT::v2f64) {
1989 if (!ArgLocs[++i].isRegLoc())
1991 if (!ArgLocs[++i].isRegLoc())
1994 } else if (!VA.isRegLoc()) {
1995 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2007 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2008 MachineFunction &MF, bool isVarArg,
2009 const SmallVectorImpl<ISD::OutputArg> &Outs,
2010 LLVMContext &Context) const {
2011 SmallVector<CCValAssign, 16> RVLocs;
2012 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2013 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2018 ARMTargetLowering::LowerReturn(SDValue Chain,
2019 CallingConv::ID CallConv, bool isVarArg,
2020 const SmallVectorImpl<ISD::OutputArg> &Outs,
2021 const SmallVectorImpl<SDValue> &OutVals,
2022 DebugLoc dl, SelectionDAG &DAG) const {
2024 // CCValAssign - represent the assignment of the return value to a location.
2025 SmallVector<CCValAssign, 16> RVLocs;
2027 // CCState - Info about the registers and stack slots.
2028 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2029 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2031 // Analyze outgoing return values.
2032 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2036 SmallVector<SDValue, 4> RetOps;
2037 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2039 // Copy the result values into the output registers.
2040 for (unsigned i = 0, realRVLocIdx = 0;
2042 ++i, ++realRVLocIdx) {
2043 CCValAssign &VA = RVLocs[i];
2044 assert(VA.isRegLoc() && "Can only return in registers!");
2046 SDValue Arg = OutVals[realRVLocIdx];
2048 switch (VA.getLocInfo()) {
2049 default: llvm_unreachable("Unknown loc info!");
2050 case CCValAssign::Full: break;
2051 case CCValAssign::BCvt:
2052 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2056 if (VA.needsCustom()) {
2057 if (VA.getLocVT() == MVT::v2f64) {
2058 // Extract the first half and return it in two registers.
2059 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2060 DAG.getConstant(0, MVT::i32));
2061 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2062 DAG.getVTList(MVT::i32, MVT::i32), Half);
2064 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2065 Flag = Chain.getValue(1);
2066 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2067 VA = RVLocs[++i]; // skip ahead to next loc
2068 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2069 HalfGPRs.getValue(1), Flag);
2070 Flag = Chain.getValue(1);
2071 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2072 VA = RVLocs[++i]; // skip ahead to next loc
2074 // Extract the 2nd half and fall through to handle it as an f64 value.
2075 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2076 DAG.getConstant(1, MVT::i32));
2078 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2080 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2081 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2082 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2083 Flag = Chain.getValue(1);
2084 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2085 VA = RVLocs[++i]; // skip ahead to next loc
2086 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2089 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2091 // Guarantee that all emitted copies are
2092 // stuck together, avoiding something bad.
2093 Flag = Chain.getValue(1);
2094 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2097 // Update chain and glue.
2100 RetOps.push_back(Flag);
2102 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2103 RetOps.data(), RetOps.size());
2106 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2107 if (N->getNumValues() != 1)
2109 if (!N->hasNUsesOfValue(1, 0))
2112 SDValue TCChain = Chain;
2113 SDNode *Copy = *N->use_begin();
2114 if (Copy->getOpcode() == ISD::CopyToReg) {
2115 // If the copy has a glue operand, we conservatively assume it isn't safe to
2116 // perform a tail call.
2117 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2119 TCChain = Copy->getOperand(0);
2120 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2121 SDNode *VMov = Copy;
2122 // f64 returned in a pair of GPRs.
2123 SmallPtrSet<SDNode*, 2> Copies;
2124 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2126 if (UI->getOpcode() != ISD::CopyToReg)
2130 if (Copies.size() > 2)
2133 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2135 SDValue UseChain = UI->getOperand(0);
2136 if (Copies.count(UseChain.getNode()))
2143 } else if (Copy->getOpcode() == ISD::BITCAST) {
2144 // f32 returned in a single GPR.
2145 if (!Copy->hasOneUse())
2147 Copy = *Copy->use_begin();
2148 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2150 TCChain = Copy->getOperand(0);
2155 bool HasRet = false;
2156 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2158 if (UI->getOpcode() != ARMISD::RET_FLAG)
2170 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2171 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2174 if (!CI->isTailCall())
2177 return !Subtarget->isThumb1Only();
2180 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2181 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2182 // one of the above mentioned nodes. It has to be wrapped because otherwise
2183 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2184 // be used to form addressing mode. These wrapped nodes will be selected
2186 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2187 EVT PtrVT = Op.getValueType();
2188 // FIXME there is no actual debug info here
2189 DebugLoc dl = Op.getDebugLoc();
2190 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2192 if (CP->isMachineConstantPoolEntry())
2193 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2194 CP->getAlignment());
2196 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2197 CP->getAlignment());
2198 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2201 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2202 return MachineJumpTableInfo::EK_Inline;
2205 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2206 SelectionDAG &DAG) const {
2207 MachineFunction &MF = DAG.getMachineFunction();
2208 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2209 unsigned ARMPCLabelIndex = 0;
2210 DebugLoc DL = Op.getDebugLoc();
2211 EVT PtrVT = getPointerTy();
2212 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2213 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2215 if (RelocM == Reloc::Static) {
2216 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2218 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2219 ARMPCLabelIndex = AFI->createPICLabelUId();
2220 ARMConstantPoolValue *CPV =
2221 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2222 ARMCP::CPBlockAddress, PCAdj);
2223 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2225 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2226 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2227 MachinePointerInfo::getConstantPool(),
2228 false, false, false, 0);
2229 if (RelocM == Reloc::Static)
2231 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2232 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2235 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2237 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2238 SelectionDAG &DAG) const {
2239 DebugLoc dl = GA->getDebugLoc();
2240 EVT PtrVT = getPointerTy();
2241 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2242 MachineFunction &MF = DAG.getMachineFunction();
2243 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2244 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2245 ARMConstantPoolValue *CPV =
2246 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2247 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2248 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2249 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2250 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2251 MachinePointerInfo::getConstantPool(),
2252 false, false, false, 0);
2253 SDValue Chain = Argument.getValue(1);
2255 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2256 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2258 // call __tls_get_addr.
2261 Entry.Node = Argument;
2262 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2263 Args.push_back(Entry);
2264 // FIXME: is there useful debug info available here?
2265 TargetLowering::CallLoweringInfo CLI(Chain,
2266 (Type *) Type::getInt32Ty(*DAG.getContext()),
2267 false, false, false, false,
2268 0, CallingConv::C, /*isTailCall=*/false,
2269 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2270 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2271 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2272 return CallResult.first;
2275 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2276 // "local exec" model.
2278 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2280 TLSModel::Model model) const {
2281 const GlobalValue *GV = GA->getGlobal();
2282 DebugLoc dl = GA->getDebugLoc();
2284 SDValue Chain = DAG.getEntryNode();
2285 EVT PtrVT = getPointerTy();
2286 // Get the Thread Pointer
2287 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2289 if (model == TLSModel::InitialExec) {
2290 MachineFunction &MF = DAG.getMachineFunction();
2291 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2292 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2293 // Initial exec model.
2294 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2295 ARMConstantPoolValue *CPV =
2296 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2297 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2299 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2300 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2301 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2302 MachinePointerInfo::getConstantPool(),
2303 false, false, false, 0);
2304 Chain = Offset.getValue(1);
2306 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2307 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2309 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2310 MachinePointerInfo::getConstantPool(),
2311 false, false, false, 0);
2314 assert(model == TLSModel::LocalExec);
2315 ARMConstantPoolValue *CPV =
2316 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2317 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2318 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2319 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2320 MachinePointerInfo::getConstantPool(),
2321 false, false, false, 0);
2324 // The address of the thread local variable is the add of the thread
2325 // pointer with the offset of the variable.
2326 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2330 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2331 // TODO: implement the "local dynamic" model
2332 assert(Subtarget->isTargetELF() &&
2333 "TLS not implemented for non-ELF targets");
2334 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2336 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2339 case TLSModel::GeneralDynamic:
2340 case TLSModel::LocalDynamic:
2341 return LowerToTLSGeneralDynamicModel(GA, DAG);
2342 case TLSModel::InitialExec:
2343 case TLSModel::LocalExec:
2344 return LowerToTLSExecModels(GA, DAG, model);
2346 llvm_unreachable("bogus TLS model");
2349 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2350 SelectionDAG &DAG) const {
2351 EVT PtrVT = getPointerTy();
2352 DebugLoc dl = Op.getDebugLoc();
2353 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2354 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2355 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2356 ARMConstantPoolValue *CPV =
2357 ARMConstantPoolConstant::Create(GV,
2358 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2359 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2360 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2361 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2363 MachinePointerInfo::getConstantPool(),
2364 false, false, false, 0);
2365 SDValue Chain = Result.getValue(1);
2366 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2367 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2369 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2370 MachinePointerInfo::getGOT(),
2371 false, false, false, 0);
2375 // If we have T2 ops, we can materialize the address directly via movt/movw
2376 // pair. This is always cheaper.
2377 if (Subtarget->useMovt()) {
2379 // FIXME: Once remat is capable of dealing with instructions with register
2380 // operands, expand this into two nodes.
2381 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2382 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2384 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2385 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2386 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2387 MachinePointerInfo::getConstantPool(),
2388 false, false, false, 0);
2392 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2393 SelectionDAG &DAG) const {
2394 EVT PtrVT = getPointerTy();
2395 DebugLoc dl = Op.getDebugLoc();
2396 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2397 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2399 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2400 // update ARMFastISel::ARMMaterializeGV.
2401 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2403 // FIXME: Once remat is capable of dealing with instructions with register
2404 // operands, expand this into two nodes.
2405 if (RelocM == Reloc::Static)
2406 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2407 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2409 unsigned Wrapper = (RelocM == Reloc::PIC_)
2410 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2411 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2412 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2413 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2414 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2415 MachinePointerInfo::getGOT(),
2416 false, false, false, 0);
2420 unsigned ARMPCLabelIndex = 0;
2422 if (RelocM == Reloc::Static) {
2423 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2425 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2426 ARMPCLabelIndex = AFI->createPICLabelUId();
2427 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2428 ARMConstantPoolValue *CPV =
2429 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2431 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2433 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2435 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2436 MachinePointerInfo::getConstantPool(),
2437 false, false, false, 0);
2438 SDValue Chain = Result.getValue(1);
2440 if (RelocM == Reloc::PIC_) {
2441 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2442 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2445 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2446 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2447 false, false, false, 0);
2452 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2453 SelectionDAG &DAG) const {
2454 assert(Subtarget->isTargetELF() &&
2455 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2456 MachineFunction &MF = DAG.getMachineFunction();
2457 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2458 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2459 EVT PtrVT = getPointerTy();
2460 DebugLoc dl = Op.getDebugLoc();
2461 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2462 ARMConstantPoolValue *CPV =
2463 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2464 ARMPCLabelIndex, PCAdj);
2465 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2466 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2467 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2468 MachinePointerInfo::getConstantPool(),
2469 false, false, false, 0);
2470 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2471 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2475 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2476 DebugLoc dl = Op.getDebugLoc();
2477 SDValue Val = DAG.getConstant(0, MVT::i32);
2478 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2479 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2480 Op.getOperand(1), Val);
2484 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2485 DebugLoc dl = Op.getDebugLoc();
2486 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2487 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2491 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2492 const ARMSubtarget *Subtarget) const {
2493 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2494 DebugLoc dl = Op.getDebugLoc();
2496 default: return SDValue(); // Don't custom lower most intrinsics.
2497 case Intrinsic::arm_thread_pointer: {
2498 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2499 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2501 case Intrinsic::eh_sjlj_lsda: {
2502 MachineFunction &MF = DAG.getMachineFunction();
2503 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2504 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2505 EVT PtrVT = getPointerTy();
2506 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2508 unsigned PCAdj = (RelocM != Reloc::PIC_)
2509 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2510 ARMConstantPoolValue *CPV =
2511 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2512 ARMCP::CPLSDA, PCAdj);
2513 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2514 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2516 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2517 MachinePointerInfo::getConstantPool(),
2518 false, false, false, 0);
2520 if (RelocM == Reloc::PIC_) {
2521 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2522 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2526 case Intrinsic::arm_neon_vmulls:
2527 case Intrinsic::arm_neon_vmullu: {
2528 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2529 ? ARMISD::VMULLs : ARMISD::VMULLu;
2530 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2531 Op.getOperand(1), Op.getOperand(2));
2536 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2537 const ARMSubtarget *Subtarget) {
2538 // FIXME: handle "fence singlethread" more efficiently.
2539 DebugLoc dl = Op.getDebugLoc();
2540 if (!Subtarget->hasDataBarrier()) {
2541 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2542 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2544 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2545 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2546 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2547 DAG.getConstant(0, MVT::i32));
2550 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2551 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2554 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2555 const ARMSubtarget *Subtarget) {
2556 // ARM pre v5TE and Thumb1 does not have preload instructions.
2557 if (!(Subtarget->isThumb2() ||
2558 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2559 // Just preserve the chain.
2560 return Op.getOperand(0);
2562 DebugLoc dl = Op.getDebugLoc();
2563 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2565 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2566 // ARMv7 with MP extension has PLDW.
2567 return Op.getOperand(0);
2569 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2570 if (Subtarget->isThumb()) {
2572 isRead = ~isRead & 1;
2573 isData = ~isData & 1;
2576 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2577 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2578 DAG.getConstant(isData, MVT::i32));
2581 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2582 MachineFunction &MF = DAG.getMachineFunction();
2583 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2585 // vastart just stores the address of the VarArgsFrameIndex slot into the
2586 // memory location argument.
2587 DebugLoc dl = Op.getDebugLoc();
2588 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2589 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2590 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2591 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2592 MachinePointerInfo(SV), false, false, 0);
2596 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2597 SDValue &Root, SelectionDAG &DAG,
2598 DebugLoc dl) const {
2599 MachineFunction &MF = DAG.getMachineFunction();
2600 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2602 const TargetRegisterClass *RC;
2603 if (AFI->isThumb1OnlyFunction())
2604 RC = &ARM::tGPRRegClass;
2606 RC = &ARM::GPRRegClass;
2608 // Transform the arguments stored in physical registers into virtual ones.
2609 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2610 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2613 if (NextVA.isMemLoc()) {
2614 MachineFrameInfo *MFI = MF.getFrameInfo();
2615 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2617 // Create load node to retrieve arguments from the stack.
2618 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2619 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2620 MachinePointerInfo::getFixedStack(FI),
2621 false, false, false, 0);
2623 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2624 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2627 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2631 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2632 unsigned InRegsParamRecordIdx,
2634 unsigned &ArgRegsSize,
2635 unsigned &ArgRegsSaveSize)
2638 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2639 unsigned RBegin, REnd;
2640 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2641 NumGPRs = REnd - RBegin;
2643 unsigned int firstUnalloced;
2644 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2645 sizeof(GPRArgRegs) /
2646 sizeof(GPRArgRegs[0]));
2647 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2650 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2651 ArgRegsSize = NumGPRs * 4;
2653 // If parameter is split between stack and GPRs...
2654 if (NumGPRs && Align == 8 &&
2655 (ArgRegsSize < ArgSize ||
2656 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2657 // Add padding for part of param recovered from GPRs, so
2658 // its last byte must be at address K*8 - 1.
2659 // We need to do it, since remained (stack) part of parameter has
2660 // stack alignment, and we need to "attach" "GPRs head" without gaps
2663 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2664 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2666 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2668 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2669 (ArgRegsSize + AFI->getArgRegsSaveSize());
2670 ArgRegsSaveSize = ArgRegsSize + Padding;
2672 // We don't need to extend regs save size for byval parameters if they
2673 // are passed via GPRs only.
2674 ArgRegsSaveSize = ArgRegsSize;
2677 // The remaining GPRs hold either the beginning of variable-argument
2678 // data, or the beginning of an aggregate passed by value (usually
2679 // byval). Either way, we allocate stack slots adjacent to the data
2680 // provided by our caller, and store the unallocated registers there.
2681 // If this is a variadic function, the va_list pointer will begin with
2682 // these values; otherwise, this reassembles a (byval) structure that
2683 // was split between registers and memory.
2684 // Return: The frame index registers were stored into.
2686 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2687 DebugLoc dl, SDValue &Chain,
2688 const Value *OrigArg,
2689 unsigned InRegsParamRecordIdx,
2690 unsigned OffsetFromOrigArg,
2693 bool ForceMutable) const {
2695 // Currently, two use-cases possible:
2696 // Case #1. Non var-args function, and we meet first byval parameter.
2697 // Setup first unallocated register as first byval register;
2698 // eat all remained registers
2699 // (these two actions are performed by HandleByVal method).
2700 // Then, here, we initialize stack frame with
2701 // "store-reg" instructions.
2702 // Case #2. Var-args function, that doesn't contain byval parameters.
2703 // The same: eat all remained unallocated registers,
2704 // initialize stack frame.
2706 MachineFunction &MF = DAG.getMachineFunction();
2707 MachineFrameInfo *MFI = MF.getFrameInfo();
2708 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2709 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2710 unsigned RBegin, REnd;
2711 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2712 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2713 firstRegToSaveIndex = RBegin - ARM::R0;
2714 lastRegToSaveIndex = REnd - ARM::R0;
2716 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2717 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2718 lastRegToSaveIndex = 4;
2721 unsigned ArgRegsSize, ArgRegsSaveSize;
2722 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2723 ArgRegsSize, ArgRegsSaveSize);
2725 // Store any by-val regs to their spots on the stack so that they may be
2726 // loaded by deferencing the result of formal parameter pointer or va_next.
2727 // Note: once stack area for byval/varargs registers
2728 // was initialized, it can't be initialized again.
2729 if (ArgRegsSaveSize) {
2731 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2734 assert(AFI->getStoredByValParamsPadding() == 0 &&
2735 "The only parameter may be padded.");
2736 AFI->setStoredByValParamsPadding(Padding);
2739 int FrameIndex = MFI->CreateFixedObject(
2741 Padding + ArgOffset,
2743 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2745 SmallVector<SDValue, 4> MemOps;
2746 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2747 ++firstRegToSaveIndex, ++i) {
2748 const TargetRegisterClass *RC;
2749 if (AFI->isThumb1OnlyFunction())
2750 RC = &ARM::tGPRRegClass;
2752 RC = &ARM::GPRRegClass;
2754 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2755 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2757 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2758 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2760 MemOps.push_back(Store);
2761 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2762 DAG.getConstant(4, getPointerTy()));
2765 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2767 if (!MemOps.empty())
2768 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2769 &MemOps[0], MemOps.size());
2772 // This will point to the next argument passed via stack.
2773 return MFI->CreateFixedObject(
2774 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2777 // Setup stack frame, the va_list pointer will start from.
2779 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2780 DebugLoc dl, SDValue &Chain,
2782 bool ForceMutable) const {
2783 MachineFunction &MF = DAG.getMachineFunction();
2784 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2786 // Try to store any remaining integer argument regs
2787 // to their spots on the stack so that they may be loaded by deferencing
2788 // the result of va_next.
2789 // If there is no regs to be stored, just point address after last
2790 // argument passed via stack.
2792 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2793 0, ArgOffset, 0, ForceMutable);
2795 AFI->setVarArgsFrameIndex(FrameIndex);
2799 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2800 CallingConv::ID CallConv, bool isVarArg,
2801 const SmallVectorImpl<ISD::InputArg>
2803 DebugLoc dl, SelectionDAG &DAG,
2804 SmallVectorImpl<SDValue> &InVals)
2806 MachineFunction &MF = DAG.getMachineFunction();
2807 MachineFrameInfo *MFI = MF.getFrameInfo();
2809 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2811 // Assign locations to all of the incoming arguments.
2812 SmallVector<CCValAssign, 16> ArgLocs;
2813 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2814 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2815 CCInfo.AnalyzeFormalArguments(Ins,
2816 CCAssignFnForNode(CallConv, /* Return*/ false,
2819 SmallVector<SDValue, 16> ArgValues;
2820 int lastInsIndex = -1;
2822 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2823 unsigned CurArgIdx = 0;
2825 // Initially ArgRegsSaveSize is zero.
2826 // Then we increase this value each time we meet byval parameter.
2827 // We also increase this value in case of varargs function.
2828 AFI->setArgRegsSaveSize(0);
2830 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2831 CCValAssign &VA = ArgLocs[i];
2832 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2833 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2834 // Arguments stored in registers.
2835 if (VA.isRegLoc()) {
2836 EVT RegVT = VA.getLocVT();
2838 if (VA.needsCustom()) {
2839 // f64 and vector types are split up into multiple registers or
2840 // combinations of registers and stack slots.
2841 if (VA.getLocVT() == MVT::v2f64) {
2842 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2844 VA = ArgLocs[++i]; // skip ahead to next loc
2846 if (VA.isMemLoc()) {
2847 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2848 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2849 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2850 MachinePointerInfo::getFixedStack(FI),
2851 false, false, false, 0);
2853 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2856 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2857 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2858 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2859 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2860 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2862 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2865 const TargetRegisterClass *RC;
2867 if (RegVT == MVT::f32)
2868 RC = &ARM::SPRRegClass;
2869 else if (RegVT == MVT::f64)
2870 RC = &ARM::DPRRegClass;
2871 else if (RegVT == MVT::v2f64)
2872 RC = &ARM::QPRRegClass;
2873 else if (RegVT == MVT::i32)
2874 RC = AFI->isThumb1OnlyFunction() ?
2875 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2876 (const TargetRegisterClass*)&ARM::GPRRegClass;
2878 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2880 // Transform the arguments in physical registers into virtual ones.
2881 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2882 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2885 // If this is an 8 or 16-bit value, it is really passed promoted
2886 // to 32 bits. Insert an assert[sz]ext to capture this, then
2887 // truncate to the right size.
2888 switch (VA.getLocInfo()) {
2889 default: llvm_unreachable("Unknown loc info!");
2890 case CCValAssign::Full: break;
2891 case CCValAssign::BCvt:
2892 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2894 case CCValAssign::SExt:
2895 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2896 DAG.getValueType(VA.getValVT()));
2897 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2899 case CCValAssign::ZExt:
2900 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2901 DAG.getValueType(VA.getValVT()));
2902 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2906 InVals.push_back(ArgValue);
2908 } else { // VA.isRegLoc()
2911 assert(VA.isMemLoc());
2912 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2914 int index = ArgLocs[i].getValNo();
2916 // Some Ins[] entries become multiple ArgLoc[] entries.
2917 // Process them only once.
2918 if (index != lastInsIndex)
2920 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2921 // FIXME: For now, all byval parameter objects are marked mutable.
2922 // This can be changed with more analysis.
2923 // In case of tail call optimization mark all arguments mutable.
2924 // Since they could be overwritten by lowering of arguments in case of
2926 if (Flags.isByVal()) {
2927 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2928 int FrameIndex = StoreByValRegs(
2929 CCInfo, DAG, dl, Chain, CurOrigArg,
2931 Ins[VA.getValNo()].PartOffset,
2932 VA.getLocMemOffset(),
2933 Flags.getByValSize(),
2934 true /*force mutable frames*/);
2935 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2936 CCInfo.nextInRegsParam();
2938 unsigned FIOffset = VA.getLocMemOffset() +
2939 AFI->getStoredByValParamsPadding();
2940 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2943 // Create load nodes to retrieve arguments from the stack.
2944 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2945 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2946 MachinePointerInfo::getFixedStack(FI),
2947 false, false, false, 0));
2949 lastInsIndex = index;
2956 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2957 CCInfo.getNextStackOffset());
2962 /// isFloatingPointZero - Return true if this is +0.0.
2963 static bool isFloatingPointZero(SDValue Op) {
2964 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2965 return CFP->getValueAPF().isPosZero();
2966 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2967 // Maybe this has already been legalized into the constant pool?
2968 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2969 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2970 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2971 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2972 return CFP->getValueAPF().isPosZero();
2978 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2979 /// the given operands.
2981 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2982 SDValue &ARMcc, SelectionDAG &DAG,
2983 DebugLoc dl) const {
2984 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2985 unsigned C = RHSC->getZExtValue();
2986 if (!isLegalICmpImmediate(C)) {
2987 // Constant does not fit, try adjusting it by one?
2992 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2993 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2994 RHS = DAG.getConstant(C-1, MVT::i32);
2999 if (C != 0 && isLegalICmpImmediate(C-1)) {
3000 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3001 RHS = DAG.getConstant(C-1, MVT::i32);
3006 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3007 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3008 RHS = DAG.getConstant(C+1, MVT::i32);
3013 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3014 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3015 RHS = DAG.getConstant(C+1, MVT::i32);
3022 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3023 ARMISD::NodeType CompareType;
3026 CompareType = ARMISD::CMP;
3031 CompareType = ARMISD::CMPZ;
3034 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3035 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3038 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3040 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3041 DebugLoc dl) const {
3043 if (!isFloatingPointZero(RHS))
3044 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3046 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3047 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3050 /// duplicateCmp - Glue values can have only one use, so this function
3051 /// duplicates a comparison node.
3053 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3054 unsigned Opc = Cmp.getOpcode();
3055 DebugLoc DL = Cmp.getDebugLoc();
3056 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3057 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3059 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3060 Cmp = Cmp.getOperand(0);
3061 Opc = Cmp.getOpcode();
3062 if (Opc == ARMISD::CMPFP)
3063 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3065 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3066 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3068 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3071 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3072 SDValue Cond = Op.getOperand(0);
3073 SDValue SelectTrue = Op.getOperand(1);
3074 SDValue SelectFalse = Op.getOperand(2);
3075 DebugLoc dl = Op.getDebugLoc();
3079 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3080 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3082 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3083 const ConstantSDNode *CMOVTrue =
3084 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3085 const ConstantSDNode *CMOVFalse =
3086 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3088 if (CMOVTrue && CMOVFalse) {
3089 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3090 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3094 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3096 False = SelectFalse;
3097 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3102 if (True.getNode() && False.getNode()) {
3103 EVT VT = Op.getValueType();
3104 SDValue ARMcc = Cond.getOperand(2);
3105 SDValue CCR = Cond.getOperand(3);
3106 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3107 assert(True.getValueType() == VT);
3108 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3113 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3114 // undefined bits before doing a full-word comparison with zero.
3115 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3116 DAG.getConstant(1, Cond.getValueType()));
3118 return DAG.getSelectCC(dl, Cond,
3119 DAG.getConstant(0, Cond.getValueType()),
3120 SelectTrue, SelectFalse, ISD::SETNE);
3123 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3124 EVT VT = Op.getValueType();
3125 SDValue LHS = Op.getOperand(0);
3126 SDValue RHS = Op.getOperand(1);
3127 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3128 SDValue TrueVal = Op.getOperand(2);
3129 SDValue FalseVal = Op.getOperand(3);
3130 DebugLoc dl = Op.getDebugLoc();
3132 if (LHS.getValueType() == MVT::i32) {
3134 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3135 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3136 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3139 ARMCC::CondCodes CondCode, CondCode2;
3140 FPCCToARMCC(CC, CondCode, CondCode2);
3142 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3143 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3144 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3145 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3147 if (CondCode2 != ARMCC::AL) {
3148 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3149 // FIXME: Needs another CMP because flag can have but one use.
3150 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3151 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3152 Result, TrueVal, ARMcc2, CCR, Cmp2);
3157 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3158 /// to morph to an integer compare sequence.
3159 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3160 const ARMSubtarget *Subtarget) {
3161 SDNode *N = Op.getNode();
3162 if (!N->hasOneUse())
3163 // Otherwise it requires moving the value from fp to integer registers.
3165 if (!N->getNumValues())
3167 EVT VT = Op.getValueType();
3168 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3169 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3170 // vmrs are very slow, e.g. cortex-a8.
3173 if (isFloatingPointZero(Op)) {
3177 return ISD::isNormalLoad(N);
3180 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3181 if (isFloatingPointZero(Op))
3182 return DAG.getConstant(0, MVT::i32);
3184 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3185 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3186 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3187 Ld->isVolatile(), Ld->isNonTemporal(),
3188 Ld->isInvariant(), Ld->getAlignment());
3190 llvm_unreachable("Unknown VFP cmp argument!");
3193 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3194 SDValue &RetVal1, SDValue &RetVal2) {
3195 if (isFloatingPointZero(Op)) {
3196 RetVal1 = DAG.getConstant(0, MVT::i32);
3197 RetVal2 = DAG.getConstant(0, MVT::i32);
3201 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3202 SDValue Ptr = Ld->getBasePtr();
3203 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3204 Ld->getChain(), Ptr,
3205 Ld->getPointerInfo(),
3206 Ld->isVolatile(), Ld->isNonTemporal(),
3207 Ld->isInvariant(), Ld->getAlignment());
3209 EVT PtrType = Ptr.getValueType();
3210 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3211 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3212 PtrType, Ptr, DAG.getConstant(4, PtrType));
3213 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3214 Ld->getChain(), NewPtr,
3215 Ld->getPointerInfo().getWithOffset(4),
3216 Ld->isVolatile(), Ld->isNonTemporal(),
3217 Ld->isInvariant(), NewAlign);
3221 llvm_unreachable("Unknown VFP cmp argument!");
3224 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3225 /// f32 and even f64 comparisons to integer ones.
3227 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3228 SDValue Chain = Op.getOperand(0);
3229 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3230 SDValue LHS = Op.getOperand(2);
3231 SDValue RHS = Op.getOperand(3);
3232 SDValue Dest = Op.getOperand(4);
3233 DebugLoc dl = Op.getDebugLoc();
3235 bool LHSSeenZero = false;
3236 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3237 bool RHSSeenZero = false;
3238 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3239 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3240 // If unsafe fp math optimization is enabled and there are no other uses of
3241 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3242 // to an integer comparison.
3243 if (CC == ISD::SETOEQ)
3245 else if (CC == ISD::SETUNE)
3248 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3250 if (LHS.getValueType() == MVT::f32) {
3251 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3252 bitcastf32Toi32(LHS, DAG), Mask);
3253 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3254 bitcastf32Toi32(RHS, DAG), Mask);
3255 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3256 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3257 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3258 Chain, Dest, ARMcc, CCR, Cmp);
3263 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3264 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3265 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3266 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3267 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3268 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3269 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3270 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3271 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3277 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3278 SDValue Chain = Op.getOperand(0);
3279 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3280 SDValue LHS = Op.getOperand(2);
3281 SDValue RHS = Op.getOperand(3);
3282 SDValue Dest = Op.getOperand(4);
3283 DebugLoc dl = Op.getDebugLoc();
3285 if (LHS.getValueType() == MVT::i32) {
3287 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3288 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3289 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3290 Chain, Dest, ARMcc, CCR, Cmp);
3293 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3295 if (getTargetMachine().Options.UnsafeFPMath &&
3296 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3297 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3298 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3299 if (Result.getNode())
3303 ARMCC::CondCodes CondCode, CondCode2;
3304 FPCCToARMCC(CC, CondCode, CondCode2);
3306 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3307 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3308 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3309 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3310 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3311 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3312 if (CondCode2 != ARMCC::AL) {
3313 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3314 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3315 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3320 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3321 SDValue Chain = Op.getOperand(0);
3322 SDValue Table = Op.getOperand(1);
3323 SDValue Index = Op.getOperand(2);
3324 DebugLoc dl = Op.getDebugLoc();
3326 EVT PTy = getPointerTy();
3327 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3328 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3329 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3330 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3331 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3332 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3333 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3334 if (Subtarget->isThumb2()) {
3335 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3336 // which does another jump to the destination. This also makes it easier
3337 // to translate it to TBB / TBH later.
3338 // FIXME: This might not work if the function is extremely large.
3339 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3340 Addr, Op.getOperand(2), JTI, UId);
3342 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3343 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3344 MachinePointerInfo::getJumpTable(),
3345 false, false, false, 0);
3346 Chain = Addr.getValue(1);
3347 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3348 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3350 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3351 MachinePointerInfo::getJumpTable(),
3352 false, false, false, 0);
3353 Chain = Addr.getValue(1);
3354 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3358 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3359 EVT VT = Op.getValueType();
3360 DebugLoc dl = Op.getDebugLoc();
3362 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3363 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3365 return DAG.UnrollVectorOp(Op.getNode());
3368 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3369 "Invalid type for custom lowering!");
3370 if (VT != MVT::v4i16)
3371 return DAG.UnrollVectorOp(Op.getNode());
3373 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3374 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3377 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3378 EVT VT = Op.getValueType();
3380 return LowerVectorFP_TO_INT(Op, DAG);
3382 DebugLoc dl = Op.getDebugLoc();
3385 switch (Op.getOpcode()) {
3386 default: llvm_unreachable("Invalid opcode!");
3387 case ISD::FP_TO_SINT:
3388 Opc = ARMISD::FTOSI;
3390 case ISD::FP_TO_UINT:
3391 Opc = ARMISD::FTOUI;
3394 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3395 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3398 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3399 EVT VT = Op.getValueType();
3400 DebugLoc dl = Op.getDebugLoc();
3402 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3403 if (VT.getVectorElementType() == MVT::f32)
3405 return DAG.UnrollVectorOp(Op.getNode());
3408 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3409 "Invalid type for custom lowering!");
3410 if (VT != MVT::v4f32)
3411 return DAG.UnrollVectorOp(Op.getNode());
3415 switch (Op.getOpcode()) {
3416 default: llvm_unreachable("Invalid opcode!");
3417 case ISD::SINT_TO_FP:
3418 CastOpc = ISD::SIGN_EXTEND;
3419 Opc = ISD::SINT_TO_FP;
3421 case ISD::UINT_TO_FP:
3422 CastOpc = ISD::ZERO_EXTEND;
3423 Opc = ISD::UINT_TO_FP;
3427 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3428 return DAG.getNode(Opc, dl, VT, Op);
3431 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3432 EVT VT = Op.getValueType();
3434 return LowerVectorINT_TO_FP(Op, DAG);
3436 DebugLoc dl = Op.getDebugLoc();
3439 switch (Op.getOpcode()) {
3440 default: llvm_unreachable("Invalid opcode!");
3441 case ISD::SINT_TO_FP:
3442 Opc = ARMISD::SITOF;
3444 case ISD::UINT_TO_FP:
3445 Opc = ARMISD::UITOF;
3449 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3450 return DAG.getNode(Opc, dl, VT, Op);
3453 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3454 // Implement fcopysign with a fabs and a conditional fneg.
3455 SDValue Tmp0 = Op.getOperand(0);
3456 SDValue Tmp1 = Op.getOperand(1);
3457 DebugLoc dl = Op.getDebugLoc();
3458 EVT VT = Op.getValueType();
3459 EVT SrcVT = Tmp1.getValueType();
3460 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3461 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3462 bool UseNEON = !InGPR && Subtarget->hasNEON();
3465 // Use VBSL to copy the sign bit.
3466 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3467 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3468 DAG.getTargetConstant(EncodedVal, MVT::i32));
3469 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3471 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3472 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3473 DAG.getConstant(32, MVT::i32));
3474 else /*if (VT == MVT::f32)*/
3475 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3476 if (SrcVT == MVT::f32) {
3477 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3479 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3480 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3481 DAG.getConstant(32, MVT::i32));
3482 } else if (VT == MVT::f32)
3483 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3484 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3485 DAG.getConstant(32, MVT::i32));
3486 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3487 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3489 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3491 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3492 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3493 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3495 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3496 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3497 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3498 if (VT == MVT::f32) {
3499 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3500 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3501 DAG.getConstant(0, MVT::i32));
3503 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3509 // Bitcast operand 1 to i32.
3510 if (SrcVT == MVT::f64)
3511 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3512 &Tmp1, 1).getValue(1);
3513 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3515 // Or in the signbit with integer operations.
3516 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3517 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3518 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3519 if (VT == MVT::f32) {
3520 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3521 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3522 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3523 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3526 // f64: Or the high part with signbit and then combine two parts.
3527 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3529 SDValue Lo = Tmp0.getValue(0);
3530 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3531 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3532 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3535 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3536 MachineFunction &MF = DAG.getMachineFunction();
3537 MachineFrameInfo *MFI = MF.getFrameInfo();
3538 MFI->setReturnAddressIsTaken(true);
3540 EVT VT = Op.getValueType();
3541 DebugLoc dl = Op.getDebugLoc();
3542 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3544 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3545 SDValue Offset = DAG.getConstant(4, MVT::i32);
3546 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3547 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3548 MachinePointerInfo(), false, false, false, 0);
3551 // Return LR, which contains the return address. Mark it an implicit live-in.
3552 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3553 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3556 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3557 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3558 MFI->setFrameAddressIsTaken(true);
3560 EVT VT = Op.getValueType();
3561 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3562 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3563 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3564 ? ARM::R7 : ARM::R11;
3565 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3567 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3568 MachinePointerInfo(),
3569 false, false, false, 0);
3573 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3574 /// and size(DestVec) > 128-bits.
3575 /// This is achieved by doing the one extension from the SrcVec, splitting the
3576 /// result, extending these parts, and then concatenating these into the
3578 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3579 SDValue Op = N->getOperand(0);
3580 EVT SrcVT = Op.getValueType();
3581 EVT DestVT = N->getValueType(0);
3583 assert(DestVT.getSizeInBits() > 128 &&
3584 "Custom sext/zext expansion needs >128-bit vector.");
3585 // If this is a normal length extension, use the default expansion.
3586 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3587 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3590 DebugLoc dl = N->getDebugLoc();
3591 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3592 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3593 unsigned NumElts = SrcVT.getVectorNumElements();
3594 LLVMContext &Ctx = *DAG.getContext();
3595 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3597 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3599 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3601 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3604 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3605 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3606 DAG.getIntPtrConstant(0));
3607 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3608 DAG.getIntPtrConstant(NumElts/2));
3609 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3610 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3611 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3614 /// ExpandBITCAST - If the target supports VFP, this function is called to
3615 /// expand a bit convert where either the source or destination type is i64 to
3616 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3617 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3618 /// vectors), since the legalizer won't know what to do with that.
3619 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3620 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3621 DebugLoc dl = N->getDebugLoc();
3622 SDValue Op = N->getOperand(0);
3624 // This function is only supposed to be called for i64 types, either as the
3625 // source or destination of the bit convert.
3626 EVT SrcVT = Op.getValueType();
3627 EVT DstVT = N->getValueType(0);
3628 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3629 "ExpandBITCAST called for non-i64 type");
3631 // Turn i64->f64 into VMOVDRR.
3632 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3633 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3634 DAG.getConstant(0, MVT::i32));
3635 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3636 DAG.getConstant(1, MVT::i32));
3637 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3638 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3641 // Turn f64->i64 into VMOVRRD.
3642 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3643 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3644 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3645 // Merge the pieces into a single i64 value.
3646 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3652 /// getZeroVector - Returns a vector of specified type with all zero elements.
3653 /// Zero vectors are used to represent vector negation and in those cases
3654 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3655 /// not support i64 elements, so sometimes the zero vectors will need to be
3656 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3658 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3659 assert(VT.isVector() && "Expected a vector type");
3660 // The canonical modified immediate encoding of a zero vector is....0!
3661 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3662 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3663 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3664 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3667 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3668 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3669 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3670 SelectionDAG &DAG) const {
3671 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3672 EVT VT = Op.getValueType();
3673 unsigned VTBits = VT.getSizeInBits();
3674 DebugLoc dl = Op.getDebugLoc();
3675 SDValue ShOpLo = Op.getOperand(0);
3676 SDValue ShOpHi = Op.getOperand(1);
3677 SDValue ShAmt = Op.getOperand(2);
3679 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3681 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3683 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3684 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3685 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3686 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3687 DAG.getConstant(VTBits, MVT::i32));
3688 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3689 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3690 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3692 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3693 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3695 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3696 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3699 SDValue Ops[2] = { Lo, Hi };
3700 return DAG.getMergeValues(Ops, 2, dl);
3703 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3704 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3705 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3706 SelectionDAG &DAG) const {
3707 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3708 EVT VT = Op.getValueType();
3709 unsigned VTBits = VT.getSizeInBits();
3710 DebugLoc dl = Op.getDebugLoc();
3711 SDValue ShOpLo = Op.getOperand(0);
3712 SDValue ShOpHi = Op.getOperand(1);
3713 SDValue ShAmt = Op.getOperand(2);
3716 assert(Op.getOpcode() == ISD::SHL_PARTS);
3717 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3718 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3719 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3720 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3721 DAG.getConstant(VTBits, MVT::i32));
3722 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3723 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3725 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3726 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3727 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3729 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3730 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3733 SDValue Ops[2] = { Lo, Hi };
3734 return DAG.getMergeValues(Ops, 2, dl);
3737 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3738 SelectionDAG &DAG) const {
3739 // The rounding mode is in bits 23:22 of the FPSCR.
3740 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3741 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3742 // so that the shift + and get folded into a bitfield extract.
3743 DebugLoc dl = Op.getDebugLoc();
3744 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3745 DAG.getConstant(Intrinsic::arm_get_fpscr,
3747 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3748 DAG.getConstant(1U << 22, MVT::i32));
3749 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3750 DAG.getConstant(22, MVT::i32));
3751 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3752 DAG.getConstant(3, MVT::i32));
3755 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3756 const ARMSubtarget *ST) {
3757 EVT VT = N->getValueType(0);
3758 DebugLoc dl = N->getDebugLoc();
3760 if (!ST->hasV6T2Ops())
3763 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3764 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3767 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3768 /// for each 16-bit element from operand, repeated. The basic idea is to
3769 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3771 /// Trace for v4i16:
3772 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3773 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3774 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3775 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3776 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3777 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3778 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3779 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3780 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3781 EVT VT = N->getValueType(0);
3782 DebugLoc DL = N->getDebugLoc();
3784 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3785 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3786 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3787 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3788 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3789 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3792 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3793 /// bit-count for each 16-bit element from the operand. We need slightly
3794 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3795 /// 64/128-bit registers.
3797 /// Trace for v4i16:
3798 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3799 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3800 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3801 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3802 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3803 EVT VT = N->getValueType(0);
3804 DebugLoc DL = N->getDebugLoc();
3806 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3807 if (VT.is64BitVector()) {
3808 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3809 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3810 DAG.getIntPtrConstant(0));
3812 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3813 BitCounts, DAG.getIntPtrConstant(0));
3814 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3818 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3819 /// bit-count for each 32-bit element from the operand. The idea here is
3820 /// to split the vector into 16-bit elements, leverage the 16-bit count
3821 /// routine, and then combine the results.
3823 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3824 /// input = [v0 v1 ] (vi: 32-bit elements)
3825 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3826 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3827 /// vrev: N0 = [k1 k0 k3 k2 ]
3829 /// N1 =+[k1 k0 k3 k2 ]
3831 /// N2 =+[k1 k3 k0 k2 ]
3833 /// Extended =+[k1 k3 k0 k2 ]
3835 /// Extracted=+[k1 k3 ]
3837 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3838 EVT VT = N->getValueType(0);
3839 DebugLoc DL = N->getDebugLoc();
3841 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3843 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3844 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3845 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3846 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3847 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3849 if (VT.is64BitVector()) {
3850 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3851 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3852 DAG.getIntPtrConstant(0));
3854 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3855 DAG.getIntPtrConstant(0));
3856 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3860 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3861 const ARMSubtarget *ST) {
3862 EVT VT = N->getValueType(0);
3864 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3865 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3866 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3867 "Unexpected type for custom ctpop lowering");
3869 if (VT.getVectorElementType() == MVT::i32)
3870 return lowerCTPOP32BitElements(N, DAG);
3872 return lowerCTPOP16BitElements(N, DAG);
3875 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3876 const ARMSubtarget *ST) {
3877 EVT VT = N->getValueType(0);
3878 DebugLoc dl = N->getDebugLoc();
3883 // Lower vector shifts on NEON to use VSHL.
3884 assert(ST->hasNEON() && "unexpected vector shift");
3886 // Left shifts translate directly to the vshiftu intrinsic.
3887 if (N->getOpcode() == ISD::SHL)
3888 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3889 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3890 N->getOperand(0), N->getOperand(1));
3892 assert((N->getOpcode() == ISD::SRA ||
3893 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3895 // NEON uses the same intrinsics for both left and right shifts. For
3896 // right shifts, the shift amounts are negative, so negate the vector of
3898 EVT ShiftVT = N->getOperand(1).getValueType();
3899 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3900 getZeroVector(ShiftVT, DAG, dl),
3902 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3903 Intrinsic::arm_neon_vshifts :
3904 Intrinsic::arm_neon_vshiftu);
3905 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3906 DAG.getConstant(vshiftInt, MVT::i32),
3907 N->getOperand(0), NegatedCount);
3910 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3911 const ARMSubtarget *ST) {
3912 EVT VT = N->getValueType(0);
3913 DebugLoc dl = N->getDebugLoc();
3915 // We can get here for a node like i32 = ISD::SHL i32, i64
3919 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3920 "Unknown shift to lower!");
3922 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3923 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3924 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3927 // If we are in thumb mode, we don't have RRX.
3928 if (ST->isThumb1Only()) return SDValue();
3930 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3931 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3932 DAG.getConstant(0, MVT::i32));
3933 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3934 DAG.getConstant(1, MVT::i32));
3936 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3937 // captures the result into a carry flag.
3938 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3939 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3941 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3942 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3944 // Merge the pieces into a single i64 value.
3945 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3948 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3949 SDValue TmpOp0, TmpOp1;
3950 bool Invert = false;
3954 SDValue Op0 = Op.getOperand(0);
3955 SDValue Op1 = Op.getOperand(1);
3956 SDValue CC = Op.getOperand(2);
3957 EVT VT = Op.getValueType();
3958 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3959 DebugLoc dl = Op.getDebugLoc();
3961 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3962 switch (SetCCOpcode) {
3963 default: llvm_unreachable("Illegal FP comparison");
3965 case ISD::SETNE: Invert = true; // Fallthrough
3967 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3969 case ISD::SETLT: Swap = true; // Fallthrough
3971 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3973 case ISD::SETLE: Swap = true; // Fallthrough
3975 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3976 case ISD::SETUGE: Swap = true; // Fallthrough
3977 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3978 case ISD::SETUGT: Swap = true; // Fallthrough
3979 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3980 case ISD::SETUEQ: Invert = true; // Fallthrough
3982 // Expand this to (OLT | OGT).
3986 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3987 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3989 case ISD::SETUO: Invert = true; // Fallthrough
3991 // Expand this to (OLT | OGE).
3995 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3996 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4000 // Integer comparisons.
4001 switch (SetCCOpcode) {
4002 default: llvm_unreachable("Illegal integer comparison");
4003 case ISD::SETNE: Invert = true;
4004 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4005 case ISD::SETLT: Swap = true;
4006 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4007 case ISD::SETLE: Swap = true;
4008 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4009 case ISD::SETULT: Swap = true;
4010 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4011 case ISD::SETULE: Swap = true;
4012 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4015 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4016 if (Opc == ARMISD::VCEQ) {
4019 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4021 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4024 // Ignore bitconvert.
4025 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4026 AndOp = AndOp.getOperand(0);
4028 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4030 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4031 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4038 std::swap(Op0, Op1);
4040 // If one of the operands is a constant vector zero, attempt to fold the
4041 // comparison to a specialized compare-against-zero form.
4043 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4045 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4046 if (Opc == ARMISD::VCGE)
4047 Opc = ARMISD::VCLEZ;
4048 else if (Opc == ARMISD::VCGT)
4049 Opc = ARMISD::VCLTZ;
4054 if (SingleOp.getNode()) {
4057 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4059 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4061 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4063 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4065 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4067 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4070 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4074 Result = DAG.getNOT(dl, Result, VT);
4079 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4080 /// valid vector constant for a NEON instruction with a "modified immediate"
4081 /// operand (e.g., VMOV). If so, return the encoded value.
4082 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4083 unsigned SplatBitSize, SelectionDAG &DAG,
4084 EVT &VT, bool is128Bits, NEONModImmType type) {
4085 unsigned OpCmode, Imm;
4087 // SplatBitSize is set to the smallest size that splats the vector, so a
4088 // zero vector will always have SplatBitSize == 8. However, NEON modified
4089 // immediate instructions others than VMOV do not support the 8-bit encoding
4090 // of a zero vector, and the default encoding of zero is supposed to be the
4095 switch (SplatBitSize) {
4097 if (type != VMOVModImm)
4099 // Any 1-byte value is OK. Op=0, Cmode=1110.
4100 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4103 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4107 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4108 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4109 if ((SplatBits & ~0xff) == 0) {
4110 // Value = 0x00nn: Op=x, Cmode=100x.
4115 if ((SplatBits & ~0xff00) == 0) {
4116 // Value = 0xnn00: Op=x, Cmode=101x.
4118 Imm = SplatBits >> 8;
4124 // NEON's 32-bit VMOV supports splat values where:
4125 // * only one byte is nonzero, or
4126 // * the least significant byte is 0xff and the second byte is nonzero, or
4127 // * the least significant 2 bytes are 0xff and the third is nonzero.
4128 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4129 if ((SplatBits & ~0xff) == 0) {
4130 // Value = 0x000000nn: Op=x, Cmode=000x.
4135 if ((SplatBits & ~0xff00) == 0) {
4136 // Value = 0x0000nn00: Op=x, Cmode=001x.
4138 Imm = SplatBits >> 8;
4141 if ((SplatBits & ~0xff0000) == 0) {
4142 // Value = 0x00nn0000: Op=x, Cmode=010x.
4144 Imm = SplatBits >> 16;
4147 if ((SplatBits & ~0xff000000) == 0) {
4148 // Value = 0xnn000000: Op=x, Cmode=011x.
4150 Imm = SplatBits >> 24;
4154 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4155 if (type == OtherModImm) return SDValue();
4157 if ((SplatBits & ~0xffff) == 0 &&
4158 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4159 // Value = 0x0000nnff: Op=x, Cmode=1100.
4161 Imm = SplatBits >> 8;
4166 if ((SplatBits & ~0xffffff) == 0 &&
4167 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4168 // Value = 0x00nnffff: Op=x, Cmode=1101.
4170 Imm = SplatBits >> 16;
4171 SplatBits |= 0xffff;
4175 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4176 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4177 // VMOV.I32. A (very) minor optimization would be to replicate the value
4178 // and fall through here to test for a valid 64-bit splat. But, then the
4179 // caller would also need to check and handle the change in size.
4183 if (type != VMOVModImm)
4185 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4186 uint64_t BitMask = 0xff;
4188 unsigned ImmMask = 1;
4190 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4191 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4194 } else if ((SplatBits & BitMask) != 0) {
4200 // Op=1, Cmode=1110.
4203 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4208 llvm_unreachable("unexpected size for isNEONModifiedImm");
4211 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4212 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4215 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4216 const ARMSubtarget *ST) const {
4217 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4220 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4221 assert(Op.getValueType() == MVT::f32 &&
4222 "ConstantFP custom lowering should only occur for f32.");
4224 // Try splatting with a VMOV.f32...
4225 APFloat FPVal = CFP->getValueAPF();
4226 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4228 DebugLoc DL = Op.getDebugLoc();
4229 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4230 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4232 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4233 DAG.getConstant(0, MVT::i32));
4236 // If that fails, try a VMOV.i32
4238 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4239 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4241 if (NewVal != SDValue()) {
4242 DebugLoc DL = Op.getDebugLoc();
4243 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4245 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4247 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4248 DAG.getConstant(0, MVT::i32));
4251 // Finally, try a VMVN.i32
4252 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4254 if (NewVal != SDValue()) {
4255 DebugLoc DL = Op.getDebugLoc();
4256 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4257 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4259 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4260 DAG.getConstant(0, MVT::i32));
4266 // check if an VEXT instruction can handle the shuffle mask when the
4267 // vector sources of the shuffle are the same.
4268 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4269 unsigned NumElts = VT.getVectorNumElements();
4271 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4277 // If this is a VEXT shuffle, the immediate value is the index of the first
4278 // element. The other shuffle indices must be the successive elements after
4280 unsigned ExpectedElt = Imm;
4281 for (unsigned i = 1; i < NumElts; ++i) {
4282 // Increment the expected index. If it wraps around, just follow it
4283 // back to index zero and keep going.
4285 if (ExpectedElt == NumElts)
4288 if (M[i] < 0) continue; // ignore UNDEF indices
4289 if (ExpectedElt != static_cast<unsigned>(M[i]))
4297 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4298 bool &ReverseVEXT, unsigned &Imm) {
4299 unsigned NumElts = VT.getVectorNumElements();
4300 ReverseVEXT = false;
4302 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4308 // If this is a VEXT shuffle, the immediate value is the index of the first
4309 // element. The other shuffle indices must be the successive elements after
4311 unsigned ExpectedElt = Imm;
4312 for (unsigned i = 1; i < NumElts; ++i) {
4313 // Increment the expected index. If it wraps around, it may still be
4314 // a VEXT but the source vectors must be swapped.
4316 if (ExpectedElt == NumElts * 2) {
4321 if (M[i] < 0) continue; // ignore UNDEF indices
4322 if (ExpectedElt != static_cast<unsigned>(M[i]))
4326 // Adjust the index value if the source operands will be swapped.
4333 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4334 /// instruction with the specified blocksize. (The order of the elements
4335 /// within each block of the vector is reversed.)
4336 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4337 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4338 "Only possible block sizes for VREV are: 16, 32, 64");
4340 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4344 unsigned NumElts = VT.getVectorNumElements();
4345 unsigned BlockElts = M[0] + 1;
4346 // If the first shuffle index is UNDEF, be optimistic.
4348 BlockElts = BlockSize / EltSz;
4350 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4353 for (unsigned i = 0; i < NumElts; ++i) {
4354 if (M[i] < 0) continue; // ignore UNDEF indices
4355 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4362 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4363 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4364 // range, then 0 is placed into the resulting vector. So pretty much any mask
4365 // of 8 elements can work here.
4366 return VT == MVT::v8i8 && M.size() == 8;
4369 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4370 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4374 unsigned NumElts = VT.getVectorNumElements();
4375 WhichResult = (M[0] == 0 ? 0 : 1);
4376 for (unsigned i = 0; i < NumElts; i += 2) {
4377 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4378 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4384 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4385 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4386 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4387 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4388 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4392 unsigned NumElts = VT.getVectorNumElements();
4393 WhichResult = (M[0] == 0 ? 0 : 1);
4394 for (unsigned i = 0; i < NumElts; i += 2) {
4395 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4396 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4402 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4403 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4407 unsigned NumElts = VT.getVectorNumElements();
4408 WhichResult = (M[0] == 0 ? 0 : 1);
4409 for (unsigned i = 0; i != NumElts; ++i) {
4410 if (M[i] < 0) continue; // ignore UNDEF indices
4411 if ((unsigned) M[i] != 2 * i + WhichResult)
4415 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4416 if (VT.is64BitVector() && EltSz == 32)
4422 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4423 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4424 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4425 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4426 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4430 unsigned Half = VT.getVectorNumElements() / 2;
4431 WhichResult = (M[0] == 0 ? 0 : 1);
4432 for (unsigned j = 0; j != 2; ++j) {
4433 unsigned Idx = WhichResult;
4434 for (unsigned i = 0; i != Half; ++i) {
4435 int MIdx = M[i + j * Half];
4436 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4442 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4443 if (VT.is64BitVector() && EltSz == 32)
4449 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4450 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4454 unsigned NumElts = VT.getVectorNumElements();
4455 WhichResult = (M[0] == 0 ? 0 : 1);
4456 unsigned Idx = WhichResult * NumElts / 2;
4457 for (unsigned i = 0; i != NumElts; i += 2) {
4458 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4459 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4464 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4465 if (VT.is64BitVector() && EltSz == 32)
4471 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4472 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4473 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4474 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4475 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4479 unsigned NumElts = VT.getVectorNumElements();
4480 WhichResult = (M[0] == 0 ? 0 : 1);
4481 unsigned Idx = WhichResult * NumElts / 2;
4482 for (unsigned i = 0; i != NumElts; i += 2) {
4483 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4484 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4489 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4490 if (VT.is64BitVector() && EltSz == 32)
4496 /// \return true if this is a reverse operation on an vector.
4497 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4498 unsigned NumElts = VT.getVectorNumElements();
4499 // Make sure the mask has the right size.
4500 if (NumElts != M.size())
4503 // Look for <15, ..., 3, -1, 1, 0>.
4504 for (unsigned i = 0; i != NumElts; ++i)
4505 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4511 // If N is an integer constant that can be moved into a register in one
4512 // instruction, return an SDValue of such a constant (will become a MOV
4513 // instruction). Otherwise return null.
4514 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4515 const ARMSubtarget *ST, DebugLoc dl) {
4517 if (!isa<ConstantSDNode>(N))
4519 Val = cast<ConstantSDNode>(N)->getZExtValue();
4521 if (ST->isThumb1Only()) {
4522 if (Val <= 255 || ~Val <= 255)
4523 return DAG.getConstant(Val, MVT::i32);
4525 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4526 return DAG.getConstant(Val, MVT::i32);
4531 // If this is a case we can't handle, return null and let the default
4532 // expansion code take care of it.
4533 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4534 const ARMSubtarget *ST) const {
4535 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4536 DebugLoc dl = Op.getDebugLoc();
4537 EVT VT = Op.getValueType();
4539 APInt SplatBits, SplatUndef;
4540 unsigned SplatBitSize;
4542 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4543 if (SplatBitSize <= 64) {
4544 // Check if an immediate VMOV works.
4546 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4547 SplatUndef.getZExtValue(), SplatBitSize,
4548 DAG, VmovVT, VT.is128BitVector(),
4550 if (Val.getNode()) {
4551 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4552 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4555 // Try an immediate VMVN.
4556 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4557 Val = isNEONModifiedImm(NegatedImm,
4558 SplatUndef.getZExtValue(), SplatBitSize,
4559 DAG, VmovVT, VT.is128BitVector(),
4561 if (Val.getNode()) {
4562 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4563 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4566 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4567 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4568 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4570 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4571 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4577 // Scan through the operands to see if only one value is used.
4579 // As an optimisation, even if more than one value is used it may be more
4580 // profitable to splat with one value then change some lanes.
4582 // Heuristically we decide to do this if the vector has a "dominant" value,
4583 // defined as splatted to more than half of the lanes.
4584 unsigned NumElts = VT.getVectorNumElements();
4585 bool isOnlyLowElement = true;
4586 bool usesOnlyOneValue = true;
4587 bool hasDominantValue = false;
4588 bool isConstant = true;
4590 // Map of the number of times a particular SDValue appears in the
4592 DenseMap<SDValue, unsigned> ValueCounts;
4594 for (unsigned i = 0; i < NumElts; ++i) {
4595 SDValue V = Op.getOperand(i);
4596 if (V.getOpcode() == ISD::UNDEF)
4599 isOnlyLowElement = false;
4600 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4603 ValueCounts.insert(std::make_pair(V, 0));
4604 unsigned &Count = ValueCounts[V];
4606 // Is this value dominant? (takes up more than half of the lanes)
4607 if (++Count > (NumElts / 2)) {
4608 hasDominantValue = true;
4612 if (ValueCounts.size() != 1)
4613 usesOnlyOneValue = false;
4614 if (!Value.getNode() && ValueCounts.size() > 0)
4615 Value = ValueCounts.begin()->first;
4617 if (ValueCounts.size() == 0)
4618 return DAG.getUNDEF(VT);
4620 if (isOnlyLowElement)
4621 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4623 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4625 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4626 // i32 and try again.
4627 if (hasDominantValue && EltSize <= 32) {
4631 // If we are VDUPing a value that comes directly from a vector, that will
4632 // cause an unnecessary move to and from a GPR, where instead we could
4633 // just use VDUPLANE. We can only do this if the lane being extracted
4634 // is at a constant index, as the VDUP from lane instructions only have
4635 // constant-index forms.
4636 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4637 isa<ConstantSDNode>(Value->getOperand(1))) {
4638 // We need to create a new undef vector to use for the VDUPLANE if the
4639 // size of the vector from which we get the value is different than the
4640 // size of the vector that we need to create. We will insert the element
4641 // such that the register coalescer will remove unnecessary copies.
4642 if (VT != Value->getOperand(0).getValueType()) {
4643 ConstantSDNode *constIndex;
4644 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4645 assert(constIndex && "The index is not a constant!");
4646 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4647 VT.getVectorNumElements();
4648 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4649 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4650 Value, DAG.getConstant(index, MVT::i32)),
4651 DAG.getConstant(index, MVT::i32));
4653 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4654 Value->getOperand(0), Value->getOperand(1));
4656 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4658 if (!usesOnlyOneValue) {
4659 // The dominant value was splatted as 'N', but we now have to insert
4660 // all differing elements.
4661 for (unsigned I = 0; I < NumElts; ++I) {
4662 if (Op.getOperand(I) == Value)
4664 SmallVector<SDValue, 3> Ops;
4666 Ops.push_back(Op.getOperand(I));
4667 Ops.push_back(DAG.getConstant(I, MVT::i32));
4668 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4673 if (VT.getVectorElementType().isFloatingPoint()) {
4674 SmallVector<SDValue, 8> Ops;
4675 for (unsigned i = 0; i < NumElts; ++i)
4676 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4678 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4679 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4680 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4682 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4684 if (usesOnlyOneValue) {
4685 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4686 if (isConstant && Val.getNode())
4687 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4691 // If all elements are constants and the case above didn't get hit, fall back
4692 // to the default expansion, which will generate a load from the constant
4697 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4699 SDValue shuffle = ReconstructShuffle(Op, DAG);
4700 if (shuffle != SDValue())
4704 // Vectors with 32- or 64-bit elements can be built by directly assigning
4705 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4706 // will be legalized.
4707 if (EltSize >= 32) {
4708 // Do the expansion with floating-point types, since that is what the VFP
4709 // registers are defined to use, and since i64 is not legal.
4710 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4711 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4712 SmallVector<SDValue, 8> Ops;
4713 for (unsigned i = 0; i < NumElts; ++i)
4714 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4715 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4716 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4722 // Gather data to see if the operation can be modelled as a
4723 // shuffle in combination with VEXTs.
4724 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4725 SelectionDAG &DAG) const {
4726 DebugLoc dl = Op.getDebugLoc();
4727 EVT VT = Op.getValueType();
4728 unsigned NumElts = VT.getVectorNumElements();
4730 SmallVector<SDValue, 2> SourceVecs;
4731 SmallVector<unsigned, 2> MinElts;
4732 SmallVector<unsigned, 2> MaxElts;
4734 for (unsigned i = 0; i < NumElts; ++i) {
4735 SDValue V = Op.getOperand(i);
4736 if (V.getOpcode() == ISD::UNDEF)
4738 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4739 // A shuffle can only come from building a vector from various
4740 // elements of other vectors.
4742 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4743 VT.getVectorElementType()) {
4744 // This code doesn't know how to handle shuffles where the vector
4745 // element types do not match (this happens because type legalization
4746 // promotes the return type of EXTRACT_VECTOR_ELT).
4747 // FIXME: It might be appropriate to extend this code to handle
4748 // mismatched types.
4752 // Record this extraction against the appropriate vector if possible...
4753 SDValue SourceVec = V.getOperand(0);
4754 // If the element number isn't a constant, we can't effectively
4755 // analyze what's going on.
4756 if (!isa<ConstantSDNode>(V.getOperand(1)))
4758 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4759 bool FoundSource = false;
4760 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4761 if (SourceVecs[j] == SourceVec) {
4762 if (MinElts[j] > EltNo)
4764 if (MaxElts[j] < EltNo)
4771 // Or record a new source if not...
4773 SourceVecs.push_back(SourceVec);
4774 MinElts.push_back(EltNo);
4775 MaxElts.push_back(EltNo);
4779 // Currently only do something sane when at most two source vectors
4781 if (SourceVecs.size() > 2)
4784 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4785 int VEXTOffsets[2] = {0, 0};
4787 // This loop extracts the usage patterns of the source vectors
4788 // and prepares appropriate SDValues for a shuffle if possible.
4789 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4790 if (SourceVecs[i].getValueType() == VT) {
4791 // No VEXT necessary
4792 ShuffleSrcs[i] = SourceVecs[i];
4795 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4796 // It probably isn't worth padding out a smaller vector just to
4797 // break it down again in a shuffle.
4801 // Since only 64-bit and 128-bit vectors are legal on ARM and
4802 // we've eliminated the other cases...
4803 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4804 "unexpected vector sizes in ReconstructShuffle");
4806 if (MaxElts[i] - MinElts[i] >= NumElts) {
4807 // Span too large for a VEXT to cope
4811 if (MinElts[i] >= NumElts) {
4812 // The extraction can just take the second half
4813 VEXTOffsets[i] = NumElts;
4814 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4816 DAG.getIntPtrConstant(NumElts));
4817 } else if (MaxElts[i] < NumElts) {
4818 // The extraction can just take the first half
4820 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4822 DAG.getIntPtrConstant(0));
4824 // An actual VEXT is needed
4825 VEXTOffsets[i] = MinElts[i];
4826 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4828 DAG.getIntPtrConstant(0));
4829 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4831 DAG.getIntPtrConstant(NumElts));
4832 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4833 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4837 SmallVector<int, 8> Mask;
4839 for (unsigned i = 0; i < NumElts; ++i) {
4840 SDValue Entry = Op.getOperand(i);
4841 if (Entry.getOpcode() == ISD::UNDEF) {
4846 SDValue ExtractVec = Entry.getOperand(0);
4847 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4848 .getOperand(1))->getSExtValue();
4849 if (ExtractVec == SourceVecs[0]) {
4850 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4852 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4856 // Final check before we try to produce nonsense...
4857 if (isShuffleMaskLegal(Mask, VT))
4858 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4864 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4865 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4866 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4867 /// are assumed to be legal.
4869 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4871 if (VT.getVectorNumElements() == 4 &&
4872 (VT.is128BitVector() || VT.is64BitVector())) {
4873 unsigned PFIndexes[4];
4874 for (unsigned i = 0; i != 4; ++i) {
4878 PFIndexes[i] = M[i];
4881 // Compute the index in the perfect shuffle table.
4882 unsigned PFTableIndex =
4883 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4884 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4885 unsigned Cost = (PFEntry >> 30);
4892 unsigned Imm, WhichResult;
4894 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4895 return (EltSize >= 32 ||
4896 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4897 isVREVMask(M, VT, 64) ||
4898 isVREVMask(M, VT, 32) ||
4899 isVREVMask(M, VT, 16) ||
4900 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4901 isVTBLMask(M, VT) ||
4902 isVTRNMask(M, VT, WhichResult) ||
4903 isVUZPMask(M, VT, WhichResult) ||
4904 isVZIPMask(M, VT, WhichResult) ||
4905 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4906 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4907 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4908 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4911 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4912 /// the specified operations to build the shuffle.
4913 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4914 SDValue RHS, SelectionDAG &DAG,
4916 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4917 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4918 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4921 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4930 OP_VUZPL, // VUZP, left result
4931 OP_VUZPR, // VUZP, right result
4932 OP_VZIPL, // VZIP, left result
4933 OP_VZIPR, // VZIP, right result
4934 OP_VTRNL, // VTRN, left result
4935 OP_VTRNR // VTRN, right result
4938 if (OpNum == OP_COPY) {
4939 if (LHSID == (1*9+2)*9+3) return LHS;
4940 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4944 SDValue OpLHS, OpRHS;
4945 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4946 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4947 EVT VT = OpLHS.getValueType();
4950 default: llvm_unreachable("Unknown shuffle opcode!");
4952 // VREV divides the vector in half and swaps within the half.
4953 if (VT.getVectorElementType() == MVT::i32 ||
4954 VT.getVectorElementType() == MVT::f32)
4955 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4956 // vrev <4 x i16> -> VREV32
4957 if (VT.getVectorElementType() == MVT::i16)
4958 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4959 // vrev <4 x i8> -> VREV16
4960 assert(VT.getVectorElementType() == MVT::i8);
4961 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4966 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4967 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4971 return DAG.getNode(ARMISD::VEXT, dl, VT,
4973 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4976 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4977 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4980 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4981 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4984 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4985 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4989 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4990 ArrayRef<int> ShuffleMask,
4991 SelectionDAG &DAG) {
4992 // Check to see if we can use the VTBL instruction.
4993 SDValue V1 = Op.getOperand(0);
4994 SDValue V2 = Op.getOperand(1);
4995 DebugLoc DL = Op.getDebugLoc();
4997 SmallVector<SDValue, 8> VTBLMask;
4998 for (ArrayRef<int>::iterator
4999 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5000 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5002 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5003 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5004 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5007 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5008 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5012 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5013 SelectionDAG &DAG) {
5014 DebugLoc DL = Op.getDebugLoc();
5015 SDValue OpLHS = Op.getOperand(0);
5016 EVT VT = OpLHS.getValueType();
5018 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5019 "Expect an v8i16/v16i8 type");
5020 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5021 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5022 // extract the first 8 bytes into the top double word and the last 8 bytes
5023 // into the bottom double word. The v8i16 case is similar.
5024 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5025 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5026 DAG.getConstant(ExtractNum, MVT::i32));
5029 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5030 SDValue V1 = Op.getOperand(0);
5031 SDValue V2 = Op.getOperand(1);
5032 DebugLoc dl = Op.getDebugLoc();
5033 EVT VT = Op.getValueType();
5034 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5036 // Convert shuffles that are directly supported on NEON to target-specific
5037 // DAG nodes, instead of keeping them as shuffles and matching them again
5038 // during code selection. This is more efficient and avoids the possibility
5039 // of inconsistencies between legalization and selection.
5040 // FIXME: floating-point vectors should be canonicalized to integer vectors
5041 // of the same time so that they get CSEd properly.
5042 ArrayRef<int> ShuffleMask = SVN->getMask();
5044 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5045 if (EltSize <= 32) {
5046 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5047 int Lane = SVN->getSplatIndex();
5048 // If this is undef splat, generate it via "just" vdup, if possible.
5049 if (Lane == -1) Lane = 0;
5051 // Test if V1 is a SCALAR_TO_VECTOR.
5052 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5053 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5055 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5056 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5058 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5059 !isa<ConstantSDNode>(V1.getOperand(0))) {
5060 bool IsScalarToVector = true;
5061 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5062 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5063 IsScalarToVector = false;
5066 if (IsScalarToVector)
5067 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5069 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5070 DAG.getConstant(Lane, MVT::i32));
5075 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5078 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5079 DAG.getConstant(Imm, MVT::i32));
5082 if (isVREVMask(ShuffleMask, VT, 64))
5083 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5084 if (isVREVMask(ShuffleMask, VT, 32))
5085 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5086 if (isVREVMask(ShuffleMask, VT, 16))
5087 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5089 if (V2->getOpcode() == ISD::UNDEF &&
5090 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5091 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5092 DAG.getConstant(Imm, MVT::i32));
5095 // Check for Neon shuffles that modify both input vectors in place.
5096 // If both results are used, i.e., if there are two shuffles with the same
5097 // source operands and with masks corresponding to both results of one of
5098 // these operations, DAG memoization will ensure that a single node is
5099 // used for both shuffles.
5100 unsigned WhichResult;
5101 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5102 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5103 V1, V2).getValue(WhichResult);
5104 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5105 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5106 V1, V2).getValue(WhichResult);
5107 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5108 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5109 V1, V2).getValue(WhichResult);
5111 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5112 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5113 V1, V1).getValue(WhichResult);
5114 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5115 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5116 V1, V1).getValue(WhichResult);
5117 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5118 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5119 V1, V1).getValue(WhichResult);
5122 // If the shuffle is not directly supported and it has 4 elements, use
5123 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5124 unsigned NumElts = VT.getVectorNumElements();
5126 unsigned PFIndexes[4];
5127 for (unsigned i = 0; i != 4; ++i) {
5128 if (ShuffleMask[i] < 0)
5131 PFIndexes[i] = ShuffleMask[i];
5134 // Compute the index in the perfect shuffle table.
5135 unsigned PFTableIndex =
5136 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5137 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5138 unsigned Cost = (PFEntry >> 30);
5141 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5144 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5145 if (EltSize >= 32) {
5146 // Do the expansion with floating-point types, since that is what the VFP
5147 // registers are defined to use, and since i64 is not legal.
5148 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5149 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5150 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5151 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5152 SmallVector<SDValue, 8> Ops;
5153 for (unsigned i = 0; i < NumElts; ++i) {
5154 if (ShuffleMask[i] < 0)
5155 Ops.push_back(DAG.getUNDEF(EltVT));
5157 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5158 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5159 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5162 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5163 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5166 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5167 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5169 if (VT == MVT::v8i8) {
5170 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5171 if (NewOp.getNode())
5178 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5179 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5180 SDValue Lane = Op.getOperand(2);
5181 if (!isa<ConstantSDNode>(Lane))
5187 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5188 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5189 SDValue Lane = Op.getOperand(1);
5190 if (!isa<ConstantSDNode>(Lane))
5193 SDValue Vec = Op.getOperand(0);
5194 if (Op.getValueType() == MVT::i32 &&
5195 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5196 DebugLoc dl = Op.getDebugLoc();
5197 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5203 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5204 // The only time a CONCAT_VECTORS operation can have legal types is when
5205 // two 64-bit vectors are concatenated to a 128-bit vector.
5206 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5207 "unexpected CONCAT_VECTORS");
5208 DebugLoc dl = Op.getDebugLoc();
5209 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5210 SDValue Op0 = Op.getOperand(0);
5211 SDValue Op1 = Op.getOperand(1);
5212 if (Op0.getOpcode() != ISD::UNDEF)
5213 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5214 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5215 DAG.getIntPtrConstant(0));
5216 if (Op1.getOpcode() != ISD::UNDEF)
5217 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5218 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5219 DAG.getIntPtrConstant(1));
5220 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5223 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5224 /// element has been zero/sign-extended, depending on the isSigned parameter,
5225 /// from an integer type half its size.
5226 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5228 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5229 EVT VT = N->getValueType(0);
5230 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5231 SDNode *BVN = N->getOperand(0).getNode();
5232 if (BVN->getValueType(0) != MVT::v4i32 ||
5233 BVN->getOpcode() != ISD::BUILD_VECTOR)
5235 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5236 unsigned HiElt = 1 - LoElt;
5237 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5238 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5239 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5240 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5241 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5244 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5245 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5248 if (Hi0->isNullValue() && Hi1->isNullValue())
5254 if (N->getOpcode() != ISD::BUILD_VECTOR)
5257 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5258 SDNode *Elt = N->getOperand(i).getNode();
5259 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5260 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5261 unsigned HalfSize = EltSize / 2;
5263 if (!isIntN(HalfSize, C->getSExtValue()))
5266 if (!isUIntN(HalfSize, C->getZExtValue()))
5277 /// isSignExtended - Check if a node is a vector value that is sign-extended
5278 /// or a constant BUILD_VECTOR with sign-extended elements.
5279 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5280 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5282 if (isExtendedBUILD_VECTOR(N, DAG, true))
5287 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5288 /// or a constant BUILD_VECTOR with zero-extended elements.
5289 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5290 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5292 if (isExtendedBUILD_VECTOR(N, DAG, false))
5297 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5298 if (OrigVT.getSizeInBits() >= 64)
5301 assert(OrigVT.isSimple() && "Expecting a simple value type");
5303 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5304 switch (OrigSimpleTy) {
5305 default: llvm_unreachable("Unexpected Vector Type");
5314 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5315 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5316 /// We insert the required extension here to get the vector to fill a D register.
5317 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5320 unsigned ExtOpcode) {
5321 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5322 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5323 // 64-bits we need to insert a new extension so that it will be 64-bits.
5324 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5325 if (OrigTy.getSizeInBits() >= 64)
5328 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5329 EVT NewVT = getExtensionTo64Bits(OrigTy);
5331 return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5334 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5335 /// does not do any sign/zero extension. If the original vector is less
5336 /// than 64 bits, an appropriate extension will be added after the load to
5337 /// reach a total size of 64 bits. We have to add the extension separately
5338 /// because ARM does not have a sign/zero extending load for vectors.
5339 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5340 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5342 // The load already has the right type.
5343 if (ExtendedTy == LD->getMemoryVT())
5344 return DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5345 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5346 LD->isNonTemporal(), LD->isInvariant(),
5347 LD->getAlignment());
5349 // We need to create a zextload/sextload. We cannot just create a load
5350 // followed by a zext/zext node because LowerMUL is also run during normal
5351 // operation legalization where we can't create illegal types.
5352 return DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(), ExtendedTy,
5353 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5354 LD->getMemoryVT(), LD->isVolatile(),
5355 LD->isNonTemporal(), LD->getAlignment());
5358 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5359 /// extending load, or BUILD_VECTOR with extended elements, return the
5360 /// unextended value. The unextended vector should be 64 bits so that it can
5361 /// be used as an operand to a VMULL instruction. If the original vector size
5362 /// before extension is less than 64 bits we add a an extension to resize
5363 /// the vector to 64 bits.
5364 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5365 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5366 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5367 N->getOperand(0)->getValueType(0),
5371 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5372 return SkipLoadExtensionForVMULL(LD, DAG);
5374 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5375 // have been legalized as a BITCAST from v4i32.
5376 if (N->getOpcode() == ISD::BITCAST) {
5377 SDNode *BVN = N->getOperand(0).getNode();
5378 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5379 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5380 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5381 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5382 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5384 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5385 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5386 EVT VT = N->getValueType(0);
5387 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5388 unsigned NumElts = VT.getVectorNumElements();
5389 MVT TruncVT = MVT::getIntegerVT(EltSize);
5390 SmallVector<SDValue, 8> Ops;
5391 for (unsigned i = 0; i != NumElts; ++i) {
5392 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5393 const APInt &CInt = C->getAPIntValue();
5394 // Element types smaller than 32 bits are not legal, so use i32 elements.
5395 // The values are implicitly truncated so sext vs. zext doesn't matter.
5396 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5398 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5399 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5402 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5403 unsigned Opcode = N->getOpcode();
5404 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5405 SDNode *N0 = N->getOperand(0).getNode();
5406 SDNode *N1 = N->getOperand(1).getNode();
5407 return N0->hasOneUse() && N1->hasOneUse() &&
5408 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5413 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5414 unsigned Opcode = N->getOpcode();
5415 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5416 SDNode *N0 = N->getOperand(0).getNode();
5417 SDNode *N1 = N->getOperand(1).getNode();
5418 return N0->hasOneUse() && N1->hasOneUse() &&
5419 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5424 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5425 // Multiplications are only custom-lowered for 128-bit vectors so that
5426 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5427 EVT VT = Op.getValueType();
5428 assert(VT.is128BitVector() && VT.isInteger() &&
5429 "unexpected type for custom-lowering ISD::MUL");
5430 SDNode *N0 = Op.getOperand(0).getNode();
5431 SDNode *N1 = Op.getOperand(1).getNode();
5432 unsigned NewOpc = 0;
5434 bool isN0SExt = isSignExtended(N0, DAG);
5435 bool isN1SExt = isSignExtended(N1, DAG);
5436 if (isN0SExt && isN1SExt)
5437 NewOpc = ARMISD::VMULLs;
5439 bool isN0ZExt = isZeroExtended(N0, DAG);
5440 bool isN1ZExt = isZeroExtended(N1, DAG);
5441 if (isN0ZExt && isN1ZExt)
5442 NewOpc = ARMISD::VMULLu;
5443 else if (isN1SExt || isN1ZExt) {
5444 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5445 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5446 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5447 NewOpc = ARMISD::VMULLs;
5449 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5450 NewOpc = ARMISD::VMULLu;
5452 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5454 NewOpc = ARMISD::VMULLu;
5460 if (VT == MVT::v2i64)
5461 // Fall through to expand this. It is not legal.
5464 // Other vector multiplications are legal.
5469 // Legalize to a VMULL instruction.
5470 DebugLoc DL = Op.getDebugLoc();
5472 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5474 Op0 = SkipExtensionForVMULL(N0, DAG);
5475 assert(Op0.getValueType().is64BitVector() &&
5476 Op1.getValueType().is64BitVector() &&
5477 "unexpected types for extended operands to VMULL");
5478 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5481 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5482 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5489 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5490 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5491 EVT Op1VT = Op1.getValueType();
5492 return DAG.getNode(N0->getOpcode(), DL, VT,
5493 DAG.getNode(NewOpc, DL, VT,
5494 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5495 DAG.getNode(NewOpc, DL, VT,
5496 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5500 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5502 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5503 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5504 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5505 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5506 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5507 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5508 // Get reciprocal estimate.
5509 // float4 recip = vrecpeq_f32(yf);
5510 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5511 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5512 // Because char has a smaller range than uchar, we can actually get away
5513 // without any newton steps. This requires that we use a weird bias
5514 // of 0xb000, however (again, this has been exhaustively tested).
5515 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5516 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5517 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5518 Y = DAG.getConstant(0xb000, MVT::i32);
5519 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5520 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5521 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5522 // Convert back to short.
5523 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5524 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5529 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5531 // Convert to float.
5532 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5533 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5534 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5535 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5536 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5537 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5539 // Use reciprocal estimate and one refinement step.
5540 // float4 recip = vrecpeq_f32(yf);
5541 // recip *= vrecpsq_f32(yf, recip);
5542 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5543 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5544 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5545 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5547 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5548 // Because short has a smaller range than ushort, we can actually get away
5549 // with only a single newton step. This requires that we use a weird bias
5550 // of 89, however (again, this has been exhaustively tested).
5551 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5552 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5553 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5554 N1 = DAG.getConstant(0x89, MVT::i32);
5555 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5556 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5557 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5558 // Convert back to integer and return.
5559 // return vmovn_s32(vcvt_s32_f32(result));
5560 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5561 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5565 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5566 EVT VT = Op.getValueType();
5567 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5568 "unexpected type for custom-lowering ISD::SDIV");
5570 DebugLoc dl = Op.getDebugLoc();
5571 SDValue N0 = Op.getOperand(0);
5572 SDValue N1 = Op.getOperand(1);
5575 if (VT == MVT::v8i8) {
5576 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5577 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5579 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5580 DAG.getIntPtrConstant(4));
5581 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5582 DAG.getIntPtrConstant(4));
5583 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5584 DAG.getIntPtrConstant(0));
5585 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5586 DAG.getIntPtrConstant(0));
5588 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5589 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5591 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5592 N0 = LowerCONCAT_VECTORS(N0, DAG);
5594 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5597 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5600 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5601 EVT VT = Op.getValueType();
5602 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5603 "unexpected type for custom-lowering ISD::UDIV");
5605 DebugLoc dl = Op.getDebugLoc();
5606 SDValue N0 = Op.getOperand(0);
5607 SDValue N1 = Op.getOperand(1);
5610 if (VT == MVT::v8i8) {
5611 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5612 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5614 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5615 DAG.getIntPtrConstant(4));
5616 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5617 DAG.getIntPtrConstant(4));
5618 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5619 DAG.getIntPtrConstant(0));
5620 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5621 DAG.getIntPtrConstant(0));
5623 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5624 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5626 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5627 N0 = LowerCONCAT_VECTORS(N0, DAG);
5629 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5630 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5635 // v4i16 sdiv ... Convert to float.
5636 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5637 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5638 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5639 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5640 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5641 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5643 // Use reciprocal estimate and two refinement steps.
5644 // float4 recip = vrecpeq_f32(yf);
5645 // recip *= vrecpsq_f32(yf, recip);
5646 // recip *= vrecpsq_f32(yf, recip);
5647 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5648 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5649 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5650 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5652 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5653 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5654 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5656 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5657 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5658 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5659 // and that it will never cause us to return an answer too large).
5660 // float4 result = as_float4(as_int4(xf*recip) + 2);
5661 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5662 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5663 N1 = DAG.getConstant(2, MVT::i32);
5664 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5665 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5666 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5667 // Convert back to integer and return.
5668 // return vmovn_u32(vcvt_s32_f32(result));
5669 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5670 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5674 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5675 EVT VT = Op.getNode()->getValueType(0);
5676 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5679 bool ExtraOp = false;
5680 switch (Op.getOpcode()) {
5681 default: llvm_unreachable("Invalid code");
5682 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5683 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5684 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5685 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5689 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5691 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5692 Op.getOperand(1), Op.getOperand(2));
5695 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5696 // Monotonic load/store is legal for all targets
5697 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5700 // Aquire/Release load/store is not legal for targets without a
5701 // dmb or equivalent available.
5707 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5708 SelectionDAG &DAG, unsigned NewOp) {
5709 DebugLoc dl = Node->getDebugLoc();
5710 assert (Node->getValueType(0) == MVT::i64 &&
5711 "Only know how to expand i64 atomics");
5713 SmallVector<SDValue, 6> Ops;
5714 Ops.push_back(Node->getOperand(0)); // Chain
5715 Ops.push_back(Node->getOperand(1)); // Ptr
5717 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5718 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5719 // High part of Val1
5720 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5721 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5722 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5723 // High part of Val1
5724 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5725 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5726 // High part of Val2
5727 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5728 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5730 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5732 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5733 cast<MemSDNode>(Node)->getMemOperand());
5734 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5735 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5736 Results.push_back(Result.getValue(2));
5739 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5740 switch (Op.getOpcode()) {
5741 default: llvm_unreachable("Don't know how to custom lower this!");
5742 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5743 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5744 case ISD::GlobalAddress:
5745 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5746 LowerGlobalAddressELF(Op, DAG);
5747 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5748 case ISD::SELECT: return LowerSELECT(Op, DAG);
5749 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5750 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5751 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5752 case ISD::VASTART: return LowerVASTART(Op, DAG);
5753 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5754 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5755 case ISD::SINT_TO_FP:
5756 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5757 case ISD::FP_TO_SINT:
5758 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5759 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5760 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5761 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5762 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5763 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5764 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5765 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5767 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5770 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5771 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5772 case ISD::SRL_PARTS:
5773 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5774 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5775 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5776 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5777 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5778 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5779 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5780 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5781 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5782 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5783 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5784 case ISD::MUL: return LowerMUL(Op, DAG);
5785 case ISD::SDIV: return LowerSDIV(Op, DAG);
5786 case ISD::UDIV: return LowerUDIV(Op, DAG);
5790 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5791 case ISD::ATOMIC_LOAD:
5792 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5796 /// ReplaceNodeResults - Replace the results of node with an illegal result
5797 /// type with new values built out of custom code.
5798 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5799 SmallVectorImpl<SDValue>&Results,
5800 SelectionDAG &DAG) const {
5802 switch (N->getOpcode()) {
5804 llvm_unreachable("Don't know how to custom expand this!");
5806 Res = ExpandBITCAST(N, DAG);
5808 case ISD::SIGN_EXTEND:
5809 case ISD::ZERO_EXTEND:
5810 Res = ExpandVectorExtension(N, DAG);
5814 Res = Expand64BitShift(N, DAG, Subtarget);
5816 case ISD::ATOMIC_LOAD_ADD:
5817 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5819 case ISD::ATOMIC_LOAD_AND:
5820 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5822 case ISD::ATOMIC_LOAD_NAND:
5823 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5825 case ISD::ATOMIC_LOAD_OR:
5826 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5828 case ISD::ATOMIC_LOAD_SUB:
5829 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5831 case ISD::ATOMIC_LOAD_XOR:
5832 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5834 case ISD::ATOMIC_SWAP:
5835 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5837 case ISD::ATOMIC_CMP_SWAP:
5838 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5840 case ISD::ATOMIC_LOAD_MIN:
5841 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5843 case ISD::ATOMIC_LOAD_UMIN:
5844 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5846 case ISD::ATOMIC_LOAD_MAX:
5847 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5849 case ISD::ATOMIC_LOAD_UMAX:
5850 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5854 Results.push_back(Res);
5857 //===----------------------------------------------------------------------===//
5858 // ARM Scheduler Hooks
5859 //===----------------------------------------------------------------------===//
5862 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5863 MachineBasicBlock *BB,
5864 unsigned Size) const {
5865 unsigned dest = MI->getOperand(0).getReg();
5866 unsigned ptr = MI->getOperand(1).getReg();
5867 unsigned oldval = MI->getOperand(2).getReg();
5868 unsigned newval = MI->getOperand(3).getReg();
5869 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5870 DebugLoc dl = MI->getDebugLoc();
5871 bool isThumb2 = Subtarget->isThumb2();
5873 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5874 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5875 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5876 (const TargetRegisterClass*)&ARM::GPRRegClass);
5879 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5880 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5881 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5884 unsigned ldrOpc, strOpc;
5886 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5888 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5889 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5892 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5893 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5896 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5897 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5901 MachineFunction *MF = BB->getParent();
5902 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5903 MachineFunction::iterator It = BB;
5904 ++It; // insert the new blocks after the current block
5906 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5907 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5908 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5909 MF->insert(It, loop1MBB);
5910 MF->insert(It, loop2MBB);
5911 MF->insert(It, exitMBB);
5913 // Transfer the remainder of BB and its successor edges to exitMBB.
5914 exitMBB->splice(exitMBB->begin(), BB,
5915 llvm::next(MachineBasicBlock::iterator(MI)),
5917 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5921 // fallthrough --> loop1MBB
5922 BB->addSuccessor(loop1MBB);
5925 // ldrex dest, [ptr]
5929 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5930 if (ldrOpc == ARM::t2LDREX)
5932 AddDefaultPred(MIB);
5933 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5934 .addReg(dest).addReg(oldval));
5935 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5936 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5937 BB->addSuccessor(loop2MBB);
5938 BB->addSuccessor(exitMBB);
5941 // strex scratch, newval, [ptr]
5945 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5946 if (strOpc == ARM::t2STREX)
5948 AddDefaultPred(MIB);
5949 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5950 .addReg(scratch).addImm(0));
5951 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5952 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5953 BB->addSuccessor(loop1MBB);
5954 BB->addSuccessor(exitMBB);
5960 MI->eraseFromParent(); // The instruction is gone now.
5966 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5967 unsigned Size, unsigned BinOpcode) const {
5968 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5969 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5971 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5972 MachineFunction *MF = BB->getParent();
5973 MachineFunction::iterator It = BB;
5976 unsigned dest = MI->getOperand(0).getReg();
5977 unsigned ptr = MI->getOperand(1).getReg();
5978 unsigned incr = MI->getOperand(2).getReg();
5979 DebugLoc dl = MI->getDebugLoc();
5980 bool isThumb2 = Subtarget->isThumb2();
5982 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5984 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5985 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5988 unsigned ldrOpc, strOpc;
5990 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5992 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5993 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5996 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5997 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6000 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6001 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6005 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6006 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6007 MF->insert(It, loopMBB);
6008 MF->insert(It, exitMBB);
6010 // Transfer the remainder of BB and its successor edges to exitMBB.
6011 exitMBB->splice(exitMBB->begin(), BB,
6012 llvm::next(MachineBasicBlock::iterator(MI)),
6014 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6016 const TargetRegisterClass *TRC = isThumb2 ?
6017 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6018 (const TargetRegisterClass*)&ARM::GPRRegClass;
6019 unsigned scratch = MRI.createVirtualRegister(TRC);
6020 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6024 // fallthrough --> loopMBB
6025 BB->addSuccessor(loopMBB);
6029 // <binop> scratch2, dest, incr
6030 // strex scratch, scratch2, ptr
6033 // fallthrough --> exitMBB
6035 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6036 if (ldrOpc == ARM::t2LDREX)
6038 AddDefaultPred(MIB);
6040 // operand order needs to go the other way for NAND
6041 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6042 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6043 addReg(incr).addReg(dest)).addReg(0);
6045 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6046 addReg(dest).addReg(incr)).addReg(0);
6049 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6050 if (strOpc == ARM::t2STREX)
6052 AddDefaultPred(MIB);
6053 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6054 .addReg(scratch).addImm(0));
6055 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6056 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6058 BB->addSuccessor(loopMBB);
6059 BB->addSuccessor(exitMBB);
6065 MI->eraseFromParent(); // The instruction is gone now.
6071 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6072 MachineBasicBlock *BB,
6075 ARMCC::CondCodes Cond) const {
6076 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6078 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6079 MachineFunction *MF = BB->getParent();
6080 MachineFunction::iterator It = BB;
6083 unsigned dest = MI->getOperand(0).getReg();
6084 unsigned ptr = MI->getOperand(1).getReg();
6085 unsigned incr = MI->getOperand(2).getReg();
6086 unsigned oldval = dest;
6087 DebugLoc dl = MI->getDebugLoc();
6088 bool isThumb2 = Subtarget->isThumb2();
6090 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6092 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6093 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6096 unsigned ldrOpc, strOpc, extendOpc;
6098 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6100 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6101 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6102 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6105 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6106 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6107 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6110 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6111 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6116 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6117 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6118 MF->insert(It, loopMBB);
6119 MF->insert(It, exitMBB);
6121 // Transfer the remainder of BB and its successor edges to exitMBB.
6122 exitMBB->splice(exitMBB->begin(), BB,
6123 llvm::next(MachineBasicBlock::iterator(MI)),
6125 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6127 const TargetRegisterClass *TRC = isThumb2 ?
6128 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6129 (const TargetRegisterClass*)&ARM::GPRRegClass;
6130 unsigned scratch = MRI.createVirtualRegister(TRC);
6131 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6135 // fallthrough --> loopMBB
6136 BB->addSuccessor(loopMBB);
6140 // (sign extend dest, if required)
6142 // cmov.cond scratch2, incr, dest
6143 // strex scratch, scratch2, ptr
6146 // fallthrough --> exitMBB
6148 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6149 if (ldrOpc == ARM::t2LDREX)
6151 AddDefaultPred(MIB);
6153 // Sign extend the value, if necessary.
6154 if (signExtend && extendOpc) {
6155 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6156 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6161 // Build compare and cmov instructions.
6162 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6163 .addReg(oldval).addReg(incr));
6164 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6165 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6167 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6168 if (strOpc == ARM::t2STREX)
6170 AddDefaultPred(MIB);
6171 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6172 .addReg(scratch).addImm(0));
6173 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6174 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6176 BB->addSuccessor(loopMBB);
6177 BB->addSuccessor(exitMBB);
6183 MI->eraseFromParent(); // The instruction is gone now.
6189 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6190 unsigned Op1, unsigned Op2,
6191 bool NeedsCarry, bool IsCmpxchg,
6192 bool IsMinMax, ARMCC::CondCodes CC) const {
6193 // This also handles ATOMIC_SWAP, indicated by Op1==0.
6194 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6196 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6197 MachineFunction *MF = BB->getParent();
6198 MachineFunction::iterator It = BB;
6201 unsigned destlo = MI->getOperand(0).getReg();
6202 unsigned desthi = MI->getOperand(1).getReg();
6203 unsigned ptr = MI->getOperand(2).getReg();
6204 unsigned vallo = MI->getOperand(3).getReg();
6205 unsigned valhi = MI->getOperand(4).getReg();
6206 DebugLoc dl = MI->getDebugLoc();
6207 bool isThumb2 = Subtarget->isThumb2();
6209 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6211 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6212 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6213 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6216 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6217 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6218 if (IsCmpxchg || IsMinMax)
6219 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6221 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6222 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6224 MF->insert(It, loopMBB);
6225 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6226 if (IsCmpxchg) MF->insert(It, cont2BB);
6227 MF->insert(It, exitMBB);
6229 // Transfer the remainder of BB and its successor edges to exitMBB.
6230 exitMBB->splice(exitMBB->begin(), BB,
6231 llvm::next(MachineBasicBlock::iterator(MI)),
6233 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6235 const TargetRegisterClass *TRC = isThumb2 ?
6236 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6237 (const TargetRegisterClass*)&ARM::GPRRegClass;
6238 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6242 // fallthrough --> loopMBB
6243 BB->addSuccessor(loopMBB);
6246 // ldrexd r2, r3, ptr
6247 // <binopa> r0, r2, incr
6248 // <binopb> r1, r3, incr
6249 // strexd storesuccess, r0, r1, ptr
6250 // cmp storesuccess, #0
6252 // fallthrough --> exitMBB
6257 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6258 .addReg(destlo, RegState::Define)
6259 .addReg(desthi, RegState::Define)
6262 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6263 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6264 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6265 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6266 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6267 .addReg(GPRPair0, 0, ARM::gsub_0);
6268 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6269 .addReg(GPRPair0, 0, ARM::gsub_1);
6272 unsigned StoreLo, StoreHi;
6275 for (unsigned i = 0; i < 2; i++) {
6276 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6278 .addReg(i == 0 ? destlo : desthi)
6279 .addReg(i == 0 ? vallo : valhi));
6280 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6281 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6282 BB->addSuccessor(exitMBB);
6283 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6284 BB = (i == 0 ? contBB : cont2BB);
6287 // Copy to physregs for strexd
6288 StoreLo = MI->getOperand(5).getReg();
6289 StoreHi = MI->getOperand(6).getReg();
6291 // Perform binary operation
6292 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6293 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6294 .addReg(destlo).addReg(vallo))
6295 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6296 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6297 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6298 .addReg(desthi).addReg(valhi))
6299 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6304 // Copy to physregs for strexd
6309 // Compare and branch to exit block.
6310 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6311 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6312 BB->addSuccessor(exitMBB);
6313 BB->addSuccessor(contBB);
6321 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6322 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6324 // Marshal a pair...
6325 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6326 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6327 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6328 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6329 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6332 .addImm(ARM::gsub_0);
6333 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6336 .addImm(ARM::gsub_1);
6339 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6340 .addReg(StorePair).addReg(ptr));
6343 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6344 .addReg(storesuccess).addImm(0));
6345 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6346 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6348 BB->addSuccessor(loopMBB);
6349 BB->addSuccessor(exitMBB);
6355 MI->eraseFromParent(); // The instruction is gone now.
6360 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6361 /// registers the function context.
6362 void ARMTargetLowering::
6363 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6364 MachineBasicBlock *DispatchBB, int FI) const {
6365 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6366 DebugLoc dl = MI->getDebugLoc();
6367 MachineFunction *MF = MBB->getParent();
6368 MachineRegisterInfo *MRI = &MF->getRegInfo();
6369 MachineConstantPool *MCP = MF->getConstantPool();
6370 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6371 const Function *F = MF->getFunction();
6373 bool isThumb = Subtarget->isThumb();
6374 bool isThumb2 = Subtarget->isThumb2();
6376 unsigned PCLabelId = AFI->createPICLabelUId();
6377 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6378 ARMConstantPoolValue *CPV =
6379 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6380 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6382 const TargetRegisterClass *TRC = isThumb ?
6383 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6384 (const TargetRegisterClass*)&ARM::GPRRegClass;
6386 // Grab constant pool and fixed stack memory operands.
6387 MachineMemOperand *CPMMO =
6388 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6389 MachineMemOperand::MOLoad, 4, 4);
6391 MachineMemOperand *FIMMOSt =
6392 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6393 MachineMemOperand::MOStore, 4, 4);
6395 // Load the address of the dispatch MBB into the jump buffer.
6397 // Incoming value: jbuf
6398 // ldr.n r5, LCPI1_1
6401 // str r5, [$jbuf, #+4] ; &jbuf[1]
6402 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6403 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6404 .addConstantPoolIndex(CPI)
6405 .addMemOperand(CPMMO));
6406 // Set the low bit because of thumb mode.
6407 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6409 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6410 .addReg(NewVReg1, RegState::Kill)
6412 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6413 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6414 .addReg(NewVReg2, RegState::Kill)
6416 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6417 .addReg(NewVReg3, RegState::Kill)
6419 .addImm(36) // &jbuf[1] :: pc
6420 .addMemOperand(FIMMOSt));
6421 } else if (isThumb) {
6422 // Incoming value: jbuf
6423 // ldr.n r1, LCPI1_4
6427 // add r2, $jbuf, #+4 ; &jbuf[1]
6429 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6430 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6431 .addConstantPoolIndex(CPI)
6432 .addMemOperand(CPMMO));
6433 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6434 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6435 .addReg(NewVReg1, RegState::Kill)
6437 // Set the low bit because of thumb mode.
6438 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6439 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6440 .addReg(ARM::CPSR, RegState::Define)
6442 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6443 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6444 .addReg(ARM::CPSR, RegState::Define)
6445 .addReg(NewVReg2, RegState::Kill)
6446 .addReg(NewVReg3, RegState::Kill));
6447 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6448 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6450 .addImm(36)); // &jbuf[1] :: pc
6451 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6452 .addReg(NewVReg4, RegState::Kill)
6453 .addReg(NewVReg5, RegState::Kill)
6455 .addMemOperand(FIMMOSt));
6457 // Incoming value: jbuf
6460 // str r1, [$jbuf, #+4] ; &jbuf[1]
6461 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6462 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6463 .addConstantPoolIndex(CPI)
6465 .addMemOperand(CPMMO));
6466 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6467 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6468 .addReg(NewVReg1, RegState::Kill)
6469 .addImm(PCLabelId));
6470 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6471 .addReg(NewVReg2, RegState::Kill)
6473 .addImm(36) // &jbuf[1] :: pc
6474 .addMemOperand(FIMMOSt));
6478 MachineBasicBlock *ARMTargetLowering::
6479 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6480 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6481 DebugLoc dl = MI->getDebugLoc();
6482 MachineFunction *MF = MBB->getParent();
6483 MachineRegisterInfo *MRI = &MF->getRegInfo();
6484 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6485 MachineFrameInfo *MFI = MF->getFrameInfo();
6486 int FI = MFI->getFunctionContextIndex();
6488 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6489 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6490 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6492 // Get a mapping of the call site numbers to all of the landing pads they're
6494 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6495 unsigned MaxCSNum = 0;
6496 MachineModuleInfo &MMI = MF->getMMI();
6497 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6499 if (!BB->isLandingPad()) continue;
6501 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6503 for (MachineBasicBlock::iterator
6504 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6505 if (!II->isEHLabel()) continue;
6507 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6508 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6510 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6511 for (SmallVectorImpl<unsigned>::iterator
6512 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6513 CSI != CSE; ++CSI) {
6514 CallSiteNumToLPad[*CSI].push_back(BB);
6515 MaxCSNum = std::max(MaxCSNum, *CSI);
6521 // Get an ordered list of the machine basic blocks for the jump table.
6522 std::vector<MachineBasicBlock*> LPadList;
6523 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6524 LPadList.reserve(CallSiteNumToLPad.size());
6525 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6526 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6527 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6528 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6529 LPadList.push_back(*II);
6530 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6534 assert(!LPadList.empty() &&
6535 "No landing pad destinations for the dispatch jump table!");
6537 // Create the jump table and associated information.
6538 MachineJumpTableInfo *JTI =
6539 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6540 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6541 unsigned UId = AFI->createJumpTableUId();
6542 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6544 // Create the MBBs for the dispatch code.
6546 // Shove the dispatch's address into the return slot in the function context.
6547 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6548 DispatchBB->setIsLandingPad();
6550 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6551 unsigned trap_opcode;
6552 if (Subtarget->isThumb())
6553 trap_opcode = ARM::tTRAP;
6555 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6557 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6558 DispatchBB->addSuccessor(TrapBB);
6560 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6561 DispatchBB->addSuccessor(DispContBB);
6564 MF->insert(MF->end(), DispatchBB);
6565 MF->insert(MF->end(), DispContBB);
6566 MF->insert(MF->end(), TrapBB);
6568 // Insert code into the entry block that creates and registers the function
6570 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6572 MachineMemOperand *FIMMOLd =
6573 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6574 MachineMemOperand::MOLoad |
6575 MachineMemOperand::MOVolatile, 4, 4);
6577 MachineInstrBuilder MIB;
6578 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6580 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6581 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6583 // Add a register mask with no preserved registers. This results in all
6584 // registers being marked as clobbered.
6585 MIB.addRegMask(RI.getNoPreservedMask());
6587 unsigned NumLPads = LPadList.size();
6588 if (Subtarget->isThumb2()) {
6589 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6590 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6593 .addMemOperand(FIMMOLd));
6595 if (NumLPads < 256) {
6596 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6598 .addImm(LPadList.size()));
6600 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6601 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6602 .addImm(NumLPads & 0xFFFF));
6604 unsigned VReg2 = VReg1;
6605 if ((NumLPads & 0xFFFF0000) != 0) {
6606 VReg2 = MRI->createVirtualRegister(TRC);
6607 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6609 .addImm(NumLPads >> 16));
6612 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6617 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6622 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6623 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6624 .addJumpTableIndex(MJTI)
6627 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6630 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6631 .addReg(NewVReg3, RegState::Kill)
6633 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6635 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6636 .addReg(NewVReg4, RegState::Kill)
6638 .addJumpTableIndex(MJTI)
6640 } else if (Subtarget->isThumb()) {
6641 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6642 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6645 .addMemOperand(FIMMOLd));
6647 if (NumLPads < 256) {
6648 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6652 MachineConstantPool *ConstantPool = MF->getConstantPool();
6653 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6654 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6656 // MachineConstantPool wants an explicit alignment.
6657 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6659 Align = getDataLayout()->getTypeAllocSize(C->getType());
6660 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6662 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6663 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6664 .addReg(VReg1, RegState::Define)
6665 .addConstantPoolIndex(Idx));
6666 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6671 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6676 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6677 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6678 .addReg(ARM::CPSR, RegState::Define)
6682 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6683 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6684 .addJumpTableIndex(MJTI)
6687 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6688 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6689 .addReg(ARM::CPSR, RegState::Define)
6690 .addReg(NewVReg2, RegState::Kill)
6693 MachineMemOperand *JTMMOLd =
6694 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6695 MachineMemOperand::MOLoad, 4, 4);
6697 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6698 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6699 .addReg(NewVReg4, RegState::Kill)
6701 .addMemOperand(JTMMOLd));
6703 unsigned NewVReg6 = NewVReg5;
6704 if (RelocM == Reloc::PIC_) {
6705 NewVReg6 = MRI->createVirtualRegister(TRC);
6706 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6707 .addReg(ARM::CPSR, RegState::Define)
6708 .addReg(NewVReg5, RegState::Kill)
6712 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6713 .addReg(NewVReg6, RegState::Kill)
6714 .addJumpTableIndex(MJTI)
6717 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6718 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6721 .addMemOperand(FIMMOLd));
6723 if (NumLPads < 256) {
6724 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6727 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6728 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6729 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6730 .addImm(NumLPads & 0xFFFF));
6732 unsigned VReg2 = VReg1;
6733 if ((NumLPads & 0xFFFF0000) != 0) {
6734 VReg2 = MRI->createVirtualRegister(TRC);
6735 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6737 .addImm(NumLPads >> 16));
6740 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6744 MachineConstantPool *ConstantPool = MF->getConstantPool();
6745 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6746 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6748 // MachineConstantPool wants an explicit alignment.
6749 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6751 Align = getDataLayout()->getTypeAllocSize(C->getType());
6752 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6754 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6755 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6756 .addReg(VReg1, RegState::Define)
6757 .addConstantPoolIndex(Idx)
6759 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6761 .addReg(VReg1, RegState::Kill));
6764 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6769 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6771 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6773 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6774 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6775 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6776 .addJumpTableIndex(MJTI)
6779 MachineMemOperand *JTMMOLd =
6780 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6781 MachineMemOperand::MOLoad, 4, 4);
6782 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6784 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6785 .addReg(NewVReg3, RegState::Kill)
6788 .addMemOperand(JTMMOLd));
6790 if (RelocM == Reloc::PIC_) {
6791 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6792 .addReg(NewVReg5, RegState::Kill)
6794 .addJumpTableIndex(MJTI)
6797 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6798 .addReg(NewVReg5, RegState::Kill)
6799 .addJumpTableIndex(MJTI)
6804 // Add the jump table entries as successors to the MBB.
6805 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6806 for (std::vector<MachineBasicBlock*>::iterator
6807 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6808 MachineBasicBlock *CurMBB = *I;
6809 if (SeenMBBs.insert(CurMBB))
6810 DispContBB->addSuccessor(CurMBB);
6813 // N.B. the order the invoke BBs are processed in doesn't matter here.
6814 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6815 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6816 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6817 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6818 MachineBasicBlock *BB = *I;
6820 // Remove the landing pad successor from the invoke block and replace it
6821 // with the new dispatch block.
6822 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6824 while (!Successors.empty()) {
6825 MachineBasicBlock *SMBB = Successors.pop_back_val();
6826 if (SMBB->isLandingPad()) {
6827 BB->removeSuccessor(SMBB);
6828 MBBLPads.push_back(SMBB);
6832 BB->addSuccessor(DispatchBB);
6834 // Find the invoke call and mark all of the callee-saved registers as
6835 // 'implicit defined' so that they're spilled. This prevents code from
6836 // moving instructions to before the EH block, where they will never be
6838 for (MachineBasicBlock::reverse_iterator
6839 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6840 if (!II->isCall()) continue;
6842 DenseMap<unsigned, bool> DefRegs;
6843 for (MachineInstr::mop_iterator
6844 OI = II->operands_begin(), OE = II->operands_end();
6846 if (!OI->isReg()) continue;
6847 DefRegs[OI->getReg()] = true;
6850 MachineInstrBuilder MIB(*MF, &*II);
6852 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6853 unsigned Reg = SavedRegs[i];
6854 if (Subtarget->isThumb2() &&
6855 !ARM::tGPRRegClass.contains(Reg) &&
6856 !ARM::hGPRRegClass.contains(Reg))
6858 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6860 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6863 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6870 // Mark all former landing pads as non-landing pads. The dispatch is the only
6872 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6873 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6874 (*I)->setIsLandingPad(false);
6876 // The instruction is gone now.
6877 MI->eraseFromParent();
6883 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6884 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6885 E = MBB->succ_end(); I != E; ++I)
6888 llvm_unreachable("Expecting a BB with two successors!");
6891 MachineBasicBlock *ARMTargetLowering::
6892 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6893 // This pseudo instruction has 3 operands: dst, src, size
6894 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6895 // Otherwise, we will generate unrolled scalar copies.
6896 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6897 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6898 MachineFunction::iterator It = BB;
6901 unsigned dest = MI->getOperand(0).getReg();
6902 unsigned src = MI->getOperand(1).getReg();
6903 unsigned SizeVal = MI->getOperand(2).getImm();
6904 unsigned Align = MI->getOperand(3).getImm();
6905 DebugLoc dl = MI->getDebugLoc();
6907 bool isThumb2 = Subtarget->isThumb2();
6908 MachineFunction *MF = BB->getParent();
6909 MachineRegisterInfo &MRI = MF->getRegInfo();
6910 unsigned ldrOpc, strOpc, UnitSize = 0;
6912 const TargetRegisterClass *TRC = isThumb2 ?
6913 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6914 (const TargetRegisterClass*)&ARM::GPRRegClass;
6915 const TargetRegisterClass *TRC_Vec = 0;
6918 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6919 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6921 } else if (Align & 2) {
6922 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6923 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6926 // Check whether we can use NEON instructions.
6927 if (!MF->getFunction()->getAttributes().
6928 hasAttribute(AttributeSet::FunctionIndex,
6929 Attribute::NoImplicitFloat) &&
6930 Subtarget->hasNEON()) {
6931 if ((Align % 16 == 0) && SizeVal >= 16) {
6932 ldrOpc = ARM::VLD1q32wb_fixed;
6933 strOpc = ARM::VST1q32wb_fixed;
6935 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6937 else if ((Align % 8 == 0) && SizeVal >= 8) {
6938 ldrOpc = ARM::VLD1d32wb_fixed;
6939 strOpc = ARM::VST1d32wb_fixed;
6941 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6944 // Can't use NEON instructions.
6945 if (UnitSize == 0) {
6946 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6947 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6952 unsigned BytesLeft = SizeVal % UnitSize;
6953 unsigned LoopSize = SizeVal - BytesLeft;
6955 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6956 // Use LDR and STR to copy.
6957 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6958 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6959 unsigned srcIn = src;
6960 unsigned destIn = dest;
6961 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6962 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6963 unsigned srcOut = MRI.createVirtualRegister(TRC);
6964 unsigned destOut = MRI.createVirtualRegister(TRC);
6965 if (UnitSize >= 8) {
6966 AddDefaultPred(BuildMI(*BB, MI, dl,
6967 TII->get(ldrOpc), scratch)
6968 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6970 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6971 .addReg(destIn).addImm(0).addReg(scratch));
6972 } else if (isThumb2) {
6973 AddDefaultPred(BuildMI(*BB, MI, dl,
6974 TII->get(ldrOpc), scratch)
6975 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6977 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6978 .addReg(scratch).addReg(destIn)
6981 AddDefaultPred(BuildMI(*BB, MI, dl,
6982 TII->get(ldrOpc), scratch)
6983 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6986 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6987 .addReg(scratch).addReg(destIn)
6988 .addReg(0).addImm(UnitSize));
6994 // Handle the leftover bytes with LDRB and STRB.
6995 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6996 // [destOut] = STRB_POST(scratch, destIn, 1)
6997 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6998 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6999 for (unsigned i = 0; i < BytesLeft; i++) {
7000 unsigned scratch = MRI.createVirtualRegister(TRC);
7001 unsigned srcOut = MRI.createVirtualRegister(TRC);
7002 unsigned destOut = MRI.createVirtualRegister(TRC);
7004 AddDefaultPred(BuildMI(*BB, MI, dl,
7005 TII->get(ldrOpc),scratch)
7006 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7008 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7009 .addReg(scratch).addReg(destIn)
7010 .addReg(0).addImm(1));
7012 AddDefaultPred(BuildMI(*BB, MI, dl,
7013 TII->get(ldrOpc),scratch)
7014 .addReg(srcOut, RegState::Define).addReg(srcIn)
7015 .addReg(0).addImm(1));
7017 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7018 .addReg(scratch).addReg(destIn)
7019 .addReg(0).addImm(1));
7024 MI->eraseFromParent(); // The instruction is gone now.
7028 // Expand the pseudo op to a loop.
7031 // movw varEnd, # --> with thumb2
7033 // ldrcp varEnd, idx --> without thumb2
7034 // fallthrough --> loopMBB
7036 // PHI varPhi, varEnd, varLoop
7037 // PHI srcPhi, src, srcLoop
7038 // PHI destPhi, dst, destLoop
7039 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7040 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7041 // subs varLoop, varPhi, #UnitSize
7043 // fallthrough --> exitMBB
7045 // epilogue to handle left-over bytes
7046 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7047 // [destOut] = STRB_POST(scratch, destLoop, 1)
7048 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7049 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7050 MF->insert(It, loopMBB);
7051 MF->insert(It, exitMBB);
7053 // Transfer the remainder of BB and its successor edges to exitMBB.
7054 exitMBB->splice(exitMBB->begin(), BB,
7055 llvm::next(MachineBasicBlock::iterator(MI)),
7057 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7059 // Load an immediate to varEnd.
7060 unsigned varEnd = MRI.createVirtualRegister(TRC);
7062 unsigned VReg1 = varEnd;
7063 if ((LoopSize & 0xFFFF0000) != 0)
7064 VReg1 = MRI.createVirtualRegister(TRC);
7065 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7066 .addImm(LoopSize & 0xFFFF));
7068 if ((LoopSize & 0xFFFF0000) != 0)
7069 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7071 .addImm(LoopSize >> 16));
7073 MachineConstantPool *ConstantPool = MF->getConstantPool();
7074 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7075 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7077 // MachineConstantPool wants an explicit alignment.
7078 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7080 Align = getDataLayout()->getTypeAllocSize(C->getType());
7081 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7083 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7084 .addReg(varEnd, RegState::Define)
7085 .addConstantPoolIndex(Idx)
7088 BB->addSuccessor(loopMBB);
7090 // Generate the loop body:
7091 // varPhi = PHI(varLoop, varEnd)
7092 // srcPhi = PHI(srcLoop, src)
7093 // destPhi = PHI(destLoop, dst)
7094 MachineBasicBlock *entryBB = BB;
7096 unsigned varLoop = MRI.createVirtualRegister(TRC);
7097 unsigned varPhi = MRI.createVirtualRegister(TRC);
7098 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7099 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7100 unsigned destLoop = MRI.createVirtualRegister(TRC);
7101 unsigned destPhi = MRI.createVirtualRegister(TRC);
7103 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7104 .addReg(varLoop).addMBB(loopMBB)
7105 .addReg(varEnd).addMBB(entryBB);
7106 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7107 .addReg(srcLoop).addMBB(loopMBB)
7108 .addReg(src).addMBB(entryBB);
7109 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7110 .addReg(destLoop).addMBB(loopMBB)
7111 .addReg(dest).addMBB(entryBB);
7113 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7114 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7115 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7116 if (UnitSize >= 8) {
7117 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7118 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7120 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7121 .addReg(destPhi).addImm(0).addReg(scratch));
7122 } else if (isThumb2) {
7123 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7124 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7126 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7127 .addReg(scratch).addReg(destPhi)
7130 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7131 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7134 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7135 .addReg(scratch).addReg(destPhi)
7136 .addReg(0).addImm(UnitSize));
7139 // Decrement loop variable by UnitSize.
7140 MachineInstrBuilder MIB = BuildMI(BB, dl,
7141 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7142 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7143 MIB->getOperand(5).setReg(ARM::CPSR);
7144 MIB->getOperand(5).setIsDef(true);
7146 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7147 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7149 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7150 BB->addSuccessor(loopMBB);
7151 BB->addSuccessor(exitMBB);
7153 // Add epilogue to handle BytesLeft.
7155 MachineInstr *StartOfExit = exitMBB->begin();
7156 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7157 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7159 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7160 // [destOut] = STRB_POST(scratch, destLoop, 1)
7161 unsigned srcIn = srcLoop;
7162 unsigned destIn = destLoop;
7163 for (unsigned i = 0; i < BytesLeft; i++) {
7164 unsigned scratch = MRI.createVirtualRegister(TRC);
7165 unsigned srcOut = MRI.createVirtualRegister(TRC);
7166 unsigned destOut = MRI.createVirtualRegister(TRC);
7168 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7169 TII->get(ldrOpc),scratch)
7170 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7172 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7173 .addReg(scratch).addReg(destIn)
7176 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7177 TII->get(ldrOpc),scratch)
7178 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7180 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7181 .addReg(scratch).addReg(destIn)
7182 .addReg(0).addImm(1));
7188 MI->eraseFromParent(); // The instruction is gone now.
7193 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7194 MachineBasicBlock *BB) const {
7195 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7196 DebugLoc dl = MI->getDebugLoc();
7197 bool isThumb2 = Subtarget->isThumb2();
7198 switch (MI->getOpcode()) {
7201 llvm_unreachable("Unexpected instr type to insert");
7203 // The Thumb2 pre-indexed stores have the same MI operands, they just
7204 // define them differently in the .td files from the isel patterns, so
7205 // they need pseudos.
7206 case ARM::t2STR_preidx:
7207 MI->setDesc(TII->get(ARM::t2STR_PRE));
7209 case ARM::t2STRB_preidx:
7210 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7212 case ARM::t2STRH_preidx:
7213 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7216 case ARM::STRi_preidx:
7217 case ARM::STRBi_preidx: {
7218 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7219 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7220 // Decode the offset.
7221 unsigned Offset = MI->getOperand(4).getImm();
7222 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7223 Offset = ARM_AM::getAM2Offset(Offset);
7227 MachineMemOperand *MMO = *MI->memoperands_begin();
7228 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7229 .addOperand(MI->getOperand(0)) // Rn_wb
7230 .addOperand(MI->getOperand(1)) // Rt
7231 .addOperand(MI->getOperand(2)) // Rn
7232 .addImm(Offset) // offset (skip GPR==zero_reg)
7233 .addOperand(MI->getOperand(5)) // pred
7234 .addOperand(MI->getOperand(6))
7235 .addMemOperand(MMO);
7236 MI->eraseFromParent();
7239 case ARM::STRr_preidx:
7240 case ARM::STRBr_preidx:
7241 case ARM::STRH_preidx: {
7243 switch (MI->getOpcode()) {
7244 default: llvm_unreachable("unexpected opcode!");
7245 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7246 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7247 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7249 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7250 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7251 MIB.addOperand(MI->getOperand(i));
7252 MI->eraseFromParent();
7255 case ARM::ATOMIC_LOAD_ADD_I8:
7256 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7257 case ARM::ATOMIC_LOAD_ADD_I16:
7258 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7259 case ARM::ATOMIC_LOAD_ADD_I32:
7260 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7262 case ARM::ATOMIC_LOAD_AND_I8:
7263 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7264 case ARM::ATOMIC_LOAD_AND_I16:
7265 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7266 case ARM::ATOMIC_LOAD_AND_I32:
7267 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7269 case ARM::ATOMIC_LOAD_OR_I8:
7270 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7271 case ARM::ATOMIC_LOAD_OR_I16:
7272 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7273 case ARM::ATOMIC_LOAD_OR_I32:
7274 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7276 case ARM::ATOMIC_LOAD_XOR_I8:
7277 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7278 case ARM::ATOMIC_LOAD_XOR_I16:
7279 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7280 case ARM::ATOMIC_LOAD_XOR_I32:
7281 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7283 case ARM::ATOMIC_LOAD_NAND_I8:
7284 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7285 case ARM::ATOMIC_LOAD_NAND_I16:
7286 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7287 case ARM::ATOMIC_LOAD_NAND_I32:
7288 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7290 case ARM::ATOMIC_LOAD_SUB_I8:
7291 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7292 case ARM::ATOMIC_LOAD_SUB_I16:
7293 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7294 case ARM::ATOMIC_LOAD_SUB_I32:
7295 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7297 case ARM::ATOMIC_LOAD_MIN_I8:
7298 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7299 case ARM::ATOMIC_LOAD_MIN_I16:
7300 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7301 case ARM::ATOMIC_LOAD_MIN_I32:
7302 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7304 case ARM::ATOMIC_LOAD_MAX_I8:
7305 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7306 case ARM::ATOMIC_LOAD_MAX_I16:
7307 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7308 case ARM::ATOMIC_LOAD_MAX_I32:
7309 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7311 case ARM::ATOMIC_LOAD_UMIN_I8:
7312 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7313 case ARM::ATOMIC_LOAD_UMIN_I16:
7314 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7315 case ARM::ATOMIC_LOAD_UMIN_I32:
7316 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7318 case ARM::ATOMIC_LOAD_UMAX_I8:
7319 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7320 case ARM::ATOMIC_LOAD_UMAX_I16:
7321 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7322 case ARM::ATOMIC_LOAD_UMAX_I32:
7323 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7325 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7326 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7327 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7329 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7330 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7331 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7334 case ARM::ATOMADD6432:
7335 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7336 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7337 /*NeedsCarry*/ true);
7338 case ARM::ATOMSUB6432:
7339 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7340 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7341 /*NeedsCarry*/ true);
7342 case ARM::ATOMOR6432:
7343 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7344 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7345 case ARM::ATOMXOR6432:
7346 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7347 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7348 case ARM::ATOMAND6432:
7349 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7350 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7351 case ARM::ATOMSWAP6432:
7352 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7353 case ARM::ATOMCMPXCHG6432:
7354 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7355 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7356 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7357 case ARM::ATOMMIN6432:
7358 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7359 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7360 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7361 /*IsMinMax*/ true, ARMCC::LT);
7362 case ARM::ATOMMAX6432:
7363 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7364 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7365 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7366 /*IsMinMax*/ true, ARMCC::GE);
7367 case ARM::ATOMUMIN6432:
7368 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7369 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7370 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7371 /*IsMinMax*/ true, ARMCC::LO);
7372 case ARM::ATOMUMAX6432:
7373 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7374 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7375 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7376 /*IsMinMax*/ true, ARMCC::HS);
7378 case ARM::tMOVCCr_pseudo: {
7379 // To "insert" a SELECT_CC instruction, we actually have to insert the
7380 // diamond control-flow pattern. The incoming instruction knows the
7381 // destination vreg to set, the condition code register to branch on, the
7382 // true/false values to select between, and a branch opcode to use.
7383 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7384 MachineFunction::iterator It = BB;
7390 // cmpTY ccX, r1, r2
7392 // fallthrough --> copy0MBB
7393 MachineBasicBlock *thisMBB = BB;
7394 MachineFunction *F = BB->getParent();
7395 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7396 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7397 F->insert(It, copy0MBB);
7398 F->insert(It, sinkMBB);
7400 // Transfer the remainder of BB and its successor edges to sinkMBB.
7401 sinkMBB->splice(sinkMBB->begin(), BB,
7402 llvm::next(MachineBasicBlock::iterator(MI)),
7404 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7406 BB->addSuccessor(copy0MBB);
7407 BB->addSuccessor(sinkMBB);
7409 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7410 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7413 // %FalseValue = ...
7414 // # fallthrough to sinkMBB
7417 // Update machine-CFG edges
7418 BB->addSuccessor(sinkMBB);
7421 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7424 BuildMI(*BB, BB->begin(), dl,
7425 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7426 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7427 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7429 MI->eraseFromParent(); // The pseudo instruction is gone now.
7434 case ARM::BCCZi64: {
7435 // If there is an unconditional branch to the other successor, remove it.
7436 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7438 // Compare both parts that make up the double comparison separately for
7440 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7442 unsigned LHS1 = MI->getOperand(1).getReg();
7443 unsigned LHS2 = MI->getOperand(2).getReg();
7445 AddDefaultPred(BuildMI(BB, dl,
7446 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7447 .addReg(LHS1).addImm(0));
7448 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7449 .addReg(LHS2).addImm(0)
7450 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7452 unsigned RHS1 = MI->getOperand(3).getReg();
7453 unsigned RHS2 = MI->getOperand(4).getReg();
7454 AddDefaultPred(BuildMI(BB, dl,
7455 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7456 .addReg(LHS1).addReg(RHS1));
7457 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7458 .addReg(LHS2).addReg(RHS2)
7459 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7462 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7463 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7464 if (MI->getOperand(0).getImm() == ARMCC::NE)
7465 std::swap(destMBB, exitMBB);
7467 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7468 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7470 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7472 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7474 MI->eraseFromParent(); // The pseudo instruction is gone now.
7478 case ARM::Int_eh_sjlj_setjmp:
7479 case ARM::Int_eh_sjlj_setjmp_nofp:
7480 case ARM::tInt_eh_sjlj_setjmp:
7481 case ARM::t2Int_eh_sjlj_setjmp:
7482 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7483 EmitSjLjDispatchBlock(MI, BB);
7488 // To insert an ABS instruction, we have to insert the
7489 // diamond control-flow pattern. The incoming instruction knows the
7490 // source vreg to test against 0, the destination vreg to set,
7491 // the condition code register to branch on, the
7492 // true/false values to select between, and a branch opcode to use.
7497 // BCC (branch to SinkBB if V0 >= 0)
7498 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7499 // SinkBB: V1 = PHI(V2, V3)
7500 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7501 MachineFunction::iterator BBI = BB;
7503 MachineFunction *Fn = BB->getParent();
7504 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7505 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7506 Fn->insert(BBI, RSBBB);
7507 Fn->insert(BBI, SinkBB);
7509 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7510 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7511 bool isThumb2 = Subtarget->isThumb2();
7512 MachineRegisterInfo &MRI = Fn->getRegInfo();
7513 // In Thumb mode S must not be specified if source register is the SP or
7514 // PC and if destination register is the SP, so restrict register class
7515 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7516 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7517 (const TargetRegisterClass*)&ARM::GPRRegClass);
7519 // Transfer the remainder of BB and its successor edges to sinkMBB.
7520 SinkBB->splice(SinkBB->begin(), BB,
7521 llvm::next(MachineBasicBlock::iterator(MI)),
7523 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7525 BB->addSuccessor(RSBBB);
7526 BB->addSuccessor(SinkBB);
7528 // fall through to SinkMBB
7529 RSBBB->addSuccessor(SinkBB);
7531 // insert a cmp at the end of BB
7532 AddDefaultPred(BuildMI(BB, dl,
7533 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7534 .addReg(ABSSrcReg).addImm(0));
7536 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7538 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7539 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7541 // insert rsbri in RSBBB
7542 // Note: BCC and rsbri will be converted into predicated rsbmi
7543 // by if-conversion pass
7544 BuildMI(*RSBBB, RSBBB->begin(), dl,
7545 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7546 .addReg(ABSSrcReg, RegState::Kill)
7547 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7549 // insert PHI in SinkBB,
7550 // reuse ABSDstReg to not change uses of ABS instruction
7551 BuildMI(*SinkBB, SinkBB->begin(), dl,
7552 TII->get(ARM::PHI), ABSDstReg)
7553 .addReg(NewRsbDstReg).addMBB(RSBBB)
7554 .addReg(ABSSrcReg).addMBB(BB);
7556 // remove ABS instruction
7557 MI->eraseFromParent();
7559 // return last added BB
7562 case ARM::COPY_STRUCT_BYVAL_I32:
7564 return EmitStructByval(MI, BB);
7568 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7569 SDNode *Node) const {
7570 if (!MI->hasPostISelHook()) {
7571 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7572 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7576 const MCInstrDesc *MCID = &MI->getDesc();
7577 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7578 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7579 // operand is still set to noreg. If needed, set the optional operand's
7580 // register to CPSR, and remove the redundant implicit def.
7582 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7584 // Rename pseudo opcodes.
7585 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7587 const ARMBaseInstrInfo *TII =
7588 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7589 MCID = &TII->get(NewOpc);
7591 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7592 "converted opcode should be the same except for cc_out");
7596 // Add the optional cc_out operand
7597 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7599 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7601 // Any ARM instruction that sets the 's' bit should specify an optional
7602 // "cc_out" operand in the last operand position.
7603 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7604 assert(!NewOpc && "Optional cc_out operand required");
7607 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7608 // since we already have an optional CPSR def.
7609 bool definesCPSR = false;
7610 bool deadCPSR = false;
7611 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7613 const MachineOperand &MO = MI->getOperand(i);
7614 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7618 MI->RemoveOperand(i);
7623 assert(!NewOpc && "Optional cc_out operand required");
7626 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7628 assert(!MI->getOperand(ccOutIdx).getReg() &&
7629 "expect uninitialized optional cc_out operand");
7633 // If this instruction was defined with an optional CPSR def and its dag node
7634 // had a live implicit CPSR def, then activate the optional CPSR def.
7635 MachineOperand &MO = MI->getOperand(ccOutIdx);
7636 MO.setReg(ARM::CPSR);
7640 //===----------------------------------------------------------------------===//
7641 // ARM Optimization Hooks
7642 //===----------------------------------------------------------------------===//
7644 // Helper function that checks if N is a null or all ones constant.
7645 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7646 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7649 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7652 // Return true if N is conditionally 0 or all ones.
7653 // Detects these expressions where cc is an i1 value:
7655 // (select cc 0, y) [AllOnes=0]
7656 // (select cc y, 0) [AllOnes=0]
7657 // (zext cc) [AllOnes=0]
7658 // (sext cc) [AllOnes=0/1]
7659 // (select cc -1, y) [AllOnes=1]
7660 // (select cc y, -1) [AllOnes=1]
7662 // Invert is set when N is the null/all ones constant when CC is false.
7663 // OtherOp is set to the alternative value of N.
7664 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7665 SDValue &CC, bool &Invert,
7667 SelectionDAG &DAG) {
7668 switch (N->getOpcode()) {
7669 default: return false;
7671 CC = N->getOperand(0);
7672 SDValue N1 = N->getOperand(1);
7673 SDValue N2 = N->getOperand(2);
7674 if (isZeroOrAllOnes(N1, AllOnes)) {
7679 if (isZeroOrAllOnes(N2, AllOnes)) {
7686 case ISD::ZERO_EXTEND:
7687 // (zext cc) can never be the all ones value.
7691 case ISD::SIGN_EXTEND: {
7692 EVT VT = N->getValueType(0);
7693 CC = N->getOperand(0);
7694 if (CC.getValueType() != MVT::i1)
7698 // When looking for an AllOnes constant, N is an sext, and the 'other'
7700 OtherOp = DAG.getConstant(0, VT);
7701 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7702 // When looking for a 0 constant, N can be zext or sext.
7703 OtherOp = DAG.getConstant(1, VT);
7705 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7711 // Combine a constant select operand into its use:
7713 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7714 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7715 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7716 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7717 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7719 // The transform is rejected if the select doesn't have a constant operand that
7720 // is null, or all ones when AllOnes is set.
7722 // Also recognize sext/zext from i1:
7724 // (add (zext cc), x) -> (select cc (add x, 1), x)
7725 // (add (sext cc), x) -> (select cc (add x, -1), x)
7727 // These transformations eventually create predicated instructions.
7729 // @param N The node to transform.
7730 // @param Slct The N operand that is a select.
7731 // @param OtherOp The other N operand (x above).
7732 // @param DCI Context.
7733 // @param AllOnes Require the select constant to be all ones instead of null.
7734 // @returns The new node, or SDValue() on failure.
7736 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7737 TargetLowering::DAGCombinerInfo &DCI,
7738 bool AllOnes = false) {
7739 SelectionDAG &DAG = DCI.DAG;
7740 EVT VT = N->getValueType(0);
7741 SDValue NonConstantVal;
7744 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7745 NonConstantVal, DAG))
7748 // Slct is now know to be the desired identity constant when CC is true.
7749 SDValue TrueVal = OtherOp;
7750 SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7751 OtherOp, NonConstantVal);
7752 // Unless SwapSelectOps says CC should be false.
7754 std::swap(TrueVal, FalseVal);
7756 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7757 CCOp, TrueVal, FalseVal);
7760 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7762 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7763 TargetLowering::DAGCombinerInfo &DCI) {
7764 SDValue N0 = N->getOperand(0);
7765 SDValue N1 = N->getOperand(1);
7766 if (N0.getNode()->hasOneUse()) {
7767 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7768 if (Result.getNode())
7771 if (N1.getNode()->hasOneUse()) {
7772 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7773 if (Result.getNode())
7779 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7780 // (only after legalization).
7781 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7782 TargetLowering::DAGCombinerInfo &DCI,
7783 const ARMSubtarget *Subtarget) {
7785 // Only perform optimization if after legalize, and if NEON is available. We
7786 // also expected both operands to be BUILD_VECTORs.
7787 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7788 || N0.getOpcode() != ISD::BUILD_VECTOR
7789 || N1.getOpcode() != ISD::BUILD_VECTOR)
7792 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7793 EVT VT = N->getValueType(0);
7794 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7797 // Check that the vector operands are of the right form.
7798 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7799 // operands, where N is the size of the formed vector.
7800 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7801 // index such that we have a pair wise add pattern.
7803 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7804 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7806 SDValue Vec = N0->getOperand(0)->getOperand(0);
7807 SDNode *V = Vec.getNode();
7808 unsigned nextIndex = 0;
7810 // For each operands to the ADD which are BUILD_VECTORs,
7811 // check to see if each of their operands are an EXTRACT_VECTOR with
7812 // the same vector and appropriate index.
7813 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7814 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7815 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7817 SDValue ExtVec0 = N0->getOperand(i);
7818 SDValue ExtVec1 = N1->getOperand(i);
7820 // First operand is the vector, verify its the same.
7821 if (V != ExtVec0->getOperand(0).getNode() ||
7822 V != ExtVec1->getOperand(0).getNode())
7825 // Second is the constant, verify its correct.
7826 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7827 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7829 // For the constant, we want to see all the even or all the odd.
7830 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7831 || C1->getZExtValue() != nextIndex+1)
7840 // Create VPADDL node.
7841 SelectionDAG &DAG = DCI.DAG;
7842 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7844 // Build operand list.
7845 SmallVector<SDValue, 8> Ops;
7846 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7847 TLI.getPointerTy()));
7849 // Input is the vector.
7852 // Get widened type and narrowed type.
7854 unsigned numElem = VT.getVectorNumElements();
7855 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7856 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7857 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7858 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7860 llvm_unreachable("Invalid vector element type for padd optimization.");
7863 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7864 widenType, &Ops[0], Ops.size());
7865 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7868 static SDValue findMUL_LOHI(SDValue V) {
7869 if (V->getOpcode() == ISD::UMUL_LOHI ||
7870 V->getOpcode() == ISD::SMUL_LOHI)
7875 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7876 TargetLowering::DAGCombinerInfo &DCI,
7877 const ARMSubtarget *Subtarget) {
7879 if (Subtarget->isThumb1Only()) return SDValue();
7881 // Only perform the checks after legalize when the pattern is available.
7882 if (DCI.isBeforeLegalize()) return SDValue();
7884 // Look for multiply add opportunities.
7885 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7886 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7887 // a glue link from the first add to the second add.
7888 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7889 // a S/UMLAL instruction.
7892 // \ / \ [no multiline comment]
7898 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7899 SDValue AddcOp0 = AddcNode->getOperand(0);
7900 SDValue AddcOp1 = AddcNode->getOperand(1);
7902 // Check if the two operands are from the same mul_lohi node.
7903 if (AddcOp0.getNode() == AddcOp1.getNode())
7906 assert(AddcNode->getNumValues() == 2 &&
7907 AddcNode->getValueType(0) == MVT::i32 &&
7908 AddcNode->getValueType(1) == MVT::Glue &&
7909 "Expect ADDC with two result values: i32, glue");
7911 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7912 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7913 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7914 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7915 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7918 // Look for the glued ADDE.
7919 SDNode* AddeNode = AddcNode->getGluedUser();
7920 if (AddeNode == NULL)
7923 // Make sure it is really an ADDE.
7924 if (AddeNode->getOpcode() != ISD::ADDE)
7927 assert(AddeNode->getNumOperands() == 3 &&
7928 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7929 "ADDE node has the wrong inputs");
7931 // Check for the triangle shape.
7932 SDValue AddeOp0 = AddeNode->getOperand(0);
7933 SDValue AddeOp1 = AddeNode->getOperand(1);
7935 // Make sure that the ADDE operands are not coming from the same node.
7936 if (AddeOp0.getNode() == AddeOp1.getNode())
7939 // Find the MUL_LOHI node walking up ADDE's operands.
7940 bool IsLeftOperandMUL = false;
7941 SDValue MULOp = findMUL_LOHI(AddeOp0);
7942 if (MULOp == SDValue())
7943 MULOp = findMUL_LOHI(AddeOp1);
7945 IsLeftOperandMUL = true;
7946 if (MULOp == SDValue())
7949 // Figure out the right opcode.
7950 unsigned Opc = MULOp->getOpcode();
7951 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7953 // Figure out the high and low input values to the MLAL node.
7954 SDValue* HiMul = &MULOp;
7955 SDValue* HiAdd = NULL;
7956 SDValue* LoMul = NULL;
7957 SDValue* LowAdd = NULL;
7959 if (IsLeftOperandMUL)
7965 if (AddcOp0->getOpcode() == Opc) {
7969 if (AddcOp1->getOpcode() == Opc) {
7977 if (LoMul->getNode() != HiMul->getNode())
7980 // Create the merged node.
7981 SelectionDAG &DAG = DCI.DAG;
7983 // Build operand list.
7984 SmallVector<SDValue, 8> Ops;
7985 Ops.push_back(LoMul->getOperand(0));
7986 Ops.push_back(LoMul->getOperand(1));
7987 Ops.push_back(*LowAdd);
7988 Ops.push_back(*HiAdd);
7990 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7991 DAG.getVTList(MVT::i32, MVT::i32),
7992 &Ops[0], Ops.size());
7994 // Replace the ADDs' nodes uses by the MLA node's values.
7995 SDValue HiMLALResult(MLALNode.getNode(), 1);
7996 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7998 SDValue LoMLALResult(MLALNode.getNode(), 0);
7999 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8001 // Return original node to notify the driver to stop replacing.
8002 SDValue resNode(AddcNode, 0);
8006 /// PerformADDCCombine - Target-specific dag combine transform from
8007 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8008 static SDValue PerformADDCCombine(SDNode *N,
8009 TargetLowering::DAGCombinerInfo &DCI,
8010 const ARMSubtarget *Subtarget) {
8012 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8016 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8017 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8018 /// called with the default operands, and if that fails, with commuted
8020 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8021 TargetLowering::DAGCombinerInfo &DCI,
8022 const ARMSubtarget *Subtarget){
8024 // Attempt to create vpaddl for this add.
8025 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8026 if (Result.getNode())
8029 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8030 if (N0.getNode()->hasOneUse()) {
8031 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8032 if (Result.getNode()) return Result;
8037 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8039 static SDValue PerformADDCombine(SDNode *N,
8040 TargetLowering::DAGCombinerInfo &DCI,
8041 const ARMSubtarget *Subtarget) {
8042 SDValue N0 = N->getOperand(0);
8043 SDValue N1 = N->getOperand(1);
8045 // First try with the default operand order.
8046 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8047 if (Result.getNode())
8050 // If that didn't work, try again with the operands commuted.
8051 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8054 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8056 static SDValue PerformSUBCombine(SDNode *N,
8057 TargetLowering::DAGCombinerInfo &DCI) {
8058 SDValue N0 = N->getOperand(0);
8059 SDValue N1 = N->getOperand(1);
8061 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8062 if (N1.getNode()->hasOneUse()) {
8063 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8064 if (Result.getNode()) return Result;
8070 /// PerformVMULCombine
8071 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8072 /// special multiplier accumulator forwarding.
8078 static SDValue PerformVMULCombine(SDNode *N,
8079 TargetLowering::DAGCombinerInfo &DCI,
8080 const ARMSubtarget *Subtarget) {
8081 if (!Subtarget->hasVMLxForwarding())
8084 SelectionDAG &DAG = DCI.DAG;
8085 SDValue N0 = N->getOperand(0);
8086 SDValue N1 = N->getOperand(1);
8087 unsigned Opcode = N0.getOpcode();
8088 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8089 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8090 Opcode = N1.getOpcode();
8091 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8092 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8097 EVT VT = N->getValueType(0);
8098 DebugLoc DL = N->getDebugLoc();
8099 SDValue N00 = N0->getOperand(0);
8100 SDValue N01 = N0->getOperand(1);
8101 return DAG.getNode(Opcode, DL, VT,
8102 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8103 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8106 static SDValue PerformMULCombine(SDNode *N,
8107 TargetLowering::DAGCombinerInfo &DCI,
8108 const ARMSubtarget *Subtarget) {
8109 SelectionDAG &DAG = DCI.DAG;
8111 if (Subtarget->isThumb1Only())
8114 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8117 EVT VT = N->getValueType(0);
8118 if (VT.is64BitVector() || VT.is128BitVector())
8119 return PerformVMULCombine(N, DCI, Subtarget);
8123 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8127 int64_t MulAmt = C->getSExtValue();
8128 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
8130 ShiftAmt = ShiftAmt & (32 - 1);
8131 SDValue V = N->getOperand(0);
8132 DebugLoc DL = N->getDebugLoc();
8135 MulAmt >>= ShiftAmt;
8138 if (isPowerOf2_32(MulAmt - 1)) {
8139 // (mul x, 2^N + 1) => (add (shl x, N), x)
8140 Res = DAG.getNode(ISD::ADD, DL, VT,
8142 DAG.getNode(ISD::SHL, DL, VT,
8144 DAG.getConstant(Log2_32(MulAmt - 1),
8146 } else if (isPowerOf2_32(MulAmt + 1)) {
8147 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8148 Res = DAG.getNode(ISD::SUB, DL, VT,
8149 DAG.getNode(ISD::SHL, DL, VT,
8151 DAG.getConstant(Log2_32(MulAmt + 1),
8157 uint64_t MulAmtAbs = -MulAmt;
8158 if (isPowerOf2_32(MulAmtAbs + 1)) {
8159 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8160 Res = DAG.getNode(ISD::SUB, DL, VT,
8162 DAG.getNode(ISD::SHL, DL, VT,
8164 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8166 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8167 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8168 Res = DAG.getNode(ISD::ADD, DL, VT,
8170 DAG.getNode(ISD::SHL, DL, VT,
8172 DAG.getConstant(Log2_32(MulAmtAbs-1),
8174 Res = DAG.getNode(ISD::SUB, DL, VT,
8175 DAG.getConstant(0, MVT::i32),Res);
8182 Res = DAG.getNode(ISD::SHL, DL, VT,
8183 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8185 // Do not add new nodes to DAG combiner worklist.
8186 DCI.CombineTo(N, Res, false);
8190 static SDValue PerformANDCombine(SDNode *N,
8191 TargetLowering::DAGCombinerInfo &DCI,
8192 const ARMSubtarget *Subtarget) {
8194 // Attempt to use immediate-form VBIC
8195 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8196 DebugLoc dl = N->getDebugLoc();
8197 EVT VT = N->getValueType(0);
8198 SelectionDAG &DAG = DCI.DAG;
8200 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8203 APInt SplatBits, SplatUndef;
8204 unsigned SplatBitSize;
8207 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8208 if (SplatBitSize <= 64) {
8210 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8211 SplatUndef.getZExtValue(), SplatBitSize,
8212 DAG, VbicVT, VT.is128BitVector(),
8214 if (Val.getNode()) {
8216 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8217 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8218 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8223 if (!Subtarget->isThumb1Only()) {
8224 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8225 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8226 if (Result.getNode())
8233 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8234 static SDValue PerformORCombine(SDNode *N,
8235 TargetLowering::DAGCombinerInfo &DCI,
8236 const ARMSubtarget *Subtarget) {
8237 // Attempt to use immediate-form VORR
8238 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8239 DebugLoc dl = N->getDebugLoc();
8240 EVT VT = N->getValueType(0);
8241 SelectionDAG &DAG = DCI.DAG;
8243 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8246 APInt SplatBits, SplatUndef;
8247 unsigned SplatBitSize;
8249 if (BVN && Subtarget->hasNEON() &&
8250 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8251 if (SplatBitSize <= 64) {
8253 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8254 SplatUndef.getZExtValue(), SplatBitSize,
8255 DAG, VorrVT, VT.is128BitVector(),
8257 if (Val.getNode()) {
8259 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8260 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8261 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8266 if (!Subtarget->isThumb1Only()) {
8267 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8268 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8269 if (Result.getNode())
8273 // The code below optimizes (or (and X, Y), Z).
8274 // The AND operand needs to have a single user to make these optimizations
8276 SDValue N0 = N->getOperand(0);
8277 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8279 SDValue N1 = N->getOperand(1);
8281 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8282 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8283 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8285 unsigned SplatBitSize;
8288 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8290 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8291 HasAnyUndefs) && !HasAnyUndefs) {
8292 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8294 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8295 HasAnyUndefs) && !HasAnyUndefs &&
8296 SplatBits0 == ~SplatBits1) {
8297 // Canonicalize the vector type to make instruction selection simpler.
8298 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8299 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8300 N0->getOperand(1), N0->getOperand(0),
8302 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8307 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8310 // BFI is only available on V6T2+
8311 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8314 DebugLoc DL = N->getDebugLoc();
8315 // 1) or (and A, mask), val => ARMbfi A, val, mask
8316 // iff (val & mask) == val
8318 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8319 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8320 // && mask == ~mask2
8321 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8322 // && ~mask == mask2
8323 // (i.e., copy a bitfield value into another bitfield of the same width)
8328 SDValue N00 = N0.getOperand(0);
8330 // The value and the mask need to be constants so we can verify this is
8331 // actually a bitfield set. If the mask is 0xffff, we can do better
8332 // via a movt instruction, so don't use BFI in that case.
8333 SDValue MaskOp = N0.getOperand(1);
8334 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8337 unsigned Mask = MaskC->getZExtValue();
8341 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8342 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8344 unsigned Val = N1C->getZExtValue();
8345 if ((Val & ~Mask) != Val)
8348 if (ARM::isBitFieldInvertedMask(Mask)) {
8349 Val >>= CountTrailingZeros_32(~Mask);
8351 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8352 DAG.getConstant(Val, MVT::i32),
8353 DAG.getConstant(Mask, MVT::i32));
8355 // Do not add new nodes to DAG combiner worklist.
8356 DCI.CombineTo(N, Res, false);
8359 } else if (N1.getOpcode() == ISD::AND) {
8360 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8361 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8364 unsigned Mask2 = N11C->getZExtValue();
8366 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8368 if (ARM::isBitFieldInvertedMask(Mask) &&
8370 // The pack halfword instruction works better for masks that fit it,
8371 // so use that when it's available.
8372 if (Subtarget->hasT2ExtractPack() &&
8373 (Mask == 0xffff || Mask == 0xffff0000))
8376 unsigned amt = CountTrailingZeros_32(Mask2);
8377 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8378 DAG.getConstant(amt, MVT::i32));
8379 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8380 DAG.getConstant(Mask, MVT::i32));
8381 // Do not add new nodes to DAG combiner worklist.
8382 DCI.CombineTo(N, Res, false);
8384 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8386 // The pack halfword instruction works better for masks that fit it,
8387 // so use that when it's available.
8388 if (Subtarget->hasT2ExtractPack() &&
8389 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8392 unsigned lsb = CountTrailingZeros_32(Mask);
8393 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8394 DAG.getConstant(lsb, MVT::i32));
8395 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8396 DAG.getConstant(Mask2, MVT::i32));
8397 // Do not add new nodes to DAG combiner worklist.
8398 DCI.CombineTo(N, Res, false);
8403 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8404 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8405 ARM::isBitFieldInvertedMask(~Mask)) {
8406 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8407 // where lsb(mask) == #shamt and masked bits of B are known zero.
8408 SDValue ShAmt = N00.getOperand(1);
8409 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8410 unsigned LSB = CountTrailingZeros_32(Mask);
8414 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8415 DAG.getConstant(~Mask, MVT::i32));
8417 // Do not add new nodes to DAG combiner worklist.
8418 DCI.CombineTo(N, Res, false);
8424 static SDValue PerformXORCombine(SDNode *N,
8425 TargetLowering::DAGCombinerInfo &DCI,
8426 const ARMSubtarget *Subtarget) {
8427 EVT VT = N->getValueType(0);
8428 SelectionDAG &DAG = DCI.DAG;
8430 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8433 if (!Subtarget->isThumb1Only()) {
8434 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8435 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8436 if (Result.getNode())
8443 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8444 /// the bits being cleared by the AND are not demanded by the BFI.
8445 static SDValue PerformBFICombine(SDNode *N,
8446 TargetLowering::DAGCombinerInfo &DCI) {
8447 SDValue N1 = N->getOperand(1);
8448 if (N1.getOpcode() == ISD::AND) {
8449 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8452 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8453 unsigned LSB = CountTrailingZeros_32(~InvMask);
8454 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8455 unsigned Mask = (1 << Width)-1;
8456 unsigned Mask2 = N11C->getZExtValue();
8457 if ((Mask & (~Mask2)) == 0)
8458 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8459 N->getOperand(0), N1.getOperand(0),
8465 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8466 /// ARMISD::VMOVRRD.
8467 static SDValue PerformVMOVRRDCombine(SDNode *N,
8468 TargetLowering::DAGCombinerInfo &DCI) {
8469 // vmovrrd(vmovdrr x, y) -> x,y
8470 SDValue InDouble = N->getOperand(0);
8471 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8472 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8474 // vmovrrd(load f64) -> (load i32), (load i32)
8475 SDNode *InNode = InDouble.getNode();
8476 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8477 InNode->getValueType(0) == MVT::f64 &&
8478 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8479 !cast<LoadSDNode>(InNode)->isVolatile()) {
8480 // TODO: Should this be done for non-FrameIndex operands?
8481 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8483 SelectionDAG &DAG = DCI.DAG;
8484 DebugLoc DL = LD->getDebugLoc();
8485 SDValue BasePtr = LD->getBasePtr();
8486 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8487 LD->getPointerInfo(), LD->isVolatile(),
8488 LD->isNonTemporal(), LD->isInvariant(),
8489 LD->getAlignment());
8491 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8492 DAG.getConstant(4, MVT::i32));
8493 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8494 LD->getPointerInfo(), LD->isVolatile(),
8495 LD->isNonTemporal(), LD->isInvariant(),
8496 std::min(4U, LD->getAlignment() / 2));
8498 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8499 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8500 DCI.RemoveFromWorklist(LD);
8508 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8509 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8510 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8511 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8512 SDValue Op0 = N->getOperand(0);
8513 SDValue Op1 = N->getOperand(1);
8514 if (Op0.getOpcode() == ISD::BITCAST)
8515 Op0 = Op0.getOperand(0);
8516 if (Op1.getOpcode() == ISD::BITCAST)
8517 Op1 = Op1.getOperand(0);
8518 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8519 Op0.getNode() == Op1.getNode() &&
8520 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8521 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8522 N->getValueType(0), Op0.getOperand(0));
8526 /// PerformSTORECombine - Target-specific dag combine xforms for
8528 static SDValue PerformSTORECombine(SDNode *N,
8529 TargetLowering::DAGCombinerInfo &DCI) {
8530 StoreSDNode *St = cast<StoreSDNode>(N);
8531 if (St->isVolatile())
8534 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8535 // pack all of the elements in one place. Next, store to memory in fewer
8537 SDValue StVal = St->getValue();
8538 EVT VT = StVal.getValueType();
8539 if (St->isTruncatingStore() && VT.isVector()) {
8540 SelectionDAG &DAG = DCI.DAG;
8541 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8542 EVT StVT = St->getMemoryVT();
8543 unsigned NumElems = VT.getVectorNumElements();
8544 assert(StVT != VT && "Cannot truncate to the same type");
8545 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8546 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8548 // From, To sizes and ElemCount must be pow of two
8549 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8551 // We are going to use the original vector elt for storing.
8552 // Accumulated smaller vector elements must be a multiple of the store size.
8553 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8555 unsigned SizeRatio = FromEltSz / ToEltSz;
8556 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8558 // Create a type on which we perform the shuffle.
8559 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8560 NumElems*SizeRatio);
8561 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8563 DebugLoc DL = St->getDebugLoc();
8564 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8565 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8566 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8568 // Can't shuffle using an illegal type.
8569 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8571 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8572 DAG.getUNDEF(WideVec.getValueType()),
8574 // At this point all of the data is stored at the bottom of the
8575 // register. We now need to save it to mem.
8577 // Find the largest store unit
8578 MVT StoreType = MVT::i8;
8579 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8580 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8581 MVT Tp = (MVT::SimpleValueType)tp;
8582 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8585 // Didn't find a legal store type.
8586 if (!TLI.isTypeLegal(StoreType))
8589 // Bitcast the original vector into a vector of store-size units
8590 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8591 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8592 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8593 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8594 SmallVector<SDValue, 8> Chains;
8595 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8596 TLI.getPointerTy());
8597 SDValue BasePtr = St->getBasePtr();
8599 // Perform one or more big stores into memory.
8600 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8601 for (unsigned I = 0; I < E; I++) {
8602 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8603 StoreType, ShuffWide,
8604 DAG.getIntPtrConstant(I));
8605 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8606 St->getPointerInfo(), St->isVolatile(),
8607 St->isNonTemporal(), St->getAlignment());
8608 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8610 Chains.push_back(Ch);
8612 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8616 if (!ISD::isNormalStore(St))
8619 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8620 // ARM stores of arguments in the same cache line.
8621 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8622 StVal.getNode()->hasOneUse()) {
8623 SelectionDAG &DAG = DCI.DAG;
8624 DebugLoc DL = St->getDebugLoc();
8625 SDValue BasePtr = St->getBasePtr();
8626 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8627 StVal.getNode()->getOperand(0), BasePtr,
8628 St->getPointerInfo(), St->isVolatile(),
8629 St->isNonTemporal(), St->getAlignment());
8631 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8632 DAG.getConstant(4, MVT::i32));
8633 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8634 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8635 St->isNonTemporal(),
8636 std::min(4U, St->getAlignment() / 2));
8639 if (StVal.getValueType() != MVT::i64 ||
8640 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8643 // Bitcast an i64 store extracted from a vector to f64.
8644 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8645 SelectionDAG &DAG = DCI.DAG;
8646 DebugLoc dl = StVal.getDebugLoc();
8647 SDValue IntVec = StVal.getOperand(0);
8648 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8649 IntVec.getValueType().getVectorNumElements());
8650 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8651 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8652 Vec, StVal.getOperand(1));
8653 dl = N->getDebugLoc();
8654 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8655 // Make the DAGCombiner fold the bitcasts.
8656 DCI.AddToWorklist(Vec.getNode());
8657 DCI.AddToWorklist(ExtElt.getNode());
8658 DCI.AddToWorklist(V.getNode());
8659 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8660 St->getPointerInfo(), St->isVolatile(),
8661 St->isNonTemporal(), St->getAlignment(),
8665 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8666 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8667 /// i64 vector to have f64 elements, since the value can then be loaded
8668 /// directly into a VFP register.
8669 static bool hasNormalLoadOperand(SDNode *N) {
8670 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8671 for (unsigned i = 0; i < NumElts; ++i) {
8672 SDNode *Elt = N->getOperand(i).getNode();
8673 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8679 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8680 /// ISD::BUILD_VECTOR.
8681 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8682 TargetLowering::DAGCombinerInfo &DCI){
8683 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8684 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8685 // into a pair of GPRs, which is fine when the value is used as a scalar,
8686 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8687 SelectionDAG &DAG = DCI.DAG;
8688 if (N->getNumOperands() == 2) {
8689 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8694 // Load i64 elements as f64 values so that type legalization does not split
8695 // them up into i32 values.
8696 EVT VT = N->getValueType(0);
8697 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8699 DebugLoc dl = N->getDebugLoc();
8700 SmallVector<SDValue, 8> Ops;
8701 unsigned NumElts = VT.getVectorNumElements();
8702 for (unsigned i = 0; i < NumElts; ++i) {
8703 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8705 // Make the DAGCombiner fold the bitcast.
8706 DCI.AddToWorklist(V.getNode());
8708 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8709 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8710 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8713 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8714 /// ISD::INSERT_VECTOR_ELT.
8715 static SDValue PerformInsertEltCombine(SDNode *N,
8716 TargetLowering::DAGCombinerInfo &DCI) {
8717 // Bitcast an i64 load inserted into a vector to f64.
8718 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8719 EVT VT = N->getValueType(0);
8720 SDNode *Elt = N->getOperand(1).getNode();
8721 if (VT.getVectorElementType() != MVT::i64 ||
8722 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8725 SelectionDAG &DAG = DCI.DAG;
8726 DebugLoc dl = N->getDebugLoc();
8727 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8728 VT.getVectorNumElements());
8729 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8730 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8731 // Make the DAGCombiner fold the bitcasts.
8732 DCI.AddToWorklist(Vec.getNode());
8733 DCI.AddToWorklist(V.getNode());
8734 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8735 Vec, V, N->getOperand(2));
8736 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8739 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8740 /// ISD::VECTOR_SHUFFLE.
8741 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8742 // The LLVM shufflevector instruction does not require the shuffle mask
8743 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8744 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8745 // operands do not match the mask length, they are extended by concatenating
8746 // them with undef vectors. That is probably the right thing for other
8747 // targets, but for NEON it is better to concatenate two double-register
8748 // size vector operands into a single quad-register size vector. Do that
8749 // transformation here:
8750 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8751 // shuffle(concat(v1, v2), undef)
8752 SDValue Op0 = N->getOperand(0);
8753 SDValue Op1 = N->getOperand(1);
8754 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8755 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8756 Op0.getNumOperands() != 2 ||
8757 Op1.getNumOperands() != 2)
8759 SDValue Concat0Op1 = Op0.getOperand(1);
8760 SDValue Concat1Op1 = Op1.getOperand(1);
8761 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8762 Concat1Op1.getOpcode() != ISD::UNDEF)
8764 // Skip the transformation if any of the types are illegal.
8765 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8766 EVT VT = N->getValueType(0);
8767 if (!TLI.isTypeLegal(VT) ||
8768 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8769 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8772 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8773 Op0.getOperand(0), Op1.getOperand(0));
8774 // Translate the shuffle mask.
8775 SmallVector<int, 16> NewMask;
8776 unsigned NumElts = VT.getVectorNumElements();
8777 unsigned HalfElts = NumElts/2;
8778 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8779 for (unsigned n = 0; n < NumElts; ++n) {
8780 int MaskElt = SVN->getMaskElt(n);
8782 if (MaskElt < (int)HalfElts)
8784 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8785 NewElt = HalfElts + MaskElt - NumElts;
8786 NewMask.push_back(NewElt);
8788 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8789 DAG.getUNDEF(VT), NewMask.data());
8792 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8793 /// NEON load/store intrinsics to merge base address updates.
8794 static SDValue CombineBaseUpdate(SDNode *N,
8795 TargetLowering::DAGCombinerInfo &DCI) {
8796 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8799 SelectionDAG &DAG = DCI.DAG;
8800 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8801 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8802 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8803 SDValue Addr = N->getOperand(AddrOpIdx);
8805 // Search for a use of the address operand that is an increment.
8806 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8807 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8809 if (User->getOpcode() != ISD::ADD ||
8810 UI.getUse().getResNo() != Addr.getResNo())
8813 // Check that the add is independent of the load/store. Otherwise, folding
8814 // it would create a cycle.
8815 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8818 // Find the new opcode for the updating load/store.
8820 bool isLaneOp = false;
8821 unsigned NewOpc = 0;
8822 unsigned NumVecs = 0;
8824 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8826 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8827 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8829 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8831 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8833 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8835 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8836 NumVecs = 2; isLaneOp = true; break;
8837 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8838 NumVecs = 3; isLaneOp = true; break;
8839 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8840 NumVecs = 4; isLaneOp = true; break;
8841 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8842 NumVecs = 1; isLoad = false; break;
8843 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8844 NumVecs = 2; isLoad = false; break;
8845 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8846 NumVecs = 3; isLoad = false; break;
8847 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8848 NumVecs = 4; isLoad = false; break;
8849 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8850 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8851 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8852 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8853 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8854 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8858 switch (N->getOpcode()) {
8859 default: llvm_unreachable("unexpected opcode for Neon base update");
8860 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8861 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8862 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8866 // Find the size of memory referenced by the load/store.
8869 VecTy = N->getValueType(0);
8871 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8872 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8874 NumBytes /= VecTy.getVectorNumElements();
8876 // If the increment is a constant, it must match the memory ref size.
8877 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8878 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8879 uint64_t IncVal = CInc->getZExtValue();
8880 if (IncVal != NumBytes)
8882 } else if (NumBytes >= 3 * 16) {
8883 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8884 // separate instructions that make it harder to use a non-constant update.
8888 // Create the new updating load/store node.
8890 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8892 for (n = 0; n < NumResultVecs; ++n)
8894 Tys[n++] = MVT::i32;
8895 Tys[n] = MVT::Other;
8896 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8897 SmallVector<SDValue, 8> Ops;
8898 Ops.push_back(N->getOperand(0)); // incoming chain
8899 Ops.push_back(N->getOperand(AddrOpIdx));
8901 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8902 Ops.push_back(N->getOperand(i));
8904 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8905 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8906 Ops.data(), Ops.size(),
8907 MemInt->getMemoryVT(),
8908 MemInt->getMemOperand());
8911 std::vector<SDValue> NewResults;
8912 for (unsigned i = 0; i < NumResultVecs; ++i) {
8913 NewResults.push_back(SDValue(UpdN.getNode(), i));
8915 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8916 DCI.CombineTo(N, NewResults);
8917 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8924 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8925 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8926 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8928 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8929 SelectionDAG &DAG = DCI.DAG;
8930 EVT VT = N->getValueType(0);
8931 // vldN-dup instructions only support 64-bit vectors for N > 1.
8932 if (!VT.is64BitVector())
8935 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8936 SDNode *VLD = N->getOperand(0).getNode();
8937 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8939 unsigned NumVecs = 0;
8940 unsigned NewOpc = 0;
8941 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8942 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8944 NewOpc = ARMISD::VLD2DUP;
8945 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8947 NewOpc = ARMISD::VLD3DUP;
8948 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8950 NewOpc = ARMISD::VLD4DUP;
8955 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8956 // numbers match the load.
8957 unsigned VLDLaneNo =
8958 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8959 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8961 // Ignore uses of the chain result.
8962 if (UI.getUse().getResNo() == NumVecs)
8965 if (User->getOpcode() != ARMISD::VDUPLANE ||
8966 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8970 // Create the vldN-dup node.
8973 for (n = 0; n < NumVecs; ++n)
8975 Tys[n] = MVT::Other;
8976 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8977 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8978 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8979 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8980 Ops, 2, VLDMemInt->getMemoryVT(),
8981 VLDMemInt->getMemOperand());
8984 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8986 unsigned ResNo = UI.getUse().getResNo();
8987 // Ignore uses of the chain result.
8988 if (ResNo == NumVecs)
8991 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8994 // Now the vldN-lane intrinsic is dead except for its chain result.
8995 // Update uses of the chain.
8996 std::vector<SDValue> VLDDupResults;
8997 for (unsigned n = 0; n < NumVecs; ++n)
8998 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8999 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9000 DCI.CombineTo(VLD, VLDDupResults);
9005 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9006 /// ARMISD::VDUPLANE.
9007 static SDValue PerformVDUPLANECombine(SDNode *N,
9008 TargetLowering::DAGCombinerInfo &DCI) {
9009 SDValue Op = N->getOperand(0);
9011 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9012 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9013 if (CombineVLDDUP(N, DCI))
9014 return SDValue(N, 0);
9016 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9017 // redundant. Ignore bit_converts for now; element sizes are checked below.
9018 while (Op.getOpcode() == ISD::BITCAST)
9019 Op = Op.getOperand(0);
9020 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9023 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9024 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9025 // The canonical VMOV for a zero vector uses a 32-bit element size.
9026 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9028 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9030 EVT VT = N->getValueType(0);
9031 if (EltSize > VT.getVectorElementType().getSizeInBits())
9034 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
9037 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9038 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9039 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9043 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9045 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9050 APFloat APF = C->getValueAPF();
9051 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9052 != APFloat::opOK || !isExact)
9055 c0 = (I == 0) ? cN : c0;
9056 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9063 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9064 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9065 /// when the VMUL has a constant operand that is a power of 2.
9067 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9068 /// vmul.f32 d16, d17, d16
9069 /// vcvt.s32.f32 d16, d16
9071 /// vcvt.s32.f32 d16, d16, #3
9072 static SDValue PerformVCVTCombine(SDNode *N,
9073 TargetLowering::DAGCombinerInfo &DCI,
9074 const ARMSubtarget *Subtarget) {
9075 SelectionDAG &DAG = DCI.DAG;
9076 SDValue Op = N->getOperand(0);
9078 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9079 Op.getOpcode() != ISD::FMUL)
9083 SDValue N0 = Op->getOperand(0);
9084 SDValue ConstVec = Op->getOperand(1);
9085 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9087 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9088 !isConstVecPow2(ConstVec, isSigned, C))
9091 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9092 Intrinsic::arm_neon_vcvtfp2fxu;
9093 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9095 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9096 DAG.getConstant(Log2_64(C), MVT::i32));
9099 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9100 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9101 /// when the VDIV has a constant operand that is a power of 2.
9103 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9104 /// vcvt.f32.s32 d16, d16
9105 /// vdiv.f32 d16, d17, d16
9107 /// vcvt.f32.s32 d16, d16, #3
9108 static SDValue PerformVDIVCombine(SDNode *N,
9109 TargetLowering::DAGCombinerInfo &DCI,
9110 const ARMSubtarget *Subtarget) {
9111 SelectionDAG &DAG = DCI.DAG;
9112 SDValue Op = N->getOperand(0);
9113 unsigned OpOpcode = Op.getNode()->getOpcode();
9115 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9116 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9120 SDValue ConstVec = N->getOperand(1);
9121 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9123 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9124 !isConstVecPow2(ConstVec, isSigned, C))
9127 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9128 Intrinsic::arm_neon_vcvtfxu2fp;
9129 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9131 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9132 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
9135 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9136 /// operand of a vector shift operation, where all the elements of the
9137 /// build_vector must have the same constant integer value.
9138 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9139 // Ignore bit_converts.
9140 while (Op.getOpcode() == ISD::BITCAST)
9141 Op = Op.getOperand(0);
9142 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9143 APInt SplatBits, SplatUndef;
9144 unsigned SplatBitSize;
9146 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9147 HasAnyUndefs, ElementBits) ||
9148 SplatBitSize > ElementBits)
9150 Cnt = SplatBits.getSExtValue();
9154 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9155 /// operand of a vector shift left operation. That value must be in the range:
9156 /// 0 <= Value < ElementBits for a left shift; or
9157 /// 0 <= Value <= ElementBits for a long left shift.
9158 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9159 assert(VT.isVector() && "vector shift count is not a vector type");
9160 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9161 if (! getVShiftImm(Op, ElementBits, Cnt))
9163 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9166 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9167 /// operand of a vector shift right operation. For a shift opcode, the value
9168 /// is positive, but for an intrinsic the value count must be negative. The
9169 /// absolute value must be in the range:
9170 /// 1 <= |Value| <= ElementBits for a right shift; or
9171 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9172 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9174 assert(VT.isVector() && "vector shift count is not a vector type");
9175 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9176 if (! getVShiftImm(Op, ElementBits, Cnt))
9180 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9183 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9184 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9185 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9188 // Don't do anything for most intrinsics.
9191 // Vector shifts: check for immediate versions and lower them.
9192 // Note: This is done during DAG combining instead of DAG legalizing because
9193 // the build_vectors for 64-bit vector element shift counts are generally
9194 // not legal, and it is hard to see their values after they get legalized to
9195 // loads from a constant pool.
9196 case Intrinsic::arm_neon_vshifts:
9197 case Intrinsic::arm_neon_vshiftu:
9198 case Intrinsic::arm_neon_vshiftls:
9199 case Intrinsic::arm_neon_vshiftlu:
9200 case Intrinsic::arm_neon_vshiftn:
9201 case Intrinsic::arm_neon_vrshifts:
9202 case Intrinsic::arm_neon_vrshiftu:
9203 case Intrinsic::arm_neon_vrshiftn:
9204 case Intrinsic::arm_neon_vqshifts:
9205 case Intrinsic::arm_neon_vqshiftu:
9206 case Intrinsic::arm_neon_vqshiftsu:
9207 case Intrinsic::arm_neon_vqshiftns:
9208 case Intrinsic::arm_neon_vqshiftnu:
9209 case Intrinsic::arm_neon_vqshiftnsu:
9210 case Intrinsic::arm_neon_vqrshiftns:
9211 case Intrinsic::arm_neon_vqrshiftnu:
9212 case Intrinsic::arm_neon_vqrshiftnsu: {
9213 EVT VT = N->getOperand(1).getValueType();
9215 unsigned VShiftOpc = 0;
9218 case Intrinsic::arm_neon_vshifts:
9219 case Intrinsic::arm_neon_vshiftu:
9220 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9221 VShiftOpc = ARMISD::VSHL;
9224 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9225 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9226 ARMISD::VSHRs : ARMISD::VSHRu);
9231 case Intrinsic::arm_neon_vshiftls:
9232 case Intrinsic::arm_neon_vshiftlu:
9233 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9235 llvm_unreachable("invalid shift count for vshll intrinsic");
9237 case Intrinsic::arm_neon_vrshifts:
9238 case Intrinsic::arm_neon_vrshiftu:
9239 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9243 case Intrinsic::arm_neon_vqshifts:
9244 case Intrinsic::arm_neon_vqshiftu:
9245 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9249 case Intrinsic::arm_neon_vqshiftsu:
9250 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9252 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9254 case Intrinsic::arm_neon_vshiftn:
9255 case Intrinsic::arm_neon_vrshiftn:
9256 case Intrinsic::arm_neon_vqshiftns:
9257 case Intrinsic::arm_neon_vqshiftnu:
9258 case Intrinsic::arm_neon_vqshiftnsu:
9259 case Intrinsic::arm_neon_vqrshiftns:
9260 case Intrinsic::arm_neon_vqrshiftnu:
9261 case Intrinsic::arm_neon_vqrshiftnsu:
9262 // Narrowing shifts require an immediate right shift.
9263 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9265 llvm_unreachable("invalid shift count for narrowing vector shift "
9269 llvm_unreachable("unhandled vector shift");
9273 case Intrinsic::arm_neon_vshifts:
9274 case Intrinsic::arm_neon_vshiftu:
9275 // Opcode already set above.
9277 case Intrinsic::arm_neon_vshiftls:
9278 case Intrinsic::arm_neon_vshiftlu:
9279 if (Cnt == VT.getVectorElementType().getSizeInBits())
9280 VShiftOpc = ARMISD::VSHLLi;
9282 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9283 ARMISD::VSHLLs : ARMISD::VSHLLu);
9285 case Intrinsic::arm_neon_vshiftn:
9286 VShiftOpc = ARMISD::VSHRN; break;
9287 case Intrinsic::arm_neon_vrshifts:
9288 VShiftOpc = ARMISD::VRSHRs; break;
9289 case Intrinsic::arm_neon_vrshiftu:
9290 VShiftOpc = ARMISD::VRSHRu; break;
9291 case Intrinsic::arm_neon_vrshiftn:
9292 VShiftOpc = ARMISD::VRSHRN; break;
9293 case Intrinsic::arm_neon_vqshifts:
9294 VShiftOpc = ARMISD::VQSHLs; break;
9295 case Intrinsic::arm_neon_vqshiftu:
9296 VShiftOpc = ARMISD::VQSHLu; break;
9297 case Intrinsic::arm_neon_vqshiftsu:
9298 VShiftOpc = ARMISD::VQSHLsu; break;
9299 case Intrinsic::arm_neon_vqshiftns:
9300 VShiftOpc = ARMISD::VQSHRNs; break;
9301 case Intrinsic::arm_neon_vqshiftnu:
9302 VShiftOpc = ARMISD::VQSHRNu; break;
9303 case Intrinsic::arm_neon_vqshiftnsu:
9304 VShiftOpc = ARMISD::VQSHRNsu; break;
9305 case Intrinsic::arm_neon_vqrshiftns:
9306 VShiftOpc = ARMISD::VQRSHRNs; break;
9307 case Intrinsic::arm_neon_vqrshiftnu:
9308 VShiftOpc = ARMISD::VQRSHRNu; break;
9309 case Intrinsic::arm_neon_vqrshiftnsu:
9310 VShiftOpc = ARMISD::VQRSHRNsu; break;
9313 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9314 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9317 case Intrinsic::arm_neon_vshiftins: {
9318 EVT VT = N->getOperand(1).getValueType();
9320 unsigned VShiftOpc = 0;
9322 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9323 VShiftOpc = ARMISD::VSLI;
9324 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9325 VShiftOpc = ARMISD::VSRI;
9327 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9330 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9331 N->getOperand(1), N->getOperand(2),
9332 DAG.getConstant(Cnt, MVT::i32));
9335 case Intrinsic::arm_neon_vqrshifts:
9336 case Intrinsic::arm_neon_vqrshiftu:
9337 // No immediate versions of these to check for.
9344 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9345 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9346 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9347 /// vector element shift counts are generally not legal, and it is hard to see
9348 /// their values after they get legalized to loads from a constant pool.
9349 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9350 const ARMSubtarget *ST) {
9351 EVT VT = N->getValueType(0);
9352 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9353 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9354 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9355 SDValue N1 = N->getOperand(1);
9356 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9357 SDValue N0 = N->getOperand(0);
9358 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9359 DAG.MaskedValueIsZero(N0.getOperand(0),
9360 APInt::getHighBitsSet(32, 16)))
9361 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9365 // Nothing to be done for scalar shifts.
9366 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9367 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9370 assert(ST->hasNEON() && "unexpected vector shift");
9373 switch (N->getOpcode()) {
9374 default: llvm_unreachable("unexpected shift opcode");
9377 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9378 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9379 DAG.getConstant(Cnt, MVT::i32));
9384 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9385 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9386 ARMISD::VSHRs : ARMISD::VSHRu);
9387 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9388 DAG.getConstant(Cnt, MVT::i32));
9394 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9395 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9396 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9397 const ARMSubtarget *ST) {
9398 SDValue N0 = N->getOperand(0);
9400 // Check for sign- and zero-extensions of vector extract operations of 8-
9401 // and 16-bit vector elements. NEON supports these directly. They are
9402 // handled during DAG combining because type legalization will promote them
9403 // to 32-bit types and it is messy to recognize the operations after that.
9404 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9405 SDValue Vec = N0.getOperand(0);
9406 SDValue Lane = N0.getOperand(1);
9407 EVT VT = N->getValueType(0);
9408 EVT EltVT = N0.getValueType();
9409 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9411 if (VT == MVT::i32 &&
9412 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9413 TLI.isTypeLegal(Vec.getValueType()) &&
9414 isa<ConstantSDNode>(Lane)) {
9417 switch (N->getOpcode()) {
9418 default: llvm_unreachable("unexpected opcode");
9419 case ISD::SIGN_EXTEND:
9420 Opc = ARMISD::VGETLANEs;
9422 case ISD::ZERO_EXTEND:
9423 case ISD::ANY_EXTEND:
9424 Opc = ARMISD::VGETLANEu;
9427 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9434 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9435 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9436 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9437 const ARMSubtarget *ST) {
9438 // If the target supports NEON, try to use vmax/vmin instructions for f32
9439 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9440 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9441 // a NaN; only do the transformation when it matches that behavior.
9443 // For now only do this when using NEON for FP operations; if using VFP, it
9444 // is not obvious that the benefit outweighs the cost of switching to the
9446 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9447 N->getValueType(0) != MVT::f32)
9450 SDValue CondLHS = N->getOperand(0);
9451 SDValue CondRHS = N->getOperand(1);
9452 SDValue LHS = N->getOperand(2);
9453 SDValue RHS = N->getOperand(3);
9454 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9456 unsigned Opcode = 0;
9458 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9459 IsReversed = false; // x CC y ? x : y
9460 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9461 IsReversed = true ; // x CC y ? y : x
9475 // If LHS is NaN, an ordered comparison will be false and the result will
9476 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9477 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9478 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9479 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9481 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9482 // will return -0, so vmin can only be used for unsafe math or if one of
9483 // the operands is known to be nonzero.
9484 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9485 !DAG.getTarget().Options.UnsafeFPMath &&
9486 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9488 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9497 // If LHS is NaN, an ordered comparison will be false and the result will
9498 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9499 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9500 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9501 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9503 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9504 // will return +0, so vmax can only be used for unsafe math or if one of
9505 // the operands is known to be nonzero.
9506 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9507 !DAG.getTarget().Options.UnsafeFPMath &&
9508 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9510 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9516 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9519 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9521 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9522 SDValue Cmp = N->getOperand(4);
9523 if (Cmp.getOpcode() != ARMISD::CMPZ)
9524 // Only looking at EQ and NE cases.
9527 EVT VT = N->getValueType(0);
9528 DebugLoc dl = N->getDebugLoc();
9529 SDValue LHS = Cmp.getOperand(0);
9530 SDValue RHS = Cmp.getOperand(1);
9531 SDValue FalseVal = N->getOperand(0);
9532 SDValue TrueVal = N->getOperand(1);
9533 SDValue ARMcc = N->getOperand(2);
9534 ARMCC::CondCodes CC =
9535 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9553 /// FIXME: Turn this into a target neutral optimization?
9555 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9556 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9557 N->getOperand(3), Cmp);
9558 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9560 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9561 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9562 N->getOperand(3), NewCmp);
9565 if (Res.getNode()) {
9566 APInt KnownZero, KnownOne;
9567 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9568 // Capture demanded bits information that would be otherwise lost.
9569 if (KnownZero == 0xfffffffe)
9570 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9571 DAG.getValueType(MVT::i1));
9572 else if (KnownZero == 0xffffff00)
9573 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9574 DAG.getValueType(MVT::i8));
9575 else if (KnownZero == 0xffff0000)
9576 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9577 DAG.getValueType(MVT::i16));
9583 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9584 DAGCombinerInfo &DCI) const {
9585 switch (N->getOpcode()) {
9587 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9588 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9589 case ISD::SUB: return PerformSUBCombine(N, DCI);
9590 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9591 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9592 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9593 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9594 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9595 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9596 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9597 case ISD::STORE: return PerformSTORECombine(N, DCI);
9598 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9599 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9600 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9601 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9602 case ISD::FP_TO_SINT:
9603 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9604 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9605 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9608 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9609 case ISD::SIGN_EXTEND:
9610 case ISD::ZERO_EXTEND:
9611 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9612 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9613 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9614 case ARMISD::VLD2DUP:
9615 case ARMISD::VLD3DUP:
9616 case ARMISD::VLD4DUP:
9617 return CombineBaseUpdate(N, DCI);
9618 case ISD::INTRINSIC_VOID:
9619 case ISD::INTRINSIC_W_CHAIN:
9620 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9621 case Intrinsic::arm_neon_vld1:
9622 case Intrinsic::arm_neon_vld2:
9623 case Intrinsic::arm_neon_vld3:
9624 case Intrinsic::arm_neon_vld4:
9625 case Intrinsic::arm_neon_vld2lane:
9626 case Intrinsic::arm_neon_vld3lane:
9627 case Intrinsic::arm_neon_vld4lane:
9628 case Intrinsic::arm_neon_vst1:
9629 case Intrinsic::arm_neon_vst2:
9630 case Intrinsic::arm_neon_vst3:
9631 case Intrinsic::arm_neon_vst4:
9632 case Intrinsic::arm_neon_vst2lane:
9633 case Intrinsic::arm_neon_vst3lane:
9634 case Intrinsic::arm_neon_vst4lane:
9635 return CombineBaseUpdate(N, DCI);
9643 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9645 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9648 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9649 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9650 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9652 switch (VT.getSimpleVT().SimpleTy) {
9658 // Unaligned access can use (for example) LRDB, LRDH, LDR
9659 if (AllowsUnaligned) {
9661 *Fast = Subtarget->hasV7Ops();
9668 // For any little-endian targets with neon, we can support unaligned ld/st
9669 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9670 // A big-endian target may also explictly support unaligned accesses
9671 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9681 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9682 unsigned AlignCheck) {
9683 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9684 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9687 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9688 unsigned DstAlign, unsigned SrcAlign,
9689 bool IsMemset, bool ZeroMemset,
9691 MachineFunction &MF) const {
9692 const Function *F = MF.getFunction();
9694 // See if we can use NEON instructions for this...
9695 if ((!IsMemset || ZeroMemset) &&
9696 Subtarget->hasNEON() &&
9697 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9698 Attribute::NoImplicitFloat)) {
9701 (memOpAlign(SrcAlign, DstAlign, 16) ||
9702 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9704 } else if (Size >= 8 &&
9705 (memOpAlign(SrcAlign, DstAlign, 8) ||
9706 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9711 // Lowering to i32/i16 if the size permits.
9717 // Let the target-independent logic figure it out.
9721 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9722 if (Val.getOpcode() != ISD::LOAD)
9725 EVT VT1 = Val.getValueType();
9726 if (!VT1.isSimple() || !VT1.isInteger() ||
9727 !VT2.isSimple() || !VT2.isInteger())
9730 switch (VT1.getSimpleVT().SimpleTy) {
9735 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9742 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9747 switch (VT.getSimpleVT().SimpleTy) {
9748 default: return false;
9763 if ((V & (Scale - 1)) != 0)
9766 return V == (V & ((1LL << 5) - 1));
9769 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9770 const ARMSubtarget *Subtarget) {
9777 switch (VT.getSimpleVT().SimpleTy) {
9778 default: return false;
9783 // + imm12 or - imm8
9785 return V == (V & ((1LL << 8) - 1));
9786 return V == (V & ((1LL << 12) - 1));
9789 // Same as ARM mode. FIXME: NEON?
9790 if (!Subtarget->hasVFP2())
9795 return V == (V & ((1LL << 8) - 1));
9799 /// isLegalAddressImmediate - Return true if the integer value can be used
9800 /// as the offset of the target addressing mode for load / store of the
9802 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9803 const ARMSubtarget *Subtarget) {
9810 if (Subtarget->isThumb1Only())
9811 return isLegalT1AddressImmediate(V, VT);
9812 else if (Subtarget->isThumb2())
9813 return isLegalT2AddressImmediate(V, VT, Subtarget);
9818 switch (VT.getSimpleVT().SimpleTy) {
9819 default: return false;
9824 return V == (V & ((1LL << 12) - 1));
9827 return V == (V & ((1LL << 8) - 1));
9830 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9835 return V == (V & ((1LL << 8) - 1));
9839 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9841 int Scale = AM.Scale;
9845 switch (VT.getSimpleVT().SimpleTy) {
9846 default: return false;
9855 return Scale == 2 || Scale == 4 || Scale == 8;
9858 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9862 // Note, we allow "void" uses (basically, uses that aren't loads or
9863 // stores), because arm allows folding a scale into many arithmetic
9864 // operations. This should be made more precise and revisited later.
9866 // Allow r << imm, but the imm has to be a multiple of two.
9867 if (Scale & 1) return false;
9868 return isPowerOf2_32(Scale);
9872 /// isLegalAddressingMode - Return true if the addressing mode represented
9873 /// by AM is legal for this target, for a load/store of the specified type.
9874 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9876 EVT VT = getValueType(Ty, true);
9877 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9880 // Can never fold addr of global into load/store.
9885 case 0: // no scale reg, must be "r+i" or "r", or "i".
9888 if (Subtarget->isThumb1Only())
9892 // ARM doesn't support any R+R*scale+imm addr modes.
9899 if (Subtarget->isThumb2())
9900 return isLegalT2ScaledAddressingMode(AM, VT);
9902 int Scale = AM.Scale;
9903 switch (VT.getSimpleVT().SimpleTy) {
9904 default: return false;
9908 if (Scale < 0) Scale = -Scale;
9912 return isPowerOf2_32(Scale & ~1);
9916 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9921 // Note, we allow "void" uses (basically, uses that aren't loads or
9922 // stores), because arm allows folding a scale into many arithmetic
9923 // operations. This should be made more precise and revisited later.
9925 // Allow r << imm, but the imm has to be a multiple of two.
9926 if (Scale & 1) return false;
9927 return isPowerOf2_32(Scale);
9933 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9934 /// icmp immediate, that is the target has icmp instructions which can compare
9935 /// a register against the immediate without having to materialize the
9936 /// immediate into a register.
9937 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9938 // Thumb2 and ARM modes can use cmn for negative immediates.
9939 if (!Subtarget->isThumb())
9940 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9941 if (Subtarget->isThumb2())
9942 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9943 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9944 return Imm >= 0 && Imm <= 255;
9947 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9948 /// *or sub* immediate, that is the target has add or sub instructions which can
9949 /// add a register with the immediate without having to materialize the
9950 /// immediate into a register.
9951 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9952 // Same encoding for add/sub, just flip the sign.
9953 int64_t AbsImm = llvm::abs64(Imm);
9954 if (!Subtarget->isThumb())
9955 return ARM_AM::getSOImmVal(AbsImm) != -1;
9956 if (Subtarget->isThumb2())
9957 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9958 // Thumb1 only has 8-bit unsigned immediate.
9959 return AbsImm >= 0 && AbsImm <= 255;
9962 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9963 bool isSEXTLoad, SDValue &Base,
9964 SDValue &Offset, bool &isInc,
9965 SelectionDAG &DAG) {
9966 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9969 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9971 Base = Ptr->getOperand(0);
9972 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9973 int RHSC = (int)RHS->getZExtValue();
9974 if (RHSC < 0 && RHSC > -256) {
9975 assert(Ptr->getOpcode() == ISD::ADD);
9977 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9981 isInc = (Ptr->getOpcode() == ISD::ADD);
9982 Offset = Ptr->getOperand(1);
9984 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9986 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9987 int RHSC = (int)RHS->getZExtValue();
9988 if (RHSC < 0 && RHSC > -0x1000) {
9989 assert(Ptr->getOpcode() == ISD::ADD);
9991 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9992 Base = Ptr->getOperand(0);
9997 if (Ptr->getOpcode() == ISD::ADD) {
9999 ARM_AM::ShiftOpc ShOpcVal=
10000 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10001 if (ShOpcVal != ARM_AM::no_shift) {
10002 Base = Ptr->getOperand(1);
10003 Offset = Ptr->getOperand(0);
10005 Base = Ptr->getOperand(0);
10006 Offset = Ptr->getOperand(1);
10011 isInc = (Ptr->getOpcode() == ISD::ADD);
10012 Base = Ptr->getOperand(0);
10013 Offset = Ptr->getOperand(1);
10017 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10021 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10022 bool isSEXTLoad, SDValue &Base,
10023 SDValue &Offset, bool &isInc,
10024 SelectionDAG &DAG) {
10025 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10028 Base = Ptr->getOperand(0);
10029 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10030 int RHSC = (int)RHS->getZExtValue();
10031 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10032 assert(Ptr->getOpcode() == ISD::ADD);
10034 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10036 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10037 isInc = Ptr->getOpcode() == ISD::ADD;
10038 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10046 /// getPreIndexedAddressParts - returns true by value, base pointer and
10047 /// offset pointer and addressing mode by reference if the node's address
10048 /// can be legally represented as pre-indexed load / store address.
10050 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10052 ISD::MemIndexedMode &AM,
10053 SelectionDAG &DAG) const {
10054 if (Subtarget->isThumb1Only())
10059 bool isSEXTLoad = false;
10060 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10061 Ptr = LD->getBasePtr();
10062 VT = LD->getMemoryVT();
10063 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10064 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10065 Ptr = ST->getBasePtr();
10066 VT = ST->getMemoryVT();
10071 bool isLegal = false;
10072 if (Subtarget->isThumb2())
10073 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10074 Offset, isInc, DAG);
10076 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10077 Offset, isInc, DAG);
10081 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10085 /// getPostIndexedAddressParts - returns true by value, base pointer and
10086 /// offset pointer and addressing mode by reference if this node can be
10087 /// combined with a load / store to form a post-indexed load / store.
10088 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10091 ISD::MemIndexedMode &AM,
10092 SelectionDAG &DAG) const {
10093 if (Subtarget->isThumb1Only())
10098 bool isSEXTLoad = false;
10099 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10100 VT = LD->getMemoryVT();
10101 Ptr = LD->getBasePtr();
10102 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10103 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10104 VT = ST->getMemoryVT();
10105 Ptr = ST->getBasePtr();
10110 bool isLegal = false;
10111 if (Subtarget->isThumb2())
10112 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10115 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10121 // Swap base ptr and offset to catch more post-index load / store when
10122 // it's legal. In Thumb2 mode, offset must be an immediate.
10123 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10124 !Subtarget->isThumb2())
10125 std::swap(Base, Offset);
10127 // Post-indexed load / store update the base pointer.
10132 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10136 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10139 const SelectionDAG &DAG,
10140 unsigned Depth) const {
10141 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
10142 switch (Op.getOpcode()) {
10144 case ARMISD::CMOV: {
10145 // Bits are known zero/one if known on the LHS and RHS.
10146 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10147 if (KnownZero == 0 && KnownOne == 0) return;
10149 APInt KnownZeroRHS, KnownOneRHS;
10150 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10151 KnownZero &= KnownZeroRHS;
10152 KnownOne &= KnownOneRHS;
10158 //===----------------------------------------------------------------------===//
10159 // ARM Inline Assembly Support
10160 //===----------------------------------------------------------------------===//
10162 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10163 // Looking for "rev" which is V6+.
10164 if (!Subtarget->hasV6Ops())
10167 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10168 std::string AsmStr = IA->getAsmString();
10169 SmallVector<StringRef, 4> AsmPieces;
10170 SplitString(AsmStr, AsmPieces, ";\n");
10172 switch (AsmPieces.size()) {
10173 default: return false;
10175 AsmStr = AsmPieces[0];
10177 SplitString(AsmStr, AsmPieces, " \t,");
10180 if (AsmPieces.size() == 3 &&
10181 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10182 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10183 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10184 if (Ty && Ty->getBitWidth() == 32)
10185 return IntrinsicLowering::LowerToByteSwap(CI);
10193 /// getConstraintType - Given a constraint letter, return the type of
10194 /// constraint it is for this target.
10195 ARMTargetLowering::ConstraintType
10196 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10197 if (Constraint.size() == 1) {
10198 switch (Constraint[0]) {
10200 case 'l': return C_RegisterClass;
10201 case 'w': return C_RegisterClass;
10202 case 'h': return C_RegisterClass;
10203 case 'x': return C_RegisterClass;
10204 case 't': return C_RegisterClass;
10205 case 'j': return C_Other; // Constant for movw.
10206 // An address with a single base register. Due to the way we
10207 // currently handle addresses it is the same as an 'r' memory constraint.
10208 case 'Q': return C_Memory;
10210 } else if (Constraint.size() == 2) {
10211 switch (Constraint[0]) {
10213 // All 'U+' constraints are addresses.
10214 case 'U': return C_Memory;
10217 return TargetLowering::getConstraintType(Constraint);
10220 /// Examine constraint type and operand type and determine a weight value.
10221 /// This object must already have been set up with the operand type
10222 /// and the current alternative constraint selected.
10223 TargetLowering::ConstraintWeight
10224 ARMTargetLowering::getSingleConstraintMatchWeight(
10225 AsmOperandInfo &info, const char *constraint) const {
10226 ConstraintWeight weight = CW_Invalid;
10227 Value *CallOperandVal = info.CallOperandVal;
10228 // If we don't have a value, we can't do a match,
10229 // but allow it at the lowest weight.
10230 if (CallOperandVal == NULL)
10232 Type *type = CallOperandVal->getType();
10233 // Look at the constraint type.
10234 switch (*constraint) {
10236 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10239 if (type->isIntegerTy()) {
10240 if (Subtarget->isThumb())
10241 weight = CW_SpecificReg;
10243 weight = CW_Register;
10247 if (type->isFloatingPointTy())
10248 weight = CW_Register;
10254 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10256 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10258 if (Constraint.size() == 1) {
10259 // GCC ARM Constraint Letters
10260 switch (Constraint[0]) {
10261 case 'l': // Low regs or general regs.
10262 if (Subtarget->isThumb())
10263 return RCPair(0U, &ARM::tGPRRegClass);
10264 return RCPair(0U, &ARM::GPRRegClass);
10265 case 'h': // High regs or no regs.
10266 if (Subtarget->isThumb())
10267 return RCPair(0U, &ARM::hGPRRegClass);
10270 return RCPair(0U, &ARM::GPRRegClass);
10272 if (VT == MVT::f32)
10273 return RCPair(0U, &ARM::SPRRegClass);
10274 if (VT.getSizeInBits() == 64)
10275 return RCPair(0U, &ARM::DPRRegClass);
10276 if (VT.getSizeInBits() == 128)
10277 return RCPair(0U, &ARM::QPRRegClass);
10280 if (VT == MVT::f32)
10281 return RCPair(0U, &ARM::SPR_8RegClass);
10282 if (VT.getSizeInBits() == 64)
10283 return RCPair(0U, &ARM::DPR_8RegClass);
10284 if (VT.getSizeInBits() == 128)
10285 return RCPair(0U, &ARM::QPR_8RegClass);
10288 if (VT == MVT::f32)
10289 return RCPair(0U, &ARM::SPRRegClass);
10293 if (StringRef("{cc}").equals_lower(Constraint))
10294 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10296 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10299 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10300 /// vector. If it is invalid, don't add anything to Ops.
10301 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10302 std::string &Constraint,
10303 std::vector<SDValue>&Ops,
10304 SelectionDAG &DAG) const {
10305 SDValue Result(0, 0);
10307 // Currently only support length 1 constraints.
10308 if (Constraint.length() != 1) return;
10310 char ConstraintLetter = Constraint[0];
10311 switch (ConstraintLetter) {
10314 case 'I': case 'J': case 'K': case 'L':
10315 case 'M': case 'N': case 'O':
10316 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10320 int64_t CVal64 = C->getSExtValue();
10321 int CVal = (int) CVal64;
10322 // None of these constraints allow values larger than 32 bits. Check
10323 // that the value fits in an int.
10324 if (CVal != CVal64)
10327 switch (ConstraintLetter) {
10329 // Constant suitable for movw, must be between 0 and
10331 if (Subtarget->hasV6T2Ops())
10332 if (CVal >= 0 && CVal <= 65535)
10336 if (Subtarget->isThumb1Only()) {
10337 // This must be a constant between 0 and 255, for ADD
10339 if (CVal >= 0 && CVal <= 255)
10341 } else if (Subtarget->isThumb2()) {
10342 // A constant that can be used as an immediate value in a
10343 // data-processing instruction.
10344 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10347 // A constant that can be used as an immediate value in a
10348 // data-processing instruction.
10349 if (ARM_AM::getSOImmVal(CVal) != -1)
10355 if (Subtarget->isThumb()) { // FIXME thumb2
10356 // This must be a constant between -255 and -1, for negated ADD
10357 // immediates. This can be used in GCC with an "n" modifier that
10358 // prints the negated value, for use with SUB instructions. It is
10359 // not useful otherwise but is implemented for compatibility.
10360 if (CVal >= -255 && CVal <= -1)
10363 // This must be a constant between -4095 and 4095. It is not clear
10364 // what this constraint is intended for. Implemented for
10365 // compatibility with GCC.
10366 if (CVal >= -4095 && CVal <= 4095)
10372 if (Subtarget->isThumb1Only()) {
10373 // A 32-bit value where only one byte has a nonzero value. Exclude
10374 // zero to match GCC. This constraint is used by GCC internally for
10375 // constants that can be loaded with a move/shift combination.
10376 // It is not useful otherwise but is implemented for compatibility.
10377 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10379 } else if (Subtarget->isThumb2()) {
10380 // A constant whose bitwise inverse can be used as an immediate
10381 // value in a data-processing instruction. This can be used in GCC
10382 // with a "B" modifier that prints the inverted value, for use with
10383 // BIC and MVN instructions. It is not useful otherwise but is
10384 // implemented for compatibility.
10385 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10388 // A constant whose bitwise inverse can be used as an immediate
10389 // value in a data-processing instruction. This can be used in GCC
10390 // with a "B" modifier that prints the inverted value, for use with
10391 // BIC and MVN instructions. It is not useful otherwise but is
10392 // implemented for compatibility.
10393 if (ARM_AM::getSOImmVal(~CVal) != -1)
10399 if (Subtarget->isThumb1Only()) {
10400 // This must be a constant between -7 and 7,
10401 // for 3-operand ADD/SUB immediate instructions.
10402 if (CVal >= -7 && CVal < 7)
10404 } else if (Subtarget->isThumb2()) {
10405 // A constant whose negation can be used as an immediate value in a
10406 // data-processing instruction. This can be used in GCC with an "n"
10407 // modifier that prints the negated value, for use with SUB
10408 // instructions. It is not useful otherwise but is implemented for
10410 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10413 // A constant whose negation can be used as an immediate value in a
10414 // data-processing instruction. This can be used in GCC with an "n"
10415 // modifier that prints the negated value, for use with SUB
10416 // instructions. It is not useful otherwise but is implemented for
10418 if (ARM_AM::getSOImmVal(-CVal) != -1)
10424 if (Subtarget->isThumb()) { // FIXME thumb2
10425 // This must be a multiple of 4 between 0 and 1020, for
10426 // ADD sp + immediate.
10427 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10430 // A power of two or a constant between 0 and 32. This is used in
10431 // GCC for the shift amount on shifted register operands, but it is
10432 // useful in general for any shift amounts.
10433 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10439 if (Subtarget->isThumb()) { // FIXME thumb2
10440 // This must be a constant between 0 and 31, for shift amounts.
10441 if (CVal >= 0 && CVal <= 31)
10447 if (Subtarget->isThumb()) { // FIXME thumb2
10448 // This must be a multiple of 4 between -508 and 508, for
10449 // ADD/SUB sp = sp + immediate.
10450 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10455 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10459 if (Result.getNode()) {
10460 Ops.push_back(Result);
10463 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10467 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10468 // The ARM target isn't yet aware of offsets.
10472 bool ARM::isBitFieldInvertedMask(unsigned v) {
10473 if (v == 0xffffffff)
10476 // there can be 1's on either or both "outsides", all the "inside"
10477 // bits must be 0's
10478 unsigned TO = CountTrailingOnes_32(v);
10479 unsigned LO = CountLeadingOnes_32(v);
10480 v = (v >> TO) << TO;
10481 v = (v << LO) >> LO;
10485 /// isFPImmLegal - Returns true if the target can instruction select the
10486 /// specified FP immediate natively. If false, the legalizer will
10487 /// materialize the FP immediate as a load from a constant pool.
10488 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10489 if (!Subtarget->hasVFP3())
10491 if (VT == MVT::f32)
10492 return ARM_AM::getFP32Imm(Imm) != -1;
10493 if (VT == MVT::f64)
10494 return ARM_AM::getFP64Imm(Imm) != -1;
10498 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10499 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10500 /// specified in the intrinsic calls.
10501 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10503 unsigned Intrinsic) const {
10504 switch (Intrinsic) {
10505 case Intrinsic::arm_neon_vld1:
10506 case Intrinsic::arm_neon_vld2:
10507 case Intrinsic::arm_neon_vld3:
10508 case Intrinsic::arm_neon_vld4:
10509 case Intrinsic::arm_neon_vld2lane:
10510 case Intrinsic::arm_neon_vld3lane:
10511 case Intrinsic::arm_neon_vld4lane: {
10512 Info.opc = ISD::INTRINSIC_W_CHAIN;
10513 // Conservatively set memVT to the entire set of vectors loaded.
10514 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10515 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10516 Info.ptrVal = I.getArgOperand(0);
10518 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10519 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10520 Info.vol = false; // volatile loads with NEON intrinsics not supported
10521 Info.readMem = true;
10522 Info.writeMem = false;
10525 case Intrinsic::arm_neon_vst1:
10526 case Intrinsic::arm_neon_vst2:
10527 case Intrinsic::arm_neon_vst3:
10528 case Intrinsic::arm_neon_vst4:
10529 case Intrinsic::arm_neon_vst2lane:
10530 case Intrinsic::arm_neon_vst3lane:
10531 case Intrinsic::arm_neon_vst4lane: {
10532 Info.opc = ISD::INTRINSIC_VOID;
10533 // Conservatively set memVT to the entire set of vectors stored.
10534 unsigned NumElts = 0;
10535 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10536 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10537 if (!ArgTy->isVectorTy())
10539 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10541 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10542 Info.ptrVal = I.getArgOperand(0);
10544 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10545 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10546 Info.vol = false; // volatile stores with NEON intrinsics not supported
10547 Info.readMem = false;
10548 Info.writeMem = true;
10551 case Intrinsic::arm_strexd: {
10552 Info.opc = ISD::INTRINSIC_W_CHAIN;
10553 Info.memVT = MVT::i64;
10554 Info.ptrVal = I.getArgOperand(2);
10558 Info.readMem = false;
10559 Info.writeMem = true;
10562 case Intrinsic::arm_ldrexd: {
10563 Info.opc = ISD::INTRINSIC_W_CHAIN;
10564 Info.memVT = MVT::i64;
10565 Info.ptrVal = I.getArgOperand(0);
10569 Info.readMem = true;
10570 Info.writeMem = false;