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(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 : 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 Chain = 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,
2633 unsigned &ArgRegsSize,
2634 unsigned &ArgRegsSaveSize)
2637 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2638 unsigned RBegin, REnd;
2639 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2640 NumGPRs = REnd - RBegin;
2642 unsigned int firstUnalloced;
2643 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2644 sizeof(GPRArgRegs) /
2645 sizeof(GPRArgRegs[0]));
2646 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2649 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2650 ArgRegsSize = NumGPRs * 4;
2651 ArgRegsSaveSize = (ArgRegsSize + Align - 1) & ~(Align - 1);
2654 // The remaining GPRs hold either the beginning of variable-argument
2655 // data, or the beginning of an aggregate passed by value (usually
2656 // byval). Either way, we allocate stack slots adjacent to the data
2657 // provided by our caller, and store the unallocated registers there.
2658 // If this is a variadic function, the va_list pointer will begin with
2659 // these values; otherwise, this reassembles a (byval) structure that
2660 // was split between registers and memory.
2661 // Return: The frame index registers were stored into.
2663 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2664 DebugLoc dl, SDValue &Chain,
2665 const Value *OrigArg,
2666 unsigned InRegsParamRecordIdx,
2667 unsigned OffsetFromOrigArg,
2669 bool ForceMutable) const {
2671 // Currently, two use-cases possible:
2672 // Case #1. Non var-args function, and we meet first byval parameter.
2673 // Setup first unallocated register as first byval register;
2674 // eat all remained registers
2675 // (these two actions are performed by HandleByVal method).
2676 // Then, here, we initialize stack frame with
2677 // "store-reg" instructions.
2678 // Case #2. Var-args function, that doesn't contain byval parameters.
2679 // The same: eat all remained unallocated registers,
2680 // initialize stack frame.
2682 MachineFunction &MF = DAG.getMachineFunction();
2683 MachineFrameInfo *MFI = MF.getFrameInfo();
2684 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2685 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2686 unsigned RBegin, REnd;
2687 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2688 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2689 firstRegToSaveIndex = RBegin - ARM::R0;
2690 lastRegToSaveIndex = REnd - ARM::R0;
2692 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2693 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2694 lastRegToSaveIndex = 4;
2697 unsigned ArgRegsSize, ArgRegsSaveSize;
2698 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgRegsSize, ArgRegsSaveSize);
2700 // Store any by-val regs to their spots on the stack so that they may be
2701 // loaded by deferencing the result of formal parameter pointer or va_next.
2702 // Note: once stack area for byval/varargs registers
2703 // was initialized, it can't be initialized again.
2704 if (ArgRegsSaveSize) {
2706 int FrameIndex = MFI->CreateFixedObject(
2708 ArgOffset + ArgRegsSaveSize - ArgRegsSize,
2710 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2712 SmallVector<SDValue, 4> MemOps;
2713 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2714 ++firstRegToSaveIndex, ++i) {
2715 const TargetRegisterClass *RC;
2716 if (AFI->isThumb1OnlyFunction())
2717 RC = &ARM::tGPRRegClass;
2719 RC = &ARM::GPRRegClass;
2721 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2722 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2724 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2725 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2727 MemOps.push_back(Store);
2728 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2729 DAG.getConstant(4, getPointerTy()));
2732 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2734 if (!MemOps.empty())
2735 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2736 &MemOps[0], MemOps.size());
2739 // This will point to the next argument passed via stack.
2740 return MFI->CreateFixedObject(4, ArgOffset, !ForceMutable);
2743 // Setup stack frame, the va_list pointer will start from.
2745 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2746 DebugLoc dl, SDValue &Chain,
2748 bool ForceMutable) const {
2749 MachineFunction &MF = DAG.getMachineFunction();
2750 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2752 // Try to store any remaining integer argument regs
2753 // to their spots on the stack so that they may be loaded by deferencing
2754 // the result of va_next.
2755 // If there is no regs to be stored, just point address after last
2756 // argument passed via stack.
2758 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2759 0, ArgOffset, ForceMutable);
2761 AFI->setVarArgsFrameIndex(FrameIndex);
2765 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2766 CallingConv::ID CallConv, bool isVarArg,
2767 const SmallVectorImpl<ISD::InputArg>
2769 DebugLoc dl, SelectionDAG &DAG,
2770 SmallVectorImpl<SDValue> &InVals)
2772 MachineFunction &MF = DAG.getMachineFunction();
2773 MachineFrameInfo *MFI = MF.getFrameInfo();
2775 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2777 // Assign locations to all of the incoming arguments.
2778 SmallVector<CCValAssign, 16> ArgLocs;
2779 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2780 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2781 CCInfo.AnalyzeFormalArguments(Ins,
2782 CCAssignFnForNode(CallConv, /* Return*/ false,
2785 SmallVector<SDValue, 16> ArgValues;
2786 int lastInsIndex = -1;
2788 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2789 unsigned CurArgIdx = 0;
2791 // Initially ArgRegsSaveSize is zero.
2792 // Then we increase this value each time we meet byval parameter.
2793 // We also increase this value in case of varargs function.
2794 AFI->setArgRegsSaveSize(0);
2796 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2797 CCValAssign &VA = ArgLocs[i];
2798 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2799 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2800 // Arguments stored in registers.
2801 if (VA.isRegLoc()) {
2802 EVT RegVT = VA.getLocVT();
2804 if (VA.needsCustom()) {
2805 // f64 and vector types are split up into multiple registers or
2806 // combinations of registers and stack slots.
2807 if (VA.getLocVT() == MVT::v2f64) {
2808 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2810 VA = ArgLocs[++i]; // skip ahead to next loc
2812 if (VA.isMemLoc()) {
2813 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2814 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2815 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2816 MachinePointerInfo::getFixedStack(FI),
2817 false, false, false, 0);
2819 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2822 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2823 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2824 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2825 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2826 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2828 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2831 const TargetRegisterClass *RC;
2833 if (RegVT == MVT::f32)
2834 RC = &ARM::SPRRegClass;
2835 else if (RegVT == MVT::f64)
2836 RC = &ARM::DPRRegClass;
2837 else if (RegVT == MVT::v2f64)
2838 RC = &ARM::QPRRegClass;
2839 else if (RegVT == MVT::i32)
2840 RC = AFI->isThumb1OnlyFunction() ?
2841 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2842 (const TargetRegisterClass*)&ARM::GPRRegClass;
2844 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2846 // Transform the arguments in physical registers into virtual ones.
2847 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2848 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2851 // If this is an 8 or 16-bit value, it is really passed promoted
2852 // to 32 bits. Insert an assert[sz]ext to capture this, then
2853 // truncate to the right size.
2854 switch (VA.getLocInfo()) {
2855 default: llvm_unreachable("Unknown loc info!");
2856 case CCValAssign::Full: break;
2857 case CCValAssign::BCvt:
2858 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2860 case CCValAssign::SExt:
2861 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2862 DAG.getValueType(VA.getValVT()));
2863 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2865 case CCValAssign::ZExt:
2866 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2867 DAG.getValueType(VA.getValVT()));
2868 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2872 InVals.push_back(ArgValue);
2874 } else { // VA.isRegLoc()
2877 assert(VA.isMemLoc());
2878 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2880 int index = ArgLocs[i].getValNo();
2882 // Some Ins[] entries become multiple ArgLoc[] entries.
2883 // Process them only once.
2884 if (index != lastInsIndex)
2886 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2887 // FIXME: For now, all byval parameter objects are marked mutable.
2888 // This can be changed with more analysis.
2889 // In case of tail call optimization mark all arguments mutable.
2890 // Since they could be overwritten by lowering of arguments in case of
2892 if (Flags.isByVal()) {
2893 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2894 int FrameIndex = StoreByValRegs(
2895 CCInfo, DAG, dl, Chain, CurOrigArg,
2897 Ins[VA.getValNo()].PartOffset,
2898 VA.getLocMemOffset(),
2899 true /*force mutable frames*/);
2900 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2901 CCInfo.nextInRegsParam();
2903 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2904 VA.getLocMemOffset(), true);
2906 // Create load nodes to retrieve arguments from the stack.
2907 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2908 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2909 MachinePointerInfo::getFixedStack(FI),
2910 false, false, false, 0));
2912 lastInsIndex = index;
2919 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2920 CCInfo.getNextStackOffset());
2925 /// isFloatingPointZero - Return true if this is +0.0.
2926 static bool isFloatingPointZero(SDValue Op) {
2927 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2928 return CFP->getValueAPF().isPosZero();
2929 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2930 // Maybe this has already been legalized into the constant pool?
2931 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2932 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2933 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2934 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2935 return CFP->getValueAPF().isPosZero();
2941 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2942 /// the given operands.
2944 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2945 SDValue &ARMcc, SelectionDAG &DAG,
2946 DebugLoc dl) const {
2947 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2948 unsigned C = RHSC->getZExtValue();
2949 if (!isLegalICmpImmediate(C)) {
2950 // Constant does not fit, try adjusting it by one?
2955 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2956 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2957 RHS = DAG.getConstant(C-1, MVT::i32);
2962 if (C != 0 && isLegalICmpImmediate(C-1)) {
2963 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2964 RHS = DAG.getConstant(C-1, MVT::i32);
2969 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2970 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2971 RHS = DAG.getConstant(C+1, MVT::i32);
2976 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2977 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2978 RHS = DAG.getConstant(C+1, MVT::i32);
2985 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2986 ARMISD::NodeType CompareType;
2989 CompareType = ARMISD::CMP;
2994 CompareType = ARMISD::CMPZ;
2997 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2998 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3001 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3003 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3004 DebugLoc dl) const {
3006 if (!isFloatingPointZero(RHS))
3007 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3009 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3010 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3013 /// duplicateCmp - Glue values can have only one use, so this function
3014 /// duplicates a comparison node.
3016 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3017 unsigned Opc = Cmp.getOpcode();
3018 DebugLoc DL = Cmp.getDebugLoc();
3019 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3020 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3022 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3023 Cmp = Cmp.getOperand(0);
3024 Opc = Cmp.getOpcode();
3025 if (Opc == ARMISD::CMPFP)
3026 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3028 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3029 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3031 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3034 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3035 SDValue Cond = Op.getOperand(0);
3036 SDValue SelectTrue = Op.getOperand(1);
3037 SDValue SelectFalse = Op.getOperand(2);
3038 DebugLoc dl = Op.getDebugLoc();
3042 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3043 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3045 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3046 const ConstantSDNode *CMOVTrue =
3047 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3048 const ConstantSDNode *CMOVFalse =
3049 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3051 if (CMOVTrue && CMOVFalse) {
3052 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3053 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3057 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3059 False = SelectFalse;
3060 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3065 if (True.getNode() && False.getNode()) {
3066 EVT VT = Op.getValueType();
3067 SDValue ARMcc = Cond.getOperand(2);
3068 SDValue CCR = Cond.getOperand(3);
3069 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3070 assert(True.getValueType() == VT);
3071 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3076 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3077 // undefined bits before doing a full-word comparison with zero.
3078 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3079 DAG.getConstant(1, Cond.getValueType()));
3081 return DAG.getSelectCC(dl, Cond,
3082 DAG.getConstant(0, Cond.getValueType()),
3083 SelectTrue, SelectFalse, ISD::SETNE);
3086 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3087 EVT VT = Op.getValueType();
3088 SDValue LHS = Op.getOperand(0);
3089 SDValue RHS = Op.getOperand(1);
3090 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3091 SDValue TrueVal = Op.getOperand(2);
3092 SDValue FalseVal = Op.getOperand(3);
3093 DebugLoc dl = Op.getDebugLoc();
3095 if (LHS.getValueType() == MVT::i32) {
3097 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3098 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3099 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3102 ARMCC::CondCodes CondCode, CondCode2;
3103 FPCCToARMCC(CC, CondCode, CondCode2);
3105 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3106 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3107 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3108 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3110 if (CondCode2 != ARMCC::AL) {
3111 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3112 // FIXME: Needs another CMP because flag can have but one use.
3113 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3114 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3115 Result, TrueVal, ARMcc2, CCR, Cmp2);
3120 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3121 /// to morph to an integer compare sequence.
3122 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3123 const ARMSubtarget *Subtarget) {
3124 SDNode *N = Op.getNode();
3125 if (!N->hasOneUse())
3126 // Otherwise it requires moving the value from fp to integer registers.
3128 if (!N->getNumValues())
3130 EVT VT = Op.getValueType();
3131 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3132 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3133 // vmrs are very slow, e.g. cortex-a8.
3136 if (isFloatingPointZero(Op)) {
3140 return ISD::isNormalLoad(N);
3143 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3144 if (isFloatingPointZero(Op))
3145 return DAG.getConstant(0, MVT::i32);
3147 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3148 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3149 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3150 Ld->isVolatile(), Ld->isNonTemporal(),
3151 Ld->isInvariant(), Ld->getAlignment());
3153 llvm_unreachable("Unknown VFP cmp argument!");
3156 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3157 SDValue &RetVal1, SDValue &RetVal2) {
3158 if (isFloatingPointZero(Op)) {
3159 RetVal1 = DAG.getConstant(0, MVT::i32);
3160 RetVal2 = DAG.getConstant(0, MVT::i32);
3164 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3165 SDValue Ptr = Ld->getBasePtr();
3166 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3167 Ld->getChain(), Ptr,
3168 Ld->getPointerInfo(),
3169 Ld->isVolatile(), Ld->isNonTemporal(),
3170 Ld->isInvariant(), Ld->getAlignment());
3172 EVT PtrType = Ptr.getValueType();
3173 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3174 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3175 PtrType, Ptr, DAG.getConstant(4, PtrType));
3176 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3177 Ld->getChain(), NewPtr,
3178 Ld->getPointerInfo().getWithOffset(4),
3179 Ld->isVolatile(), Ld->isNonTemporal(),
3180 Ld->isInvariant(), NewAlign);
3184 llvm_unreachable("Unknown VFP cmp argument!");
3187 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3188 /// f32 and even f64 comparisons to integer ones.
3190 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3191 SDValue Chain = Op.getOperand(0);
3192 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3193 SDValue LHS = Op.getOperand(2);
3194 SDValue RHS = Op.getOperand(3);
3195 SDValue Dest = Op.getOperand(4);
3196 DebugLoc dl = Op.getDebugLoc();
3198 bool LHSSeenZero = false;
3199 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3200 bool RHSSeenZero = false;
3201 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3202 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3203 // If unsafe fp math optimization is enabled and there are no other uses of
3204 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3205 // to an integer comparison.
3206 if (CC == ISD::SETOEQ)
3208 else if (CC == ISD::SETUNE)
3211 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3213 if (LHS.getValueType() == MVT::f32) {
3214 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3215 bitcastf32Toi32(LHS, DAG), Mask);
3216 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3217 bitcastf32Toi32(RHS, DAG), Mask);
3218 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3219 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3220 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3221 Chain, Dest, ARMcc, CCR, Cmp);
3226 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3227 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3228 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3229 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3230 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3231 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3232 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3233 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3234 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3240 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3241 SDValue Chain = Op.getOperand(0);
3242 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3243 SDValue LHS = Op.getOperand(2);
3244 SDValue RHS = Op.getOperand(3);
3245 SDValue Dest = Op.getOperand(4);
3246 DebugLoc dl = Op.getDebugLoc();
3248 if (LHS.getValueType() == MVT::i32) {
3250 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3251 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3252 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3253 Chain, Dest, ARMcc, CCR, Cmp);
3256 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3258 if (getTargetMachine().Options.UnsafeFPMath &&
3259 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3260 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3261 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3262 if (Result.getNode())
3266 ARMCC::CondCodes CondCode, CondCode2;
3267 FPCCToARMCC(CC, CondCode, CondCode2);
3269 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3270 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3271 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3272 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3273 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3274 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3275 if (CondCode2 != ARMCC::AL) {
3276 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3277 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3278 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3283 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3284 SDValue Chain = Op.getOperand(0);
3285 SDValue Table = Op.getOperand(1);
3286 SDValue Index = Op.getOperand(2);
3287 DebugLoc dl = Op.getDebugLoc();
3289 EVT PTy = getPointerTy();
3290 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3291 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3292 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3293 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3294 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3295 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3296 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3297 if (Subtarget->isThumb2()) {
3298 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3299 // which does another jump to the destination. This also makes it easier
3300 // to translate it to TBB / TBH later.
3301 // FIXME: This might not work if the function is extremely large.
3302 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3303 Addr, Op.getOperand(2), JTI, UId);
3305 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3306 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3307 MachinePointerInfo::getJumpTable(),
3308 false, false, false, 0);
3309 Chain = Addr.getValue(1);
3310 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3311 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3313 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3314 MachinePointerInfo::getJumpTable(),
3315 false, false, false, 0);
3316 Chain = Addr.getValue(1);
3317 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3321 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3322 EVT VT = Op.getValueType();
3323 DebugLoc dl = Op.getDebugLoc();
3325 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3326 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3328 return DAG.UnrollVectorOp(Op.getNode());
3331 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3332 "Invalid type for custom lowering!");
3333 if (VT != MVT::v4i16)
3334 return DAG.UnrollVectorOp(Op.getNode());
3336 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3337 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3340 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3341 EVT VT = Op.getValueType();
3343 return LowerVectorFP_TO_INT(Op, DAG);
3345 DebugLoc dl = Op.getDebugLoc();
3348 switch (Op.getOpcode()) {
3349 default: llvm_unreachable("Invalid opcode!");
3350 case ISD::FP_TO_SINT:
3351 Opc = ARMISD::FTOSI;
3353 case ISD::FP_TO_UINT:
3354 Opc = ARMISD::FTOUI;
3357 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3358 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3361 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3362 EVT VT = Op.getValueType();
3363 DebugLoc dl = Op.getDebugLoc();
3365 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3366 if (VT.getVectorElementType() == MVT::f32)
3368 return DAG.UnrollVectorOp(Op.getNode());
3371 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3372 "Invalid type for custom lowering!");
3373 if (VT != MVT::v4f32)
3374 return DAG.UnrollVectorOp(Op.getNode());
3378 switch (Op.getOpcode()) {
3379 default: llvm_unreachable("Invalid opcode!");
3380 case ISD::SINT_TO_FP:
3381 CastOpc = ISD::SIGN_EXTEND;
3382 Opc = ISD::SINT_TO_FP;
3384 case ISD::UINT_TO_FP:
3385 CastOpc = ISD::ZERO_EXTEND;
3386 Opc = ISD::UINT_TO_FP;
3390 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3391 return DAG.getNode(Opc, dl, VT, Op);
3394 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3395 EVT VT = Op.getValueType();
3397 return LowerVectorINT_TO_FP(Op, DAG);
3399 DebugLoc dl = Op.getDebugLoc();
3402 switch (Op.getOpcode()) {
3403 default: llvm_unreachable("Invalid opcode!");
3404 case ISD::SINT_TO_FP:
3405 Opc = ARMISD::SITOF;
3407 case ISD::UINT_TO_FP:
3408 Opc = ARMISD::UITOF;
3412 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3413 return DAG.getNode(Opc, dl, VT, Op);
3416 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3417 // Implement fcopysign with a fabs and a conditional fneg.
3418 SDValue Tmp0 = Op.getOperand(0);
3419 SDValue Tmp1 = Op.getOperand(1);
3420 DebugLoc dl = Op.getDebugLoc();
3421 EVT VT = Op.getValueType();
3422 EVT SrcVT = Tmp1.getValueType();
3423 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3424 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3425 bool UseNEON = !InGPR && Subtarget->hasNEON();
3428 // Use VBSL to copy the sign bit.
3429 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3430 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3431 DAG.getTargetConstant(EncodedVal, MVT::i32));
3432 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3434 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3435 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3436 DAG.getConstant(32, MVT::i32));
3437 else /*if (VT == MVT::f32)*/
3438 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3439 if (SrcVT == MVT::f32) {
3440 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3442 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3443 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3444 DAG.getConstant(32, MVT::i32));
3445 } else if (VT == MVT::f32)
3446 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3447 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3448 DAG.getConstant(32, MVT::i32));
3449 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3450 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3452 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3454 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3455 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3456 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3458 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3459 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3460 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3461 if (VT == MVT::f32) {
3462 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3463 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3464 DAG.getConstant(0, MVT::i32));
3466 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3472 // Bitcast operand 1 to i32.
3473 if (SrcVT == MVT::f64)
3474 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3475 &Tmp1, 1).getValue(1);
3476 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3478 // Or in the signbit with integer operations.
3479 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3480 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3481 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3482 if (VT == MVT::f32) {
3483 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3484 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3485 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3486 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3489 // f64: Or the high part with signbit and then combine two parts.
3490 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3492 SDValue Lo = Tmp0.getValue(0);
3493 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3494 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3495 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3498 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3499 MachineFunction &MF = DAG.getMachineFunction();
3500 MachineFrameInfo *MFI = MF.getFrameInfo();
3501 MFI->setReturnAddressIsTaken(true);
3503 EVT VT = Op.getValueType();
3504 DebugLoc dl = Op.getDebugLoc();
3505 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3507 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3508 SDValue Offset = DAG.getConstant(4, MVT::i32);
3509 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3510 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3511 MachinePointerInfo(), false, false, false, 0);
3514 // Return LR, which contains the return address. Mark it an implicit live-in.
3515 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3516 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3519 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3520 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3521 MFI->setFrameAddressIsTaken(true);
3523 EVT VT = Op.getValueType();
3524 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3525 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3526 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3527 ? ARM::R7 : ARM::R11;
3528 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3530 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3531 MachinePointerInfo(),
3532 false, false, false, 0);
3536 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3537 /// and size(DestVec) > 128-bits.
3538 /// This is achieved by doing the one extension from the SrcVec, splitting the
3539 /// result, extending these parts, and then concatenating these into the
3541 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3542 SDValue Op = N->getOperand(0);
3543 EVT SrcVT = Op.getValueType();
3544 EVT DestVT = N->getValueType(0);
3546 assert(DestVT.getSizeInBits() > 128 &&
3547 "Custom sext/zext expansion needs >128-bit vector.");
3548 // If this is a normal length extension, use the default expansion.
3549 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3550 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3553 DebugLoc dl = N->getDebugLoc();
3554 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3555 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3556 unsigned NumElts = SrcVT.getVectorNumElements();
3557 LLVMContext &Ctx = *DAG.getContext();
3558 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3560 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3562 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3564 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3567 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3568 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3569 DAG.getIntPtrConstant(0));
3570 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3571 DAG.getIntPtrConstant(NumElts/2));
3572 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3573 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3574 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3577 /// ExpandBITCAST - If the target supports VFP, this function is called to
3578 /// expand a bit convert where either the source or destination type is i64 to
3579 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3580 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3581 /// vectors), since the legalizer won't know what to do with that.
3582 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3583 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3584 DebugLoc dl = N->getDebugLoc();
3585 SDValue Op = N->getOperand(0);
3587 // This function is only supposed to be called for i64 types, either as the
3588 // source or destination of the bit convert.
3589 EVT SrcVT = Op.getValueType();
3590 EVT DstVT = N->getValueType(0);
3591 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3592 "ExpandBITCAST called for non-i64 type");
3594 // Turn i64->f64 into VMOVDRR.
3595 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3596 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3597 DAG.getConstant(0, MVT::i32));
3598 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3599 DAG.getConstant(1, MVT::i32));
3600 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3601 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3604 // Turn f64->i64 into VMOVRRD.
3605 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3606 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3607 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3608 // Merge the pieces into a single i64 value.
3609 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3615 /// getZeroVector - Returns a vector of specified type with all zero elements.
3616 /// Zero vectors are used to represent vector negation and in those cases
3617 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3618 /// not support i64 elements, so sometimes the zero vectors will need to be
3619 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3621 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3622 assert(VT.isVector() && "Expected a vector type");
3623 // The canonical modified immediate encoding of a zero vector is....0!
3624 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3625 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3626 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3627 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3630 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3631 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3632 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3633 SelectionDAG &DAG) const {
3634 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3635 EVT VT = Op.getValueType();
3636 unsigned VTBits = VT.getSizeInBits();
3637 DebugLoc dl = Op.getDebugLoc();
3638 SDValue ShOpLo = Op.getOperand(0);
3639 SDValue ShOpHi = Op.getOperand(1);
3640 SDValue ShAmt = Op.getOperand(2);
3642 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3644 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3646 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3647 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3648 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3649 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3650 DAG.getConstant(VTBits, MVT::i32));
3651 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3652 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3653 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3655 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3656 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3658 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3659 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3662 SDValue Ops[2] = { Lo, Hi };
3663 return DAG.getMergeValues(Ops, 2, dl);
3666 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3667 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3668 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3669 SelectionDAG &DAG) const {
3670 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3671 EVT VT = Op.getValueType();
3672 unsigned VTBits = VT.getSizeInBits();
3673 DebugLoc dl = Op.getDebugLoc();
3674 SDValue ShOpLo = Op.getOperand(0);
3675 SDValue ShOpHi = Op.getOperand(1);
3676 SDValue ShAmt = Op.getOperand(2);
3679 assert(Op.getOpcode() == ISD::SHL_PARTS);
3680 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3681 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3682 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3683 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3684 DAG.getConstant(VTBits, MVT::i32));
3685 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3686 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3688 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3689 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3690 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3692 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3693 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3696 SDValue Ops[2] = { Lo, Hi };
3697 return DAG.getMergeValues(Ops, 2, dl);
3700 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3701 SelectionDAG &DAG) const {
3702 // The rounding mode is in bits 23:22 of the FPSCR.
3703 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3704 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3705 // so that the shift + and get folded into a bitfield extract.
3706 DebugLoc dl = Op.getDebugLoc();
3707 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3708 DAG.getConstant(Intrinsic::arm_get_fpscr,
3710 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3711 DAG.getConstant(1U << 22, MVT::i32));
3712 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3713 DAG.getConstant(22, MVT::i32));
3714 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3715 DAG.getConstant(3, MVT::i32));
3718 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3719 const ARMSubtarget *ST) {
3720 EVT VT = N->getValueType(0);
3721 DebugLoc dl = N->getDebugLoc();
3723 if (!ST->hasV6T2Ops())
3726 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3727 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3730 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3731 /// for each 16-bit element from operand, repeated. The basic idea is to
3732 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3734 /// Trace for v4i16:
3735 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3736 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3737 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3738 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3739 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3740 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3741 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3742 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3743 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3744 EVT VT = N->getValueType(0);
3745 DebugLoc DL = N->getDebugLoc();
3747 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3748 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3749 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3750 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3751 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3752 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3755 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3756 /// bit-count for each 16-bit element from the operand. We need slightly
3757 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3758 /// 64/128-bit registers.
3760 /// Trace for v4i16:
3761 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3762 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3763 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3764 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3765 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3766 EVT VT = N->getValueType(0);
3767 DebugLoc DL = N->getDebugLoc();
3769 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3770 if (VT.is64BitVector()) {
3771 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3772 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3773 DAG.getIntPtrConstant(0));
3775 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3776 BitCounts, DAG.getIntPtrConstant(0));
3777 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3781 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3782 /// bit-count for each 32-bit element from the operand. The idea here is
3783 /// to split the vector into 16-bit elements, leverage the 16-bit count
3784 /// routine, and then combine the results.
3786 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3787 /// input = [v0 v1 ] (vi: 32-bit elements)
3788 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3789 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3790 /// vrev: N0 = [k1 k0 k3 k2 ]
3792 /// N1 =+[k1 k0 k3 k2 ]
3794 /// N2 =+[k1 k3 k0 k2 ]
3796 /// Extended =+[k1 k3 k0 k2 ]
3798 /// Extracted=+[k1 k3 ]
3800 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3801 EVT VT = N->getValueType(0);
3802 DebugLoc DL = N->getDebugLoc();
3804 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3806 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3807 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3808 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3809 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3810 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3812 if (VT.is64BitVector()) {
3813 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3814 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3815 DAG.getIntPtrConstant(0));
3817 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3818 DAG.getIntPtrConstant(0));
3819 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3823 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3824 const ARMSubtarget *ST) {
3825 EVT VT = N->getValueType(0);
3827 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3828 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3829 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3830 "Unexpected type for custom ctpop lowering");
3832 if (VT.getVectorElementType() == MVT::i32)
3833 return lowerCTPOP32BitElements(N, DAG);
3835 return lowerCTPOP16BitElements(N, DAG);
3838 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3839 const ARMSubtarget *ST) {
3840 EVT VT = N->getValueType(0);
3841 DebugLoc dl = N->getDebugLoc();
3846 // Lower vector shifts on NEON to use VSHL.
3847 assert(ST->hasNEON() && "unexpected vector shift");
3849 // Left shifts translate directly to the vshiftu intrinsic.
3850 if (N->getOpcode() == ISD::SHL)
3851 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3852 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3853 N->getOperand(0), N->getOperand(1));
3855 assert((N->getOpcode() == ISD::SRA ||
3856 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3858 // NEON uses the same intrinsics for both left and right shifts. For
3859 // right shifts, the shift amounts are negative, so negate the vector of
3861 EVT ShiftVT = N->getOperand(1).getValueType();
3862 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3863 getZeroVector(ShiftVT, DAG, dl),
3865 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3866 Intrinsic::arm_neon_vshifts :
3867 Intrinsic::arm_neon_vshiftu);
3868 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3869 DAG.getConstant(vshiftInt, MVT::i32),
3870 N->getOperand(0), NegatedCount);
3873 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3874 const ARMSubtarget *ST) {
3875 EVT VT = N->getValueType(0);
3876 DebugLoc dl = N->getDebugLoc();
3878 // We can get here for a node like i32 = ISD::SHL i32, i64
3882 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3883 "Unknown shift to lower!");
3885 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3886 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3887 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3890 // If we are in thumb mode, we don't have RRX.
3891 if (ST->isThumb1Only()) return SDValue();
3893 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3894 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3895 DAG.getConstant(0, MVT::i32));
3896 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3897 DAG.getConstant(1, MVT::i32));
3899 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3900 // captures the result into a carry flag.
3901 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3902 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3904 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3905 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3907 // Merge the pieces into a single i64 value.
3908 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3911 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3912 SDValue TmpOp0, TmpOp1;
3913 bool Invert = false;
3917 SDValue Op0 = Op.getOperand(0);
3918 SDValue Op1 = Op.getOperand(1);
3919 SDValue CC = Op.getOperand(2);
3920 EVT VT = Op.getValueType();
3921 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3922 DebugLoc dl = Op.getDebugLoc();
3924 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3925 switch (SetCCOpcode) {
3926 default: llvm_unreachable("Illegal FP comparison");
3928 case ISD::SETNE: Invert = true; // Fallthrough
3930 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3932 case ISD::SETLT: Swap = true; // Fallthrough
3934 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3936 case ISD::SETLE: Swap = true; // Fallthrough
3938 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3939 case ISD::SETUGE: Swap = true; // Fallthrough
3940 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3941 case ISD::SETUGT: Swap = true; // Fallthrough
3942 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3943 case ISD::SETUEQ: Invert = true; // Fallthrough
3945 // Expand this to (OLT | OGT).
3949 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3950 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3952 case ISD::SETUO: Invert = true; // Fallthrough
3954 // Expand this to (OLT | OGE).
3958 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3959 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3963 // Integer comparisons.
3964 switch (SetCCOpcode) {
3965 default: llvm_unreachable("Illegal integer comparison");
3966 case ISD::SETNE: Invert = true;
3967 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3968 case ISD::SETLT: Swap = true;
3969 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3970 case ISD::SETLE: Swap = true;
3971 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3972 case ISD::SETULT: Swap = true;
3973 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3974 case ISD::SETULE: Swap = true;
3975 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3978 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3979 if (Opc == ARMISD::VCEQ) {
3982 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3984 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3987 // Ignore bitconvert.
3988 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3989 AndOp = AndOp.getOperand(0);
3991 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3993 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3994 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4001 std::swap(Op0, Op1);
4003 // If one of the operands is a constant vector zero, attempt to fold the
4004 // comparison to a specialized compare-against-zero form.
4006 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4008 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4009 if (Opc == ARMISD::VCGE)
4010 Opc = ARMISD::VCLEZ;
4011 else if (Opc == ARMISD::VCGT)
4012 Opc = ARMISD::VCLTZ;
4017 if (SingleOp.getNode()) {
4020 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4022 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4024 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4026 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4028 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4030 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4033 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4037 Result = DAG.getNOT(dl, Result, VT);
4042 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4043 /// valid vector constant for a NEON instruction with a "modified immediate"
4044 /// operand (e.g., VMOV). If so, return the encoded value.
4045 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4046 unsigned SplatBitSize, SelectionDAG &DAG,
4047 EVT &VT, bool is128Bits, NEONModImmType type) {
4048 unsigned OpCmode, Imm;
4050 // SplatBitSize is set to the smallest size that splats the vector, so a
4051 // zero vector will always have SplatBitSize == 8. However, NEON modified
4052 // immediate instructions others than VMOV do not support the 8-bit encoding
4053 // of a zero vector, and the default encoding of zero is supposed to be the
4058 switch (SplatBitSize) {
4060 if (type != VMOVModImm)
4062 // Any 1-byte value is OK. Op=0, Cmode=1110.
4063 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4066 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4070 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4071 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4072 if ((SplatBits & ~0xff) == 0) {
4073 // Value = 0x00nn: Op=x, Cmode=100x.
4078 if ((SplatBits & ~0xff00) == 0) {
4079 // Value = 0xnn00: Op=x, Cmode=101x.
4081 Imm = SplatBits >> 8;
4087 // NEON's 32-bit VMOV supports splat values where:
4088 // * only one byte is nonzero, or
4089 // * the least significant byte is 0xff and the second byte is nonzero, or
4090 // * the least significant 2 bytes are 0xff and the third is nonzero.
4091 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4092 if ((SplatBits & ~0xff) == 0) {
4093 // Value = 0x000000nn: Op=x, Cmode=000x.
4098 if ((SplatBits & ~0xff00) == 0) {
4099 // Value = 0x0000nn00: Op=x, Cmode=001x.
4101 Imm = SplatBits >> 8;
4104 if ((SplatBits & ~0xff0000) == 0) {
4105 // Value = 0x00nn0000: Op=x, Cmode=010x.
4107 Imm = SplatBits >> 16;
4110 if ((SplatBits & ~0xff000000) == 0) {
4111 // Value = 0xnn000000: Op=x, Cmode=011x.
4113 Imm = SplatBits >> 24;
4117 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4118 if (type == OtherModImm) return SDValue();
4120 if ((SplatBits & ~0xffff) == 0 &&
4121 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4122 // Value = 0x0000nnff: Op=x, Cmode=1100.
4124 Imm = SplatBits >> 8;
4129 if ((SplatBits & ~0xffffff) == 0 &&
4130 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4131 // Value = 0x00nnffff: Op=x, Cmode=1101.
4133 Imm = SplatBits >> 16;
4134 SplatBits |= 0xffff;
4138 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4139 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4140 // VMOV.I32. A (very) minor optimization would be to replicate the value
4141 // and fall through here to test for a valid 64-bit splat. But, then the
4142 // caller would also need to check and handle the change in size.
4146 if (type != VMOVModImm)
4148 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4149 uint64_t BitMask = 0xff;
4151 unsigned ImmMask = 1;
4153 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4154 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4157 } else if ((SplatBits & BitMask) != 0) {
4163 // Op=1, Cmode=1110.
4166 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4171 llvm_unreachable("unexpected size for isNEONModifiedImm");
4174 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4175 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4178 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4179 const ARMSubtarget *ST) const {
4180 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4183 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4184 assert(Op.getValueType() == MVT::f32 &&
4185 "ConstantFP custom lowering should only occur for f32.");
4187 // Try splatting with a VMOV.f32...
4188 APFloat FPVal = CFP->getValueAPF();
4189 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4191 DebugLoc DL = Op.getDebugLoc();
4192 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4193 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4195 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4196 DAG.getConstant(0, MVT::i32));
4199 // If that fails, try a VMOV.i32
4201 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4202 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4204 if (NewVal != SDValue()) {
4205 DebugLoc DL = Op.getDebugLoc();
4206 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4208 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4210 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4211 DAG.getConstant(0, MVT::i32));
4214 // Finally, try a VMVN.i32
4215 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4217 if (NewVal != SDValue()) {
4218 DebugLoc DL = Op.getDebugLoc();
4219 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4220 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4222 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4223 DAG.getConstant(0, MVT::i32));
4229 // check if an VEXT instruction can handle the shuffle mask when the
4230 // vector sources of the shuffle are the same.
4231 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4232 unsigned NumElts = VT.getVectorNumElements();
4234 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4240 // If this is a VEXT shuffle, the immediate value is the index of the first
4241 // element. The other shuffle indices must be the successive elements after
4243 unsigned ExpectedElt = Imm;
4244 for (unsigned i = 1; i < NumElts; ++i) {
4245 // Increment the expected index. If it wraps around, just follow it
4246 // back to index zero and keep going.
4248 if (ExpectedElt == NumElts)
4251 if (M[i] < 0) continue; // ignore UNDEF indices
4252 if (ExpectedElt != static_cast<unsigned>(M[i]))
4260 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4261 bool &ReverseVEXT, unsigned &Imm) {
4262 unsigned NumElts = VT.getVectorNumElements();
4263 ReverseVEXT = false;
4265 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4271 // If this is a VEXT shuffle, the immediate value is the index of the first
4272 // element. The other shuffle indices must be the successive elements after
4274 unsigned ExpectedElt = Imm;
4275 for (unsigned i = 1; i < NumElts; ++i) {
4276 // Increment the expected index. If it wraps around, it may still be
4277 // a VEXT but the source vectors must be swapped.
4279 if (ExpectedElt == NumElts * 2) {
4284 if (M[i] < 0) continue; // ignore UNDEF indices
4285 if (ExpectedElt != static_cast<unsigned>(M[i]))
4289 // Adjust the index value if the source operands will be swapped.
4296 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4297 /// instruction with the specified blocksize. (The order of the elements
4298 /// within each block of the vector is reversed.)
4299 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4300 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4301 "Only possible block sizes for VREV are: 16, 32, 64");
4303 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4307 unsigned NumElts = VT.getVectorNumElements();
4308 unsigned BlockElts = M[0] + 1;
4309 // If the first shuffle index is UNDEF, be optimistic.
4311 BlockElts = BlockSize / EltSz;
4313 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4316 for (unsigned i = 0; i < NumElts; ++i) {
4317 if (M[i] < 0) continue; // ignore UNDEF indices
4318 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4325 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4326 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4327 // range, then 0 is placed into the resulting vector. So pretty much any mask
4328 // of 8 elements can work here.
4329 return VT == MVT::v8i8 && M.size() == 8;
4332 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4333 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4337 unsigned NumElts = VT.getVectorNumElements();
4338 WhichResult = (M[0] == 0 ? 0 : 1);
4339 for (unsigned i = 0; i < NumElts; i += 2) {
4340 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4341 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4347 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4348 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4349 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4350 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4351 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4355 unsigned NumElts = VT.getVectorNumElements();
4356 WhichResult = (M[0] == 0 ? 0 : 1);
4357 for (unsigned i = 0; i < NumElts; i += 2) {
4358 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4359 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4365 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4366 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4370 unsigned NumElts = VT.getVectorNumElements();
4371 WhichResult = (M[0] == 0 ? 0 : 1);
4372 for (unsigned i = 0; i != NumElts; ++i) {
4373 if (M[i] < 0) continue; // ignore UNDEF indices
4374 if ((unsigned) M[i] != 2 * i + WhichResult)
4378 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4379 if (VT.is64BitVector() && EltSz == 32)
4385 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4386 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4387 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4388 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4389 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4393 unsigned Half = VT.getVectorNumElements() / 2;
4394 WhichResult = (M[0] == 0 ? 0 : 1);
4395 for (unsigned j = 0; j != 2; ++j) {
4396 unsigned Idx = WhichResult;
4397 for (unsigned i = 0; i != Half; ++i) {
4398 int MIdx = M[i + j * Half];
4399 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4405 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4406 if (VT.is64BitVector() && EltSz == 32)
4412 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4413 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4417 unsigned NumElts = VT.getVectorNumElements();
4418 WhichResult = (M[0] == 0 ? 0 : 1);
4419 unsigned Idx = WhichResult * NumElts / 2;
4420 for (unsigned i = 0; i != NumElts; i += 2) {
4421 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4422 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4427 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4428 if (VT.is64BitVector() && EltSz == 32)
4434 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4435 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4436 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4437 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4438 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4442 unsigned NumElts = VT.getVectorNumElements();
4443 WhichResult = (M[0] == 0 ? 0 : 1);
4444 unsigned Idx = WhichResult * NumElts / 2;
4445 for (unsigned i = 0; i != NumElts; i += 2) {
4446 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4447 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4452 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4453 if (VT.is64BitVector() && EltSz == 32)
4459 /// \return true if this is a reverse operation on an vector.
4460 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4461 unsigned NumElts = VT.getVectorNumElements();
4462 // Make sure the mask has the right size.
4463 if (NumElts != M.size())
4466 // Look for <15, ..., 3, -1, 1, 0>.
4467 for (unsigned i = 0; i != NumElts; ++i)
4468 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4474 // If N is an integer constant that can be moved into a register in one
4475 // instruction, return an SDValue of such a constant (will become a MOV
4476 // instruction). Otherwise return null.
4477 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4478 const ARMSubtarget *ST, DebugLoc dl) {
4480 if (!isa<ConstantSDNode>(N))
4482 Val = cast<ConstantSDNode>(N)->getZExtValue();
4484 if (ST->isThumb1Only()) {
4485 if (Val <= 255 || ~Val <= 255)
4486 return DAG.getConstant(Val, MVT::i32);
4488 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4489 return DAG.getConstant(Val, MVT::i32);
4494 // If this is a case we can't handle, return null and let the default
4495 // expansion code take care of it.
4496 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4497 const ARMSubtarget *ST) const {
4498 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4499 DebugLoc dl = Op.getDebugLoc();
4500 EVT VT = Op.getValueType();
4502 APInt SplatBits, SplatUndef;
4503 unsigned SplatBitSize;
4505 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4506 if (SplatBitSize <= 64) {
4507 // Check if an immediate VMOV works.
4509 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4510 SplatUndef.getZExtValue(), SplatBitSize,
4511 DAG, VmovVT, VT.is128BitVector(),
4513 if (Val.getNode()) {
4514 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4515 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4518 // Try an immediate VMVN.
4519 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4520 Val = isNEONModifiedImm(NegatedImm,
4521 SplatUndef.getZExtValue(), SplatBitSize,
4522 DAG, VmovVT, VT.is128BitVector(),
4524 if (Val.getNode()) {
4525 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4526 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4529 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4530 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4531 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4533 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4534 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4540 // Scan through the operands to see if only one value is used.
4542 // As an optimisation, even if more than one value is used it may be more
4543 // profitable to splat with one value then change some lanes.
4545 // Heuristically we decide to do this if the vector has a "dominant" value,
4546 // defined as splatted to more than half of the lanes.
4547 unsigned NumElts = VT.getVectorNumElements();
4548 bool isOnlyLowElement = true;
4549 bool usesOnlyOneValue = true;
4550 bool hasDominantValue = false;
4551 bool isConstant = true;
4553 // Map of the number of times a particular SDValue appears in the
4555 DenseMap<SDValue, unsigned> ValueCounts;
4557 for (unsigned i = 0; i < NumElts; ++i) {
4558 SDValue V = Op.getOperand(i);
4559 if (V.getOpcode() == ISD::UNDEF)
4562 isOnlyLowElement = false;
4563 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4566 ValueCounts.insert(std::make_pair(V, 0));
4567 unsigned &Count = ValueCounts[V];
4569 // Is this value dominant? (takes up more than half of the lanes)
4570 if (++Count > (NumElts / 2)) {
4571 hasDominantValue = true;
4575 if (ValueCounts.size() != 1)
4576 usesOnlyOneValue = false;
4577 if (!Value.getNode() && ValueCounts.size() > 0)
4578 Value = ValueCounts.begin()->first;
4580 if (ValueCounts.size() == 0)
4581 return DAG.getUNDEF(VT);
4583 if (isOnlyLowElement)
4584 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4586 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4588 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4589 // i32 and try again.
4590 if (hasDominantValue && EltSize <= 32) {
4594 // If we are VDUPing a value that comes directly from a vector, that will
4595 // cause an unnecessary move to and from a GPR, where instead we could
4596 // just use VDUPLANE. We can only do this if the lane being extracted
4597 // is at a constant index, as the VDUP from lane instructions only have
4598 // constant-index forms.
4599 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4600 isa<ConstantSDNode>(Value->getOperand(1))) {
4601 // We need to create a new undef vector to use for the VDUPLANE if the
4602 // size of the vector from which we get the value is different than the
4603 // size of the vector that we need to create. We will insert the element
4604 // such that the register coalescer will remove unnecessary copies.
4605 if (VT != Value->getOperand(0).getValueType()) {
4606 ConstantSDNode *constIndex;
4607 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4608 assert(constIndex && "The index is not a constant!");
4609 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4610 VT.getVectorNumElements();
4611 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4612 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4613 Value, DAG.getConstant(index, MVT::i32)),
4614 DAG.getConstant(index, MVT::i32));
4616 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4617 Value->getOperand(0), Value->getOperand(1));
4619 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4621 if (!usesOnlyOneValue) {
4622 // The dominant value was splatted as 'N', but we now have to insert
4623 // all differing elements.
4624 for (unsigned I = 0; I < NumElts; ++I) {
4625 if (Op.getOperand(I) == Value)
4627 SmallVector<SDValue, 3> Ops;
4629 Ops.push_back(Op.getOperand(I));
4630 Ops.push_back(DAG.getConstant(I, MVT::i32));
4631 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4636 if (VT.getVectorElementType().isFloatingPoint()) {
4637 SmallVector<SDValue, 8> Ops;
4638 for (unsigned i = 0; i < NumElts; ++i)
4639 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4641 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4642 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4643 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4645 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4647 if (usesOnlyOneValue) {
4648 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4649 if (isConstant && Val.getNode())
4650 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4654 // If all elements are constants and the case above didn't get hit, fall back
4655 // to the default expansion, which will generate a load from the constant
4660 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4662 SDValue shuffle = ReconstructShuffle(Op, DAG);
4663 if (shuffle != SDValue())
4667 // Vectors with 32- or 64-bit elements can be built by directly assigning
4668 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4669 // will be legalized.
4670 if (EltSize >= 32) {
4671 // Do the expansion with floating-point types, since that is what the VFP
4672 // registers are defined to use, and since i64 is not legal.
4673 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4674 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4675 SmallVector<SDValue, 8> Ops;
4676 for (unsigned i = 0; i < NumElts; ++i)
4677 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4678 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4679 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4685 // Gather data to see if the operation can be modelled as a
4686 // shuffle in combination with VEXTs.
4687 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4688 SelectionDAG &DAG) const {
4689 DebugLoc dl = Op.getDebugLoc();
4690 EVT VT = Op.getValueType();
4691 unsigned NumElts = VT.getVectorNumElements();
4693 SmallVector<SDValue, 2> SourceVecs;
4694 SmallVector<unsigned, 2> MinElts;
4695 SmallVector<unsigned, 2> MaxElts;
4697 for (unsigned i = 0; i < NumElts; ++i) {
4698 SDValue V = Op.getOperand(i);
4699 if (V.getOpcode() == ISD::UNDEF)
4701 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4702 // A shuffle can only come from building a vector from various
4703 // elements of other vectors.
4705 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4706 VT.getVectorElementType()) {
4707 // This code doesn't know how to handle shuffles where the vector
4708 // element types do not match (this happens because type legalization
4709 // promotes the return type of EXTRACT_VECTOR_ELT).
4710 // FIXME: It might be appropriate to extend this code to handle
4711 // mismatched types.
4715 // Record this extraction against the appropriate vector if possible...
4716 SDValue SourceVec = V.getOperand(0);
4717 // If the element number isn't a constant, we can't effectively
4718 // analyze what's going on.
4719 if (!isa<ConstantSDNode>(V.getOperand(1)))
4721 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4722 bool FoundSource = false;
4723 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4724 if (SourceVecs[j] == SourceVec) {
4725 if (MinElts[j] > EltNo)
4727 if (MaxElts[j] < EltNo)
4734 // Or record a new source if not...
4736 SourceVecs.push_back(SourceVec);
4737 MinElts.push_back(EltNo);
4738 MaxElts.push_back(EltNo);
4742 // Currently only do something sane when at most two source vectors
4744 if (SourceVecs.size() > 2)
4747 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4748 int VEXTOffsets[2] = {0, 0};
4750 // This loop extracts the usage patterns of the source vectors
4751 // and prepares appropriate SDValues for a shuffle if possible.
4752 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4753 if (SourceVecs[i].getValueType() == VT) {
4754 // No VEXT necessary
4755 ShuffleSrcs[i] = SourceVecs[i];
4758 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4759 // It probably isn't worth padding out a smaller vector just to
4760 // break it down again in a shuffle.
4764 // Since only 64-bit and 128-bit vectors are legal on ARM and
4765 // we've eliminated the other cases...
4766 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4767 "unexpected vector sizes in ReconstructShuffle");
4769 if (MaxElts[i] - MinElts[i] >= NumElts) {
4770 // Span too large for a VEXT to cope
4774 if (MinElts[i] >= NumElts) {
4775 // The extraction can just take the second half
4776 VEXTOffsets[i] = NumElts;
4777 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4779 DAG.getIntPtrConstant(NumElts));
4780 } else if (MaxElts[i] < NumElts) {
4781 // The extraction can just take the first half
4783 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4785 DAG.getIntPtrConstant(0));
4787 // An actual VEXT is needed
4788 VEXTOffsets[i] = MinElts[i];
4789 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4791 DAG.getIntPtrConstant(0));
4792 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4794 DAG.getIntPtrConstant(NumElts));
4795 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4796 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4800 SmallVector<int, 8> Mask;
4802 for (unsigned i = 0; i < NumElts; ++i) {
4803 SDValue Entry = Op.getOperand(i);
4804 if (Entry.getOpcode() == ISD::UNDEF) {
4809 SDValue ExtractVec = Entry.getOperand(0);
4810 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4811 .getOperand(1))->getSExtValue();
4812 if (ExtractVec == SourceVecs[0]) {
4813 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4815 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4819 // Final check before we try to produce nonsense...
4820 if (isShuffleMaskLegal(Mask, VT))
4821 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4827 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4828 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4829 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4830 /// are assumed to be legal.
4832 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4834 if (VT.getVectorNumElements() == 4 &&
4835 (VT.is128BitVector() || VT.is64BitVector())) {
4836 unsigned PFIndexes[4];
4837 for (unsigned i = 0; i != 4; ++i) {
4841 PFIndexes[i] = M[i];
4844 // Compute the index in the perfect shuffle table.
4845 unsigned PFTableIndex =
4846 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4847 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4848 unsigned Cost = (PFEntry >> 30);
4855 unsigned Imm, WhichResult;
4857 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4858 return (EltSize >= 32 ||
4859 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4860 isVREVMask(M, VT, 64) ||
4861 isVREVMask(M, VT, 32) ||
4862 isVREVMask(M, VT, 16) ||
4863 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4864 isVTBLMask(M, VT) ||
4865 isVTRNMask(M, VT, WhichResult) ||
4866 isVUZPMask(M, VT, WhichResult) ||
4867 isVZIPMask(M, VT, WhichResult) ||
4868 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4869 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4870 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4871 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4874 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4875 /// the specified operations to build the shuffle.
4876 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4877 SDValue RHS, SelectionDAG &DAG,
4879 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4880 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4881 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4884 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4893 OP_VUZPL, // VUZP, left result
4894 OP_VUZPR, // VUZP, right result
4895 OP_VZIPL, // VZIP, left result
4896 OP_VZIPR, // VZIP, right result
4897 OP_VTRNL, // VTRN, left result
4898 OP_VTRNR // VTRN, right result
4901 if (OpNum == OP_COPY) {
4902 if (LHSID == (1*9+2)*9+3) return LHS;
4903 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4907 SDValue OpLHS, OpRHS;
4908 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4909 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4910 EVT VT = OpLHS.getValueType();
4913 default: llvm_unreachable("Unknown shuffle opcode!");
4915 // VREV divides the vector in half and swaps within the half.
4916 if (VT.getVectorElementType() == MVT::i32 ||
4917 VT.getVectorElementType() == MVT::f32)
4918 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4919 // vrev <4 x i16> -> VREV32
4920 if (VT.getVectorElementType() == MVT::i16)
4921 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4922 // vrev <4 x i8> -> VREV16
4923 assert(VT.getVectorElementType() == MVT::i8);
4924 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4929 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4930 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4934 return DAG.getNode(ARMISD::VEXT, dl, VT,
4936 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4939 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4940 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4943 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4944 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4947 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4948 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4952 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4953 ArrayRef<int> ShuffleMask,
4954 SelectionDAG &DAG) {
4955 // Check to see if we can use the VTBL instruction.
4956 SDValue V1 = Op.getOperand(0);
4957 SDValue V2 = Op.getOperand(1);
4958 DebugLoc DL = Op.getDebugLoc();
4960 SmallVector<SDValue, 8> VTBLMask;
4961 for (ArrayRef<int>::iterator
4962 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4963 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4965 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4966 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4967 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4970 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4971 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4975 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
4976 SelectionDAG &DAG) {
4977 DebugLoc DL = Op.getDebugLoc();
4978 SDValue OpLHS = Op.getOperand(0);
4979 EVT VT = OpLHS.getValueType();
4981 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
4982 "Expect an v8i16/v16i8 type");
4983 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
4984 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
4985 // extract the first 8 bytes into the top double word and the last 8 bytes
4986 // into the bottom double word. The v8i16 case is similar.
4987 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
4988 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
4989 DAG.getConstant(ExtractNum, MVT::i32));
4992 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4993 SDValue V1 = Op.getOperand(0);
4994 SDValue V2 = Op.getOperand(1);
4995 DebugLoc dl = Op.getDebugLoc();
4996 EVT VT = Op.getValueType();
4997 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4999 // Convert shuffles that are directly supported on NEON to target-specific
5000 // DAG nodes, instead of keeping them as shuffles and matching them again
5001 // during code selection. This is more efficient and avoids the possibility
5002 // of inconsistencies between legalization and selection.
5003 // FIXME: floating-point vectors should be canonicalized to integer vectors
5004 // of the same time so that they get CSEd properly.
5005 ArrayRef<int> ShuffleMask = SVN->getMask();
5007 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5008 if (EltSize <= 32) {
5009 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5010 int Lane = SVN->getSplatIndex();
5011 // If this is undef splat, generate it via "just" vdup, if possible.
5012 if (Lane == -1) Lane = 0;
5014 // Test if V1 is a SCALAR_TO_VECTOR.
5015 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5016 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5018 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5019 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5021 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5022 !isa<ConstantSDNode>(V1.getOperand(0))) {
5023 bool IsScalarToVector = true;
5024 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5025 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5026 IsScalarToVector = false;
5029 if (IsScalarToVector)
5030 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5032 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5033 DAG.getConstant(Lane, MVT::i32));
5038 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5041 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5042 DAG.getConstant(Imm, MVT::i32));
5045 if (isVREVMask(ShuffleMask, VT, 64))
5046 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5047 if (isVREVMask(ShuffleMask, VT, 32))
5048 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5049 if (isVREVMask(ShuffleMask, VT, 16))
5050 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5052 if (V2->getOpcode() == ISD::UNDEF &&
5053 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5054 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5055 DAG.getConstant(Imm, MVT::i32));
5058 // Check for Neon shuffles that modify both input vectors in place.
5059 // If both results are used, i.e., if there are two shuffles with the same
5060 // source operands and with masks corresponding to both results of one of
5061 // these operations, DAG memoization will ensure that a single node is
5062 // used for both shuffles.
5063 unsigned WhichResult;
5064 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5065 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5066 V1, V2).getValue(WhichResult);
5067 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5068 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5069 V1, V2).getValue(WhichResult);
5070 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5071 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5072 V1, V2).getValue(WhichResult);
5074 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5075 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5076 V1, V1).getValue(WhichResult);
5077 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5078 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5079 V1, V1).getValue(WhichResult);
5080 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5081 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5082 V1, V1).getValue(WhichResult);
5085 // If the shuffle is not directly supported and it has 4 elements, use
5086 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5087 unsigned NumElts = VT.getVectorNumElements();
5089 unsigned PFIndexes[4];
5090 for (unsigned i = 0; i != 4; ++i) {
5091 if (ShuffleMask[i] < 0)
5094 PFIndexes[i] = ShuffleMask[i];
5097 // Compute the index in the perfect shuffle table.
5098 unsigned PFTableIndex =
5099 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5100 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5101 unsigned Cost = (PFEntry >> 30);
5104 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5107 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5108 if (EltSize >= 32) {
5109 // Do the expansion with floating-point types, since that is what the VFP
5110 // registers are defined to use, and since i64 is not legal.
5111 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5112 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5113 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5114 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5115 SmallVector<SDValue, 8> Ops;
5116 for (unsigned i = 0; i < NumElts; ++i) {
5117 if (ShuffleMask[i] < 0)
5118 Ops.push_back(DAG.getUNDEF(EltVT));
5120 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5121 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5122 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5125 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5126 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5129 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5130 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5132 if (VT == MVT::v8i8) {
5133 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5134 if (NewOp.getNode())
5141 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5142 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5143 SDValue Lane = Op.getOperand(2);
5144 if (!isa<ConstantSDNode>(Lane))
5150 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5151 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5152 SDValue Lane = Op.getOperand(1);
5153 if (!isa<ConstantSDNode>(Lane))
5156 SDValue Vec = Op.getOperand(0);
5157 if (Op.getValueType() == MVT::i32 &&
5158 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5159 DebugLoc dl = Op.getDebugLoc();
5160 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5166 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5167 // The only time a CONCAT_VECTORS operation can have legal types is when
5168 // two 64-bit vectors are concatenated to a 128-bit vector.
5169 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5170 "unexpected CONCAT_VECTORS");
5171 DebugLoc dl = Op.getDebugLoc();
5172 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5173 SDValue Op0 = Op.getOperand(0);
5174 SDValue Op1 = Op.getOperand(1);
5175 if (Op0.getOpcode() != ISD::UNDEF)
5176 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5177 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5178 DAG.getIntPtrConstant(0));
5179 if (Op1.getOpcode() != ISD::UNDEF)
5180 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5181 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5182 DAG.getIntPtrConstant(1));
5183 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5186 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5187 /// element has been zero/sign-extended, depending on the isSigned parameter,
5188 /// from an integer type half its size.
5189 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5191 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5192 EVT VT = N->getValueType(0);
5193 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5194 SDNode *BVN = N->getOperand(0).getNode();
5195 if (BVN->getValueType(0) != MVT::v4i32 ||
5196 BVN->getOpcode() != ISD::BUILD_VECTOR)
5198 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5199 unsigned HiElt = 1 - LoElt;
5200 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5201 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5202 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5203 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5204 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5207 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5208 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5211 if (Hi0->isNullValue() && Hi1->isNullValue())
5217 if (N->getOpcode() != ISD::BUILD_VECTOR)
5220 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5221 SDNode *Elt = N->getOperand(i).getNode();
5222 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5223 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5224 unsigned HalfSize = EltSize / 2;
5226 if (!isIntN(HalfSize, C->getSExtValue()))
5229 if (!isUIntN(HalfSize, C->getZExtValue()))
5240 /// isSignExtended - Check if a node is a vector value that is sign-extended
5241 /// or a constant BUILD_VECTOR with sign-extended elements.
5242 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5243 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5245 if (isExtendedBUILD_VECTOR(N, DAG, true))
5250 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5251 /// or a constant BUILD_VECTOR with zero-extended elements.
5252 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5253 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5255 if (isExtendedBUILD_VECTOR(N, DAG, false))
5260 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5261 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5262 /// We insert the required extension here to get the vector to fill a D register.
5263 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5266 unsigned ExtOpcode) {
5267 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5268 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5269 // 64-bits we need to insert a new extension so that it will be 64-bits.
5270 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5271 if (OrigTy.getSizeInBits() >= 64)
5274 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5275 MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5277 switch (OrigSimpleTy) {
5278 default: llvm_unreachable("Unexpected Orig Vector Type");
5287 return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5290 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5291 /// does not do any sign/zero extension. If the original vector is less
5292 /// than 64 bits, an appropriate extension will be added after the load to
5293 /// reach a total size of 64 bits. We have to add the extension separately
5294 /// because ARM does not have a sign/zero extending load for vectors.
5295 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5296 SDValue NonExtendingLoad =
5297 DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5298 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5299 LD->isNonTemporal(), LD->isInvariant(),
5300 LD->getAlignment());
5302 switch (LD->getExtensionType()) {
5303 default: llvm_unreachable("Unexpected LoadExtType");
5305 case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5306 case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5308 MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5309 MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5310 return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5311 MemType, ExtType, ExtOp);
5314 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5315 /// extending load, or BUILD_VECTOR with extended elements, return the
5316 /// unextended value. The unextended vector should be 64 bits so that it can
5317 /// be used as an operand to a VMULL instruction. If the original vector size
5318 /// before extension is less than 64 bits we add a an extension to resize
5319 /// the vector to 64 bits.
5320 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5321 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5322 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5323 N->getOperand(0)->getValueType(0),
5327 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5328 return SkipLoadExtensionForVMULL(LD, DAG);
5330 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5331 // have been legalized as a BITCAST from v4i32.
5332 if (N->getOpcode() == ISD::BITCAST) {
5333 SDNode *BVN = N->getOperand(0).getNode();
5334 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5335 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5336 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5337 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5338 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5340 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5341 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5342 EVT VT = N->getValueType(0);
5343 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5344 unsigned NumElts = VT.getVectorNumElements();
5345 MVT TruncVT = MVT::getIntegerVT(EltSize);
5346 SmallVector<SDValue, 8> Ops;
5347 for (unsigned i = 0; i != NumElts; ++i) {
5348 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5349 const APInt &CInt = C->getAPIntValue();
5350 // Element types smaller than 32 bits are not legal, so use i32 elements.
5351 // The values are implicitly truncated so sext vs. zext doesn't matter.
5352 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5354 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5355 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5358 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5359 unsigned Opcode = N->getOpcode();
5360 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5361 SDNode *N0 = N->getOperand(0).getNode();
5362 SDNode *N1 = N->getOperand(1).getNode();
5363 return N0->hasOneUse() && N1->hasOneUse() &&
5364 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5369 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5370 unsigned Opcode = N->getOpcode();
5371 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5372 SDNode *N0 = N->getOperand(0).getNode();
5373 SDNode *N1 = N->getOperand(1).getNode();
5374 return N0->hasOneUse() && N1->hasOneUse() &&
5375 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5380 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5381 // Multiplications are only custom-lowered for 128-bit vectors so that
5382 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5383 EVT VT = Op.getValueType();
5384 assert(VT.is128BitVector() && VT.isInteger() &&
5385 "unexpected type for custom-lowering ISD::MUL");
5386 SDNode *N0 = Op.getOperand(0).getNode();
5387 SDNode *N1 = Op.getOperand(1).getNode();
5388 unsigned NewOpc = 0;
5390 bool isN0SExt = isSignExtended(N0, DAG);
5391 bool isN1SExt = isSignExtended(N1, DAG);
5392 if (isN0SExt && isN1SExt)
5393 NewOpc = ARMISD::VMULLs;
5395 bool isN0ZExt = isZeroExtended(N0, DAG);
5396 bool isN1ZExt = isZeroExtended(N1, DAG);
5397 if (isN0ZExt && isN1ZExt)
5398 NewOpc = ARMISD::VMULLu;
5399 else if (isN1SExt || isN1ZExt) {
5400 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5401 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5402 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5403 NewOpc = ARMISD::VMULLs;
5405 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5406 NewOpc = ARMISD::VMULLu;
5408 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5410 NewOpc = ARMISD::VMULLu;
5416 if (VT == MVT::v2i64)
5417 // Fall through to expand this. It is not legal.
5420 // Other vector multiplications are legal.
5425 // Legalize to a VMULL instruction.
5426 DebugLoc DL = Op.getDebugLoc();
5428 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5430 Op0 = SkipExtensionForVMULL(N0, DAG);
5431 assert(Op0.getValueType().is64BitVector() &&
5432 Op1.getValueType().is64BitVector() &&
5433 "unexpected types for extended operands to VMULL");
5434 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5437 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5438 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5445 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5446 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5447 EVT Op1VT = Op1.getValueType();
5448 return DAG.getNode(N0->getOpcode(), DL, VT,
5449 DAG.getNode(NewOpc, DL, VT,
5450 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5451 DAG.getNode(NewOpc, DL, VT,
5452 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5456 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5458 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5459 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5460 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5461 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5462 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5463 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5464 // Get reciprocal estimate.
5465 // float4 recip = vrecpeq_f32(yf);
5466 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5467 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5468 // Because char has a smaller range than uchar, we can actually get away
5469 // without any newton steps. This requires that we use a weird bias
5470 // of 0xb000, however (again, this has been exhaustively tested).
5471 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5472 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5473 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5474 Y = DAG.getConstant(0xb000, MVT::i32);
5475 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5476 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5477 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5478 // Convert back to short.
5479 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5480 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5485 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5487 // Convert to float.
5488 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5489 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5490 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5491 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5492 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5493 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5495 // Use reciprocal estimate and one refinement step.
5496 // float4 recip = vrecpeq_f32(yf);
5497 // recip *= vrecpsq_f32(yf, recip);
5498 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5499 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5500 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5501 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5503 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5504 // Because short has a smaller range than ushort, we can actually get away
5505 // with only a single newton step. This requires that we use a weird bias
5506 // of 89, however (again, this has been exhaustively tested).
5507 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5508 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5509 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5510 N1 = DAG.getConstant(0x89, MVT::i32);
5511 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5512 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5513 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5514 // Convert back to integer and return.
5515 // return vmovn_s32(vcvt_s32_f32(result));
5516 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5517 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5521 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5522 EVT VT = Op.getValueType();
5523 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5524 "unexpected type for custom-lowering ISD::SDIV");
5526 DebugLoc dl = Op.getDebugLoc();
5527 SDValue N0 = Op.getOperand(0);
5528 SDValue N1 = Op.getOperand(1);
5531 if (VT == MVT::v8i8) {
5532 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5533 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5535 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5536 DAG.getIntPtrConstant(4));
5537 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5538 DAG.getIntPtrConstant(4));
5539 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5540 DAG.getIntPtrConstant(0));
5541 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5542 DAG.getIntPtrConstant(0));
5544 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5545 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5547 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5548 N0 = LowerCONCAT_VECTORS(N0, DAG);
5550 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5553 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5556 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5557 EVT VT = Op.getValueType();
5558 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5559 "unexpected type for custom-lowering ISD::UDIV");
5561 DebugLoc dl = Op.getDebugLoc();
5562 SDValue N0 = Op.getOperand(0);
5563 SDValue N1 = Op.getOperand(1);
5566 if (VT == MVT::v8i8) {
5567 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5568 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5570 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5571 DAG.getIntPtrConstant(4));
5572 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5573 DAG.getIntPtrConstant(4));
5574 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5575 DAG.getIntPtrConstant(0));
5576 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5577 DAG.getIntPtrConstant(0));
5579 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5580 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5582 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5583 N0 = LowerCONCAT_VECTORS(N0, DAG);
5585 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5586 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5591 // v4i16 sdiv ... Convert to float.
5592 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5593 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5594 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5595 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5596 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5597 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5599 // Use reciprocal estimate and two refinement steps.
5600 // float4 recip = vrecpeq_f32(yf);
5601 // recip *= vrecpsq_f32(yf, recip);
5602 // recip *= vrecpsq_f32(yf, recip);
5603 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5604 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5605 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5606 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5608 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5609 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5610 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5612 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5613 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5614 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5615 // and that it will never cause us to return an answer too large).
5616 // float4 result = as_float4(as_int4(xf*recip) + 2);
5617 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5618 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5619 N1 = DAG.getConstant(2, MVT::i32);
5620 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5621 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5622 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5623 // Convert back to integer and return.
5624 // return vmovn_u32(vcvt_s32_f32(result));
5625 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5626 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5630 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5631 EVT VT = Op.getNode()->getValueType(0);
5632 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5635 bool ExtraOp = false;
5636 switch (Op.getOpcode()) {
5637 default: llvm_unreachable("Invalid code");
5638 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5639 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5640 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5641 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5645 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5647 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5648 Op.getOperand(1), Op.getOperand(2));
5651 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5652 // Monotonic load/store is legal for all targets
5653 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5656 // Aquire/Release load/store is not legal for targets without a
5657 // dmb or equivalent available.
5663 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5664 SelectionDAG &DAG, unsigned NewOp) {
5665 DebugLoc dl = Node->getDebugLoc();
5666 assert (Node->getValueType(0) == MVT::i64 &&
5667 "Only know how to expand i64 atomics");
5669 SmallVector<SDValue, 6> Ops;
5670 Ops.push_back(Node->getOperand(0)); // Chain
5671 Ops.push_back(Node->getOperand(1)); // Ptr
5673 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5674 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5675 // High part of Val1
5676 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5677 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5678 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5679 // High part of Val1
5680 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5681 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5682 // High part of Val2
5683 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5684 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5686 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5688 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5689 cast<MemSDNode>(Node)->getMemOperand());
5690 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5691 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5692 Results.push_back(Result.getValue(2));
5695 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5696 switch (Op.getOpcode()) {
5697 default: llvm_unreachable("Don't know how to custom lower this!");
5698 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5699 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5700 case ISD::GlobalAddress:
5701 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5702 LowerGlobalAddressELF(Op, DAG);
5703 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5704 case ISD::SELECT: return LowerSELECT(Op, DAG);
5705 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5706 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5707 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5708 case ISD::VASTART: return LowerVASTART(Op, DAG);
5709 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5710 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5711 case ISD::SINT_TO_FP:
5712 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5713 case ISD::FP_TO_SINT:
5714 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5715 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5716 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5717 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5718 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5719 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5720 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5721 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5723 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5726 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5727 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5728 case ISD::SRL_PARTS:
5729 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5730 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5731 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5732 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5733 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5734 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5735 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5736 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5737 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5738 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5739 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5740 case ISD::MUL: return LowerMUL(Op, DAG);
5741 case ISD::SDIV: return LowerSDIV(Op, DAG);
5742 case ISD::UDIV: return LowerUDIV(Op, DAG);
5746 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5747 case ISD::ATOMIC_LOAD:
5748 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5752 /// ReplaceNodeResults - Replace the results of node with an illegal result
5753 /// type with new values built out of custom code.
5754 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5755 SmallVectorImpl<SDValue>&Results,
5756 SelectionDAG &DAG) const {
5758 switch (N->getOpcode()) {
5760 llvm_unreachable("Don't know how to custom expand this!");
5762 Res = ExpandBITCAST(N, DAG);
5764 case ISD::SIGN_EXTEND:
5765 case ISD::ZERO_EXTEND:
5766 Res = ExpandVectorExtension(N, DAG);
5770 Res = Expand64BitShift(N, DAG, Subtarget);
5772 case ISD::ATOMIC_LOAD_ADD:
5773 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5775 case ISD::ATOMIC_LOAD_AND:
5776 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5778 case ISD::ATOMIC_LOAD_NAND:
5779 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5781 case ISD::ATOMIC_LOAD_OR:
5782 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5784 case ISD::ATOMIC_LOAD_SUB:
5785 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5787 case ISD::ATOMIC_LOAD_XOR:
5788 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5790 case ISD::ATOMIC_SWAP:
5791 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5793 case ISD::ATOMIC_CMP_SWAP:
5794 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5796 case ISD::ATOMIC_LOAD_MIN:
5797 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5799 case ISD::ATOMIC_LOAD_UMIN:
5800 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5802 case ISD::ATOMIC_LOAD_MAX:
5803 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5805 case ISD::ATOMIC_LOAD_UMAX:
5806 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5810 Results.push_back(Res);
5813 //===----------------------------------------------------------------------===//
5814 // ARM Scheduler Hooks
5815 //===----------------------------------------------------------------------===//
5818 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5819 MachineBasicBlock *BB,
5820 unsigned Size) const {
5821 unsigned dest = MI->getOperand(0).getReg();
5822 unsigned ptr = MI->getOperand(1).getReg();
5823 unsigned oldval = MI->getOperand(2).getReg();
5824 unsigned newval = MI->getOperand(3).getReg();
5825 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5826 DebugLoc dl = MI->getDebugLoc();
5827 bool isThumb2 = Subtarget->isThumb2();
5829 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5830 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5831 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5832 (const TargetRegisterClass*)&ARM::GPRRegClass);
5835 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5836 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5837 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5840 unsigned ldrOpc, strOpc;
5842 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5844 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5845 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5848 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5849 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5852 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5853 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5857 MachineFunction *MF = BB->getParent();
5858 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5859 MachineFunction::iterator It = BB;
5860 ++It; // insert the new blocks after the current block
5862 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5863 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5864 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5865 MF->insert(It, loop1MBB);
5866 MF->insert(It, loop2MBB);
5867 MF->insert(It, exitMBB);
5869 // Transfer the remainder of BB and its successor edges to exitMBB.
5870 exitMBB->splice(exitMBB->begin(), BB,
5871 llvm::next(MachineBasicBlock::iterator(MI)),
5873 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5877 // fallthrough --> loop1MBB
5878 BB->addSuccessor(loop1MBB);
5881 // ldrex dest, [ptr]
5885 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5886 if (ldrOpc == ARM::t2LDREX)
5888 AddDefaultPred(MIB);
5889 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5890 .addReg(dest).addReg(oldval));
5891 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5892 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5893 BB->addSuccessor(loop2MBB);
5894 BB->addSuccessor(exitMBB);
5897 // strex scratch, newval, [ptr]
5901 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5902 if (strOpc == ARM::t2STREX)
5904 AddDefaultPred(MIB);
5905 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5906 .addReg(scratch).addImm(0));
5907 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5908 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5909 BB->addSuccessor(loop1MBB);
5910 BB->addSuccessor(exitMBB);
5916 MI->eraseFromParent(); // The instruction is gone now.
5922 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5923 unsigned Size, unsigned BinOpcode) const {
5924 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5925 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5927 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5928 MachineFunction *MF = BB->getParent();
5929 MachineFunction::iterator It = BB;
5932 unsigned dest = MI->getOperand(0).getReg();
5933 unsigned ptr = MI->getOperand(1).getReg();
5934 unsigned incr = MI->getOperand(2).getReg();
5935 DebugLoc dl = MI->getDebugLoc();
5936 bool isThumb2 = Subtarget->isThumb2();
5938 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5940 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5941 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5944 unsigned ldrOpc, strOpc;
5946 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5948 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5949 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5952 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5953 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5956 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5957 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5961 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5962 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5963 MF->insert(It, loopMBB);
5964 MF->insert(It, exitMBB);
5966 // Transfer the remainder of BB and its successor edges to exitMBB.
5967 exitMBB->splice(exitMBB->begin(), BB,
5968 llvm::next(MachineBasicBlock::iterator(MI)),
5970 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5972 const TargetRegisterClass *TRC = isThumb2 ?
5973 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5974 (const TargetRegisterClass*)&ARM::GPRRegClass;
5975 unsigned scratch = MRI.createVirtualRegister(TRC);
5976 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5980 // fallthrough --> loopMBB
5981 BB->addSuccessor(loopMBB);
5985 // <binop> scratch2, dest, incr
5986 // strex scratch, scratch2, ptr
5989 // fallthrough --> exitMBB
5991 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5992 if (ldrOpc == ARM::t2LDREX)
5994 AddDefaultPred(MIB);
5996 // operand order needs to go the other way for NAND
5997 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5998 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5999 addReg(incr).addReg(dest)).addReg(0);
6001 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6002 addReg(dest).addReg(incr)).addReg(0);
6005 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6006 if (strOpc == ARM::t2STREX)
6008 AddDefaultPred(MIB);
6009 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6010 .addReg(scratch).addImm(0));
6011 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6012 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6014 BB->addSuccessor(loopMBB);
6015 BB->addSuccessor(exitMBB);
6021 MI->eraseFromParent(); // The instruction is gone now.
6027 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6028 MachineBasicBlock *BB,
6031 ARMCC::CondCodes Cond) const {
6032 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6034 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6035 MachineFunction *MF = BB->getParent();
6036 MachineFunction::iterator It = BB;
6039 unsigned dest = MI->getOperand(0).getReg();
6040 unsigned ptr = MI->getOperand(1).getReg();
6041 unsigned incr = MI->getOperand(2).getReg();
6042 unsigned oldval = dest;
6043 DebugLoc dl = MI->getDebugLoc();
6044 bool isThumb2 = Subtarget->isThumb2();
6046 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6048 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6049 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6052 unsigned ldrOpc, strOpc, extendOpc;
6054 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6056 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6057 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6058 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6061 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6062 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6063 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6066 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6067 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6072 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6073 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6074 MF->insert(It, loopMBB);
6075 MF->insert(It, exitMBB);
6077 // Transfer the remainder of BB and its successor edges to exitMBB.
6078 exitMBB->splice(exitMBB->begin(), BB,
6079 llvm::next(MachineBasicBlock::iterator(MI)),
6081 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6083 const TargetRegisterClass *TRC = isThumb2 ?
6084 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6085 (const TargetRegisterClass*)&ARM::GPRRegClass;
6086 unsigned scratch = MRI.createVirtualRegister(TRC);
6087 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6091 // fallthrough --> loopMBB
6092 BB->addSuccessor(loopMBB);
6096 // (sign extend dest, if required)
6098 // cmov.cond scratch2, incr, dest
6099 // strex scratch, scratch2, ptr
6102 // fallthrough --> exitMBB
6104 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6105 if (ldrOpc == ARM::t2LDREX)
6107 AddDefaultPred(MIB);
6109 // Sign extend the value, if necessary.
6110 if (signExtend && extendOpc) {
6111 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6112 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6117 // Build compare and cmov instructions.
6118 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6119 .addReg(oldval).addReg(incr));
6120 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6121 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6123 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6124 if (strOpc == ARM::t2STREX)
6126 AddDefaultPred(MIB);
6127 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6128 .addReg(scratch).addImm(0));
6129 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6130 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6132 BB->addSuccessor(loopMBB);
6133 BB->addSuccessor(exitMBB);
6139 MI->eraseFromParent(); // The instruction is gone now.
6145 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6146 unsigned Op1, unsigned Op2,
6147 bool NeedsCarry, bool IsCmpxchg,
6148 bool IsMinMax, ARMCC::CondCodes CC) const {
6149 // This also handles ATOMIC_SWAP, indicated by Op1==0.
6150 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6152 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6153 MachineFunction *MF = BB->getParent();
6154 MachineFunction::iterator It = BB;
6157 unsigned destlo = MI->getOperand(0).getReg();
6158 unsigned desthi = MI->getOperand(1).getReg();
6159 unsigned ptr = MI->getOperand(2).getReg();
6160 unsigned vallo = MI->getOperand(3).getReg();
6161 unsigned valhi = MI->getOperand(4).getReg();
6162 DebugLoc dl = MI->getDebugLoc();
6163 bool isThumb2 = Subtarget->isThumb2();
6165 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6167 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6168 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6169 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6172 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6173 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6174 if (IsCmpxchg || IsMinMax)
6175 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6177 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6178 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6180 MF->insert(It, loopMBB);
6181 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6182 if (IsCmpxchg) MF->insert(It, cont2BB);
6183 MF->insert(It, exitMBB);
6185 // Transfer the remainder of BB and its successor edges to exitMBB.
6186 exitMBB->splice(exitMBB->begin(), BB,
6187 llvm::next(MachineBasicBlock::iterator(MI)),
6189 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6191 const TargetRegisterClass *TRC = isThumb2 ?
6192 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6193 (const TargetRegisterClass*)&ARM::GPRRegClass;
6194 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6198 // fallthrough --> loopMBB
6199 BB->addSuccessor(loopMBB);
6202 // ldrexd r2, r3, ptr
6203 // <binopa> r0, r2, incr
6204 // <binopb> r1, r3, incr
6205 // strexd storesuccess, r0, r1, ptr
6206 // cmp storesuccess, #0
6208 // fallthrough --> exitMBB
6213 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6214 .addReg(destlo, RegState::Define)
6215 .addReg(desthi, RegState::Define)
6218 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6219 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6220 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6221 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6222 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6223 .addReg(GPRPair0, 0, ARM::gsub_0);
6224 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6225 .addReg(GPRPair0, 0, ARM::gsub_1);
6228 unsigned StoreLo, StoreHi;
6231 for (unsigned i = 0; i < 2; i++) {
6232 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6234 .addReg(i == 0 ? destlo : desthi)
6235 .addReg(i == 0 ? vallo : valhi));
6236 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6237 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6238 BB->addSuccessor(exitMBB);
6239 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6240 BB = (i == 0 ? contBB : cont2BB);
6243 // Copy to physregs for strexd
6244 StoreLo = MI->getOperand(5).getReg();
6245 StoreHi = MI->getOperand(6).getReg();
6247 // Perform binary operation
6248 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6249 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6250 .addReg(destlo).addReg(vallo))
6251 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6252 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6253 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6254 .addReg(desthi).addReg(valhi))
6255 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6260 // Copy to physregs for strexd
6265 // Compare and branch to exit block.
6266 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6267 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6268 BB->addSuccessor(exitMBB);
6269 BB->addSuccessor(contBB);
6277 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6278 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6280 // Marshal a pair...
6281 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6282 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6283 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6284 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6285 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6288 .addImm(ARM::gsub_0);
6289 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6292 .addImm(ARM::gsub_1);
6295 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6296 .addReg(StorePair).addReg(ptr));
6299 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6300 .addReg(storesuccess).addImm(0));
6301 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6302 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6304 BB->addSuccessor(loopMBB);
6305 BB->addSuccessor(exitMBB);
6311 MI->eraseFromParent(); // The instruction is gone now.
6316 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6317 /// registers the function context.
6318 void ARMTargetLowering::
6319 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6320 MachineBasicBlock *DispatchBB, int FI) const {
6321 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6322 DebugLoc dl = MI->getDebugLoc();
6323 MachineFunction *MF = MBB->getParent();
6324 MachineRegisterInfo *MRI = &MF->getRegInfo();
6325 MachineConstantPool *MCP = MF->getConstantPool();
6326 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6327 const Function *F = MF->getFunction();
6329 bool isThumb = Subtarget->isThumb();
6330 bool isThumb2 = Subtarget->isThumb2();
6332 unsigned PCLabelId = AFI->createPICLabelUId();
6333 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6334 ARMConstantPoolValue *CPV =
6335 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6336 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6338 const TargetRegisterClass *TRC = isThumb ?
6339 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6340 (const TargetRegisterClass*)&ARM::GPRRegClass;
6342 // Grab constant pool and fixed stack memory operands.
6343 MachineMemOperand *CPMMO =
6344 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6345 MachineMemOperand::MOLoad, 4, 4);
6347 MachineMemOperand *FIMMOSt =
6348 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6349 MachineMemOperand::MOStore, 4, 4);
6351 // Load the address of the dispatch MBB into the jump buffer.
6353 // Incoming value: jbuf
6354 // ldr.n r5, LCPI1_1
6357 // str r5, [$jbuf, #+4] ; &jbuf[1]
6358 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6359 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6360 .addConstantPoolIndex(CPI)
6361 .addMemOperand(CPMMO));
6362 // Set the low bit because of thumb mode.
6363 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6365 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6366 .addReg(NewVReg1, RegState::Kill)
6368 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6369 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6370 .addReg(NewVReg2, RegState::Kill)
6372 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6373 .addReg(NewVReg3, RegState::Kill)
6375 .addImm(36) // &jbuf[1] :: pc
6376 .addMemOperand(FIMMOSt));
6377 } else if (isThumb) {
6378 // Incoming value: jbuf
6379 // ldr.n r1, LCPI1_4
6383 // add r2, $jbuf, #+4 ; &jbuf[1]
6385 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6386 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6387 .addConstantPoolIndex(CPI)
6388 .addMemOperand(CPMMO));
6389 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6390 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6391 .addReg(NewVReg1, RegState::Kill)
6393 // Set the low bit because of thumb mode.
6394 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6395 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6396 .addReg(ARM::CPSR, RegState::Define)
6398 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6399 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6400 .addReg(ARM::CPSR, RegState::Define)
6401 .addReg(NewVReg2, RegState::Kill)
6402 .addReg(NewVReg3, RegState::Kill));
6403 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6404 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6406 .addImm(36)); // &jbuf[1] :: pc
6407 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6408 .addReg(NewVReg4, RegState::Kill)
6409 .addReg(NewVReg5, RegState::Kill)
6411 .addMemOperand(FIMMOSt));
6413 // Incoming value: jbuf
6416 // str r1, [$jbuf, #+4] ; &jbuf[1]
6417 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6418 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6419 .addConstantPoolIndex(CPI)
6421 .addMemOperand(CPMMO));
6422 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6423 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6424 .addReg(NewVReg1, RegState::Kill)
6425 .addImm(PCLabelId));
6426 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6427 .addReg(NewVReg2, RegState::Kill)
6429 .addImm(36) // &jbuf[1] :: pc
6430 .addMemOperand(FIMMOSt));
6434 MachineBasicBlock *ARMTargetLowering::
6435 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6436 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6437 DebugLoc dl = MI->getDebugLoc();
6438 MachineFunction *MF = MBB->getParent();
6439 MachineRegisterInfo *MRI = &MF->getRegInfo();
6440 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6441 MachineFrameInfo *MFI = MF->getFrameInfo();
6442 int FI = MFI->getFunctionContextIndex();
6444 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6445 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6446 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6448 // Get a mapping of the call site numbers to all of the landing pads they're
6450 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6451 unsigned MaxCSNum = 0;
6452 MachineModuleInfo &MMI = MF->getMMI();
6453 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6455 if (!BB->isLandingPad()) continue;
6457 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6459 for (MachineBasicBlock::iterator
6460 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6461 if (!II->isEHLabel()) continue;
6463 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6464 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6466 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6467 for (SmallVectorImpl<unsigned>::iterator
6468 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6469 CSI != CSE; ++CSI) {
6470 CallSiteNumToLPad[*CSI].push_back(BB);
6471 MaxCSNum = std::max(MaxCSNum, *CSI);
6477 // Get an ordered list of the machine basic blocks for the jump table.
6478 std::vector<MachineBasicBlock*> LPadList;
6479 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6480 LPadList.reserve(CallSiteNumToLPad.size());
6481 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6482 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6483 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6484 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6485 LPadList.push_back(*II);
6486 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6490 assert(!LPadList.empty() &&
6491 "No landing pad destinations for the dispatch jump table!");
6493 // Create the jump table and associated information.
6494 MachineJumpTableInfo *JTI =
6495 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6496 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6497 unsigned UId = AFI->createJumpTableUId();
6498 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6500 // Create the MBBs for the dispatch code.
6502 // Shove the dispatch's address into the return slot in the function context.
6503 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6504 DispatchBB->setIsLandingPad();
6506 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6507 unsigned trap_opcode;
6508 if (Subtarget->isThumb())
6509 trap_opcode = ARM::tTRAP;
6511 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6513 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6514 DispatchBB->addSuccessor(TrapBB);
6516 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6517 DispatchBB->addSuccessor(DispContBB);
6520 MF->insert(MF->end(), DispatchBB);
6521 MF->insert(MF->end(), DispContBB);
6522 MF->insert(MF->end(), TrapBB);
6524 // Insert code into the entry block that creates and registers the function
6526 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6528 MachineMemOperand *FIMMOLd =
6529 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6530 MachineMemOperand::MOLoad |
6531 MachineMemOperand::MOVolatile, 4, 4);
6533 MachineInstrBuilder MIB;
6534 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6536 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6537 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6539 // Add a register mask with no preserved registers. This results in all
6540 // registers being marked as clobbered.
6541 MIB.addRegMask(RI.getNoPreservedMask());
6543 unsigned NumLPads = LPadList.size();
6544 if (Subtarget->isThumb2()) {
6545 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6546 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6549 .addMemOperand(FIMMOLd));
6551 if (NumLPads < 256) {
6552 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6554 .addImm(LPadList.size()));
6556 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6557 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6558 .addImm(NumLPads & 0xFFFF));
6560 unsigned VReg2 = VReg1;
6561 if ((NumLPads & 0xFFFF0000) != 0) {
6562 VReg2 = MRI->createVirtualRegister(TRC);
6563 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6565 .addImm(NumLPads >> 16));
6568 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6573 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6578 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6579 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6580 .addJumpTableIndex(MJTI)
6583 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6586 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6587 .addReg(NewVReg3, RegState::Kill)
6589 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6591 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6592 .addReg(NewVReg4, RegState::Kill)
6594 .addJumpTableIndex(MJTI)
6596 } else if (Subtarget->isThumb()) {
6597 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6598 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6601 .addMemOperand(FIMMOLd));
6603 if (NumLPads < 256) {
6604 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6608 MachineConstantPool *ConstantPool = MF->getConstantPool();
6609 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6610 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6612 // MachineConstantPool wants an explicit alignment.
6613 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6615 Align = getDataLayout()->getTypeAllocSize(C->getType());
6616 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6618 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6619 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6620 .addReg(VReg1, RegState::Define)
6621 .addConstantPoolIndex(Idx));
6622 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6627 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6632 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6633 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6634 .addReg(ARM::CPSR, RegState::Define)
6638 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6639 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6640 .addJumpTableIndex(MJTI)
6643 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6644 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6645 .addReg(ARM::CPSR, RegState::Define)
6646 .addReg(NewVReg2, RegState::Kill)
6649 MachineMemOperand *JTMMOLd =
6650 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6651 MachineMemOperand::MOLoad, 4, 4);
6653 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6654 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6655 .addReg(NewVReg4, RegState::Kill)
6657 .addMemOperand(JTMMOLd));
6659 unsigned NewVReg6 = NewVReg5;
6660 if (RelocM == Reloc::PIC_) {
6661 NewVReg6 = MRI->createVirtualRegister(TRC);
6662 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6663 .addReg(ARM::CPSR, RegState::Define)
6664 .addReg(NewVReg5, RegState::Kill)
6668 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6669 .addReg(NewVReg6, RegState::Kill)
6670 .addJumpTableIndex(MJTI)
6673 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6674 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6677 .addMemOperand(FIMMOLd));
6679 if (NumLPads < 256) {
6680 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6683 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6684 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6685 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6686 .addImm(NumLPads & 0xFFFF));
6688 unsigned VReg2 = VReg1;
6689 if ((NumLPads & 0xFFFF0000) != 0) {
6690 VReg2 = MRI->createVirtualRegister(TRC);
6691 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6693 .addImm(NumLPads >> 16));
6696 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6700 MachineConstantPool *ConstantPool = MF->getConstantPool();
6701 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6702 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6704 // MachineConstantPool wants an explicit alignment.
6705 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6707 Align = getDataLayout()->getTypeAllocSize(C->getType());
6708 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6710 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6711 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6712 .addReg(VReg1, RegState::Define)
6713 .addConstantPoolIndex(Idx)
6715 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6717 .addReg(VReg1, RegState::Kill));
6720 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6725 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6727 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6729 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6730 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6731 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6732 .addJumpTableIndex(MJTI)
6735 MachineMemOperand *JTMMOLd =
6736 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6737 MachineMemOperand::MOLoad, 4, 4);
6738 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6740 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6741 .addReg(NewVReg3, RegState::Kill)
6744 .addMemOperand(JTMMOLd));
6746 if (RelocM == Reloc::PIC_) {
6747 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6748 .addReg(NewVReg5, RegState::Kill)
6750 .addJumpTableIndex(MJTI)
6753 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6754 .addReg(NewVReg5, RegState::Kill)
6755 .addJumpTableIndex(MJTI)
6760 // Add the jump table entries as successors to the MBB.
6761 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6762 for (std::vector<MachineBasicBlock*>::iterator
6763 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6764 MachineBasicBlock *CurMBB = *I;
6765 if (SeenMBBs.insert(CurMBB))
6766 DispContBB->addSuccessor(CurMBB);
6769 // N.B. the order the invoke BBs are processed in doesn't matter here.
6770 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6771 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6772 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6773 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6774 MachineBasicBlock *BB = *I;
6776 // Remove the landing pad successor from the invoke block and replace it
6777 // with the new dispatch block.
6778 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6780 while (!Successors.empty()) {
6781 MachineBasicBlock *SMBB = Successors.pop_back_val();
6782 if (SMBB->isLandingPad()) {
6783 BB->removeSuccessor(SMBB);
6784 MBBLPads.push_back(SMBB);
6788 BB->addSuccessor(DispatchBB);
6790 // Find the invoke call and mark all of the callee-saved registers as
6791 // 'implicit defined' so that they're spilled. This prevents code from
6792 // moving instructions to before the EH block, where they will never be
6794 for (MachineBasicBlock::reverse_iterator
6795 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6796 if (!II->isCall()) continue;
6798 DenseMap<unsigned, bool> DefRegs;
6799 for (MachineInstr::mop_iterator
6800 OI = II->operands_begin(), OE = II->operands_end();
6802 if (!OI->isReg()) continue;
6803 DefRegs[OI->getReg()] = true;
6806 MachineInstrBuilder MIB(*MF, &*II);
6808 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6809 unsigned Reg = SavedRegs[i];
6810 if (Subtarget->isThumb2() &&
6811 !ARM::tGPRRegClass.contains(Reg) &&
6812 !ARM::hGPRRegClass.contains(Reg))
6814 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6816 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6819 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6826 // Mark all former landing pads as non-landing pads. The dispatch is the only
6828 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6829 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6830 (*I)->setIsLandingPad(false);
6832 // The instruction is gone now.
6833 MI->eraseFromParent();
6839 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6840 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6841 E = MBB->succ_end(); I != E; ++I)
6844 llvm_unreachable("Expecting a BB with two successors!");
6847 MachineBasicBlock *ARMTargetLowering::
6848 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6849 // This pseudo instruction has 3 operands: dst, src, size
6850 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6851 // Otherwise, we will generate unrolled scalar copies.
6852 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6853 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6854 MachineFunction::iterator It = BB;
6857 unsigned dest = MI->getOperand(0).getReg();
6858 unsigned src = MI->getOperand(1).getReg();
6859 unsigned SizeVal = MI->getOperand(2).getImm();
6860 unsigned Align = MI->getOperand(3).getImm();
6861 DebugLoc dl = MI->getDebugLoc();
6863 bool isThumb2 = Subtarget->isThumb2();
6864 MachineFunction *MF = BB->getParent();
6865 MachineRegisterInfo &MRI = MF->getRegInfo();
6866 unsigned ldrOpc, strOpc, UnitSize = 0;
6868 const TargetRegisterClass *TRC = isThumb2 ?
6869 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6870 (const TargetRegisterClass*)&ARM::GPRRegClass;
6871 const TargetRegisterClass *TRC_Vec = 0;
6874 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6875 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6877 } else if (Align & 2) {
6878 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6879 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6882 // Check whether we can use NEON instructions.
6883 if (!MF->getFunction()->getAttributes().
6884 hasAttribute(AttributeSet::FunctionIndex,
6885 Attribute::NoImplicitFloat) &&
6886 Subtarget->hasNEON()) {
6887 if ((Align % 16 == 0) && SizeVal >= 16) {
6888 ldrOpc = ARM::VLD1q32wb_fixed;
6889 strOpc = ARM::VST1q32wb_fixed;
6891 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6893 else if ((Align % 8 == 0) && SizeVal >= 8) {
6894 ldrOpc = ARM::VLD1d32wb_fixed;
6895 strOpc = ARM::VST1d32wb_fixed;
6897 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6900 // Can't use NEON instructions.
6901 if (UnitSize == 0) {
6902 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6903 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6908 unsigned BytesLeft = SizeVal % UnitSize;
6909 unsigned LoopSize = SizeVal - BytesLeft;
6911 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6912 // Use LDR and STR to copy.
6913 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6914 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6915 unsigned srcIn = src;
6916 unsigned destIn = dest;
6917 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6918 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6919 unsigned srcOut = MRI.createVirtualRegister(TRC);
6920 unsigned destOut = MRI.createVirtualRegister(TRC);
6921 if (UnitSize >= 8) {
6922 AddDefaultPred(BuildMI(*BB, MI, dl,
6923 TII->get(ldrOpc), scratch)
6924 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6926 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6927 .addReg(destIn).addImm(0).addReg(scratch));
6928 } else if (isThumb2) {
6929 AddDefaultPred(BuildMI(*BB, MI, dl,
6930 TII->get(ldrOpc), scratch)
6931 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6933 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6934 .addReg(scratch).addReg(destIn)
6937 AddDefaultPred(BuildMI(*BB, MI, dl,
6938 TII->get(ldrOpc), scratch)
6939 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6942 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6943 .addReg(scratch).addReg(destIn)
6944 .addReg(0).addImm(UnitSize));
6950 // Handle the leftover bytes with LDRB and STRB.
6951 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6952 // [destOut] = STRB_POST(scratch, destIn, 1)
6953 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6954 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6955 for (unsigned i = 0; i < BytesLeft; i++) {
6956 unsigned scratch = MRI.createVirtualRegister(TRC);
6957 unsigned srcOut = MRI.createVirtualRegister(TRC);
6958 unsigned destOut = MRI.createVirtualRegister(TRC);
6960 AddDefaultPred(BuildMI(*BB, MI, dl,
6961 TII->get(ldrOpc),scratch)
6962 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6964 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6965 .addReg(scratch).addReg(destIn)
6966 .addReg(0).addImm(1));
6968 AddDefaultPred(BuildMI(*BB, MI, dl,
6969 TII->get(ldrOpc),scratch)
6970 .addReg(srcOut, RegState::Define).addReg(srcIn)
6971 .addReg(0).addImm(1));
6973 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6974 .addReg(scratch).addReg(destIn)
6975 .addReg(0).addImm(1));
6980 MI->eraseFromParent(); // The instruction is gone now.
6984 // Expand the pseudo op to a loop.
6987 // movw varEnd, # --> with thumb2
6989 // ldrcp varEnd, idx --> without thumb2
6990 // fallthrough --> loopMBB
6992 // PHI varPhi, varEnd, varLoop
6993 // PHI srcPhi, src, srcLoop
6994 // PHI destPhi, dst, destLoop
6995 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6996 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6997 // subs varLoop, varPhi, #UnitSize
6999 // fallthrough --> exitMBB
7001 // epilogue to handle left-over bytes
7002 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7003 // [destOut] = STRB_POST(scratch, destLoop, 1)
7004 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7005 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7006 MF->insert(It, loopMBB);
7007 MF->insert(It, exitMBB);
7009 // Transfer the remainder of BB and its successor edges to exitMBB.
7010 exitMBB->splice(exitMBB->begin(), BB,
7011 llvm::next(MachineBasicBlock::iterator(MI)),
7013 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7015 // Load an immediate to varEnd.
7016 unsigned varEnd = MRI.createVirtualRegister(TRC);
7018 unsigned VReg1 = varEnd;
7019 if ((LoopSize & 0xFFFF0000) != 0)
7020 VReg1 = MRI.createVirtualRegister(TRC);
7021 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7022 .addImm(LoopSize & 0xFFFF));
7024 if ((LoopSize & 0xFFFF0000) != 0)
7025 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7027 .addImm(LoopSize >> 16));
7029 MachineConstantPool *ConstantPool = MF->getConstantPool();
7030 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7031 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7033 // MachineConstantPool wants an explicit alignment.
7034 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7036 Align = getDataLayout()->getTypeAllocSize(C->getType());
7037 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7039 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7040 .addReg(varEnd, RegState::Define)
7041 .addConstantPoolIndex(Idx)
7044 BB->addSuccessor(loopMBB);
7046 // Generate the loop body:
7047 // varPhi = PHI(varLoop, varEnd)
7048 // srcPhi = PHI(srcLoop, src)
7049 // destPhi = PHI(destLoop, dst)
7050 MachineBasicBlock *entryBB = BB;
7052 unsigned varLoop = MRI.createVirtualRegister(TRC);
7053 unsigned varPhi = MRI.createVirtualRegister(TRC);
7054 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7055 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7056 unsigned destLoop = MRI.createVirtualRegister(TRC);
7057 unsigned destPhi = MRI.createVirtualRegister(TRC);
7059 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7060 .addReg(varLoop).addMBB(loopMBB)
7061 .addReg(varEnd).addMBB(entryBB);
7062 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7063 .addReg(srcLoop).addMBB(loopMBB)
7064 .addReg(src).addMBB(entryBB);
7065 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7066 .addReg(destLoop).addMBB(loopMBB)
7067 .addReg(dest).addMBB(entryBB);
7069 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7070 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7071 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7072 if (UnitSize >= 8) {
7073 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7074 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7076 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7077 .addReg(destPhi).addImm(0).addReg(scratch));
7078 } else if (isThumb2) {
7079 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7080 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7082 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7083 .addReg(scratch).addReg(destPhi)
7086 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7087 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7090 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7091 .addReg(scratch).addReg(destPhi)
7092 .addReg(0).addImm(UnitSize));
7095 // Decrement loop variable by UnitSize.
7096 MachineInstrBuilder MIB = BuildMI(BB, dl,
7097 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7098 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7099 MIB->getOperand(5).setReg(ARM::CPSR);
7100 MIB->getOperand(5).setIsDef(true);
7102 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7103 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7105 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7106 BB->addSuccessor(loopMBB);
7107 BB->addSuccessor(exitMBB);
7109 // Add epilogue to handle BytesLeft.
7111 MachineInstr *StartOfExit = exitMBB->begin();
7112 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7113 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7115 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7116 // [destOut] = STRB_POST(scratch, destLoop, 1)
7117 unsigned srcIn = srcLoop;
7118 unsigned destIn = destLoop;
7119 for (unsigned i = 0; i < BytesLeft; i++) {
7120 unsigned scratch = MRI.createVirtualRegister(TRC);
7121 unsigned srcOut = MRI.createVirtualRegister(TRC);
7122 unsigned destOut = MRI.createVirtualRegister(TRC);
7124 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7125 TII->get(ldrOpc),scratch)
7126 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7128 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7129 .addReg(scratch).addReg(destIn)
7132 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7133 TII->get(ldrOpc),scratch)
7134 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7136 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7137 .addReg(scratch).addReg(destIn)
7138 .addReg(0).addImm(1));
7144 MI->eraseFromParent(); // The instruction is gone now.
7149 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7150 MachineBasicBlock *BB) const {
7151 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7152 DebugLoc dl = MI->getDebugLoc();
7153 bool isThumb2 = Subtarget->isThumb2();
7154 switch (MI->getOpcode()) {
7157 llvm_unreachable("Unexpected instr type to insert");
7159 // The Thumb2 pre-indexed stores have the same MI operands, they just
7160 // define them differently in the .td files from the isel patterns, so
7161 // they need pseudos.
7162 case ARM::t2STR_preidx:
7163 MI->setDesc(TII->get(ARM::t2STR_PRE));
7165 case ARM::t2STRB_preidx:
7166 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7168 case ARM::t2STRH_preidx:
7169 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7172 case ARM::STRi_preidx:
7173 case ARM::STRBi_preidx: {
7174 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7175 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7176 // Decode the offset.
7177 unsigned Offset = MI->getOperand(4).getImm();
7178 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7179 Offset = ARM_AM::getAM2Offset(Offset);
7183 MachineMemOperand *MMO = *MI->memoperands_begin();
7184 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7185 .addOperand(MI->getOperand(0)) // Rn_wb
7186 .addOperand(MI->getOperand(1)) // Rt
7187 .addOperand(MI->getOperand(2)) // Rn
7188 .addImm(Offset) // offset (skip GPR==zero_reg)
7189 .addOperand(MI->getOperand(5)) // pred
7190 .addOperand(MI->getOperand(6))
7191 .addMemOperand(MMO);
7192 MI->eraseFromParent();
7195 case ARM::STRr_preidx:
7196 case ARM::STRBr_preidx:
7197 case ARM::STRH_preidx: {
7199 switch (MI->getOpcode()) {
7200 default: llvm_unreachable("unexpected opcode!");
7201 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7202 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7203 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7205 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7206 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7207 MIB.addOperand(MI->getOperand(i));
7208 MI->eraseFromParent();
7211 case ARM::ATOMIC_LOAD_ADD_I8:
7212 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7213 case ARM::ATOMIC_LOAD_ADD_I16:
7214 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7215 case ARM::ATOMIC_LOAD_ADD_I32:
7216 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7218 case ARM::ATOMIC_LOAD_AND_I8:
7219 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7220 case ARM::ATOMIC_LOAD_AND_I16:
7221 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7222 case ARM::ATOMIC_LOAD_AND_I32:
7223 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7225 case ARM::ATOMIC_LOAD_OR_I8:
7226 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7227 case ARM::ATOMIC_LOAD_OR_I16:
7228 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7229 case ARM::ATOMIC_LOAD_OR_I32:
7230 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7232 case ARM::ATOMIC_LOAD_XOR_I8:
7233 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7234 case ARM::ATOMIC_LOAD_XOR_I16:
7235 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7236 case ARM::ATOMIC_LOAD_XOR_I32:
7237 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7239 case ARM::ATOMIC_LOAD_NAND_I8:
7240 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7241 case ARM::ATOMIC_LOAD_NAND_I16:
7242 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7243 case ARM::ATOMIC_LOAD_NAND_I32:
7244 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7246 case ARM::ATOMIC_LOAD_SUB_I8:
7247 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7248 case ARM::ATOMIC_LOAD_SUB_I16:
7249 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7250 case ARM::ATOMIC_LOAD_SUB_I32:
7251 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7253 case ARM::ATOMIC_LOAD_MIN_I8:
7254 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7255 case ARM::ATOMIC_LOAD_MIN_I16:
7256 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7257 case ARM::ATOMIC_LOAD_MIN_I32:
7258 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7260 case ARM::ATOMIC_LOAD_MAX_I8:
7261 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7262 case ARM::ATOMIC_LOAD_MAX_I16:
7263 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7264 case ARM::ATOMIC_LOAD_MAX_I32:
7265 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7267 case ARM::ATOMIC_LOAD_UMIN_I8:
7268 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7269 case ARM::ATOMIC_LOAD_UMIN_I16:
7270 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7271 case ARM::ATOMIC_LOAD_UMIN_I32:
7272 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7274 case ARM::ATOMIC_LOAD_UMAX_I8:
7275 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7276 case ARM::ATOMIC_LOAD_UMAX_I16:
7277 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7278 case ARM::ATOMIC_LOAD_UMAX_I32:
7279 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7281 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7282 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7283 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7285 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7286 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7287 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7290 case ARM::ATOMADD6432:
7291 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7292 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7293 /*NeedsCarry*/ true);
7294 case ARM::ATOMSUB6432:
7295 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7296 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7297 /*NeedsCarry*/ true);
7298 case ARM::ATOMOR6432:
7299 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7300 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7301 case ARM::ATOMXOR6432:
7302 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7303 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7304 case ARM::ATOMAND6432:
7305 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7306 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7307 case ARM::ATOMSWAP6432:
7308 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7309 case ARM::ATOMCMPXCHG6432:
7310 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7311 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7312 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7313 case ARM::ATOMMIN6432:
7314 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7315 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7316 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7317 /*IsMinMax*/ true, ARMCC::LT);
7318 case ARM::ATOMMAX6432:
7319 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7320 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7321 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7322 /*IsMinMax*/ true, ARMCC::GE);
7323 case ARM::ATOMUMIN6432:
7324 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7325 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7326 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7327 /*IsMinMax*/ true, ARMCC::LO);
7328 case ARM::ATOMUMAX6432:
7329 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7330 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7331 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7332 /*IsMinMax*/ true, ARMCC::HS);
7334 case ARM::tMOVCCr_pseudo: {
7335 // To "insert" a SELECT_CC instruction, we actually have to insert the
7336 // diamond control-flow pattern. The incoming instruction knows the
7337 // destination vreg to set, the condition code register to branch on, the
7338 // true/false values to select between, and a branch opcode to use.
7339 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7340 MachineFunction::iterator It = BB;
7346 // cmpTY ccX, r1, r2
7348 // fallthrough --> copy0MBB
7349 MachineBasicBlock *thisMBB = BB;
7350 MachineFunction *F = BB->getParent();
7351 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7352 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7353 F->insert(It, copy0MBB);
7354 F->insert(It, sinkMBB);
7356 // Transfer the remainder of BB and its successor edges to sinkMBB.
7357 sinkMBB->splice(sinkMBB->begin(), BB,
7358 llvm::next(MachineBasicBlock::iterator(MI)),
7360 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7362 BB->addSuccessor(copy0MBB);
7363 BB->addSuccessor(sinkMBB);
7365 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7366 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7369 // %FalseValue = ...
7370 // # fallthrough to sinkMBB
7373 // Update machine-CFG edges
7374 BB->addSuccessor(sinkMBB);
7377 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7380 BuildMI(*BB, BB->begin(), dl,
7381 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7382 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7383 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7385 MI->eraseFromParent(); // The pseudo instruction is gone now.
7390 case ARM::BCCZi64: {
7391 // If there is an unconditional branch to the other successor, remove it.
7392 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7394 // Compare both parts that make up the double comparison separately for
7396 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7398 unsigned LHS1 = MI->getOperand(1).getReg();
7399 unsigned LHS2 = MI->getOperand(2).getReg();
7401 AddDefaultPred(BuildMI(BB, dl,
7402 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7403 .addReg(LHS1).addImm(0));
7404 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7405 .addReg(LHS2).addImm(0)
7406 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7408 unsigned RHS1 = MI->getOperand(3).getReg();
7409 unsigned RHS2 = MI->getOperand(4).getReg();
7410 AddDefaultPred(BuildMI(BB, dl,
7411 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7412 .addReg(LHS1).addReg(RHS1));
7413 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7414 .addReg(LHS2).addReg(RHS2)
7415 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7418 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7419 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7420 if (MI->getOperand(0).getImm() == ARMCC::NE)
7421 std::swap(destMBB, exitMBB);
7423 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7424 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7426 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7428 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7430 MI->eraseFromParent(); // The pseudo instruction is gone now.
7434 case ARM::Int_eh_sjlj_setjmp:
7435 case ARM::Int_eh_sjlj_setjmp_nofp:
7436 case ARM::tInt_eh_sjlj_setjmp:
7437 case ARM::t2Int_eh_sjlj_setjmp:
7438 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7439 EmitSjLjDispatchBlock(MI, BB);
7444 // To insert an ABS instruction, we have to insert the
7445 // diamond control-flow pattern. The incoming instruction knows the
7446 // source vreg to test against 0, the destination vreg to set,
7447 // the condition code register to branch on, the
7448 // true/false values to select between, and a branch opcode to use.
7453 // BCC (branch to SinkBB if V0 >= 0)
7454 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7455 // SinkBB: V1 = PHI(V2, V3)
7456 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7457 MachineFunction::iterator BBI = BB;
7459 MachineFunction *Fn = BB->getParent();
7460 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7461 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7462 Fn->insert(BBI, RSBBB);
7463 Fn->insert(BBI, SinkBB);
7465 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7466 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7467 bool isThumb2 = Subtarget->isThumb2();
7468 MachineRegisterInfo &MRI = Fn->getRegInfo();
7469 // In Thumb mode S must not be specified if source register is the SP or
7470 // PC and if destination register is the SP, so restrict register class
7471 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7472 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7473 (const TargetRegisterClass*)&ARM::GPRRegClass);
7475 // Transfer the remainder of BB and its successor edges to sinkMBB.
7476 SinkBB->splice(SinkBB->begin(), BB,
7477 llvm::next(MachineBasicBlock::iterator(MI)),
7479 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7481 BB->addSuccessor(RSBBB);
7482 BB->addSuccessor(SinkBB);
7484 // fall through to SinkMBB
7485 RSBBB->addSuccessor(SinkBB);
7487 // insert a cmp at the end of BB
7488 AddDefaultPred(BuildMI(BB, dl,
7489 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7490 .addReg(ABSSrcReg).addImm(0));
7492 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7494 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7495 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7497 // insert rsbri in RSBBB
7498 // Note: BCC and rsbri will be converted into predicated rsbmi
7499 // by if-conversion pass
7500 BuildMI(*RSBBB, RSBBB->begin(), dl,
7501 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7502 .addReg(ABSSrcReg, RegState::Kill)
7503 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7505 // insert PHI in SinkBB,
7506 // reuse ABSDstReg to not change uses of ABS instruction
7507 BuildMI(*SinkBB, SinkBB->begin(), dl,
7508 TII->get(ARM::PHI), ABSDstReg)
7509 .addReg(NewRsbDstReg).addMBB(RSBBB)
7510 .addReg(ABSSrcReg).addMBB(BB);
7512 // remove ABS instruction
7513 MI->eraseFromParent();
7515 // return last added BB
7518 case ARM::COPY_STRUCT_BYVAL_I32:
7520 return EmitStructByval(MI, BB);
7524 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7525 SDNode *Node) const {
7526 if (!MI->hasPostISelHook()) {
7527 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7528 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7532 const MCInstrDesc *MCID = &MI->getDesc();
7533 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7534 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7535 // operand is still set to noreg. If needed, set the optional operand's
7536 // register to CPSR, and remove the redundant implicit def.
7538 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7540 // Rename pseudo opcodes.
7541 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7543 const ARMBaseInstrInfo *TII =
7544 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7545 MCID = &TII->get(NewOpc);
7547 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7548 "converted opcode should be the same except for cc_out");
7552 // Add the optional cc_out operand
7553 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7555 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7557 // Any ARM instruction that sets the 's' bit should specify an optional
7558 // "cc_out" operand in the last operand position.
7559 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7560 assert(!NewOpc && "Optional cc_out operand required");
7563 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7564 // since we already have an optional CPSR def.
7565 bool definesCPSR = false;
7566 bool deadCPSR = false;
7567 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7569 const MachineOperand &MO = MI->getOperand(i);
7570 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7574 MI->RemoveOperand(i);
7579 assert(!NewOpc && "Optional cc_out operand required");
7582 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7584 assert(!MI->getOperand(ccOutIdx).getReg() &&
7585 "expect uninitialized optional cc_out operand");
7589 // If this instruction was defined with an optional CPSR def and its dag node
7590 // had a live implicit CPSR def, then activate the optional CPSR def.
7591 MachineOperand &MO = MI->getOperand(ccOutIdx);
7592 MO.setReg(ARM::CPSR);
7596 //===----------------------------------------------------------------------===//
7597 // ARM Optimization Hooks
7598 //===----------------------------------------------------------------------===//
7600 // Helper function that checks if N is a null or all ones constant.
7601 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7602 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7605 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7608 // Return true if N is conditionally 0 or all ones.
7609 // Detects these expressions where cc is an i1 value:
7611 // (select cc 0, y) [AllOnes=0]
7612 // (select cc y, 0) [AllOnes=0]
7613 // (zext cc) [AllOnes=0]
7614 // (sext cc) [AllOnes=0/1]
7615 // (select cc -1, y) [AllOnes=1]
7616 // (select cc y, -1) [AllOnes=1]
7618 // Invert is set when N is the null/all ones constant when CC is false.
7619 // OtherOp is set to the alternative value of N.
7620 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7621 SDValue &CC, bool &Invert,
7623 SelectionDAG &DAG) {
7624 switch (N->getOpcode()) {
7625 default: return false;
7627 CC = N->getOperand(0);
7628 SDValue N1 = N->getOperand(1);
7629 SDValue N2 = N->getOperand(2);
7630 if (isZeroOrAllOnes(N1, AllOnes)) {
7635 if (isZeroOrAllOnes(N2, AllOnes)) {
7642 case ISD::ZERO_EXTEND:
7643 // (zext cc) can never be the all ones value.
7647 case ISD::SIGN_EXTEND: {
7648 EVT VT = N->getValueType(0);
7649 CC = N->getOperand(0);
7650 if (CC.getValueType() != MVT::i1)
7654 // When looking for an AllOnes constant, N is an sext, and the 'other'
7656 OtherOp = DAG.getConstant(0, VT);
7657 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7658 // When looking for a 0 constant, N can be zext or sext.
7659 OtherOp = DAG.getConstant(1, VT);
7661 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7667 // Combine a constant select operand into its use:
7669 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7670 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7671 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7672 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7673 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7675 // The transform is rejected if the select doesn't have a constant operand that
7676 // is null, or all ones when AllOnes is set.
7678 // Also recognize sext/zext from i1:
7680 // (add (zext cc), x) -> (select cc (add x, 1), x)
7681 // (add (sext cc), x) -> (select cc (add x, -1), x)
7683 // These transformations eventually create predicated instructions.
7685 // @param N The node to transform.
7686 // @param Slct The N operand that is a select.
7687 // @param OtherOp The other N operand (x above).
7688 // @param DCI Context.
7689 // @param AllOnes Require the select constant to be all ones instead of null.
7690 // @returns The new node, or SDValue() on failure.
7692 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7693 TargetLowering::DAGCombinerInfo &DCI,
7694 bool AllOnes = false) {
7695 SelectionDAG &DAG = DCI.DAG;
7696 EVT VT = N->getValueType(0);
7697 SDValue NonConstantVal;
7700 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7701 NonConstantVal, DAG))
7704 // Slct is now know to be the desired identity constant when CC is true.
7705 SDValue TrueVal = OtherOp;
7706 SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7707 OtherOp, NonConstantVal);
7708 // Unless SwapSelectOps says CC should be false.
7710 std::swap(TrueVal, FalseVal);
7712 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7713 CCOp, TrueVal, FalseVal);
7716 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7718 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7719 TargetLowering::DAGCombinerInfo &DCI) {
7720 SDValue N0 = N->getOperand(0);
7721 SDValue N1 = N->getOperand(1);
7722 if (N0.getNode()->hasOneUse()) {
7723 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7724 if (Result.getNode())
7727 if (N1.getNode()->hasOneUse()) {
7728 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7729 if (Result.getNode())
7735 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7736 // (only after legalization).
7737 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7738 TargetLowering::DAGCombinerInfo &DCI,
7739 const ARMSubtarget *Subtarget) {
7741 // Only perform optimization if after legalize, and if NEON is available. We
7742 // also expected both operands to be BUILD_VECTORs.
7743 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7744 || N0.getOpcode() != ISD::BUILD_VECTOR
7745 || N1.getOpcode() != ISD::BUILD_VECTOR)
7748 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7749 EVT VT = N->getValueType(0);
7750 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7753 // Check that the vector operands are of the right form.
7754 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7755 // operands, where N is the size of the formed vector.
7756 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7757 // index such that we have a pair wise add pattern.
7759 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7760 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7762 SDValue Vec = N0->getOperand(0)->getOperand(0);
7763 SDNode *V = Vec.getNode();
7764 unsigned nextIndex = 0;
7766 // For each operands to the ADD which are BUILD_VECTORs,
7767 // check to see if each of their operands are an EXTRACT_VECTOR with
7768 // the same vector and appropriate index.
7769 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7770 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7771 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7773 SDValue ExtVec0 = N0->getOperand(i);
7774 SDValue ExtVec1 = N1->getOperand(i);
7776 // First operand is the vector, verify its the same.
7777 if (V != ExtVec0->getOperand(0).getNode() ||
7778 V != ExtVec1->getOperand(0).getNode())
7781 // Second is the constant, verify its correct.
7782 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7783 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7785 // For the constant, we want to see all the even or all the odd.
7786 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7787 || C1->getZExtValue() != nextIndex+1)
7796 // Create VPADDL node.
7797 SelectionDAG &DAG = DCI.DAG;
7798 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7800 // Build operand list.
7801 SmallVector<SDValue, 8> Ops;
7802 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7803 TLI.getPointerTy()));
7805 // Input is the vector.
7808 // Get widened type and narrowed type.
7810 unsigned numElem = VT.getVectorNumElements();
7811 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7812 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7813 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7814 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7816 llvm_unreachable("Invalid vector element type for padd optimization.");
7819 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7820 widenType, &Ops[0], Ops.size());
7821 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7824 static SDValue findMUL_LOHI(SDValue V) {
7825 if (V->getOpcode() == ISD::UMUL_LOHI ||
7826 V->getOpcode() == ISD::SMUL_LOHI)
7831 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7832 TargetLowering::DAGCombinerInfo &DCI,
7833 const ARMSubtarget *Subtarget) {
7835 if (Subtarget->isThumb1Only()) return SDValue();
7837 // Only perform the checks after legalize when the pattern is available.
7838 if (DCI.isBeforeLegalize()) return SDValue();
7840 // Look for multiply add opportunities.
7841 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7842 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7843 // a glue link from the first add to the second add.
7844 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7845 // a S/UMLAL instruction.
7848 // \ / \ [no multiline comment]
7854 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7855 SDValue AddcOp0 = AddcNode->getOperand(0);
7856 SDValue AddcOp1 = AddcNode->getOperand(1);
7858 // Check if the two operands are from the same mul_lohi node.
7859 if (AddcOp0.getNode() == AddcOp1.getNode())
7862 assert(AddcNode->getNumValues() == 2 &&
7863 AddcNode->getValueType(0) == MVT::i32 &&
7864 AddcNode->getValueType(1) == MVT::Glue &&
7865 "Expect ADDC with two result values: i32, glue");
7867 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7868 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7869 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7870 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7871 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7874 // Look for the glued ADDE.
7875 SDNode* AddeNode = AddcNode->getGluedUser();
7876 if (AddeNode == NULL)
7879 // Make sure it is really an ADDE.
7880 if (AddeNode->getOpcode() != ISD::ADDE)
7883 assert(AddeNode->getNumOperands() == 3 &&
7884 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7885 "ADDE node has the wrong inputs");
7887 // Check for the triangle shape.
7888 SDValue AddeOp0 = AddeNode->getOperand(0);
7889 SDValue AddeOp1 = AddeNode->getOperand(1);
7891 // Make sure that the ADDE operands are not coming from the same node.
7892 if (AddeOp0.getNode() == AddeOp1.getNode())
7895 // Find the MUL_LOHI node walking up ADDE's operands.
7896 bool IsLeftOperandMUL = false;
7897 SDValue MULOp = findMUL_LOHI(AddeOp0);
7898 if (MULOp == SDValue())
7899 MULOp = findMUL_LOHI(AddeOp1);
7901 IsLeftOperandMUL = true;
7902 if (MULOp == SDValue())
7905 // Figure out the right opcode.
7906 unsigned Opc = MULOp->getOpcode();
7907 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7909 // Figure out the high and low input values to the MLAL node.
7910 SDValue* HiMul = &MULOp;
7911 SDValue* HiAdd = NULL;
7912 SDValue* LoMul = NULL;
7913 SDValue* LowAdd = NULL;
7915 if (IsLeftOperandMUL)
7921 if (AddcOp0->getOpcode() == Opc) {
7925 if (AddcOp1->getOpcode() == Opc) {
7933 if (LoMul->getNode() != HiMul->getNode())
7936 // Create the merged node.
7937 SelectionDAG &DAG = DCI.DAG;
7939 // Build operand list.
7940 SmallVector<SDValue, 8> Ops;
7941 Ops.push_back(LoMul->getOperand(0));
7942 Ops.push_back(LoMul->getOperand(1));
7943 Ops.push_back(*LowAdd);
7944 Ops.push_back(*HiAdd);
7946 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7947 DAG.getVTList(MVT::i32, MVT::i32),
7948 &Ops[0], Ops.size());
7950 // Replace the ADDs' nodes uses by the MLA node's values.
7951 SDValue HiMLALResult(MLALNode.getNode(), 1);
7952 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7954 SDValue LoMLALResult(MLALNode.getNode(), 0);
7955 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7957 // Return original node to notify the driver to stop replacing.
7958 SDValue resNode(AddcNode, 0);
7962 /// PerformADDCCombine - Target-specific dag combine transform from
7963 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7964 static SDValue PerformADDCCombine(SDNode *N,
7965 TargetLowering::DAGCombinerInfo &DCI,
7966 const ARMSubtarget *Subtarget) {
7968 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7972 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7973 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7974 /// called with the default operands, and if that fails, with commuted
7976 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7977 TargetLowering::DAGCombinerInfo &DCI,
7978 const ARMSubtarget *Subtarget){
7980 // Attempt to create vpaddl for this add.
7981 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7982 if (Result.getNode())
7985 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7986 if (N0.getNode()->hasOneUse()) {
7987 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7988 if (Result.getNode()) return Result;
7993 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7995 static SDValue PerformADDCombine(SDNode *N,
7996 TargetLowering::DAGCombinerInfo &DCI,
7997 const ARMSubtarget *Subtarget) {
7998 SDValue N0 = N->getOperand(0);
7999 SDValue N1 = N->getOperand(1);
8001 // First try with the default operand order.
8002 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8003 if (Result.getNode())
8006 // If that didn't work, try again with the operands commuted.
8007 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8010 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8012 static SDValue PerformSUBCombine(SDNode *N,
8013 TargetLowering::DAGCombinerInfo &DCI) {
8014 SDValue N0 = N->getOperand(0);
8015 SDValue N1 = N->getOperand(1);
8017 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8018 if (N1.getNode()->hasOneUse()) {
8019 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8020 if (Result.getNode()) return Result;
8026 /// PerformVMULCombine
8027 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8028 /// special multiplier accumulator forwarding.
8034 static SDValue PerformVMULCombine(SDNode *N,
8035 TargetLowering::DAGCombinerInfo &DCI,
8036 const ARMSubtarget *Subtarget) {
8037 if (!Subtarget->hasVMLxForwarding())
8040 SelectionDAG &DAG = DCI.DAG;
8041 SDValue N0 = N->getOperand(0);
8042 SDValue N1 = N->getOperand(1);
8043 unsigned Opcode = N0.getOpcode();
8044 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8045 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8046 Opcode = N1.getOpcode();
8047 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8048 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8053 EVT VT = N->getValueType(0);
8054 DebugLoc DL = N->getDebugLoc();
8055 SDValue N00 = N0->getOperand(0);
8056 SDValue N01 = N0->getOperand(1);
8057 return DAG.getNode(Opcode, DL, VT,
8058 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8059 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8062 static SDValue PerformMULCombine(SDNode *N,
8063 TargetLowering::DAGCombinerInfo &DCI,
8064 const ARMSubtarget *Subtarget) {
8065 SelectionDAG &DAG = DCI.DAG;
8067 if (Subtarget->isThumb1Only())
8070 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8073 EVT VT = N->getValueType(0);
8074 if (VT.is64BitVector() || VT.is128BitVector())
8075 return PerformVMULCombine(N, DCI, Subtarget);
8079 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8083 int64_t MulAmt = C->getSExtValue();
8084 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
8086 ShiftAmt = ShiftAmt & (32 - 1);
8087 SDValue V = N->getOperand(0);
8088 DebugLoc DL = N->getDebugLoc();
8091 MulAmt >>= ShiftAmt;
8094 if (isPowerOf2_32(MulAmt - 1)) {
8095 // (mul x, 2^N + 1) => (add (shl x, N), x)
8096 Res = DAG.getNode(ISD::ADD, DL, VT,
8098 DAG.getNode(ISD::SHL, DL, VT,
8100 DAG.getConstant(Log2_32(MulAmt - 1),
8102 } else if (isPowerOf2_32(MulAmt + 1)) {
8103 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8104 Res = DAG.getNode(ISD::SUB, DL, VT,
8105 DAG.getNode(ISD::SHL, DL, VT,
8107 DAG.getConstant(Log2_32(MulAmt + 1),
8113 uint64_t MulAmtAbs = -MulAmt;
8114 if (isPowerOf2_32(MulAmtAbs + 1)) {
8115 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8116 Res = DAG.getNode(ISD::SUB, DL, VT,
8118 DAG.getNode(ISD::SHL, DL, VT,
8120 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8122 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8123 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8124 Res = DAG.getNode(ISD::ADD, DL, VT,
8126 DAG.getNode(ISD::SHL, DL, VT,
8128 DAG.getConstant(Log2_32(MulAmtAbs-1),
8130 Res = DAG.getNode(ISD::SUB, DL, VT,
8131 DAG.getConstant(0, MVT::i32),Res);
8138 Res = DAG.getNode(ISD::SHL, DL, VT,
8139 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8141 // Do not add new nodes to DAG combiner worklist.
8142 DCI.CombineTo(N, Res, false);
8146 static SDValue PerformANDCombine(SDNode *N,
8147 TargetLowering::DAGCombinerInfo &DCI,
8148 const ARMSubtarget *Subtarget) {
8150 // Attempt to use immediate-form VBIC
8151 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8152 DebugLoc dl = N->getDebugLoc();
8153 EVT VT = N->getValueType(0);
8154 SelectionDAG &DAG = DCI.DAG;
8156 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8159 APInt SplatBits, SplatUndef;
8160 unsigned SplatBitSize;
8163 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8164 if (SplatBitSize <= 64) {
8166 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8167 SplatUndef.getZExtValue(), SplatBitSize,
8168 DAG, VbicVT, VT.is128BitVector(),
8170 if (Val.getNode()) {
8172 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8173 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8174 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8179 if (!Subtarget->isThumb1Only()) {
8180 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8181 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8182 if (Result.getNode())
8189 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8190 static SDValue PerformORCombine(SDNode *N,
8191 TargetLowering::DAGCombinerInfo &DCI,
8192 const ARMSubtarget *Subtarget) {
8193 // Attempt to use immediate-form VORR
8194 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8195 DebugLoc dl = N->getDebugLoc();
8196 EVT VT = N->getValueType(0);
8197 SelectionDAG &DAG = DCI.DAG;
8199 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8202 APInt SplatBits, SplatUndef;
8203 unsigned SplatBitSize;
8205 if (BVN && Subtarget->hasNEON() &&
8206 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8207 if (SplatBitSize <= 64) {
8209 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8210 SplatUndef.getZExtValue(), SplatBitSize,
8211 DAG, VorrVT, VT.is128BitVector(),
8213 if (Val.getNode()) {
8215 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8216 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8217 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8222 if (!Subtarget->isThumb1Only()) {
8223 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8224 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8225 if (Result.getNode())
8229 // The code below optimizes (or (and X, Y), Z).
8230 // The AND operand needs to have a single user to make these optimizations
8232 SDValue N0 = N->getOperand(0);
8233 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8235 SDValue N1 = N->getOperand(1);
8237 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8238 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8239 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8241 unsigned SplatBitSize;
8244 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8246 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8247 HasAnyUndefs) && !HasAnyUndefs) {
8248 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8250 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8251 HasAnyUndefs) && !HasAnyUndefs &&
8252 SplatBits0 == ~SplatBits1) {
8253 // Canonicalize the vector type to make instruction selection simpler.
8254 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8255 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8256 N0->getOperand(1), N0->getOperand(0),
8258 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8263 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8266 // BFI is only available on V6T2+
8267 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8270 DebugLoc DL = N->getDebugLoc();
8271 // 1) or (and A, mask), val => ARMbfi A, val, mask
8272 // iff (val & mask) == val
8274 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8275 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8276 // && mask == ~mask2
8277 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8278 // && ~mask == mask2
8279 // (i.e., copy a bitfield value into another bitfield of the same width)
8284 SDValue N00 = N0.getOperand(0);
8286 // The value and the mask need to be constants so we can verify this is
8287 // actually a bitfield set. If the mask is 0xffff, we can do better
8288 // via a movt instruction, so don't use BFI in that case.
8289 SDValue MaskOp = N0.getOperand(1);
8290 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8293 unsigned Mask = MaskC->getZExtValue();
8297 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8298 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8300 unsigned Val = N1C->getZExtValue();
8301 if ((Val & ~Mask) != Val)
8304 if (ARM::isBitFieldInvertedMask(Mask)) {
8305 Val >>= CountTrailingZeros_32(~Mask);
8307 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8308 DAG.getConstant(Val, MVT::i32),
8309 DAG.getConstant(Mask, MVT::i32));
8311 // Do not add new nodes to DAG combiner worklist.
8312 DCI.CombineTo(N, Res, false);
8315 } else if (N1.getOpcode() == ISD::AND) {
8316 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8317 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8320 unsigned Mask2 = N11C->getZExtValue();
8322 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8324 if (ARM::isBitFieldInvertedMask(Mask) &&
8326 // The pack halfword instruction works better for masks that fit it,
8327 // so use that when it's available.
8328 if (Subtarget->hasT2ExtractPack() &&
8329 (Mask == 0xffff || Mask == 0xffff0000))
8332 unsigned amt = CountTrailingZeros_32(Mask2);
8333 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8334 DAG.getConstant(amt, MVT::i32));
8335 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8336 DAG.getConstant(Mask, MVT::i32));
8337 // Do not add new nodes to DAG combiner worklist.
8338 DCI.CombineTo(N, Res, false);
8340 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8342 // The pack halfword instruction works better for masks that fit it,
8343 // so use that when it's available.
8344 if (Subtarget->hasT2ExtractPack() &&
8345 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8348 unsigned lsb = CountTrailingZeros_32(Mask);
8349 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8350 DAG.getConstant(lsb, MVT::i32));
8351 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8352 DAG.getConstant(Mask2, MVT::i32));
8353 // Do not add new nodes to DAG combiner worklist.
8354 DCI.CombineTo(N, Res, false);
8359 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8360 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8361 ARM::isBitFieldInvertedMask(~Mask)) {
8362 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8363 // where lsb(mask) == #shamt and masked bits of B are known zero.
8364 SDValue ShAmt = N00.getOperand(1);
8365 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8366 unsigned LSB = CountTrailingZeros_32(Mask);
8370 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8371 DAG.getConstant(~Mask, MVT::i32));
8373 // Do not add new nodes to DAG combiner worklist.
8374 DCI.CombineTo(N, Res, false);
8380 static SDValue PerformXORCombine(SDNode *N,
8381 TargetLowering::DAGCombinerInfo &DCI,
8382 const ARMSubtarget *Subtarget) {
8383 EVT VT = N->getValueType(0);
8384 SelectionDAG &DAG = DCI.DAG;
8386 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8389 if (!Subtarget->isThumb1Only()) {
8390 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8391 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8392 if (Result.getNode())
8399 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8400 /// the bits being cleared by the AND are not demanded by the BFI.
8401 static SDValue PerformBFICombine(SDNode *N,
8402 TargetLowering::DAGCombinerInfo &DCI) {
8403 SDValue N1 = N->getOperand(1);
8404 if (N1.getOpcode() == ISD::AND) {
8405 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8408 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8409 unsigned LSB = CountTrailingZeros_32(~InvMask);
8410 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8411 unsigned Mask = (1 << Width)-1;
8412 unsigned Mask2 = N11C->getZExtValue();
8413 if ((Mask & (~Mask2)) == 0)
8414 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8415 N->getOperand(0), N1.getOperand(0),
8421 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8422 /// ARMISD::VMOVRRD.
8423 static SDValue PerformVMOVRRDCombine(SDNode *N,
8424 TargetLowering::DAGCombinerInfo &DCI) {
8425 // vmovrrd(vmovdrr x, y) -> x,y
8426 SDValue InDouble = N->getOperand(0);
8427 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8428 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8430 // vmovrrd(load f64) -> (load i32), (load i32)
8431 SDNode *InNode = InDouble.getNode();
8432 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8433 InNode->getValueType(0) == MVT::f64 &&
8434 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8435 !cast<LoadSDNode>(InNode)->isVolatile()) {
8436 // TODO: Should this be done for non-FrameIndex operands?
8437 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8439 SelectionDAG &DAG = DCI.DAG;
8440 DebugLoc DL = LD->getDebugLoc();
8441 SDValue BasePtr = LD->getBasePtr();
8442 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8443 LD->getPointerInfo(), LD->isVolatile(),
8444 LD->isNonTemporal(), LD->isInvariant(),
8445 LD->getAlignment());
8447 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8448 DAG.getConstant(4, MVT::i32));
8449 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8450 LD->getPointerInfo(), LD->isVolatile(),
8451 LD->isNonTemporal(), LD->isInvariant(),
8452 std::min(4U, LD->getAlignment() / 2));
8454 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8455 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8456 DCI.RemoveFromWorklist(LD);
8464 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8465 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8466 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8467 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8468 SDValue Op0 = N->getOperand(0);
8469 SDValue Op1 = N->getOperand(1);
8470 if (Op0.getOpcode() == ISD::BITCAST)
8471 Op0 = Op0.getOperand(0);
8472 if (Op1.getOpcode() == ISD::BITCAST)
8473 Op1 = Op1.getOperand(0);
8474 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8475 Op0.getNode() == Op1.getNode() &&
8476 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8477 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8478 N->getValueType(0), Op0.getOperand(0));
8482 /// PerformSTORECombine - Target-specific dag combine xforms for
8484 static SDValue PerformSTORECombine(SDNode *N,
8485 TargetLowering::DAGCombinerInfo &DCI) {
8486 StoreSDNode *St = cast<StoreSDNode>(N);
8487 if (St->isVolatile())
8490 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8491 // pack all of the elements in one place. Next, store to memory in fewer
8493 SDValue StVal = St->getValue();
8494 EVT VT = StVal.getValueType();
8495 if (St->isTruncatingStore() && VT.isVector()) {
8496 SelectionDAG &DAG = DCI.DAG;
8497 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8498 EVT StVT = St->getMemoryVT();
8499 unsigned NumElems = VT.getVectorNumElements();
8500 assert(StVT != VT && "Cannot truncate to the same type");
8501 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8502 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8504 // From, To sizes and ElemCount must be pow of two
8505 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8507 // We are going to use the original vector elt for storing.
8508 // Accumulated smaller vector elements must be a multiple of the store size.
8509 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8511 unsigned SizeRatio = FromEltSz / ToEltSz;
8512 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8514 // Create a type on which we perform the shuffle.
8515 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8516 NumElems*SizeRatio);
8517 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8519 DebugLoc DL = St->getDebugLoc();
8520 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8521 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8522 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8524 // Can't shuffle using an illegal type.
8525 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8527 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8528 DAG.getUNDEF(WideVec.getValueType()),
8530 // At this point all of the data is stored at the bottom of the
8531 // register. We now need to save it to mem.
8533 // Find the largest store unit
8534 MVT StoreType = MVT::i8;
8535 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8536 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8537 MVT Tp = (MVT::SimpleValueType)tp;
8538 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8541 // Didn't find a legal store type.
8542 if (!TLI.isTypeLegal(StoreType))
8545 // Bitcast the original vector into a vector of store-size units
8546 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8547 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8548 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8549 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8550 SmallVector<SDValue, 8> Chains;
8551 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8552 TLI.getPointerTy());
8553 SDValue BasePtr = St->getBasePtr();
8555 // Perform one or more big stores into memory.
8556 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8557 for (unsigned I = 0; I < E; I++) {
8558 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8559 StoreType, ShuffWide,
8560 DAG.getIntPtrConstant(I));
8561 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8562 St->getPointerInfo(), St->isVolatile(),
8563 St->isNonTemporal(), St->getAlignment());
8564 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8566 Chains.push_back(Ch);
8568 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8572 if (!ISD::isNormalStore(St))
8575 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8576 // ARM stores of arguments in the same cache line.
8577 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8578 StVal.getNode()->hasOneUse()) {
8579 SelectionDAG &DAG = DCI.DAG;
8580 DebugLoc DL = St->getDebugLoc();
8581 SDValue BasePtr = St->getBasePtr();
8582 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8583 StVal.getNode()->getOperand(0), BasePtr,
8584 St->getPointerInfo(), St->isVolatile(),
8585 St->isNonTemporal(), St->getAlignment());
8587 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8588 DAG.getConstant(4, MVT::i32));
8589 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8590 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8591 St->isNonTemporal(),
8592 std::min(4U, St->getAlignment() / 2));
8595 if (StVal.getValueType() != MVT::i64 ||
8596 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8599 // Bitcast an i64 store extracted from a vector to f64.
8600 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8601 SelectionDAG &DAG = DCI.DAG;
8602 DebugLoc dl = StVal.getDebugLoc();
8603 SDValue IntVec = StVal.getOperand(0);
8604 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8605 IntVec.getValueType().getVectorNumElements());
8606 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8607 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8608 Vec, StVal.getOperand(1));
8609 dl = N->getDebugLoc();
8610 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8611 // Make the DAGCombiner fold the bitcasts.
8612 DCI.AddToWorklist(Vec.getNode());
8613 DCI.AddToWorklist(ExtElt.getNode());
8614 DCI.AddToWorklist(V.getNode());
8615 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8616 St->getPointerInfo(), St->isVolatile(),
8617 St->isNonTemporal(), St->getAlignment(),
8621 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8622 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8623 /// i64 vector to have f64 elements, since the value can then be loaded
8624 /// directly into a VFP register.
8625 static bool hasNormalLoadOperand(SDNode *N) {
8626 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8627 for (unsigned i = 0; i < NumElts; ++i) {
8628 SDNode *Elt = N->getOperand(i).getNode();
8629 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8635 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8636 /// ISD::BUILD_VECTOR.
8637 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8638 TargetLowering::DAGCombinerInfo &DCI){
8639 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8640 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8641 // into a pair of GPRs, which is fine when the value is used as a scalar,
8642 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8643 SelectionDAG &DAG = DCI.DAG;
8644 if (N->getNumOperands() == 2) {
8645 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8650 // Load i64 elements as f64 values so that type legalization does not split
8651 // them up into i32 values.
8652 EVT VT = N->getValueType(0);
8653 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8655 DebugLoc dl = N->getDebugLoc();
8656 SmallVector<SDValue, 8> Ops;
8657 unsigned NumElts = VT.getVectorNumElements();
8658 for (unsigned i = 0; i < NumElts; ++i) {
8659 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8661 // Make the DAGCombiner fold the bitcast.
8662 DCI.AddToWorklist(V.getNode());
8664 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8665 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8666 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8669 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8670 /// ISD::INSERT_VECTOR_ELT.
8671 static SDValue PerformInsertEltCombine(SDNode *N,
8672 TargetLowering::DAGCombinerInfo &DCI) {
8673 // Bitcast an i64 load inserted into a vector to f64.
8674 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8675 EVT VT = N->getValueType(0);
8676 SDNode *Elt = N->getOperand(1).getNode();
8677 if (VT.getVectorElementType() != MVT::i64 ||
8678 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8681 SelectionDAG &DAG = DCI.DAG;
8682 DebugLoc dl = N->getDebugLoc();
8683 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8684 VT.getVectorNumElements());
8685 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8686 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8687 // Make the DAGCombiner fold the bitcasts.
8688 DCI.AddToWorklist(Vec.getNode());
8689 DCI.AddToWorklist(V.getNode());
8690 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8691 Vec, V, N->getOperand(2));
8692 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8695 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8696 /// ISD::VECTOR_SHUFFLE.
8697 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8698 // The LLVM shufflevector instruction does not require the shuffle mask
8699 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8700 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8701 // operands do not match the mask length, they are extended by concatenating
8702 // them with undef vectors. That is probably the right thing for other
8703 // targets, but for NEON it is better to concatenate two double-register
8704 // size vector operands into a single quad-register size vector. Do that
8705 // transformation here:
8706 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8707 // shuffle(concat(v1, v2), undef)
8708 SDValue Op0 = N->getOperand(0);
8709 SDValue Op1 = N->getOperand(1);
8710 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8711 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8712 Op0.getNumOperands() != 2 ||
8713 Op1.getNumOperands() != 2)
8715 SDValue Concat0Op1 = Op0.getOperand(1);
8716 SDValue Concat1Op1 = Op1.getOperand(1);
8717 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8718 Concat1Op1.getOpcode() != ISD::UNDEF)
8720 // Skip the transformation if any of the types are illegal.
8721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8722 EVT VT = N->getValueType(0);
8723 if (!TLI.isTypeLegal(VT) ||
8724 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8725 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8728 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8729 Op0.getOperand(0), Op1.getOperand(0));
8730 // Translate the shuffle mask.
8731 SmallVector<int, 16> NewMask;
8732 unsigned NumElts = VT.getVectorNumElements();
8733 unsigned HalfElts = NumElts/2;
8734 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8735 for (unsigned n = 0; n < NumElts; ++n) {
8736 int MaskElt = SVN->getMaskElt(n);
8738 if (MaskElt < (int)HalfElts)
8740 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8741 NewElt = HalfElts + MaskElt - NumElts;
8742 NewMask.push_back(NewElt);
8744 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8745 DAG.getUNDEF(VT), NewMask.data());
8748 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8749 /// NEON load/store intrinsics to merge base address updates.
8750 static SDValue CombineBaseUpdate(SDNode *N,
8751 TargetLowering::DAGCombinerInfo &DCI) {
8752 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8755 SelectionDAG &DAG = DCI.DAG;
8756 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8757 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8758 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8759 SDValue Addr = N->getOperand(AddrOpIdx);
8761 // Search for a use of the address operand that is an increment.
8762 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8763 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8765 if (User->getOpcode() != ISD::ADD ||
8766 UI.getUse().getResNo() != Addr.getResNo())
8769 // Check that the add is independent of the load/store. Otherwise, folding
8770 // it would create a cycle.
8771 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8774 // Find the new opcode for the updating load/store.
8776 bool isLaneOp = false;
8777 unsigned NewOpc = 0;
8778 unsigned NumVecs = 0;
8780 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8782 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8783 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8785 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8787 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8789 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8791 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8792 NumVecs = 2; isLaneOp = true; break;
8793 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8794 NumVecs = 3; isLaneOp = true; break;
8795 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8796 NumVecs = 4; isLaneOp = true; break;
8797 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8798 NumVecs = 1; isLoad = false; break;
8799 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8800 NumVecs = 2; isLoad = false; break;
8801 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8802 NumVecs = 3; isLoad = false; break;
8803 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8804 NumVecs = 4; isLoad = false; break;
8805 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8806 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8807 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8808 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8809 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8810 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8814 switch (N->getOpcode()) {
8815 default: llvm_unreachable("unexpected opcode for Neon base update");
8816 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8817 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8818 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8822 // Find the size of memory referenced by the load/store.
8825 VecTy = N->getValueType(0);
8827 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8828 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8830 NumBytes /= VecTy.getVectorNumElements();
8832 // If the increment is a constant, it must match the memory ref size.
8833 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8834 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8835 uint64_t IncVal = CInc->getZExtValue();
8836 if (IncVal != NumBytes)
8838 } else if (NumBytes >= 3 * 16) {
8839 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8840 // separate instructions that make it harder to use a non-constant update.
8844 // Create the new updating load/store node.
8846 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8848 for (n = 0; n < NumResultVecs; ++n)
8850 Tys[n++] = MVT::i32;
8851 Tys[n] = MVT::Other;
8852 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8853 SmallVector<SDValue, 8> Ops;
8854 Ops.push_back(N->getOperand(0)); // incoming chain
8855 Ops.push_back(N->getOperand(AddrOpIdx));
8857 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8858 Ops.push_back(N->getOperand(i));
8860 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8861 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8862 Ops.data(), Ops.size(),
8863 MemInt->getMemoryVT(),
8864 MemInt->getMemOperand());
8867 std::vector<SDValue> NewResults;
8868 for (unsigned i = 0; i < NumResultVecs; ++i) {
8869 NewResults.push_back(SDValue(UpdN.getNode(), i));
8871 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8872 DCI.CombineTo(N, NewResults);
8873 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8880 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8881 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8882 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8884 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8885 SelectionDAG &DAG = DCI.DAG;
8886 EVT VT = N->getValueType(0);
8887 // vldN-dup instructions only support 64-bit vectors for N > 1.
8888 if (!VT.is64BitVector())
8891 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8892 SDNode *VLD = N->getOperand(0).getNode();
8893 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8895 unsigned NumVecs = 0;
8896 unsigned NewOpc = 0;
8897 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8898 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8900 NewOpc = ARMISD::VLD2DUP;
8901 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8903 NewOpc = ARMISD::VLD3DUP;
8904 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8906 NewOpc = ARMISD::VLD4DUP;
8911 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8912 // numbers match the load.
8913 unsigned VLDLaneNo =
8914 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8915 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8917 // Ignore uses of the chain result.
8918 if (UI.getUse().getResNo() == NumVecs)
8921 if (User->getOpcode() != ARMISD::VDUPLANE ||
8922 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8926 // Create the vldN-dup node.
8929 for (n = 0; n < NumVecs; ++n)
8931 Tys[n] = MVT::Other;
8932 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8933 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8934 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8935 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8936 Ops, 2, VLDMemInt->getMemoryVT(),
8937 VLDMemInt->getMemOperand());
8940 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8942 unsigned ResNo = UI.getUse().getResNo();
8943 // Ignore uses of the chain result.
8944 if (ResNo == NumVecs)
8947 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8950 // Now the vldN-lane intrinsic is dead except for its chain result.
8951 // Update uses of the chain.
8952 std::vector<SDValue> VLDDupResults;
8953 for (unsigned n = 0; n < NumVecs; ++n)
8954 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8955 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8956 DCI.CombineTo(VLD, VLDDupResults);
8961 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8962 /// ARMISD::VDUPLANE.
8963 static SDValue PerformVDUPLANECombine(SDNode *N,
8964 TargetLowering::DAGCombinerInfo &DCI) {
8965 SDValue Op = N->getOperand(0);
8967 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8968 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8969 if (CombineVLDDUP(N, DCI))
8970 return SDValue(N, 0);
8972 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8973 // redundant. Ignore bit_converts for now; element sizes are checked below.
8974 while (Op.getOpcode() == ISD::BITCAST)
8975 Op = Op.getOperand(0);
8976 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8979 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8980 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8981 // The canonical VMOV for a zero vector uses a 32-bit element size.
8982 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8984 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8986 EVT VT = N->getValueType(0);
8987 if (EltSize > VT.getVectorElementType().getSizeInBits())
8990 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8993 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8994 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8995 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8999 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9001 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9006 APFloat APF = C->getValueAPF();
9007 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9008 != APFloat::opOK || !isExact)
9011 c0 = (I == 0) ? cN : c0;
9012 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9019 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9020 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9021 /// when the VMUL has a constant operand that is a power of 2.
9023 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9024 /// vmul.f32 d16, d17, d16
9025 /// vcvt.s32.f32 d16, d16
9027 /// vcvt.s32.f32 d16, d16, #3
9028 static SDValue PerformVCVTCombine(SDNode *N,
9029 TargetLowering::DAGCombinerInfo &DCI,
9030 const ARMSubtarget *Subtarget) {
9031 SelectionDAG &DAG = DCI.DAG;
9032 SDValue Op = N->getOperand(0);
9034 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9035 Op.getOpcode() != ISD::FMUL)
9039 SDValue N0 = Op->getOperand(0);
9040 SDValue ConstVec = Op->getOperand(1);
9041 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9043 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9044 !isConstVecPow2(ConstVec, isSigned, C))
9047 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9048 Intrinsic::arm_neon_vcvtfp2fxu;
9049 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9051 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9052 DAG.getConstant(Log2_64(C), MVT::i32));
9055 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9056 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9057 /// when the VDIV has a constant operand that is a power of 2.
9059 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9060 /// vcvt.f32.s32 d16, d16
9061 /// vdiv.f32 d16, d17, d16
9063 /// vcvt.f32.s32 d16, d16, #3
9064 static SDValue PerformVDIVCombine(SDNode *N,
9065 TargetLowering::DAGCombinerInfo &DCI,
9066 const ARMSubtarget *Subtarget) {
9067 SelectionDAG &DAG = DCI.DAG;
9068 SDValue Op = N->getOperand(0);
9069 unsigned OpOpcode = Op.getNode()->getOpcode();
9071 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9072 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9076 SDValue ConstVec = N->getOperand(1);
9077 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9079 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9080 !isConstVecPow2(ConstVec, isSigned, C))
9083 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9084 Intrinsic::arm_neon_vcvtfxu2fp;
9085 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
9087 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9088 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
9091 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9092 /// operand of a vector shift operation, where all the elements of the
9093 /// build_vector must have the same constant integer value.
9094 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9095 // Ignore bit_converts.
9096 while (Op.getOpcode() == ISD::BITCAST)
9097 Op = Op.getOperand(0);
9098 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9099 APInt SplatBits, SplatUndef;
9100 unsigned SplatBitSize;
9102 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9103 HasAnyUndefs, ElementBits) ||
9104 SplatBitSize > ElementBits)
9106 Cnt = SplatBits.getSExtValue();
9110 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9111 /// operand of a vector shift left operation. That value must be in the range:
9112 /// 0 <= Value < ElementBits for a left shift; or
9113 /// 0 <= Value <= ElementBits for a long left shift.
9114 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9115 assert(VT.isVector() && "vector shift count is not a vector type");
9116 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9117 if (! getVShiftImm(Op, ElementBits, Cnt))
9119 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9122 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9123 /// operand of a vector shift right operation. For a shift opcode, the value
9124 /// is positive, but for an intrinsic the value count must be negative. The
9125 /// absolute value must be in the range:
9126 /// 1 <= |Value| <= ElementBits for a right shift; or
9127 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9128 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9130 assert(VT.isVector() && "vector shift count is not a vector type");
9131 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9132 if (! getVShiftImm(Op, ElementBits, Cnt))
9136 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9139 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9140 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9141 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9144 // Don't do anything for most intrinsics.
9147 // Vector shifts: check for immediate versions and lower them.
9148 // Note: This is done during DAG combining instead of DAG legalizing because
9149 // the build_vectors for 64-bit vector element shift counts are generally
9150 // not legal, and it is hard to see their values after they get legalized to
9151 // loads from a constant pool.
9152 case Intrinsic::arm_neon_vshifts:
9153 case Intrinsic::arm_neon_vshiftu:
9154 case Intrinsic::arm_neon_vshiftls:
9155 case Intrinsic::arm_neon_vshiftlu:
9156 case Intrinsic::arm_neon_vshiftn:
9157 case Intrinsic::arm_neon_vrshifts:
9158 case Intrinsic::arm_neon_vrshiftu:
9159 case Intrinsic::arm_neon_vrshiftn:
9160 case Intrinsic::arm_neon_vqshifts:
9161 case Intrinsic::arm_neon_vqshiftu:
9162 case Intrinsic::arm_neon_vqshiftsu:
9163 case Intrinsic::arm_neon_vqshiftns:
9164 case Intrinsic::arm_neon_vqshiftnu:
9165 case Intrinsic::arm_neon_vqshiftnsu:
9166 case Intrinsic::arm_neon_vqrshiftns:
9167 case Intrinsic::arm_neon_vqrshiftnu:
9168 case Intrinsic::arm_neon_vqrshiftnsu: {
9169 EVT VT = N->getOperand(1).getValueType();
9171 unsigned VShiftOpc = 0;
9174 case Intrinsic::arm_neon_vshifts:
9175 case Intrinsic::arm_neon_vshiftu:
9176 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9177 VShiftOpc = ARMISD::VSHL;
9180 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9181 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9182 ARMISD::VSHRs : ARMISD::VSHRu);
9187 case Intrinsic::arm_neon_vshiftls:
9188 case Intrinsic::arm_neon_vshiftlu:
9189 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9191 llvm_unreachable("invalid shift count for vshll intrinsic");
9193 case Intrinsic::arm_neon_vrshifts:
9194 case Intrinsic::arm_neon_vrshiftu:
9195 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9199 case Intrinsic::arm_neon_vqshifts:
9200 case Intrinsic::arm_neon_vqshiftu:
9201 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9205 case Intrinsic::arm_neon_vqshiftsu:
9206 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9208 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9210 case Intrinsic::arm_neon_vshiftn:
9211 case Intrinsic::arm_neon_vrshiftn:
9212 case Intrinsic::arm_neon_vqshiftns:
9213 case Intrinsic::arm_neon_vqshiftnu:
9214 case Intrinsic::arm_neon_vqshiftnsu:
9215 case Intrinsic::arm_neon_vqrshiftns:
9216 case Intrinsic::arm_neon_vqrshiftnu:
9217 case Intrinsic::arm_neon_vqrshiftnsu:
9218 // Narrowing shifts require an immediate right shift.
9219 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9221 llvm_unreachable("invalid shift count for narrowing vector shift "
9225 llvm_unreachable("unhandled vector shift");
9229 case Intrinsic::arm_neon_vshifts:
9230 case Intrinsic::arm_neon_vshiftu:
9231 // Opcode already set above.
9233 case Intrinsic::arm_neon_vshiftls:
9234 case Intrinsic::arm_neon_vshiftlu:
9235 if (Cnt == VT.getVectorElementType().getSizeInBits())
9236 VShiftOpc = ARMISD::VSHLLi;
9238 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9239 ARMISD::VSHLLs : ARMISD::VSHLLu);
9241 case Intrinsic::arm_neon_vshiftn:
9242 VShiftOpc = ARMISD::VSHRN; break;
9243 case Intrinsic::arm_neon_vrshifts:
9244 VShiftOpc = ARMISD::VRSHRs; break;
9245 case Intrinsic::arm_neon_vrshiftu:
9246 VShiftOpc = ARMISD::VRSHRu; break;
9247 case Intrinsic::arm_neon_vrshiftn:
9248 VShiftOpc = ARMISD::VRSHRN; break;
9249 case Intrinsic::arm_neon_vqshifts:
9250 VShiftOpc = ARMISD::VQSHLs; break;
9251 case Intrinsic::arm_neon_vqshiftu:
9252 VShiftOpc = ARMISD::VQSHLu; break;
9253 case Intrinsic::arm_neon_vqshiftsu:
9254 VShiftOpc = ARMISD::VQSHLsu; break;
9255 case Intrinsic::arm_neon_vqshiftns:
9256 VShiftOpc = ARMISD::VQSHRNs; break;
9257 case Intrinsic::arm_neon_vqshiftnu:
9258 VShiftOpc = ARMISD::VQSHRNu; break;
9259 case Intrinsic::arm_neon_vqshiftnsu:
9260 VShiftOpc = ARMISD::VQSHRNsu; break;
9261 case Intrinsic::arm_neon_vqrshiftns:
9262 VShiftOpc = ARMISD::VQRSHRNs; break;
9263 case Intrinsic::arm_neon_vqrshiftnu:
9264 VShiftOpc = ARMISD::VQRSHRNu; break;
9265 case Intrinsic::arm_neon_vqrshiftnsu:
9266 VShiftOpc = ARMISD::VQRSHRNsu; break;
9269 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9270 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9273 case Intrinsic::arm_neon_vshiftins: {
9274 EVT VT = N->getOperand(1).getValueType();
9276 unsigned VShiftOpc = 0;
9278 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9279 VShiftOpc = ARMISD::VSLI;
9280 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9281 VShiftOpc = ARMISD::VSRI;
9283 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9286 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9287 N->getOperand(1), N->getOperand(2),
9288 DAG.getConstant(Cnt, MVT::i32));
9291 case Intrinsic::arm_neon_vqrshifts:
9292 case Intrinsic::arm_neon_vqrshiftu:
9293 // No immediate versions of these to check for.
9300 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9301 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9302 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9303 /// vector element shift counts are generally not legal, and it is hard to see
9304 /// their values after they get legalized to loads from a constant pool.
9305 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9306 const ARMSubtarget *ST) {
9307 EVT VT = N->getValueType(0);
9308 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9309 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9310 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9311 SDValue N1 = N->getOperand(1);
9312 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9313 SDValue N0 = N->getOperand(0);
9314 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9315 DAG.MaskedValueIsZero(N0.getOperand(0),
9316 APInt::getHighBitsSet(32, 16)))
9317 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9321 // Nothing to be done for scalar shifts.
9322 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9323 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9326 assert(ST->hasNEON() && "unexpected vector shift");
9329 switch (N->getOpcode()) {
9330 default: llvm_unreachable("unexpected shift opcode");
9333 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9334 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9335 DAG.getConstant(Cnt, MVT::i32));
9340 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9341 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9342 ARMISD::VSHRs : ARMISD::VSHRu);
9343 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9344 DAG.getConstant(Cnt, MVT::i32));
9350 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9351 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9352 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9353 const ARMSubtarget *ST) {
9354 SDValue N0 = N->getOperand(0);
9356 // Check for sign- and zero-extensions of vector extract operations of 8-
9357 // and 16-bit vector elements. NEON supports these directly. They are
9358 // handled during DAG combining because type legalization will promote them
9359 // to 32-bit types and it is messy to recognize the operations after that.
9360 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9361 SDValue Vec = N0.getOperand(0);
9362 SDValue Lane = N0.getOperand(1);
9363 EVT VT = N->getValueType(0);
9364 EVT EltVT = N0.getValueType();
9365 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9367 if (VT == MVT::i32 &&
9368 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9369 TLI.isTypeLegal(Vec.getValueType()) &&
9370 isa<ConstantSDNode>(Lane)) {
9373 switch (N->getOpcode()) {
9374 default: llvm_unreachable("unexpected opcode");
9375 case ISD::SIGN_EXTEND:
9376 Opc = ARMISD::VGETLANEs;
9378 case ISD::ZERO_EXTEND:
9379 case ISD::ANY_EXTEND:
9380 Opc = ARMISD::VGETLANEu;
9383 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9390 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9391 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9392 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9393 const ARMSubtarget *ST) {
9394 // If the target supports NEON, try to use vmax/vmin instructions for f32
9395 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9396 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9397 // a NaN; only do the transformation when it matches that behavior.
9399 // For now only do this when using NEON for FP operations; if using VFP, it
9400 // is not obvious that the benefit outweighs the cost of switching to the
9402 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9403 N->getValueType(0) != MVT::f32)
9406 SDValue CondLHS = N->getOperand(0);
9407 SDValue CondRHS = N->getOperand(1);
9408 SDValue LHS = N->getOperand(2);
9409 SDValue RHS = N->getOperand(3);
9410 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9412 unsigned Opcode = 0;
9414 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9415 IsReversed = false; // x CC y ? x : y
9416 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9417 IsReversed = true ; // x CC y ? y : x
9431 // If LHS is NaN, an ordered comparison will be false and the result will
9432 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9433 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9434 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9435 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9437 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9438 // will return -0, so vmin can only be used for unsafe math or if one of
9439 // the operands is known to be nonzero.
9440 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9441 !DAG.getTarget().Options.UnsafeFPMath &&
9442 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9444 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9453 // If LHS is NaN, an ordered comparison will be false and the result will
9454 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9455 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9456 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9457 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9459 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9460 // will return +0, so vmax can only be used for unsafe math or if one of
9461 // the operands is known to be nonzero.
9462 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9463 !DAG.getTarget().Options.UnsafeFPMath &&
9464 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9466 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9472 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9475 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9477 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9478 SDValue Cmp = N->getOperand(4);
9479 if (Cmp.getOpcode() != ARMISD::CMPZ)
9480 // Only looking at EQ and NE cases.
9483 EVT VT = N->getValueType(0);
9484 DebugLoc dl = N->getDebugLoc();
9485 SDValue LHS = Cmp.getOperand(0);
9486 SDValue RHS = Cmp.getOperand(1);
9487 SDValue FalseVal = N->getOperand(0);
9488 SDValue TrueVal = N->getOperand(1);
9489 SDValue ARMcc = N->getOperand(2);
9490 ARMCC::CondCodes CC =
9491 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9509 /// FIXME: Turn this into a target neutral optimization?
9511 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9512 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9513 N->getOperand(3), Cmp);
9514 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9516 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9517 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9518 N->getOperand(3), NewCmp);
9521 if (Res.getNode()) {
9522 APInt KnownZero, KnownOne;
9523 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9524 // Capture demanded bits information that would be otherwise lost.
9525 if (KnownZero == 0xfffffffe)
9526 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9527 DAG.getValueType(MVT::i1));
9528 else if (KnownZero == 0xffffff00)
9529 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9530 DAG.getValueType(MVT::i8));
9531 else if (KnownZero == 0xffff0000)
9532 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9533 DAG.getValueType(MVT::i16));
9539 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9540 DAGCombinerInfo &DCI) const {
9541 switch (N->getOpcode()) {
9543 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9544 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9545 case ISD::SUB: return PerformSUBCombine(N, DCI);
9546 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9547 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9548 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9549 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9550 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9551 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9552 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9553 case ISD::STORE: return PerformSTORECombine(N, DCI);
9554 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9555 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9556 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9557 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9558 case ISD::FP_TO_SINT:
9559 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9560 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9561 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9564 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9565 case ISD::SIGN_EXTEND:
9566 case ISD::ZERO_EXTEND:
9567 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9568 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9569 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9570 case ARMISD::VLD2DUP:
9571 case ARMISD::VLD3DUP:
9572 case ARMISD::VLD4DUP:
9573 return CombineBaseUpdate(N, DCI);
9574 case ISD::INTRINSIC_VOID:
9575 case ISD::INTRINSIC_W_CHAIN:
9576 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9577 case Intrinsic::arm_neon_vld1:
9578 case Intrinsic::arm_neon_vld2:
9579 case Intrinsic::arm_neon_vld3:
9580 case Intrinsic::arm_neon_vld4:
9581 case Intrinsic::arm_neon_vld2lane:
9582 case Intrinsic::arm_neon_vld3lane:
9583 case Intrinsic::arm_neon_vld4lane:
9584 case Intrinsic::arm_neon_vst1:
9585 case Intrinsic::arm_neon_vst2:
9586 case Intrinsic::arm_neon_vst3:
9587 case Intrinsic::arm_neon_vst4:
9588 case Intrinsic::arm_neon_vst2lane:
9589 case Intrinsic::arm_neon_vst3lane:
9590 case Intrinsic::arm_neon_vst4lane:
9591 return CombineBaseUpdate(N, DCI);
9599 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9601 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9604 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9605 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9606 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9608 switch (VT.getSimpleVT().SimpleTy) {
9614 // Unaligned access can use (for example) LRDB, LRDH, LDR
9615 if (AllowsUnaligned) {
9617 *Fast = Subtarget->hasV7Ops();
9624 // For any little-endian targets with neon, we can support unaligned ld/st
9625 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9626 // A big-endian target may also explictly support unaligned accesses
9627 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9637 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9638 unsigned AlignCheck) {
9639 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9640 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9643 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9644 unsigned DstAlign, unsigned SrcAlign,
9645 bool IsMemset, bool ZeroMemset,
9647 MachineFunction &MF) const {
9648 const Function *F = MF.getFunction();
9650 // See if we can use NEON instructions for this...
9651 if ((!IsMemset || ZeroMemset) &&
9652 Subtarget->hasNEON() &&
9653 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9654 Attribute::NoImplicitFloat)) {
9657 (memOpAlign(SrcAlign, DstAlign, 16) ||
9658 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9660 } else if (Size >= 8 &&
9661 (memOpAlign(SrcAlign, DstAlign, 8) ||
9662 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9667 // Lowering to i32/i16 if the size permits.
9673 // Let the target-independent logic figure it out.
9677 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9678 if (Val.getOpcode() != ISD::LOAD)
9681 EVT VT1 = Val.getValueType();
9682 if (!VT1.isSimple() || !VT1.isInteger() ||
9683 !VT2.isSimple() || !VT2.isInteger())
9686 switch (VT1.getSimpleVT().SimpleTy) {
9691 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9698 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9703 switch (VT.getSimpleVT().SimpleTy) {
9704 default: return false;
9719 if ((V & (Scale - 1)) != 0)
9722 return V == (V & ((1LL << 5) - 1));
9725 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9726 const ARMSubtarget *Subtarget) {
9733 switch (VT.getSimpleVT().SimpleTy) {
9734 default: return false;
9739 // + imm12 or - imm8
9741 return V == (V & ((1LL << 8) - 1));
9742 return V == (V & ((1LL << 12) - 1));
9745 // Same as ARM mode. FIXME: NEON?
9746 if (!Subtarget->hasVFP2())
9751 return V == (V & ((1LL << 8) - 1));
9755 /// isLegalAddressImmediate - Return true if the integer value can be used
9756 /// as the offset of the target addressing mode for load / store of the
9758 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9759 const ARMSubtarget *Subtarget) {
9766 if (Subtarget->isThumb1Only())
9767 return isLegalT1AddressImmediate(V, VT);
9768 else if (Subtarget->isThumb2())
9769 return isLegalT2AddressImmediate(V, VT, Subtarget);
9774 switch (VT.getSimpleVT().SimpleTy) {
9775 default: return false;
9780 return V == (V & ((1LL << 12) - 1));
9783 return V == (V & ((1LL << 8) - 1));
9786 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9791 return V == (V & ((1LL << 8) - 1));
9795 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9797 int Scale = AM.Scale;
9801 switch (VT.getSimpleVT().SimpleTy) {
9802 default: return false;
9811 return Scale == 2 || Scale == 4 || Scale == 8;
9814 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9818 // Note, we allow "void" uses (basically, uses that aren't loads or
9819 // stores), because arm allows folding a scale into many arithmetic
9820 // operations. This should be made more precise and revisited later.
9822 // Allow r << imm, but the imm has to be a multiple of two.
9823 if (Scale & 1) return false;
9824 return isPowerOf2_32(Scale);
9828 /// isLegalAddressingMode - Return true if the addressing mode represented
9829 /// by AM is legal for this target, for a load/store of the specified type.
9830 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9832 EVT VT = getValueType(Ty, true);
9833 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9836 // Can never fold addr of global into load/store.
9841 case 0: // no scale reg, must be "r+i" or "r", or "i".
9844 if (Subtarget->isThumb1Only())
9848 // ARM doesn't support any R+R*scale+imm addr modes.
9855 if (Subtarget->isThumb2())
9856 return isLegalT2ScaledAddressingMode(AM, VT);
9858 int Scale = AM.Scale;
9859 switch (VT.getSimpleVT().SimpleTy) {
9860 default: return false;
9864 if (Scale < 0) Scale = -Scale;
9868 return isPowerOf2_32(Scale & ~1);
9872 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9877 // Note, we allow "void" uses (basically, uses that aren't loads or
9878 // stores), because arm allows folding a scale into many arithmetic
9879 // operations. This should be made more precise and revisited later.
9881 // Allow r << imm, but the imm has to be a multiple of two.
9882 if (Scale & 1) return false;
9883 return isPowerOf2_32(Scale);
9889 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9890 /// icmp immediate, that is the target has icmp instructions which can compare
9891 /// a register against the immediate without having to materialize the
9892 /// immediate into a register.
9893 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9894 // Thumb2 and ARM modes can use cmn for negative immediates.
9895 if (!Subtarget->isThumb())
9896 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9897 if (Subtarget->isThumb2())
9898 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9899 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9900 return Imm >= 0 && Imm <= 255;
9903 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9904 /// *or sub* immediate, that is the target has add or sub instructions which can
9905 /// add a register with the immediate without having to materialize the
9906 /// immediate into a register.
9907 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9908 // Same encoding for add/sub, just flip the sign.
9909 int64_t AbsImm = llvm::abs64(Imm);
9910 if (!Subtarget->isThumb())
9911 return ARM_AM::getSOImmVal(AbsImm) != -1;
9912 if (Subtarget->isThumb2())
9913 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9914 // Thumb1 only has 8-bit unsigned immediate.
9915 return AbsImm >= 0 && AbsImm <= 255;
9918 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9919 bool isSEXTLoad, SDValue &Base,
9920 SDValue &Offset, bool &isInc,
9921 SelectionDAG &DAG) {
9922 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9925 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9927 Base = Ptr->getOperand(0);
9928 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9929 int RHSC = (int)RHS->getZExtValue();
9930 if (RHSC < 0 && RHSC > -256) {
9931 assert(Ptr->getOpcode() == ISD::ADD);
9933 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9937 isInc = (Ptr->getOpcode() == ISD::ADD);
9938 Offset = Ptr->getOperand(1);
9940 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9942 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9943 int RHSC = (int)RHS->getZExtValue();
9944 if (RHSC < 0 && RHSC > -0x1000) {
9945 assert(Ptr->getOpcode() == ISD::ADD);
9947 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9948 Base = Ptr->getOperand(0);
9953 if (Ptr->getOpcode() == ISD::ADD) {
9955 ARM_AM::ShiftOpc ShOpcVal=
9956 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9957 if (ShOpcVal != ARM_AM::no_shift) {
9958 Base = Ptr->getOperand(1);
9959 Offset = Ptr->getOperand(0);
9961 Base = Ptr->getOperand(0);
9962 Offset = Ptr->getOperand(1);
9967 isInc = (Ptr->getOpcode() == ISD::ADD);
9968 Base = Ptr->getOperand(0);
9969 Offset = Ptr->getOperand(1);
9973 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9977 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9978 bool isSEXTLoad, SDValue &Base,
9979 SDValue &Offset, bool &isInc,
9980 SelectionDAG &DAG) {
9981 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9984 Base = Ptr->getOperand(0);
9985 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9986 int RHSC = (int)RHS->getZExtValue();
9987 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9988 assert(Ptr->getOpcode() == ISD::ADD);
9990 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9992 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9993 isInc = Ptr->getOpcode() == ISD::ADD;
9994 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10002 /// getPreIndexedAddressParts - returns true by value, base pointer and
10003 /// offset pointer and addressing mode by reference if the node's address
10004 /// can be legally represented as pre-indexed load / store address.
10006 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10008 ISD::MemIndexedMode &AM,
10009 SelectionDAG &DAG) const {
10010 if (Subtarget->isThumb1Only())
10015 bool isSEXTLoad = false;
10016 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10017 Ptr = LD->getBasePtr();
10018 VT = LD->getMemoryVT();
10019 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10020 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10021 Ptr = ST->getBasePtr();
10022 VT = ST->getMemoryVT();
10027 bool isLegal = false;
10028 if (Subtarget->isThumb2())
10029 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10030 Offset, isInc, DAG);
10032 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10033 Offset, isInc, DAG);
10037 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10041 /// getPostIndexedAddressParts - returns true by value, base pointer and
10042 /// offset pointer and addressing mode by reference if this node can be
10043 /// combined with a load / store to form a post-indexed load / store.
10044 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10047 ISD::MemIndexedMode &AM,
10048 SelectionDAG &DAG) const {
10049 if (Subtarget->isThumb1Only())
10054 bool isSEXTLoad = false;
10055 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10056 VT = LD->getMemoryVT();
10057 Ptr = LD->getBasePtr();
10058 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10059 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10060 VT = ST->getMemoryVT();
10061 Ptr = ST->getBasePtr();
10066 bool isLegal = false;
10067 if (Subtarget->isThumb2())
10068 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10071 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10077 // Swap base ptr and offset to catch more post-index load / store when
10078 // it's legal. In Thumb2 mode, offset must be an immediate.
10079 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10080 !Subtarget->isThumb2())
10081 std::swap(Base, Offset);
10083 // Post-indexed load / store update the base pointer.
10088 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10092 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10095 const SelectionDAG &DAG,
10096 unsigned Depth) const {
10097 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
10098 switch (Op.getOpcode()) {
10100 case ARMISD::CMOV: {
10101 // Bits are known zero/one if known on the LHS and RHS.
10102 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10103 if (KnownZero == 0 && KnownOne == 0) return;
10105 APInt KnownZeroRHS, KnownOneRHS;
10106 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10107 KnownZero &= KnownZeroRHS;
10108 KnownOne &= KnownOneRHS;
10114 //===----------------------------------------------------------------------===//
10115 // ARM Inline Assembly Support
10116 //===----------------------------------------------------------------------===//
10118 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10119 // Looking for "rev" which is V6+.
10120 if (!Subtarget->hasV6Ops())
10123 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10124 std::string AsmStr = IA->getAsmString();
10125 SmallVector<StringRef, 4> AsmPieces;
10126 SplitString(AsmStr, AsmPieces, ";\n");
10128 switch (AsmPieces.size()) {
10129 default: return false;
10131 AsmStr = AsmPieces[0];
10133 SplitString(AsmStr, AsmPieces, " \t,");
10136 if (AsmPieces.size() == 3 &&
10137 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10138 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10139 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10140 if (Ty && Ty->getBitWidth() == 32)
10141 return IntrinsicLowering::LowerToByteSwap(CI);
10149 /// getConstraintType - Given a constraint letter, return the type of
10150 /// constraint it is for this target.
10151 ARMTargetLowering::ConstraintType
10152 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10153 if (Constraint.size() == 1) {
10154 switch (Constraint[0]) {
10156 case 'l': return C_RegisterClass;
10157 case 'w': return C_RegisterClass;
10158 case 'h': return C_RegisterClass;
10159 case 'x': return C_RegisterClass;
10160 case 't': return C_RegisterClass;
10161 case 'j': return C_Other; // Constant for movw.
10162 // An address with a single base register. Due to the way we
10163 // currently handle addresses it is the same as an 'r' memory constraint.
10164 case 'Q': return C_Memory;
10166 } else if (Constraint.size() == 2) {
10167 switch (Constraint[0]) {
10169 // All 'U+' constraints are addresses.
10170 case 'U': return C_Memory;
10173 return TargetLowering::getConstraintType(Constraint);
10176 /// Examine constraint type and operand type and determine a weight value.
10177 /// This object must already have been set up with the operand type
10178 /// and the current alternative constraint selected.
10179 TargetLowering::ConstraintWeight
10180 ARMTargetLowering::getSingleConstraintMatchWeight(
10181 AsmOperandInfo &info, const char *constraint) const {
10182 ConstraintWeight weight = CW_Invalid;
10183 Value *CallOperandVal = info.CallOperandVal;
10184 // If we don't have a value, we can't do a match,
10185 // but allow it at the lowest weight.
10186 if (CallOperandVal == NULL)
10188 Type *type = CallOperandVal->getType();
10189 // Look at the constraint type.
10190 switch (*constraint) {
10192 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10195 if (type->isIntegerTy()) {
10196 if (Subtarget->isThumb())
10197 weight = CW_SpecificReg;
10199 weight = CW_Register;
10203 if (type->isFloatingPointTy())
10204 weight = CW_Register;
10210 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10212 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10214 if (Constraint.size() == 1) {
10215 // GCC ARM Constraint Letters
10216 switch (Constraint[0]) {
10217 case 'l': // Low regs or general regs.
10218 if (Subtarget->isThumb())
10219 return RCPair(0U, &ARM::tGPRRegClass);
10220 return RCPair(0U, &ARM::GPRRegClass);
10221 case 'h': // High regs or no regs.
10222 if (Subtarget->isThumb())
10223 return RCPair(0U, &ARM::hGPRRegClass);
10226 return RCPair(0U, &ARM::GPRRegClass);
10228 if (VT == MVT::f32)
10229 return RCPair(0U, &ARM::SPRRegClass);
10230 if (VT.getSizeInBits() == 64)
10231 return RCPair(0U, &ARM::DPRRegClass);
10232 if (VT.getSizeInBits() == 128)
10233 return RCPair(0U, &ARM::QPRRegClass);
10236 if (VT == MVT::f32)
10237 return RCPair(0U, &ARM::SPR_8RegClass);
10238 if (VT.getSizeInBits() == 64)
10239 return RCPair(0U, &ARM::DPR_8RegClass);
10240 if (VT.getSizeInBits() == 128)
10241 return RCPair(0U, &ARM::QPR_8RegClass);
10244 if (VT == MVT::f32)
10245 return RCPair(0U, &ARM::SPRRegClass);
10249 if (StringRef("{cc}").equals_lower(Constraint))
10250 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10252 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10255 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10256 /// vector. If it is invalid, don't add anything to Ops.
10257 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10258 std::string &Constraint,
10259 std::vector<SDValue>&Ops,
10260 SelectionDAG &DAG) const {
10261 SDValue Result(0, 0);
10263 // Currently only support length 1 constraints.
10264 if (Constraint.length() != 1) return;
10266 char ConstraintLetter = Constraint[0];
10267 switch (ConstraintLetter) {
10270 case 'I': case 'J': case 'K': case 'L':
10271 case 'M': case 'N': case 'O':
10272 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10276 int64_t CVal64 = C->getSExtValue();
10277 int CVal = (int) CVal64;
10278 // None of these constraints allow values larger than 32 bits. Check
10279 // that the value fits in an int.
10280 if (CVal != CVal64)
10283 switch (ConstraintLetter) {
10285 // Constant suitable for movw, must be between 0 and
10287 if (Subtarget->hasV6T2Ops())
10288 if (CVal >= 0 && CVal <= 65535)
10292 if (Subtarget->isThumb1Only()) {
10293 // This must be a constant between 0 and 255, for ADD
10295 if (CVal >= 0 && CVal <= 255)
10297 } else if (Subtarget->isThumb2()) {
10298 // A constant that can be used as an immediate value in a
10299 // data-processing instruction.
10300 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10303 // A constant that can be used as an immediate value in a
10304 // data-processing instruction.
10305 if (ARM_AM::getSOImmVal(CVal) != -1)
10311 if (Subtarget->isThumb()) { // FIXME thumb2
10312 // This must be a constant between -255 and -1, for negated ADD
10313 // immediates. This can be used in GCC with an "n" modifier that
10314 // prints the negated value, for use with SUB instructions. It is
10315 // not useful otherwise but is implemented for compatibility.
10316 if (CVal >= -255 && CVal <= -1)
10319 // This must be a constant between -4095 and 4095. It is not clear
10320 // what this constraint is intended for. Implemented for
10321 // compatibility with GCC.
10322 if (CVal >= -4095 && CVal <= 4095)
10328 if (Subtarget->isThumb1Only()) {
10329 // A 32-bit value where only one byte has a nonzero value. Exclude
10330 // zero to match GCC. This constraint is used by GCC internally for
10331 // constants that can be loaded with a move/shift combination.
10332 // It is not useful otherwise but is implemented for compatibility.
10333 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10335 } else if (Subtarget->isThumb2()) {
10336 // A constant whose bitwise inverse can be used as an immediate
10337 // value in a data-processing instruction. This can be used in GCC
10338 // with a "B" modifier that prints the inverted value, for use with
10339 // BIC and MVN instructions. It is not useful otherwise but is
10340 // implemented for compatibility.
10341 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10344 // A constant whose bitwise inverse can be used as an immediate
10345 // value in a data-processing instruction. This can be used in GCC
10346 // with a "B" modifier that prints the inverted value, for use with
10347 // BIC and MVN instructions. It is not useful otherwise but is
10348 // implemented for compatibility.
10349 if (ARM_AM::getSOImmVal(~CVal) != -1)
10355 if (Subtarget->isThumb1Only()) {
10356 // This must be a constant between -7 and 7,
10357 // for 3-operand ADD/SUB immediate instructions.
10358 if (CVal >= -7 && CVal < 7)
10360 } else if (Subtarget->isThumb2()) {
10361 // A constant whose negation can be used as an immediate value in a
10362 // data-processing instruction. This can be used in GCC with an "n"
10363 // modifier that prints the negated value, for use with SUB
10364 // instructions. It is not useful otherwise but is implemented for
10366 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10369 // A constant whose negation can be used as an immediate value in a
10370 // data-processing instruction. This can be used in GCC with an "n"
10371 // modifier that prints the negated value, for use with SUB
10372 // instructions. It is not useful otherwise but is implemented for
10374 if (ARM_AM::getSOImmVal(-CVal) != -1)
10380 if (Subtarget->isThumb()) { // FIXME thumb2
10381 // This must be a multiple of 4 between 0 and 1020, for
10382 // ADD sp + immediate.
10383 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10386 // A power of two or a constant between 0 and 32. This is used in
10387 // GCC for the shift amount on shifted register operands, but it is
10388 // useful in general for any shift amounts.
10389 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10395 if (Subtarget->isThumb()) { // FIXME thumb2
10396 // This must be a constant between 0 and 31, for shift amounts.
10397 if (CVal >= 0 && CVal <= 31)
10403 if (Subtarget->isThumb()) { // FIXME thumb2
10404 // This must be a multiple of 4 between -508 and 508, for
10405 // ADD/SUB sp = sp + immediate.
10406 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10411 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10415 if (Result.getNode()) {
10416 Ops.push_back(Result);
10419 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10423 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10424 // The ARM target isn't yet aware of offsets.
10428 bool ARM::isBitFieldInvertedMask(unsigned v) {
10429 if (v == 0xffffffff)
10431 // there can be 1's on either or both "outsides", all the "inside"
10432 // bits must be 0's
10433 unsigned int lsb = 0, msb = 31;
10434 while (v & (1 << msb)) --msb;
10435 while (v & (1 << lsb)) ++lsb;
10436 for (unsigned int i = lsb; i <= msb; ++i) {
10443 /// isFPImmLegal - Returns true if the target can instruction select the
10444 /// specified FP immediate natively. If false, the legalizer will
10445 /// materialize the FP immediate as a load from a constant pool.
10446 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10447 if (!Subtarget->hasVFP3())
10449 if (VT == MVT::f32)
10450 return ARM_AM::getFP32Imm(Imm) != -1;
10451 if (VT == MVT::f64)
10452 return ARM_AM::getFP64Imm(Imm) != -1;
10456 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10457 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10458 /// specified in the intrinsic calls.
10459 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10461 unsigned Intrinsic) const {
10462 switch (Intrinsic) {
10463 case Intrinsic::arm_neon_vld1:
10464 case Intrinsic::arm_neon_vld2:
10465 case Intrinsic::arm_neon_vld3:
10466 case Intrinsic::arm_neon_vld4:
10467 case Intrinsic::arm_neon_vld2lane:
10468 case Intrinsic::arm_neon_vld3lane:
10469 case Intrinsic::arm_neon_vld4lane: {
10470 Info.opc = ISD::INTRINSIC_W_CHAIN;
10471 // Conservatively set memVT to the entire set of vectors loaded.
10472 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10473 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10474 Info.ptrVal = I.getArgOperand(0);
10476 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10477 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10478 Info.vol = false; // volatile loads with NEON intrinsics not supported
10479 Info.readMem = true;
10480 Info.writeMem = false;
10483 case Intrinsic::arm_neon_vst1:
10484 case Intrinsic::arm_neon_vst2:
10485 case Intrinsic::arm_neon_vst3:
10486 case Intrinsic::arm_neon_vst4:
10487 case Intrinsic::arm_neon_vst2lane:
10488 case Intrinsic::arm_neon_vst3lane:
10489 case Intrinsic::arm_neon_vst4lane: {
10490 Info.opc = ISD::INTRINSIC_VOID;
10491 // Conservatively set memVT to the entire set of vectors stored.
10492 unsigned NumElts = 0;
10493 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10494 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10495 if (!ArgTy->isVectorTy())
10497 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10499 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10500 Info.ptrVal = I.getArgOperand(0);
10502 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10503 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10504 Info.vol = false; // volatile stores with NEON intrinsics not supported
10505 Info.readMem = false;
10506 Info.writeMem = true;
10509 case Intrinsic::arm_strexd: {
10510 Info.opc = ISD::INTRINSIC_W_CHAIN;
10511 Info.memVT = MVT::i64;
10512 Info.ptrVal = I.getArgOperand(2);
10516 Info.readMem = false;
10517 Info.writeMem = true;
10520 case Intrinsic::arm_ldrexd: {
10521 Info.opc = ISD::INTRINSIC_W_CHAIN;
10522 Info.memVT = MVT::i64;
10523 Info.ptrVal = I.getArgOperand(0);
10527 Info.readMem = true;
10528 Info.writeMem = false;