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/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 // This option should go away when tail calls fully work.
58 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
59 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
63 EnableARMLongCalls("arm-long-calls", cl::Hidden,
64 cl::desc("Generate calls via indirect call instructions"),
68 ARMInterworking("arm-interworking", cl::Hidden,
69 cl::desc("Enable / disable ARM interworking (for debugging only)"),
73 class ARMCCState : public CCState {
75 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
76 const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
77 LLVMContext &C, ParmContext PC)
78 : CCState(CC, isVarArg, MF, TM, locs, C) {
79 assert(((PC == Call) || (PC == Prologue)) &&
80 "ARMCCState users must specify whether their context is call"
81 "or prologue generation.");
87 // The APCS parameter registers.
88 static const uint16_t GPRArgRegs[] = {
89 ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
93 EVT PromotedBitwiseVT) {
94 if (VT != PromotedLdStVT) {
95 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
96 AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
97 PromotedLdStVT.getSimpleVT());
99 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
100 AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
101 PromotedLdStVT.getSimpleVT());
104 EVT ElemTy = VT.getVectorElementType();
105 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
107 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
108 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
109 if (ElemTy == MVT::i32) {
110 setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
111 setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
112 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
113 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
115 setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
116 setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
117 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
118 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
120 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
121 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
122 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
123 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
124 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
125 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
127 if (VT.isInteger()) {
128 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
129 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
130 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
133 // Promote all bit-wise operations.
134 if (VT.isInteger() && VT != PromotedBitwiseVT) {
135 setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
136 AddPromotedToType (ISD::AND, VT.getSimpleVT(),
137 PromotedBitwiseVT.getSimpleVT());
138 setOperationAction(ISD::OR, VT.getSimpleVT(), Promote);
139 AddPromotedToType (ISD::OR, VT.getSimpleVT(),
140 PromotedBitwiseVT.getSimpleVT());
141 setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
142 AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
143 PromotedBitwiseVT.getSimpleVT());
146 // Neon does not support vector divide/remainder operations.
147 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
148 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
149 setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
150 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
151 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
152 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
155 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
156 addRegisterClass(VT, &ARM::DPRRegClass);
157 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
161 addRegisterClass(VT, &ARM::QPRRegClass);
162 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
166 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
167 return new TargetLoweringObjectFileMachO();
169 return new ARMElfTargetObjectFile();
172 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
173 : TargetLowering(TM, createTLOF(TM)) {
174 Subtarget = &TM.getSubtarget<ARMSubtarget>();
175 RegInfo = TM.getRegisterInfo();
176 Itins = TM.getInstrItineraryData();
178 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
180 if (Subtarget->isTargetDarwin()) {
181 // Uses VFP for Thumb libfuncs if available.
182 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
183 // Single-precision floating-point arithmetic.
184 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
185 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
186 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
187 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
189 // Double-precision floating-point arithmetic.
190 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
191 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
192 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
193 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
195 // Single-precision comparisons.
196 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
197 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
198 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
199 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
200 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
201 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
202 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
203 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
205 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
210 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
211 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
212 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
214 // Double-precision comparisons.
215 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
216 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
217 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
218 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
219 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
220 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
221 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
222 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
224 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
229 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
230 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
231 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
233 // Floating-point to integer conversions.
234 // i64 conversions are done via library routines even when generating VFP
235 // instructions, so use the same ones.
236 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
237 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
238 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
239 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
241 // Conversions between floating types.
242 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
243 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
245 // Integer to floating-point conversions.
246 // i64 conversions are done via library routines even when generating VFP
247 // instructions, so use the same ones.
248 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
249 // e.g., __floatunsidf vs. __floatunssidfvfp.
250 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
251 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
252 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
253 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
257 // These libcalls are not available in 32-bit.
258 setLibcallName(RTLIB::SHL_I128, 0);
259 setLibcallName(RTLIB::SRL_I128, 0);
260 setLibcallName(RTLIB::SRA_I128, 0);
262 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
263 // Double-precision floating-point arithmetic helper functions
264 // RTABI chapter 4.1.2, Table 2
265 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
266 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
267 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
268 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
269 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
270 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
271 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
272 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
274 // Double-precision floating-point comparison helper functions
275 // RTABI chapter 4.1.2, Table 3
276 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
277 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
278 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
279 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
280 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
281 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
282 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
283 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
284 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
285 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
286 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
287 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
288 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
289 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
290 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
291 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
292 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
297 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
298 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
299 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
301 // Single-precision floating-point arithmetic helper functions
302 // RTABI chapter 4.1.2, Table 4
303 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
304 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
305 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
306 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
307 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
308 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
309 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
310 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
312 // Single-precision floating-point comparison helper functions
313 // RTABI chapter 4.1.2, Table 5
314 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
315 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
316 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
317 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
318 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
319 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
320 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
321 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
322 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
323 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
324 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
325 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
326 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
327 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
328 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
329 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
330 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
335 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
336 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
337 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
339 // Floating-point to integer conversions.
340 // RTABI chapter 4.1.2, Table 6
341 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
342 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
343 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
344 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
345 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
346 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
347 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
348 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
349 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
354 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
355 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
356 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
358 // Conversions between floating types.
359 // RTABI chapter 4.1.2, Table 7
360 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
361 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
362 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
363 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
365 // Integer to floating-point conversions.
366 // RTABI chapter 4.1.2, Table 8
367 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
368 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
369 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
370 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
371 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
372 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
373 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
374 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
375 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
381 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384 // Long long helper functions
385 // RTABI chapter 4.2, Table 9
386 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
387 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
388 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
389 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
390 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
395 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
397 // Integer division functions
398 // RTABI chapter 4.3.1
399 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
400 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
401 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
402 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
403 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
404 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
405 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
406 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
407 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
412 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
413 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
414 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
417 // RTABI chapter 4.3.4
418 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
419 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
420 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
421 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
422 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
423 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
426 // Use divmod compiler-rt calls for iOS 5.0 and later.
427 if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
428 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
429 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
430 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
433 if (Subtarget->isThumb1Only())
434 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
436 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
437 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
438 !Subtarget->isThumb1Only()) {
439 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
440 if (!Subtarget->isFPOnlySP())
441 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
443 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
446 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
447 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
448 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
449 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
450 setTruncStoreAction((MVT::SimpleValueType)VT,
451 (MVT::SimpleValueType)InnerVT, Expand);
452 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
454 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
457 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
459 if (Subtarget->hasNEON()) {
460 addDRTypeForNEON(MVT::v2f32);
461 addDRTypeForNEON(MVT::v8i8);
462 addDRTypeForNEON(MVT::v4i16);
463 addDRTypeForNEON(MVT::v2i32);
464 addDRTypeForNEON(MVT::v1i64);
466 addQRTypeForNEON(MVT::v4f32);
467 addQRTypeForNEON(MVT::v2f64);
468 addQRTypeForNEON(MVT::v16i8);
469 addQRTypeForNEON(MVT::v8i16);
470 addQRTypeForNEON(MVT::v4i32);
471 addQRTypeForNEON(MVT::v2i64);
473 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474 // neither Neon nor VFP support any arithmetic operations on it.
475 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476 // supported for v4f32.
477 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480 // FIXME: Code duplication: FDIV and FREM are expanded always, see
481 // ARMTargetLowering::addTypeForNEON method for details.
482 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484 // FIXME: Create unittest.
485 // In another words, find a way when "copysign" appears in DAG with vector
487 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488 // FIXME: Code duplication: SETCC has custom operation action, see
489 // ARMTargetLowering::addTypeForNEON method for details.
490 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491 // FIXME: Create unittest for FNEG and for FABS.
492 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
511 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
512 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
513 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
514 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
515 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
516 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
518 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
519 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
520 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522 // Neon does not support some operations on v1i64 and v2i64 types.
523 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524 // Custom handling for some quad-vector types to detect VMULL.
525 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528 // Custom handling for some vector types to avoid expensive expansions
529 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536 // a destination type that is wider than the source, and nor does
537 // it have a FP_TO_[SU]INT instruction with a narrower destination than
539 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
544 setTargetDAGCombine(ISD::INTRINSIC_VOID);
545 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
546 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
547 setTargetDAGCombine(ISD::SHL);
548 setTargetDAGCombine(ISD::SRL);
549 setTargetDAGCombine(ISD::SRA);
550 setTargetDAGCombine(ISD::SIGN_EXTEND);
551 setTargetDAGCombine(ISD::ZERO_EXTEND);
552 setTargetDAGCombine(ISD::ANY_EXTEND);
553 setTargetDAGCombine(ISD::SELECT_CC);
554 setTargetDAGCombine(ISD::BUILD_VECTOR);
555 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
556 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
557 setTargetDAGCombine(ISD::STORE);
558 setTargetDAGCombine(ISD::FP_TO_SINT);
559 setTargetDAGCombine(ISD::FP_TO_UINT);
560 setTargetDAGCombine(ISD::FDIV);
562 // It is legal to extload from v4i8 to v4i16 or v4i32.
563 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
564 MVT::v4i16, MVT::v2i16,
566 for (unsigned i = 0; i < 6; ++i) {
567 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
568 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
569 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
573 computeRegisterProperties();
575 // ARM does not have f32 extending load.
576 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
578 // ARM does not have i1 sign extending load.
579 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
581 // ARM supports all 4 flavors of integer indexed load / store.
582 if (!Subtarget->isThumb1Only()) {
583 for (unsigned im = (unsigned)ISD::PRE_INC;
584 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
585 setIndexedLoadAction(im, MVT::i1, Legal);
586 setIndexedLoadAction(im, MVT::i8, Legal);
587 setIndexedLoadAction(im, MVT::i16, Legal);
588 setIndexedLoadAction(im, MVT::i32, Legal);
589 setIndexedStoreAction(im, MVT::i1, Legal);
590 setIndexedStoreAction(im, MVT::i8, Legal);
591 setIndexedStoreAction(im, MVT::i16, Legal);
592 setIndexedStoreAction(im, MVT::i32, Legal);
596 // i64 operation support.
597 setOperationAction(ISD::MUL, MVT::i64, Expand);
598 setOperationAction(ISD::MULHU, MVT::i32, Expand);
599 if (Subtarget->isThumb1Only()) {
600 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
601 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
603 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
604 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
605 setOperationAction(ISD::MULHS, MVT::i32, Expand);
607 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
608 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
609 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
610 setOperationAction(ISD::SRL, MVT::i64, Custom);
611 setOperationAction(ISD::SRA, MVT::i64, Custom);
613 if (!Subtarget->isThumb1Only()) {
614 // FIXME: We should do this for Thumb1 as well.
615 setOperationAction(ISD::ADDC, MVT::i32, Custom);
616 setOperationAction(ISD::ADDE, MVT::i32, Custom);
617 setOperationAction(ISD::SUBC, MVT::i32, Custom);
618 setOperationAction(ISD::SUBE, MVT::i32, Custom);
621 // ARM does not have ROTL.
622 setOperationAction(ISD::ROTL, MVT::i32, Expand);
623 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
624 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
625 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
626 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
628 // These just redirect to CTTZ and CTLZ on ARM.
629 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
630 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
632 // Only ARMv6 has BSWAP.
633 if (!Subtarget->hasV6Ops())
634 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
636 // These are expanded into libcalls.
637 if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
638 // v7M has a hardware divider
639 setOperationAction(ISD::SDIV, MVT::i32, Expand);
640 setOperationAction(ISD::UDIV, MVT::i32, Expand);
642 setOperationAction(ISD::SREM, MVT::i32, Expand);
643 setOperationAction(ISD::UREM, MVT::i32, Expand);
644 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
645 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
647 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
648 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
649 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
650 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
651 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
653 setOperationAction(ISD::TRAP, MVT::Other, Legal);
655 // Use the default implementation.
656 setOperationAction(ISD::VASTART, MVT::Other, Custom);
657 setOperationAction(ISD::VAARG, MVT::Other, Expand);
658 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
659 setOperationAction(ISD::VAEND, MVT::Other, Expand);
660 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
661 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
663 if (!Subtarget->isTargetDarwin()) {
664 // Non-Darwin platforms may return values in these registers via the
665 // personality function.
666 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
667 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
668 setExceptionPointerRegister(ARM::R0);
669 setExceptionSelectorRegister(ARM::R1);
672 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
673 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
674 // the default expansion.
675 // FIXME: This should be checking for v6k, not just v6.
676 if (Subtarget->hasDataBarrier() ||
677 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
678 // membarrier needs custom lowering; the rest are legal and handled
680 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
681 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
682 // Custom lowering for 64-bit ops
683 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
684 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
685 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
686 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
687 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
688 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
689 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
690 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
691 setInsertFencesForAtomic(true);
693 // Set them all for expansion, which will force libcalls.
694 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
695 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
696 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
697 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
698 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
699 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
700 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
701 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
702 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
703 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
704 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
705 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
706 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
707 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
708 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
709 // Unordered/Monotonic case.
710 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
711 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
712 // Since the libcalls include locking, fold in the fences
713 setShouldFoldAtomicFences(true);
716 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
718 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
719 if (!Subtarget->hasV6Ops()) {
720 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
721 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
723 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
725 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
726 !Subtarget->isThumb1Only()) {
727 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
728 // iff target supports vfp2.
729 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
730 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
733 // We want to custom lower some of our intrinsics.
734 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
735 if (Subtarget->isTargetDarwin()) {
736 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
737 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
738 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
741 setOperationAction(ISD::SETCC, MVT::i32, Expand);
742 setOperationAction(ISD::SETCC, MVT::f32, Expand);
743 setOperationAction(ISD::SETCC, MVT::f64, Expand);
744 setOperationAction(ISD::SELECT, MVT::i32, Custom);
745 setOperationAction(ISD::SELECT, MVT::f32, Custom);
746 setOperationAction(ISD::SELECT, MVT::f64, Custom);
747 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
748 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
749 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
751 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
752 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
753 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
754 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
755 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
757 // We don't support sin/cos/fmod/copysign/pow
758 setOperationAction(ISD::FSIN, MVT::f64, Expand);
759 setOperationAction(ISD::FSIN, MVT::f32, Expand);
760 setOperationAction(ISD::FCOS, MVT::f32, Expand);
761 setOperationAction(ISD::FCOS, MVT::f64, Expand);
762 setOperationAction(ISD::FREM, MVT::f64, Expand);
763 setOperationAction(ISD::FREM, MVT::f32, Expand);
764 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
765 !Subtarget->isThumb1Only()) {
766 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
767 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
769 setOperationAction(ISD::FPOW, MVT::f64, Expand);
770 setOperationAction(ISD::FPOW, MVT::f32, Expand);
772 if (!Subtarget->hasVFP4()) {
773 setOperationAction(ISD::FMA, MVT::f64, Expand);
774 setOperationAction(ISD::FMA, MVT::f32, Expand);
777 // Various VFP goodness
778 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
779 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
780 if (Subtarget->hasVFP2()) {
781 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
782 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
783 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
784 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
786 // Special handling for half-precision FP.
787 if (!Subtarget->hasFP16()) {
788 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
789 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
793 // We have target-specific dag combine patterns for the following nodes:
794 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
795 setTargetDAGCombine(ISD::ADD);
796 setTargetDAGCombine(ISD::SUB);
797 setTargetDAGCombine(ISD::MUL);
799 if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
800 setTargetDAGCombine(ISD::AND);
801 setTargetDAGCombine(ISD::OR);
802 setTargetDAGCombine(ISD::XOR);
805 if (Subtarget->hasV6Ops())
806 setTargetDAGCombine(ISD::SRL);
808 setStackPointerRegisterToSaveRestore(ARM::SP);
810 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
811 !Subtarget->hasVFP2())
812 setSchedulingPreference(Sched::RegPressure);
814 setSchedulingPreference(Sched::Hybrid);
816 //// temporary - rewrite interface to use type
817 maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
818 maxStoresPerMemset = 16;
819 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
821 // On ARM arguments smaller than 4 bytes are extended, so all arguments
822 // are at least 4 bytes aligned.
823 setMinStackArgumentAlignment(4);
825 benefitFromCodePlacementOpt = true;
827 // Prefer likely predicted branches to selects on out-of-order cores.
828 predictableSelectIsExpensive = Subtarget->isCortexA9();
830 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
833 // FIXME: It might make sense to define the representative register class as the
834 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
835 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
836 // SPR's representative would be DPR_VFP2. This should work well if register
837 // pressure tracking were modified such that a register use would increment the
838 // pressure of the register class's representative and all of it's super
839 // classes' representatives transitively. We have not implemented this because
840 // of the difficulty prior to coalescing of modeling operand register classes
841 // due to the common occurrence of cross class copies and subregister insertions
843 std::pair<const TargetRegisterClass*, uint8_t>
844 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
845 const TargetRegisterClass *RRC = 0;
847 switch (VT.getSimpleVT().SimpleTy) {
849 return TargetLowering::findRepresentativeClass(VT);
850 // Use DPR as representative register class for all floating point
851 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
852 // the cost is 1 for both f32 and f64.
853 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
854 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
855 RRC = &ARM::DPRRegClass;
856 // When NEON is used for SP, only half of the register file is available
857 // because operations that define both SP and DP results will be constrained
858 // to the VFP2 class (D0-D15). We currently model this constraint prior to
859 // coalescing by double-counting the SP regs. See the FIXME above.
860 if (Subtarget->useNEONForSinglePrecisionFP())
863 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
864 case MVT::v4f32: case MVT::v2f64:
865 RRC = &ARM::DPRRegClass;
869 RRC = &ARM::DPRRegClass;
873 RRC = &ARM::DPRRegClass;
877 return std::make_pair(RRC, Cost);
880 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
883 case ARMISD::Wrapper: return "ARMISD::Wrapper";
884 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
885 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
886 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
887 case ARMISD::CALL: return "ARMISD::CALL";
888 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
889 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
890 case ARMISD::tCALL: return "ARMISD::tCALL";
891 case ARMISD::BRCOND: return "ARMISD::BRCOND";
892 case ARMISD::BR_JT: return "ARMISD::BR_JT";
893 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
894 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
895 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
896 case ARMISD::CMP: return "ARMISD::CMP";
897 case ARMISD::CMPZ: return "ARMISD::CMPZ";
898 case ARMISD::CMPFP: return "ARMISD::CMPFP";
899 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
900 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
901 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
903 case ARMISD::CMOV: return "ARMISD::CMOV";
904 case ARMISD::CAND: return "ARMISD::CAND";
905 case ARMISD::COR: return "ARMISD::COR";
906 case ARMISD::CXOR: return "ARMISD::CXOR";
908 case ARMISD::RBIT: return "ARMISD::RBIT";
910 case ARMISD::FTOSI: return "ARMISD::FTOSI";
911 case ARMISD::FTOUI: return "ARMISD::FTOUI";
912 case ARMISD::SITOF: return "ARMISD::SITOF";
913 case ARMISD::UITOF: return "ARMISD::UITOF";
915 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
916 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
917 case ARMISD::RRX: return "ARMISD::RRX";
919 case ARMISD::ADDC: return "ARMISD::ADDC";
920 case ARMISD::ADDE: return "ARMISD::ADDE";
921 case ARMISD::SUBC: return "ARMISD::SUBC";
922 case ARMISD::SUBE: return "ARMISD::SUBE";
924 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
925 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
927 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
928 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
930 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
932 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
934 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
936 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
937 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
939 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
941 case ARMISD::VCEQ: return "ARMISD::VCEQ";
942 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
943 case ARMISD::VCGE: return "ARMISD::VCGE";
944 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
945 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
946 case ARMISD::VCGEU: return "ARMISD::VCGEU";
947 case ARMISD::VCGT: return "ARMISD::VCGT";
948 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
949 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
950 case ARMISD::VCGTU: return "ARMISD::VCGTU";
951 case ARMISD::VTST: return "ARMISD::VTST";
953 case ARMISD::VSHL: return "ARMISD::VSHL";
954 case ARMISD::VSHRs: return "ARMISD::VSHRs";
955 case ARMISD::VSHRu: return "ARMISD::VSHRu";
956 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
957 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
958 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
959 case ARMISD::VSHRN: return "ARMISD::VSHRN";
960 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
961 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
962 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
963 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
964 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
965 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
966 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
967 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
968 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
969 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
970 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
971 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
972 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
973 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
974 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
975 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
976 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
977 case ARMISD::VDUP: return "ARMISD::VDUP";
978 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
979 case ARMISD::VEXT: return "ARMISD::VEXT";
980 case ARMISD::VREV64: return "ARMISD::VREV64";
981 case ARMISD::VREV32: return "ARMISD::VREV32";
982 case ARMISD::VREV16: return "ARMISD::VREV16";
983 case ARMISD::VZIP: return "ARMISD::VZIP";
984 case ARMISD::VUZP: return "ARMISD::VUZP";
985 case ARMISD::VTRN: return "ARMISD::VTRN";
986 case ARMISD::VTBL1: return "ARMISD::VTBL1";
987 case ARMISD::VTBL2: return "ARMISD::VTBL2";
988 case ARMISD::VMULLs: return "ARMISD::VMULLs";
989 case ARMISD::VMULLu: return "ARMISD::VMULLu";
990 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
991 case ARMISD::FMAX: return "ARMISD::FMAX";
992 case ARMISD::FMIN: return "ARMISD::FMIN";
993 case ARMISD::BFI: return "ARMISD::BFI";
994 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
995 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
996 case ARMISD::VBSL: return "ARMISD::VBSL";
997 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
998 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
999 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1000 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1001 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1002 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1003 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1004 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1005 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1006 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1007 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1008 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1009 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1010 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1011 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1012 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1013 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1014 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1015 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1016 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1020 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1021 if (!VT.isVector()) return getPointerTy();
1022 return VT.changeVectorElementTypeToInteger();
1025 /// getRegClassFor - Return the register class that should be used for the
1026 /// specified value type.
1027 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1028 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1029 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1030 // load / store 4 to 8 consecutive D registers.
1031 if (Subtarget->hasNEON()) {
1032 if (VT == MVT::v4i64)
1033 return &ARM::QQPRRegClass;
1034 if (VT == MVT::v8i64)
1035 return &ARM::QQQQPRRegClass;
1037 return TargetLowering::getRegClassFor(VT);
1040 // Create a fast isel object.
1042 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1043 return ARM::createFastISel(funcInfo);
1046 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1047 /// be used for loads / stores from the global.
1048 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1049 return (Subtarget->isThumb1Only() ? 127 : 4095);
1052 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1053 unsigned NumVals = N->getNumValues();
1055 return Sched::RegPressure;
1057 for (unsigned i = 0; i != NumVals; ++i) {
1058 EVT VT = N->getValueType(i);
1059 if (VT == MVT::Glue || VT == MVT::Other)
1061 if (VT.isFloatingPoint() || VT.isVector())
1065 if (!N->isMachineOpcode())
1066 return Sched::RegPressure;
1068 // Load are scheduled for latency even if there instruction itinerary
1069 // is not available.
1070 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1071 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1073 if (MCID.getNumDefs() == 0)
1074 return Sched::RegPressure;
1075 if (!Itins->isEmpty() &&
1076 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1079 return Sched::RegPressure;
1082 //===----------------------------------------------------------------------===//
1084 //===----------------------------------------------------------------------===//
1086 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1087 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1089 default: llvm_unreachable("Unknown condition code!");
1090 case ISD::SETNE: return ARMCC::NE;
1091 case ISD::SETEQ: return ARMCC::EQ;
1092 case ISD::SETGT: return ARMCC::GT;
1093 case ISD::SETGE: return ARMCC::GE;
1094 case ISD::SETLT: return ARMCC::LT;
1095 case ISD::SETLE: return ARMCC::LE;
1096 case ISD::SETUGT: return ARMCC::HI;
1097 case ISD::SETUGE: return ARMCC::HS;
1098 case ISD::SETULT: return ARMCC::LO;
1099 case ISD::SETULE: return ARMCC::LS;
1103 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1104 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1105 ARMCC::CondCodes &CondCode2) {
1106 CondCode2 = ARMCC::AL;
1108 default: llvm_unreachable("Unknown FP condition!");
1110 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1112 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1114 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1115 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1116 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1117 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1118 case ISD::SETO: CondCode = ARMCC::VC; break;
1119 case ISD::SETUO: CondCode = ARMCC::VS; break;
1120 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1121 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1122 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1124 case ISD::SETULT: CondCode = ARMCC::LT; break;
1126 case ISD::SETULE: CondCode = ARMCC::LE; break;
1128 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1132 //===----------------------------------------------------------------------===//
1133 // Calling Convention Implementation
1134 //===----------------------------------------------------------------------===//
1136 #include "ARMGenCallingConv.inc"
1138 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1139 /// given CallingConvention value.
1140 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1142 bool isVarArg) const {
1145 llvm_unreachable("Unsupported calling convention");
1146 case CallingConv::Fast:
1147 if (Subtarget->hasVFP2() && !isVarArg) {
1148 if (!Subtarget->isAAPCS_ABI())
1149 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1150 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1151 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1154 case CallingConv::C: {
1155 // Use target triple & subtarget features to do actual dispatch.
1156 if (!Subtarget->isAAPCS_ABI())
1157 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1158 else if (Subtarget->hasVFP2() &&
1159 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1161 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1162 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1164 case CallingConv::ARM_AAPCS_VFP:
1166 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1168 case CallingConv::ARM_AAPCS:
1169 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1170 case CallingConv::ARM_APCS:
1171 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1175 /// LowerCallResult - Lower the result values of a call into the
1176 /// appropriate copies out of appropriate physical registers.
1178 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1179 CallingConv::ID CallConv, bool isVarArg,
1180 const SmallVectorImpl<ISD::InputArg> &Ins,
1181 DebugLoc dl, SelectionDAG &DAG,
1182 SmallVectorImpl<SDValue> &InVals) const {
1184 // Assign locations to each value returned by this call.
1185 SmallVector<CCValAssign, 16> RVLocs;
1186 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1187 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1188 CCInfo.AnalyzeCallResult(Ins,
1189 CCAssignFnForNode(CallConv, /* Return*/ true,
1192 // Copy all of the result registers out of their specified physreg.
1193 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1194 CCValAssign VA = RVLocs[i];
1197 if (VA.needsCustom()) {
1198 // Handle f64 or half of a v2f64.
1199 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1201 Chain = Lo.getValue(1);
1202 InFlag = Lo.getValue(2);
1203 VA = RVLocs[++i]; // skip ahead to next loc
1204 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1206 Chain = Hi.getValue(1);
1207 InFlag = Hi.getValue(2);
1208 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1210 if (VA.getLocVT() == MVT::v2f64) {
1211 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1212 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1213 DAG.getConstant(0, MVT::i32));
1215 VA = RVLocs[++i]; // skip ahead to next loc
1216 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1217 Chain = Lo.getValue(1);
1218 InFlag = Lo.getValue(2);
1219 VA = RVLocs[++i]; // skip ahead to next loc
1220 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1221 Chain = Hi.getValue(1);
1222 InFlag = Hi.getValue(2);
1223 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1224 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1225 DAG.getConstant(1, MVT::i32));
1228 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1230 Chain = Val.getValue(1);
1231 InFlag = Val.getValue(2);
1234 switch (VA.getLocInfo()) {
1235 default: llvm_unreachable("Unknown loc info!");
1236 case CCValAssign::Full: break;
1237 case CCValAssign::BCvt:
1238 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1242 InVals.push_back(Val);
1248 /// LowerMemOpCallTo - Store the argument to the stack.
1250 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1251 SDValue StackPtr, SDValue Arg,
1252 DebugLoc dl, SelectionDAG &DAG,
1253 const CCValAssign &VA,
1254 ISD::ArgFlagsTy Flags) const {
1255 unsigned LocMemOffset = VA.getLocMemOffset();
1256 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1257 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1258 return DAG.getStore(Chain, dl, Arg, PtrOff,
1259 MachinePointerInfo::getStack(LocMemOffset),
1263 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1264 SDValue Chain, SDValue &Arg,
1265 RegsToPassVector &RegsToPass,
1266 CCValAssign &VA, CCValAssign &NextVA,
1268 SmallVector<SDValue, 8> &MemOpChains,
1269 ISD::ArgFlagsTy Flags) const {
1271 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1272 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1273 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1275 if (NextVA.isRegLoc())
1276 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1278 assert(NextVA.isMemLoc());
1279 if (StackPtr.getNode() == 0)
1280 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1282 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1288 /// LowerCall - Lowering a call into a callseq_start <-
1289 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1292 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1293 SmallVectorImpl<SDValue> &InVals) const {
1294 SelectionDAG &DAG = CLI.DAG;
1295 DebugLoc &dl = CLI.DL;
1296 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1297 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1298 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1299 SDValue Chain = CLI.Chain;
1300 SDValue Callee = CLI.Callee;
1301 bool &isTailCall = CLI.IsTailCall;
1302 CallingConv::ID CallConv = CLI.CallConv;
1303 bool doesNotRet = CLI.DoesNotReturn;
1304 bool isVarArg = CLI.IsVarArg;
1306 MachineFunction &MF = DAG.getMachineFunction();
1307 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1308 bool IsSibCall = false;
1309 // Disable tail calls if they're not supported.
1310 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1313 // Check if it's really possible to do a tail call.
1314 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1315 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1316 Outs, OutVals, Ins, DAG);
1317 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1318 // detected sibcalls.
1325 // Analyze operands of the call, assigning locations to each operand.
1326 SmallVector<CCValAssign, 16> ArgLocs;
1327 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1328 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1329 CCInfo.AnalyzeCallOperands(Outs,
1330 CCAssignFnForNode(CallConv, /* Return*/ false,
1333 // Get a count of how many bytes are to be pushed on the stack.
1334 unsigned NumBytes = CCInfo.getNextStackOffset();
1336 // For tail calls, memory operands are available in our caller's stack.
1340 // Adjust the stack pointer for the new arguments...
1341 // These operations are automatically eliminated by the prolog/epilog pass
1343 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1345 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1347 RegsToPassVector RegsToPass;
1348 SmallVector<SDValue, 8> MemOpChains;
1350 // Walk the register/memloc assignments, inserting copies/loads. In the case
1351 // of tail call optimization, arguments are handled later.
1352 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1354 ++i, ++realArgIdx) {
1355 CCValAssign &VA = ArgLocs[i];
1356 SDValue Arg = OutVals[realArgIdx];
1357 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1358 bool isByVal = Flags.isByVal();
1360 // Promote the value if needed.
1361 switch (VA.getLocInfo()) {
1362 default: llvm_unreachable("Unknown loc info!");
1363 case CCValAssign::Full: break;
1364 case CCValAssign::SExt:
1365 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1367 case CCValAssign::ZExt:
1368 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1370 case CCValAssign::AExt:
1371 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1373 case CCValAssign::BCvt:
1374 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1378 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1379 if (VA.needsCustom()) {
1380 if (VA.getLocVT() == MVT::v2f64) {
1381 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1382 DAG.getConstant(0, MVT::i32));
1383 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1384 DAG.getConstant(1, MVT::i32));
1386 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1387 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1389 VA = ArgLocs[++i]; // skip ahead to next loc
1390 if (VA.isRegLoc()) {
1391 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1392 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1394 assert(VA.isMemLoc());
1396 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1397 dl, DAG, VA, Flags));
1400 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1401 StackPtr, MemOpChains, Flags);
1403 } else if (VA.isRegLoc()) {
1404 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1405 } else if (isByVal) {
1406 assert(VA.isMemLoc());
1407 unsigned offset = 0;
1409 // True if this byval aggregate will be split between registers
1411 if (CCInfo.isFirstByValRegValid()) {
1412 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1414 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1415 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1416 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1417 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1418 MachinePointerInfo(),
1419 false, false, false, 0);
1420 MemOpChains.push_back(Load.getValue(1));
1421 RegsToPass.push_back(std::make_pair(j, Load));
1423 offset = ARM::R4 - CCInfo.getFirstByValReg();
1424 CCInfo.clearFirstByValReg();
1427 unsigned LocMemOffset = VA.getLocMemOffset();
1428 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1429 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1431 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1432 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1433 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1435 MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1436 Flags.getByValAlign(),
1437 /*isVolatile=*/false,
1438 /*AlwaysInline=*/false,
1439 MachinePointerInfo(0),
1440 MachinePointerInfo(0)));
1442 } else if (!IsSibCall) {
1443 assert(VA.isMemLoc());
1445 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1446 dl, DAG, VA, Flags));
1450 if (!MemOpChains.empty())
1451 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1452 &MemOpChains[0], MemOpChains.size());
1454 // Build a sequence of copy-to-reg nodes chained together with token chain
1455 // and flag operands which copy the outgoing args into the appropriate regs.
1457 // Tail call byval lowering might overwrite argument registers so in case of
1458 // tail call optimization the copies to registers are lowered later.
1460 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1461 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1462 RegsToPass[i].second, InFlag);
1463 InFlag = Chain.getValue(1);
1466 // For tail calls lower the arguments to the 'real' stack slot.
1468 // Force all the incoming stack arguments to be loaded from the stack
1469 // before any new outgoing arguments are stored to the stack, because the
1470 // outgoing stack slots may alias the incoming argument stack slots, and
1471 // the alias isn't otherwise explicit. This is slightly more conservative
1472 // than necessary, because it means that each store effectively depends
1473 // on every argument instead of just those arguments it would clobber.
1475 // Do not flag preceding copytoreg stuff together with the following stuff.
1477 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1478 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1479 RegsToPass[i].second, InFlag);
1480 InFlag = Chain.getValue(1);
1485 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1486 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1487 // node so that legalize doesn't hack it.
1488 bool isDirect = false;
1489 bool isARMFunc = false;
1490 bool isLocalARMFunc = false;
1491 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1493 if (EnableARMLongCalls) {
1494 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1495 && "long-calls with non-static relocation model!");
1496 // Handle a global address or an external symbol. If it's not one of
1497 // those, the target's already in a register, so we don't need to do
1499 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1500 const GlobalValue *GV = G->getGlobal();
1501 // Create a constant pool entry for the callee address
1502 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1503 ARMConstantPoolValue *CPV =
1504 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1506 // Get the address of the callee into a register
1507 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1508 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1509 Callee = DAG.getLoad(getPointerTy(), dl,
1510 DAG.getEntryNode(), CPAddr,
1511 MachinePointerInfo::getConstantPool(),
1512 false, false, false, 0);
1513 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1514 const char *Sym = S->getSymbol();
1516 // Create a constant pool entry for the callee address
1517 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1518 ARMConstantPoolValue *CPV =
1519 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1520 ARMPCLabelIndex, 0);
1521 // Get the address of the callee into a register
1522 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1523 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1524 Callee = DAG.getLoad(getPointerTy(), dl,
1525 DAG.getEntryNode(), CPAddr,
1526 MachinePointerInfo::getConstantPool(),
1527 false, false, false, 0);
1529 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1530 const GlobalValue *GV = G->getGlobal();
1532 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1533 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1534 getTargetMachine().getRelocationModel() != Reloc::Static;
1535 isARMFunc = !Subtarget->isThumb() || isStub;
1536 // ARM call to a local ARM function is predicable.
1537 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1538 // tBX takes a register source operand.
1539 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1540 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1541 ARMConstantPoolValue *CPV =
1542 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1543 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1544 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1545 Callee = DAG.getLoad(getPointerTy(), dl,
1546 DAG.getEntryNode(), CPAddr,
1547 MachinePointerInfo::getConstantPool(),
1548 false, false, false, 0);
1549 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1550 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1551 getPointerTy(), Callee, PICLabel);
1553 // On ELF targets for PIC code, direct calls should go through the PLT
1554 unsigned OpFlags = 0;
1555 if (Subtarget->isTargetELF() &&
1556 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1557 OpFlags = ARMII::MO_PLT;
1558 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1560 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1562 bool isStub = Subtarget->isTargetDarwin() &&
1563 getTargetMachine().getRelocationModel() != Reloc::Static;
1564 isARMFunc = !Subtarget->isThumb() || isStub;
1565 // tBX takes a register source operand.
1566 const char *Sym = S->getSymbol();
1567 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1568 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1569 ARMConstantPoolValue *CPV =
1570 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1571 ARMPCLabelIndex, 4);
1572 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1573 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1574 Callee = DAG.getLoad(getPointerTy(), dl,
1575 DAG.getEntryNode(), CPAddr,
1576 MachinePointerInfo::getConstantPool(),
1577 false, false, false, 0);
1578 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1579 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1580 getPointerTy(), Callee, PICLabel);
1582 unsigned OpFlags = 0;
1583 // On ELF targets for PIC code, direct calls should go through the PLT
1584 if (Subtarget->isTargetELF() &&
1585 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1586 OpFlags = ARMII::MO_PLT;
1587 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1591 // FIXME: handle tail calls differently.
1593 if (Subtarget->isThumb()) {
1594 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1595 CallOpc = ARMISD::CALL_NOLINK;
1596 else if (doesNotRet && isDirect && !isARMFunc &&
1597 Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1598 // "mov lr, pc; b _foo" to avoid confusing the RSP
1599 CallOpc = ARMISD::CALL_NOLINK;
1601 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1603 if (!isDirect && !Subtarget->hasV5TOps()) {
1604 CallOpc = ARMISD::CALL_NOLINK;
1605 } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1606 // "mov lr, pc; b _foo" to avoid confusing the RSP
1607 CallOpc = ARMISD::CALL_NOLINK;
1609 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1612 std::vector<SDValue> Ops;
1613 Ops.push_back(Chain);
1614 Ops.push_back(Callee);
1616 // Add argument registers to the end of the list so that they are known live
1618 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1619 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1620 RegsToPass[i].second.getValueType()));
1622 // Add a register mask operand representing the call-preserved registers.
1623 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1624 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1625 assert(Mask && "Missing call preserved mask for calling convention");
1626 Ops.push_back(DAG.getRegisterMask(Mask));
1628 if (InFlag.getNode())
1629 Ops.push_back(InFlag);
1631 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1633 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1635 // Returns a chain and a flag for retval copy to use.
1636 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1637 InFlag = Chain.getValue(1);
1639 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1640 DAG.getIntPtrConstant(0, true), InFlag);
1642 InFlag = Chain.getValue(1);
1644 // Handle result values, copying them out of physregs into vregs that we
1646 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1650 /// HandleByVal - Every parameter *after* a byval parameter is passed
1651 /// on the stack. Remember the next parameter register to allocate,
1652 /// and then confiscate the rest of the parameter registers to insure
1655 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1656 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1657 assert((State->getCallOrPrologue() == Prologue ||
1658 State->getCallOrPrologue() == Call) &&
1659 "unhandled ParmContext");
1660 if ((!State->isFirstByValRegValid()) &&
1661 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1662 State->setFirstByValReg(reg);
1663 // At a call site, a byval parameter that is split between
1664 // registers and memory needs its size truncated here. In a
1665 // function prologue, such byval parameters are reassembled in
1666 // memory, and are not truncated.
1667 if (State->getCallOrPrologue() == Call) {
1668 unsigned excess = 4 * (ARM::R4 - reg);
1669 assert(size >= excess && "expected larger existing stack allocation");
1673 // Confiscate any remaining parameter registers to preclude their
1674 // assignment to subsequent parameters.
1675 while (State->AllocateReg(GPRArgRegs, 4))
1679 /// MatchingStackOffset - Return true if the given stack call argument is
1680 /// already available in the same position (relatively) of the caller's
1681 /// incoming argument stack.
1683 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1684 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1685 const TargetInstrInfo *TII) {
1686 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1688 if (Arg.getOpcode() == ISD::CopyFromReg) {
1689 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1690 if (!TargetRegisterInfo::isVirtualRegister(VR))
1692 MachineInstr *Def = MRI->getVRegDef(VR);
1695 if (!Flags.isByVal()) {
1696 if (!TII->isLoadFromStackSlot(Def, FI))
1701 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1702 if (Flags.isByVal())
1703 // ByVal argument is passed in as a pointer but it's now being
1704 // dereferenced. e.g.
1705 // define @foo(%struct.X* %A) {
1706 // tail call @bar(%struct.X* byval %A)
1709 SDValue Ptr = Ld->getBasePtr();
1710 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1713 FI = FINode->getIndex();
1717 assert(FI != INT_MAX);
1718 if (!MFI->isFixedObjectIndex(FI))
1720 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1723 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1724 /// for tail call optimization. Targets which want to do tail call
1725 /// optimization should implement this function.
1727 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1728 CallingConv::ID CalleeCC,
1730 bool isCalleeStructRet,
1731 bool isCallerStructRet,
1732 const SmallVectorImpl<ISD::OutputArg> &Outs,
1733 const SmallVectorImpl<SDValue> &OutVals,
1734 const SmallVectorImpl<ISD::InputArg> &Ins,
1735 SelectionDAG& DAG) const {
1736 const Function *CallerF = DAG.getMachineFunction().getFunction();
1737 CallingConv::ID CallerCC = CallerF->getCallingConv();
1738 bool CCMatch = CallerCC == CalleeCC;
1740 // Look for obvious safe cases to perform tail call optimization that do not
1741 // require ABI changes. This is what gcc calls sibcall.
1743 // Do not sibcall optimize vararg calls unless the call site is not passing
1745 if (isVarArg && !Outs.empty())
1748 // Also avoid sibcall optimization if either caller or callee uses struct
1749 // return semantics.
1750 if (isCalleeStructRet || isCallerStructRet)
1753 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1754 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1755 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1756 // support in the assembler and linker to be used. This would need to be
1757 // fixed to fully support tail calls in Thumb1.
1759 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1760 // LR. This means if we need to reload LR, it takes an extra instructions,
1761 // which outweighs the value of the tail call; but here we don't know yet
1762 // whether LR is going to be used. Probably the right approach is to
1763 // generate the tail call here and turn it back into CALL/RET in
1764 // emitEpilogue if LR is used.
1766 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1767 // but we need to make sure there are enough registers; the only valid
1768 // registers are the 4 used for parameters. We don't currently do this
1770 if (Subtarget->isThumb1Only())
1773 // If the calling conventions do not match, then we'd better make sure the
1774 // results are returned in the same way as what the caller expects.
1776 SmallVector<CCValAssign, 16> RVLocs1;
1777 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1778 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1779 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1781 SmallVector<CCValAssign, 16> RVLocs2;
1782 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1783 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1784 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1786 if (RVLocs1.size() != RVLocs2.size())
1788 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1789 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1791 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1793 if (RVLocs1[i].isRegLoc()) {
1794 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1797 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1803 // If the callee takes no arguments then go on to check the results of the
1805 if (!Outs.empty()) {
1806 // Check if stack adjustment is needed. For now, do not do this if any
1807 // argument is passed on the stack.
1808 SmallVector<CCValAssign, 16> ArgLocs;
1809 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1810 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1811 CCInfo.AnalyzeCallOperands(Outs,
1812 CCAssignFnForNode(CalleeCC, false, isVarArg));
1813 if (CCInfo.getNextStackOffset()) {
1814 MachineFunction &MF = DAG.getMachineFunction();
1816 // Check if the arguments are already laid out in the right way as
1817 // the caller's fixed stack objects.
1818 MachineFrameInfo *MFI = MF.getFrameInfo();
1819 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1820 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1821 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1823 ++i, ++realArgIdx) {
1824 CCValAssign &VA = ArgLocs[i];
1825 EVT RegVT = VA.getLocVT();
1826 SDValue Arg = OutVals[realArgIdx];
1827 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1828 if (VA.getLocInfo() == CCValAssign::Indirect)
1830 if (VA.needsCustom()) {
1831 // f64 and vector types are split into multiple registers or
1832 // register/stack-slot combinations. The types will not match
1833 // the registers; give up on memory f64 refs until we figure
1834 // out what to do about this.
1837 if (!ArgLocs[++i].isRegLoc())
1839 if (RegVT == MVT::v2f64) {
1840 if (!ArgLocs[++i].isRegLoc())
1842 if (!ArgLocs[++i].isRegLoc())
1845 } else if (!VA.isRegLoc()) {
1846 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1858 ARMTargetLowering::LowerReturn(SDValue Chain,
1859 CallingConv::ID CallConv, bool isVarArg,
1860 const SmallVectorImpl<ISD::OutputArg> &Outs,
1861 const SmallVectorImpl<SDValue> &OutVals,
1862 DebugLoc dl, SelectionDAG &DAG) const {
1864 // CCValAssign - represent the assignment of the return value to a location.
1865 SmallVector<CCValAssign, 16> RVLocs;
1867 // CCState - Info about the registers and stack slots.
1868 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1869 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1871 // Analyze outgoing return values.
1872 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1875 // If this is the first return lowered for this function, add
1876 // the regs to the liveout set for the function.
1877 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1878 for (unsigned i = 0; i != RVLocs.size(); ++i)
1879 if (RVLocs[i].isRegLoc())
1880 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1885 // Copy the result values into the output registers.
1886 for (unsigned i = 0, realRVLocIdx = 0;
1888 ++i, ++realRVLocIdx) {
1889 CCValAssign &VA = RVLocs[i];
1890 assert(VA.isRegLoc() && "Can only return in registers!");
1892 SDValue Arg = OutVals[realRVLocIdx];
1894 switch (VA.getLocInfo()) {
1895 default: llvm_unreachable("Unknown loc info!");
1896 case CCValAssign::Full: break;
1897 case CCValAssign::BCvt:
1898 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1902 if (VA.needsCustom()) {
1903 if (VA.getLocVT() == MVT::v2f64) {
1904 // Extract the first half and return it in two registers.
1905 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1906 DAG.getConstant(0, MVT::i32));
1907 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1908 DAG.getVTList(MVT::i32, MVT::i32), Half);
1910 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1911 Flag = Chain.getValue(1);
1912 VA = RVLocs[++i]; // skip ahead to next loc
1913 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1914 HalfGPRs.getValue(1), Flag);
1915 Flag = Chain.getValue(1);
1916 VA = RVLocs[++i]; // skip ahead to next loc
1918 // Extract the 2nd half and fall through to handle it as an f64 value.
1919 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1920 DAG.getConstant(1, MVT::i32));
1922 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1924 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1925 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1926 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1927 Flag = Chain.getValue(1);
1928 VA = RVLocs[++i]; // skip ahead to next loc
1929 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1932 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1934 // Guarantee that all emitted copies are
1935 // stuck together, avoiding something bad.
1936 Flag = Chain.getValue(1);
1941 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1943 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1948 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1949 if (N->getNumValues() != 1)
1951 if (!N->hasNUsesOfValue(1, 0))
1954 SDValue TCChain = Chain;
1955 SDNode *Copy = *N->use_begin();
1956 if (Copy->getOpcode() == ISD::CopyToReg) {
1957 // If the copy has a glue operand, we conservatively assume it isn't safe to
1958 // perform a tail call.
1959 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1961 TCChain = Copy->getOperand(0);
1962 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1963 SDNode *VMov = Copy;
1964 // f64 returned in a pair of GPRs.
1965 SmallPtrSet<SDNode*, 2> Copies;
1966 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1968 if (UI->getOpcode() != ISD::CopyToReg)
1972 if (Copies.size() > 2)
1975 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1977 SDValue UseChain = UI->getOperand(0);
1978 if (Copies.count(UseChain.getNode()))
1985 } else if (Copy->getOpcode() == ISD::BITCAST) {
1986 // f32 returned in a single GPR.
1987 if (!Copy->hasOneUse())
1989 Copy = *Copy->use_begin();
1990 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1992 Chain = Copy->getOperand(0);
1997 bool HasRet = false;
1998 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2000 if (UI->getOpcode() != ARMISD::RET_FLAG)
2012 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2013 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2016 if (!CI->isTailCall())
2019 return !Subtarget->isThumb1Only();
2022 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2023 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2024 // one of the above mentioned nodes. It has to be wrapped because otherwise
2025 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2026 // be used to form addressing mode. These wrapped nodes will be selected
2028 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2029 EVT PtrVT = Op.getValueType();
2030 // FIXME there is no actual debug info here
2031 DebugLoc dl = Op.getDebugLoc();
2032 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2034 if (CP->isMachineConstantPoolEntry())
2035 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2036 CP->getAlignment());
2038 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2039 CP->getAlignment());
2040 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2043 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2044 return MachineJumpTableInfo::EK_Inline;
2047 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2048 SelectionDAG &DAG) const {
2049 MachineFunction &MF = DAG.getMachineFunction();
2050 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2051 unsigned ARMPCLabelIndex = 0;
2052 DebugLoc DL = Op.getDebugLoc();
2053 EVT PtrVT = getPointerTy();
2054 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2055 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2057 if (RelocM == Reloc::Static) {
2058 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2060 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2061 ARMPCLabelIndex = AFI->createPICLabelUId();
2062 ARMConstantPoolValue *CPV =
2063 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2064 ARMCP::CPBlockAddress, PCAdj);
2065 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2067 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2068 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2069 MachinePointerInfo::getConstantPool(),
2070 false, false, false, 0);
2071 if (RelocM == Reloc::Static)
2073 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2074 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2077 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2079 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2080 SelectionDAG &DAG) const {
2081 DebugLoc dl = GA->getDebugLoc();
2082 EVT PtrVT = getPointerTy();
2083 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2084 MachineFunction &MF = DAG.getMachineFunction();
2085 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2086 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2087 ARMConstantPoolValue *CPV =
2088 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2089 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2090 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2091 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2092 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2093 MachinePointerInfo::getConstantPool(),
2094 false, false, false, 0);
2095 SDValue Chain = Argument.getValue(1);
2097 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2098 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2100 // call __tls_get_addr.
2103 Entry.Node = Argument;
2104 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2105 Args.push_back(Entry);
2106 // FIXME: is there useful debug info available here?
2107 TargetLowering::CallLoweringInfo CLI(Chain,
2108 (Type *) Type::getInt32Ty(*DAG.getContext()),
2109 false, false, false, false,
2110 0, CallingConv::C, /*isTailCall=*/false,
2111 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2112 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2113 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2114 return CallResult.first;
2117 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2118 // "local exec" model.
2120 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2122 TLSModel::Model model) const {
2123 const GlobalValue *GV = GA->getGlobal();
2124 DebugLoc dl = GA->getDebugLoc();
2126 SDValue Chain = DAG.getEntryNode();
2127 EVT PtrVT = getPointerTy();
2128 // Get the Thread Pointer
2129 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2131 if (model == TLSModel::InitialExec) {
2132 MachineFunction &MF = DAG.getMachineFunction();
2133 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2134 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2135 // Initial exec model.
2136 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2137 ARMConstantPoolValue *CPV =
2138 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2139 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2141 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2142 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2143 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2144 MachinePointerInfo::getConstantPool(),
2145 false, false, false, 0);
2146 Chain = Offset.getValue(1);
2148 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2149 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2151 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2152 MachinePointerInfo::getConstantPool(),
2153 false, false, false, 0);
2156 assert(model == TLSModel::LocalExec);
2157 ARMConstantPoolValue *CPV =
2158 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2159 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2160 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2161 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2162 MachinePointerInfo::getConstantPool(),
2163 false, false, false, 0);
2166 // The address of the thread local variable is the add of the thread
2167 // pointer with the offset of the variable.
2168 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2172 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2173 // TODO: implement the "local dynamic" model
2174 assert(Subtarget->isTargetELF() &&
2175 "TLS not implemented for non-ELF targets");
2176 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2178 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2181 case TLSModel::GeneralDynamic:
2182 case TLSModel::LocalDynamic:
2183 return LowerToTLSGeneralDynamicModel(GA, DAG);
2184 case TLSModel::InitialExec:
2185 case TLSModel::LocalExec:
2186 return LowerToTLSExecModels(GA, DAG, model);
2188 llvm_unreachable("bogus TLS model");
2191 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2192 SelectionDAG &DAG) const {
2193 EVT PtrVT = getPointerTy();
2194 DebugLoc dl = Op.getDebugLoc();
2195 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2196 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2197 if (RelocM == Reloc::PIC_) {
2198 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2199 ARMConstantPoolValue *CPV =
2200 ARMConstantPoolConstant::Create(GV,
2201 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2202 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2203 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2204 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2206 MachinePointerInfo::getConstantPool(),
2207 false, false, false, 0);
2208 SDValue Chain = Result.getValue(1);
2209 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2210 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2212 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2213 MachinePointerInfo::getGOT(),
2214 false, false, false, 0);
2218 // If we have T2 ops, we can materialize the address directly via movt/movw
2219 // pair. This is always cheaper.
2220 if (Subtarget->useMovt()) {
2222 // FIXME: Once remat is capable of dealing with instructions with register
2223 // operands, expand this into two nodes.
2224 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2225 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2227 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2228 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2229 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2230 MachinePointerInfo::getConstantPool(),
2231 false, false, false, 0);
2235 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2236 SelectionDAG &DAG) const {
2237 EVT PtrVT = getPointerTy();
2238 DebugLoc dl = Op.getDebugLoc();
2239 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2240 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2241 MachineFunction &MF = DAG.getMachineFunction();
2242 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2244 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2245 // update ARMFastISel::ARMMaterializeGV.
2246 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2248 // FIXME: Once remat is capable of dealing with instructions with register
2249 // operands, expand this into two nodes.
2250 if (RelocM == Reloc::Static)
2251 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2252 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2254 unsigned Wrapper = (RelocM == Reloc::PIC_)
2255 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2256 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2257 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2258 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2259 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2260 MachinePointerInfo::getGOT(),
2261 false, false, false, 0);
2265 unsigned ARMPCLabelIndex = 0;
2267 if (RelocM == Reloc::Static) {
2268 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2270 ARMPCLabelIndex = AFI->createPICLabelUId();
2271 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2272 ARMConstantPoolValue *CPV =
2273 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2275 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2277 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2279 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2280 MachinePointerInfo::getConstantPool(),
2281 false, false, false, 0);
2282 SDValue Chain = Result.getValue(1);
2284 if (RelocM == Reloc::PIC_) {
2285 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2286 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2289 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2290 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2291 false, false, false, 0);
2296 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2297 SelectionDAG &DAG) const {
2298 assert(Subtarget->isTargetELF() &&
2299 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2300 MachineFunction &MF = DAG.getMachineFunction();
2301 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2302 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2303 EVT PtrVT = getPointerTy();
2304 DebugLoc dl = Op.getDebugLoc();
2305 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2306 ARMConstantPoolValue *CPV =
2307 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2308 ARMPCLabelIndex, PCAdj);
2309 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2310 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2311 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2312 MachinePointerInfo::getConstantPool(),
2313 false, false, false, 0);
2314 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2315 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2319 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2320 DebugLoc dl = Op.getDebugLoc();
2321 SDValue Val = DAG.getConstant(0, MVT::i32);
2322 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2323 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2324 Op.getOperand(1), Val);
2328 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2329 DebugLoc dl = Op.getDebugLoc();
2330 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2331 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2335 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2336 const ARMSubtarget *Subtarget) const {
2337 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2338 DebugLoc dl = Op.getDebugLoc();
2340 default: return SDValue(); // Don't custom lower most intrinsics.
2341 case Intrinsic::arm_thread_pointer: {
2342 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2343 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2345 case Intrinsic::eh_sjlj_lsda: {
2346 MachineFunction &MF = DAG.getMachineFunction();
2347 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2348 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2349 EVT PtrVT = getPointerTy();
2350 DebugLoc dl = Op.getDebugLoc();
2351 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2353 unsigned PCAdj = (RelocM != Reloc::PIC_)
2354 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2355 ARMConstantPoolValue *CPV =
2356 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2357 ARMCP::CPLSDA, PCAdj);
2358 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2359 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2361 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2362 MachinePointerInfo::getConstantPool(),
2363 false, false, false, 0);
2365 if (RelocM == Reloc::PIC_) {
2366 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2367 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2371 case Intrinsic::arm_neon_vmulls:
2372 case Intrinsic::arm_neon_vmullu: {
2373 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2374 ? ARMISD::VMULLs : ARMISD::VMULLu;
2375 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2376 Op.getOperand(1), Op.getOperand(2));
2381 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2382 const ARMSubtarget *Subtarget) {
2383 DebugLoc dl = Op.getDebugLoc();
2384 if (!Subtarget->hasDataBarrier()) {
2385 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2386 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2388 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2389 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2390 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2391 DAG.getConstant(0, MVT::i32));
2394 SDValue Op5 = Op.getOperand(5);
2395 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2396 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2397 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2398 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2400 ARM_MB::MemBOpt DMBOpt;
2401 if (isDeviceBarrier)
2402 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2404 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2405 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2406 DAG.getConstant(DMBOpt, MVT::i32));
2410 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2411 const ARMSubtarget *Subtarget) {
2412 // FIXME: handle "fence singlethread" more efficiently.
2413 DebugLoc dl = Op.getDebugLoc();
2414 if (!Subtarget->hasDataBarrier()) {
2415 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2416 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2418 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2419 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2420 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2421 DAG.getConstant(0, MVT::i32));
2424 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2425 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2428 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2429 const ARMSubtarget *Subtarget) {
2430 // ARM pre v5TE and Thumb1 does not have preload instructions.
2431 if (!(Subtarget->isThumb2() ||
2432 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2433 // Just preserve the chain.
2434 return Op.getOperand(0);
2436 DebugLoc dl = Op.getDebugLoc();
2437 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2439 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2440 // ARMv7 with MP extension has PLDW.
2441 return Op.getOperand(0);
2443 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2444 if (Subtarget->isThumb()) {
2446 isRead = ~isRead & 1;
2447 isData = ~isData & 1;
2450 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2451 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2452 DAG.getConstant(isData, MVT::i32));
2455 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2456 MachineFunction &MF = DAG.getMachineFunction();
2457 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2459 // vastart just stores the address of the VarArgsFrameIndex slot into the
2460 // memory location argument.
2461 DebugLoc dl = Op.getDebugLoc();
2462 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2463 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2464 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2465 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2466 MachinePointerInfo(SV), false, false, 0);
2470 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2471 SDValue &Root, SelectionDAG &DAG,
2472 DebugLoc dl) const {
2473 MachineFunction &MF = DAG.getMachineFunction();
2474 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2476 const TargetRegisterClass *RC;
2477 if (AFI->isThumb1OnlyFunction())
2478 RC = &ARM::tGPRRegClass;
2480 RC = &ARM::GPRRegClass;
2482 // Transform the arguments stored in physical registers into virtual ones.
2483 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2484 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2487 if (NextVA.isMemLoc()) {
2488 MachineFrameInfo *MFI = MF.getFrameInfo();
2489 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2491 // Create load node to retrieve arguments from the stack.
2492 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2493 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2494 MachinePointerInfo::getFixedStack(FI),
2495 false, false, false, 0);
2497 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2498 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2501 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2505 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2506 unsigned &VARegSize, unsigned &VARegSaveSize)
2509 if (CCInfo.isFirstByValRegValid())
2510 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2512 unsigned int firstUnalloced;
2513 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2514 sizeof(GPRArgRegs) /
2515 sizeof(GPRArgRegs[0]));
2516 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2519 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2520 VARegSize = NumGPRs * 4;
2521 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2524 // The remaining GPRs hold either the beginning of variable-argument
2525 // data, or the beginning of an aggregate passed by value (usuall
2526 // byval). Either way, we allocate stack slots adjacent to the data
2527 // provided by our caller, and store the unallocated registers there.
2528 // If this is a variadic function, the va_list pointer will begin with
2529 // these values; otherwise, this reassembles a (byval) structure that
2530 // was split between registers and memory.
2532 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2533 DebugLoc dl, SDValue &Chain,
2534 unsigned ArgOffset) const {
2535 MachineFunction &MF = DAG.getMachineFunction();
2536 MachineFrameInfo *MFI = MF.getFrameInfo();
2537 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2538 unsigned firstRegToSaveIndex;
2539 if (CCInfo.isFirstByValRegValid())
2540 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2542 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2543 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2546 unsigned VARegSize, VARegSaveSize;
2547 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2548 if (VARegSaveSize) {
2549 // If this function is vararg, store any remaining integer argument regs
2550 // to their spots on the stack so that they may be loaded by deferencing
2551 // the result of va_next.
2552 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2553 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2554 ArgOffset + VARegSaveSize
2557 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2560 SmallVector<SDValue, 4> MemOps;
2561 for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2562 const TargetRegisterClass *RC;
2563 if (AFI->isThumb1OnlyFunction())
2564 RC = &ARM::tGPRRegClass;
2566 RC = &ARM::GPRRegClass;
2568 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2569 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2571 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2572 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2574 MemOps.push_back(Store);
2575 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2576 DAG.getConstant(4, getPointerTy()));
2578 if (!MemOps.empty())
2579 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2580 &MemOps[0], MemOps.size());
2582 // This will point to the next argument passed via stack.
2583 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2587 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2588 CallingConv::ID CallConv, bool isVarArg,
2589 const SmallVectorImpl<ISD::InputArg>
2591 DebugLoc dl, SelectionDAG &DAG,
2592 SmallVectorImpl<SDValue> &InVals)
2594 MachineFunction &MF = DAG.getMachineFunction();
2595 MachineFrameInfo *MFI = MF.getFrameInfo();
2597 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2599 // Assign locations to all of the incoming arguments.
2600 SmallVector<CCValAssign, 16> ArgLocs;
2601 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2602 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2603 CCInfo.AnalyzeFormalArguments(Ins,
2604 CCAssignFnForNode(CallConv, /* Return*/ false,
2607 SmallVector<SDValue, 16> ArgValues;
2608 int lastInsIndex = -1;
2611 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2612 CCValAssign &VA = ArgLocs[i];
2614 // Arguments stored in registers.
2615 if (VA.isRegLoc()) {
2616 EVT RegVT = VA.getLocVT();
2618 if (VA.needsCustom()) {
2619 // f64 and vector types are split up into multiple registers or
2620 // combinations of registers and stack slots.
2621 if (VA.getLocVT() == MVT::v2f64) {
2622 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2624 VA = ArgLocs[++i]; // skip ahead to next loc
2626 if (VA.isMemLoc()) {
2627 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2628 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2629 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2630 MachinePointerInfo::getFixedStack(FI),
2631 false, false, false, 0);
2633 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2636 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2637 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2638 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2639 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2640 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2642 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2645 const TargetRegisterClass *RC;
2647 if (RegVT == MVT::f32)
2648 RC = &ARM::SPRRegClass;
2649 else if (RegVT == MVT::f64)
2650 RC = &ARM::DPRRegClass;
2651 else if (RegVT == MVT::v2f64)
2652 RC = &ARM::QPRRegClass;
2653 else if (RegVT == MVT::i32)
2654 RC = AFI->isThumb1OnlyFunction() ?
2655 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2656 (const TargetRegisterClass*)&ARM::GPRRegClass;
2658 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2660 // Transform the arguments in physical registers into virtual ones.
2661 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2662 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2665 // If this is an 8 or 16-bit value, it is really passed promoted
2666 // to 32 bits. Insert an assert[sz]ext to capture this, then
2667 // truncate to the right size.
2668 switch (VA.getLocInfo()) {
2669 default: llvm_unreachable("Unknown loc info!");
2670 case CCValAssign::Full: break;
2671 case CCValAssign::BCvt:
2672 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2674 case CCValAssign::SExt:
2675 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2676 DAG.getValueType(VA.getValVT()));
2677 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2679 case CCValAssign::ZExt:
2680 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2681 DAG.getValueType(VA.getValVT()));
2682 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2686 InVals.push_back(ArgValue);
2688 } else { // VA.isRegLoc()
2691 assert(VA.isMemLoc());
2692 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2694 int index = ArgLocs[i].getValNo();
2696 // Some Ins[] entries become multiple ArgLoc[] entries.
2697 // Process them only once.
2698 if (index != lastInsIndex)
2700 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2701 // FIXME: For now, all byval parameter objects are marked mutable.
2702 // This can be changed with more analysis.
2703 // In case of tail call optimization mark all arguments mutable.
2704 // Since they could be overwritten by lowering of arguments in case of
2706 if (Flags.isByVal()) {
2707 unsigned VARegSize, VARegSaveSize;
2708 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2709 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2710 unsigned Bytes = Flags.getByValSize() - VARegSize;
2711 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2712 int FI = MFI->CreateFixedObject(Bytes,
2713 VA.getLocMemOffset(), false);
2714 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2716 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2717 VA.getLocMemOffset(), true);
2719 // Create load nodes to retrieve arguments from the stack.
2720 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2721 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2722 MachinePointerInfo::getFixedStack(FI),
2723 false, false, false, 0));
2725 lastInsIndex = index;
2732 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2737 /// isFloatingPointZero - Return true if this is +0.0.
2738 static bool isFloatingPointZero(SDValue Op) {
2739 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2740 return CFP->getValueAPF().isPosZero();
2741 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2742 // Maybe this has already been legalized into the constant pool?
2743 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2744 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2745 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2746 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2747 return CFP->getValueAPF().isPosZero();
2753 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2754 /// the given operands.
2756 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2757 SDValue &ARMcc, SelectionDAG &DAG,
2758 DebugLoc dl) const {
2759 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2760 unsigned C = RHSC->getZExtValue();
2761 if (!isLegalICmpImmediate(C)) {
2762 // Constant does not fit, try adjusting it by one?
2767 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2768 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2769 RHS = DAG.getConstant(C-1, MVT::i32);
2774 if (C != 0 && isLegalICmpImmediate(C-1)) {
2775 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2776 RHS = DAG.getConstant(C-1, MVT::i32);
2781 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2782 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2783 RHS = DAG.getConstant(C+1, MVT::i32);
2788 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2789 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2790 RHS = DAG.getConstant(C+1, MVT::i32);
2797 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2798 ARMISD::NodeType CompareType;
2801 CompareType = ARMISD::CMP;
2806 CompareType = ARMISD::CMPZ;
2809 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2810 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2813 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2815 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2816 DebugLoc dl) const {
2818 if (!isFloatingPointZero(RHS))
2819 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2821 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2822 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2825 /// duplicateCmp - Glue values can have only one use, so this function
2826 /// duplicates a comparison node.
2828 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2829 unsigned Opc = Cmp.getOpcode();
2830 DebugLoc DL = Cmp.getDebugLoc();
2831 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2832 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2834 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2835 Cmp = Cmp.getOperand(0);
2836 Opc = Cmp.getOpcode();
2837 if (Opc == ARMISD::CMPFP)
2838 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2840 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2841 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2843 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2846 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2847 SDValue Cond = Op.getOperand(0);
2848 SDValue SelectTrue = Op.getOperand(1);
2849 SDValue SelectFalse = Op.getOperand(2);
2850 DebugLoc dl = Op.getDebugLoc();
2854 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2855 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2857 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2858 const ConstantSDNode *CMOVTrue =
2859 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2860 const ConstantSDNode *CMOVFalse =
2861 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2863 if (CMOVTrue && CMOVFalse) {
2864 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2865 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2869 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2871 False = SelectFalse;
2872 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2877 if (True.getNode() && False.getNode()) {
2878 EVT VT = Op.getValueType();
2879 SDValue ARMcc = Cond.getOperand(2);
2880 SDValue CCR = Cond.getOperand(3);
2881 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2882 assert(True.getValueType() == VT);
2883 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2888 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2889 // undefined bits before doing a full-word comparison with zero.
2890 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2891 DAG.getConstant(1, Cond.getValueType()));
2893 return DAG.getSelectCC(dl, Cond,
2894 DAG.getConstant(0, Cond.getValueType()),
2895 SelectTrue, SelectFalse, ISD::SETNE);
2898 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2899 EVT VT = Op.getValueType();
2900 SDValue LHS = Op.getOperand(0);
2901 SDValue RHS = Op.getOperand(1);
2902 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2903 SDValue TrueVal = Op.getOperand(2);
2904 SDValue FalseVal = Op.getOperand(3);
2905 DebugLoc dl = Op.getDebugLoc();
2907 if (LHS.getValueType() == MVT::i32) {
2909 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2910 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2911 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2914 ARMCC::CondCodes CondCode, CondCode2;
2915 FPCCToARMCC(CC, CondCode, CondCode2);
2917 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2918 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2919 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2920 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2922 if (CondCode2 != ARMCC::AL) {
2923 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2924 // FIXME: Needs another CMP because flag can have but one use.
2925 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2926 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2927 Result, TrueVal, ARMcc2, CCR, Cmp2);
2932 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2933 /// to morph to an integer compare sequence.
2934 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2935 const ARMSubtarget *Subtarget) {
2936 SDNode *N = Op.getNode();
2937 if (!N->hasOneUse())
2938 // Otherwise it requires moving the value from fp to integer registers.
2940 if (!N->getNumValues())
2942 EVT VT = Op.getValueType();
2943 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2944 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2945 // vmrs are very slow, e.g. cortex-a8.
2948 if (isFloatingPointZero(Op)) {
2952 return ISD::isNormalLoad(N);
2955 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2956 if (isFloatingPointZero(Op))
2957 return DAG.getConstant(0, MVT::i32);
2959 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2960 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2961 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2962 Ld->isVolatile(), Ld->isNonTemporal(),
2963 Ld->isInvariant(), Ld->getAlignment());
2965 llvm_unreachable("Unknown VFP cmp argument!");
2968 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2969 SDValue &RetVal1, SDValue &RetVal2) {
2970 if (isFloatingPointZero(Op)) {
2971 RetVal1 = DAG.getConstant(0, MVT::i32);
2972 RetVal2 = DAG.getConstant(0, MVT::i32);
2976 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2977 SDValue Ptr = Ld->getBasePtr();
2978 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2979 Ld->getChain(), Ptr,
2980 Ld->getPointerInfo(),
2981 Ld->isVolatile(), Ld->isNonTemporal(),
2982 Ld->isInvariant(), Ld->getAlignment());
2984 EVT PtrType = Ptr.getValueType();
2985 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2986 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2987 PtrType, Ptr, DAG.getConstant(4, PtrType));
2988 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2989 Ld->getChain(), NewPtr,
2990 Ld->getPointerInfo().getWithOffset(4),
2991 Ld->isVolatile(), Ld->isNonTemporal(),
2992 Ld->isInvariant(), NewAlign);
2996 llvm_unreachable("Unknown VFP cmp argument!");
2999 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3000 /// f32 and even f64 comparisons to integer ones.
3002 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3003 SDValue Chain = Op.getOperand(0);
3004 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3005 SDValue LHS = Op.getOperand(2);
3006 SDValue RHS = Op.getOperand(3);
3007 SDValue Dest = Op.getOperand(4);
3008 DebugLoc dl = Op.getDebugLoc();
3010 bool LHSSeenZero = false;
3011 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3012 bool RHSSeenZero = false;
3013 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3014 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3015 // If unsafe fp math optimization is enabled and there are no other uses of
3016 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3017 // to an integer comparison.
3018 if (CC == ISD::SETOEQ)
3020 else if (CC == ISD::SETUNE)
3023 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3025 if (LHS.getValueType() == MVT::f32) {
3026 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3027 bitcastf32Toi32(LHS, DAG), Mask);
3028 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3029 bitcastf32Toi32(RHS, DAG), Mask);
3030 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3031 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3032 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3033 Chain, Dest, ARMcc, CCR, Cmp);
3038 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3039 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3040 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3041 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3042 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3043 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3044 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3045 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3046 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3052 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3053 SDValue Chain = Op.getOperand(0);
3054 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3055 SDValue LHS = Op.getOperand(2);
3056 SDValue RHS = Op.getOperand(3);
3057 SDValue Dest = Op.getOperand(4);
3058 DebugLoc dl = Op.getDebugLoc();
3060 if (LHS.getValueType() == MVT::i32) {
3062 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3063 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3064 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3065 Chain, Dest, ARMcc, CCR, Cmp);
3068 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3070 if (getTargetMachine().Options.UnsafeFPMath &&
3071 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3072 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3073 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3074 if (Result.getNode())
3078 ARMCC::CondCodes CondCode, CondCode2;
3079 FPCCToARMCC(CC, CondCode, CondCode2);
3081 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3082 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3083 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3084 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3085 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3086 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3087 if (CondCode2 != ARMCC::AL) {
3088 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3089 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3090 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3095 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3096 SDValue Chain = Op.getOperand(0);
3097 SDValue Table = Op.getOperand(1);
3098 SDValue Index = Op.getOperand(2);
3099 DebugLoc dl = Op.getDebugLoc();
3101 EVT PTy = getPointerTy();
3102 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3103 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3104 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3105 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3106 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3107 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3108 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3109 if (Subtarget->isThumb2()) {
3110 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3111 // which does another jump to the destination. This also makes it easier
3112 // to translate it to TBB / TBH later.
3113 // FIXME: This might not work if the function is extremely large.
3114 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3115 Addr, Op.getOperand(2), JTI, UId);
3117 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3118 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3119 MachinePointerInfo::getJumpTable(),
3120 false, false, false, 0);
3121 Chain = Addr.getValue(1);
3122 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3123 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3125 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3126 MachinePointerInfo::getJumpTable(),
3127 false, false, false, 0);
3128 Chain = Addr.getValue(1);
3129 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3133 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3134 EVT VT = Op.getValueType();
3135 DebugLoc dl = Op.getDebugLoc();
3137 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3138 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3140 return DAG.UnrollVectorOp(Op.getNode());
3143 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3144 "Invalid type for custom lowering!");
3145 if (VT != MVT::v4i16)
3146 return DAG.UnrollVectorOp(Op.getNode());
3148 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3149 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3152 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3153 EVT VT = Op.getValueType();
3155 return LowerVectorFP_TO_INT(Op, DAG);
3157 DebugLoc dl = Op.getDebugLoc();
3160 switch (Op.getOpcode()) {
3161 default: llvm_unreachable("Invalid opcode!");
3162 case ISD::FP_TO_SINT:
3163 Opc = ARMISD::FTOSI;
3165 case ISD::FP_TO_UINT:
3166 Opc = ARMISD::FTOUI;
3169 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3170 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3173 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3174 EVT VT = Op.getValueType();
3175 DebugLoc dl = Op.getDebugLoc();
3177 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3178 if (VT.getVectorElementType() == MVT::f32)
3180 return DAG.UnrollVectorOp(Op.getNode());
3183 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3184 "Invalid type for custom lowering!");
3185 if (VT != MVT::v4f32)
3186 return DAG.UnrollVectorOp(Op.getNode());
3190 switch (Op.getOpcode()) {
3191 default: llvm_unreachable("Invalid opcode!");
3192 case ISD::SINT_TO_FP:
3193 CastOpc = ISD::SIGN_EXTEND;
3194 Opc = ISD::SINT_TO_FP;
3196 case ISD::UINT_TO_FP:
3197 CastOpc = ISD::ZERO_EXTEND;
3198 Opc = ISD::UINT_TO_FP;
3202 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3203 return DAG.getNode(Opc, dl, VT, Op);
3206 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3207 EVT VT = Op.getValueType();
3209 return LowerVectorINT_TO_FP(Op, DAG);
3211 DebugLoc dl = Op.getDebugLoc();
3214 switch (Op.getOpcode()) {
3215 default: llvm_unreachable("Invalid opcode!");
3216 case ISD::SINT_TO_FP:
3217 Opc = ARMISD::SITOF;
3219 case ISD::UINT_TO_FP:
3220 Opc = ARMISD::UITOF;
3224 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3225 return DAG.getNode(Opc, dl, VT, Op);
3228 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3229 // Implement fcopysign with a fabs and a conditional fneg.
3230 SDValue Tmp0 = Op.getOperand(0);
3231 SDValue Tmp1 = Op.getOperand(1);
3232 DebugLoc dl = Op.getDebugLoc();
3233 EVT VT = Op.getValueType();
3234 EVT SrcVT = Tmp1.getValueType();
3235 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3236 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3237 bool UseNEON = !InGPR && Subtarget->hasNEON();
3240 // Use VBSL to copy the sign bit.
3241 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3242 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3243 DAG.getTargetConstant(EncodedVal, MVT::i32));
3244 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3246 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3247 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3248 DAG.getConstant(32, MVT::i32));
3249 else /*if (VT == MVT::f32)*/
3250 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3251 if (SrcVT == MVT::f32) {
3252 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3254 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3255 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3256 DAG.getConstant(32, MVT::i32));
3257 } else if (VT == MVT::f32)
3258 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3259 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3260 DAG.getConstant(32, MVT::i32));
3261 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3262 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3264 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3266 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3267 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3268 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3270 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3271 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3272 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3273 if (VT == MVT::f32) {
3274 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3275 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3276 DAG.getConstant(0, MVT::i32));
3278 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3284 // Bitcast operand 1 to i32.
3285 if (SrcVT == MVT::f64)
3286 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3287 &Tmp1, 1).getValue(1);
3288 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3290 // Or in the signbit with integer operations.
3291 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3292 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3293 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3294 if (VT == MVT::f32) {
3295 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3296 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3297 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3298 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3301 // f64: Or the high part with signbit and then combine two parts.
3302 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3304 SDValue Lo = Tmp0.getValue(0);
3305 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3306 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3307 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3310 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3311 MachineFunction &MF = DAG.getMachineFunction();
3312 MachineFrameInfo *MFI = MF.getFrameInfo();
3313 MFI->setReturnAddressIsTaken(true);
3315 EVT VT = Op.getValueType();
3316 DebugLoc dl = Op.getDebugLoc();
3317 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3319 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3320 SDValue Offset = DAG.getConstant(4, MVT::i32);
3321 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3322 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3323 MachinePointerInfo(), false, false, false, 0);
3326 // Return LR, which contains the return address. Mark it an implicit live-in.
3327 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3328 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3331 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3332 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3333 MFI->setFrameAddressIsTaken(true);
3335 EVT VT = Op.getValueType();
3336 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3337 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3338 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3339 ? ARM::R7 : ARM::R11;
3340 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3342 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3343 MachinePointerInfo(),
3344 false, false, false, 0);
3348 /// ExpandBITCAST - If the target supports VFP, this function is called to
3349 /// expand a bit convert where either the source or destination type is i64 to
3350 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3351 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3352 /// vectors), since the legalizer won't know what to do with that.
3353 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3354 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3355 DebugLoc dl = N->getDebugLoc();
3356 SDValue Op = N->getOperand(0);
3358 // This function is only supposed to be called for i64 types, either as the
3359 // source or destination of the bit convert.
3360 EVT SrcVT = Op.getValueType();
3361 EVT DstVT = N->getValueType(0);
3362 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3363 "ExpandBITCAST called for non-i64 type");
3365 // Turn i64->f64 into VMOVDRR.
3366 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3367 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3368 DAG.getConstant(0, MVT::i32));
3369 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3370 DAG.getConstant(1, MVT::i32));
3371 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3372 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3375 // Turn f64->i64 into VMOVRRD.
3376 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3377 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3378 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3379 // Merge the pieces into a single i64 value.
3380 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3386 /// getZeroVector - Returns a vector of specified type with all zero elements.
3387 /// Zero vectors are used to represent vector negation and in those cases
3388 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3389 /// not support i64 elements, so sometimes the zero vectors will need to be
3390 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3392 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3393 assert(VT.isVector() && "Expected a vector type");
3394 // The canonical modified immediate encoding of a zero vector is....0!
3395 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3396 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3397 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3398 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3401 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3402 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3403 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3404 SelectionDAG &DAG) const {
3405 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3406 EVT VT = Op.getValueType();
3407 unsigned VTBits = VT.getSizeInBits();
3408 DebugLoc dl = Op.getDebugLoc();
3409 SDValue ShOpLo = Op.getOperand(0);
3410 SDValue ShOpHi = Op.getOperand(1);
3411 SDValue ShAmt = Op.getOperand(2);
3413 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3415 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3417 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3418 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3419 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3420 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3421 DAG.getConstant(VTBits, MVT::i32));
3422 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3423 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3424 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3426 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3427 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3429 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3430 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3433 SDValue Ops[2] = { Lo, Hi };
3434 return DAG.getMergeValues(Ops, 2, dl);
3437 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3438 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3439 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3440 SelectionDAG &DAG) const {
3441 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3442 EVT VT = Op.getValueType();
3443 unsigned VTBits = VT.getSizeInBits();
3444 DebugLoc dl = Op.getDebugLoc();
3445 SDValue ShOpLo = Op.getOperand(0);
3446 SDValue ShOpHi = Op.getOperand(1);
3447 SDValue ShAmt = Op.getOperand(2);
3450 assert(Op.getOpcode() == ISD::SHL_PARTS);
3451 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3452 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3453 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3454 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3455 DAG.getConstant(VTBits, MVT::i32));
3456 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3457 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3459 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3460 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3461 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3463 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3464 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3467 SDValue Ops[2] = { Lo, Hi };
3468 return DAG.getMergeValues(Ops, 2, dl);
3471 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3472 SelectionDAG &DAG) const {
3473 // The rounding mode is in bits 23:22 of the FPSCR.
3474 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3475 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3476 // so that the shift + and get folded into a bitfield extract.
3477 DebugLoc dl = Op.getDebugLoc();
3478 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3479 DAG.getConstant(Intrinsic::arm_get_fpscr,
3481 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3482 DAG.getConstant(1U << 22, MVT::i32));
3483 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3484 DAG.getConstant(22, MVT::i32));
3485 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3486 DAG.getConstant(3, MVT::i32));
3489 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3490 const ARMSubtarget *ST) {
3491 EVT VT = N->getValueType(0);
3492 DebugLoc dl = N->getDebugLoc();
3494 if (!ST->hasV6T2Ops())
3497 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3498 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3501 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3502 const ARMSubtarget *ST) {
3503 EVT VT = N->getValueType(0);
3504 DebugLoc dl = N->getDebugLoc();
3509 // Lower vector shifts on NEON to use VSHL.
3510 assert(ST->hasNEON() && "unexpected vector shift");
3512 // Left shifts translate directly to the vshiftu intrinsic.
3513 if (N->getOpcode() == ISD::SHL)
3514 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3515 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3516 N->getOperand(0), N->getOperand(1));
3518 assert((N->getOpcode() == ISD::SRA ||
3519 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3521 // NEON uses the same intrinsics for both left and right shifts. For
3522 // right shifts, the shift amounts are negative, so negate the vector of
3524 EVT ShiftVT = N->getOperand(1).getValueType();
3525 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3526 getZeroVector(ShiftVT, DAG, dl),
3528 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3529 Intrinsic::arm_neon_vshifts :
3530 Intrinsic::arm_neon_vshiftu);
3531 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3532 DAG.getConstant(vshiftInt, MVT::i32),
3533 N->getOperand(0), NegatedCount);
3536 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3537 const ARMSubtarget *ST) {
3538 EVT VT = N->getValueType(0);
3539 DebugLoc dl = N->getDebugLoc();
3541 // We can get here for a node like i32 = ISD::SHL i32, i64
3545 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3546 "Unknown shift to lower!");
3548 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3549 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3550 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3553 // If we are in thumb mode, we don't have RRX.
3554 if (ST->isThumb1Only()) return SDValue();
3556 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3557 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3558 DAG.getConstant(0, MVT::i32));
3559 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3560 DAG.getConstant(1, MVT::i32));
3562 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3563 // captures the result into a carry flag.
3564 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3565 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3567 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3568 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3570 // Merge the pieces into a single i64 value.
3571 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3574 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3575 SDValue TmpOp0, TmpOp1;
3576 bool Invert = false;
3580 SDValue Op0 = Op.getOperand(0);
3581 SDValue Op1 = Op.getOperand(1);
3582 SDValue CC = Op.getOperand(2);
3583 EVT VT = Op.getValueType();
3584 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3585 DebugLoc dl = Op.getDebugLoc();
3587 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3588 switch (SetCCOpcode) {
3589 default: llvm_unreachable("Illegal FP comparison");
3591 case ISD::SETNE: Invert = true; // Fallthrough
3593 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3595 case ISD::SETLT: Swap = true; // Fallthrough
3597 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3599 case ISD::SETLE: Swap = true; // Fallthrough
3601 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3602 case ISD::SETUGE: Swap = true; // Fallthrough
3603 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3604 case ISD::SETUGT: Swap = true; // Fallthrough
3605 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3606 case ISD::SETUEQ: Invert = true; // Fallthrough
3608 // Expand this to (OLT | OGT).
3612 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3613 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3615 case ISD::SETUO: Invert = true; // Fallthrough
3617 // Expand this to (OLT | OGE).
3621 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3622 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3626 // Integer comparisons.
3627 switch (SetCCOpcode) {
3628 default: llvm_unreachable("Illegal integer comparison");
3629 case ISD::SETNE: Invert = true;
3630 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3631 case ISD::SETLT: Swap = true;
3632 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3633 case ISD::SETLE: Swap = true;
3634 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3635 case ISD::SETULT: Swap = true;
3636 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3637 case ISD::SETULE: Swap = true;
3638 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3641 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3642 if (Opc == ARMISD::VCEQ) {
3645 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3647 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3650 // Ignore bitconvert.
3651 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3652 AndOp = AndOp.getOperand(0);
3654 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3656 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3657 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3664 std::swap(Op0, Op1);
3666 // If one of the operands is a constant vector zero, attempt to fold the
3667 // comparison to a specialized compare-against-zero form.
3669 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3671 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3672 if (Opc == ARMISD::VCGE)
3673 Opc = ARMISD::VCLEZ;
3674 else if (Opc == ARMISD::VCGT)
3675 Opc = ARMISD::VCLTZ;
3680 if (SingleOp.getNode()) {
3683 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3685 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3687 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3689 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3691 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3693 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3696 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3700 Result = DAG.getNOT(dl, Result, VT);
3705 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3706 /// valid vector constant for a NEON instruction with a "modified immediate"
3707 /// operand (e.g., VMOV). If so, return the encoded value.
3708 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3709 unsigned SplatBitSize, SelectionDAG &DAG,
3710 EVT &VT, bool is128Bits, NEONModImmType type) {
3711 unsigned OpCmode, Imm;
3713 // SplatBitSize is set to the smallest size that splats the vector, so a
3714 // zero vector will always have SplatBitSize == 8. However, NEON modified
3715 // immediate instructions others than VMOV do not support the 8-bit encoding
3716 // of a zero vector, and the default encoding of zero is supposed to be the
3721 switch (SplatBitSize) {
3723 if (type != VMOVModImm)
3725 // Any 1-byte value is OK. Op=0, Cmode=1110.
3726 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3729 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3733 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3734 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3735 if ((SplatBits & ~0xff) == 0) {
3736 // Value = 0x00nn: Op=x, Cmode=100x.
3741 if ((SplatBits & ~0xff00) == 0) {
3742 // Value = 0xnn00: Op=x, Cmode=101x.
3744 Imm = SplatBits >> 8;
3750 // NEON's 32-bit VMOV supports splat values where:
3751 // * only one byte is nonzero, or
3752 // * the least significant byte is 0xff and the second byte is nonzero, or
3753 // * the least significant 2 bytes are 0xff and the third is nonzero.
3754 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3755 if ((SplatBits & ~0xff) == 0) {
3756 // Value = 0x000000nn: Op=x, Cmode=000x.
3761 if ((SplatBits & ~0xff00) == 0) {
3762 // Value = 0x0000nn00: Op=x, Cmode=001x.
3764 Imm = SplatBits >> 8;
3767 if ((SplatBits & ~0xff0000) == 0) {
3768 // Value = 0x00nn0000: Op=x, Cmode=010x.
3770 Imm = SplatBits >> 16;
3773 if ((SplatBits & ~0xff000000) == 0) {
3774 // Value = 0xnn000000: Op=x, Cmode=011x.
3776 Imm = SplatBits >> 24;
3780 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3781 if (type == OtherModImm) return SDValue();
3783 if ((SplatBits & ~0xffff) == 0 &&
3784 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3785 // Value = 0x0000nnff: Op=x, Cmode=1100.
3787 Imm = SplatBits >> 8;
3792 if ((SplatBits & ~0xffffff) == 0 &&
3793 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3794 // Value = 0x00nnffff: Op=x, Cmode=1101.
3796 Imm = SplatBits >> 16;
3797 SplatBits |= 0xffff;
3801 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3802 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3803 // VMOV.I32. A (very) minor optimization would be to replicate the value
3804 // and fall through here to test for a valid 64-bit splat. But, then the
3805 // caller would also need to check and handle the change in size.
3809 if (type != VMOVModImm)
3811 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3812 uint64_t BitMask = 0xff;
3814 unsigned ImmMask = 1;
3816 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3817 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3820 } else if ((SplatBits & BitMask) != 0) {
3826 // Op=1, Cmode=1110.
3829 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3834 llvm_unreachable("unexpected size for isNEONModifiedImm");
3837 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3838 return DAG.getTargetConstant(EncodedVal, MVT::i32);
3841 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3842 const ARMSubtarget *ST) const {
3843 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3846 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3847 assert(Op.getValueType() == MVT::f32 &&
3848 "ConstantFP custom lowering should only occur for f32.");
3850 // Try splatting with a VMOV.f32...
3851 APFloat FPVal = CFP->getValueAPF();
3852 int ImmVal = ARM_AM::getFP32Imm(FPVal);
3854 DebugLoc DL = Op.getDebugLoc();
3855 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3856 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3858 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3859 DAG.getConstant(0, MVT::i32));
3862 // If that fails, try a VMOV.i32
3864 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3865 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3867 if (NewVal != SDValue()) {
3868 DebugLoc DL = Op.getDebugLoc();
3869 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3871 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3873 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3874 DAG.getConstant(0, MVT::i32));
3877 // Finally, try a VMVN.i32
3878 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3880 if (NewVal != SDValue()) {
3881 DebugLoc DL = Op.getDebugLoc();
3882 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3883 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3885 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3886 DAG.getConstant(0, MVT::i32));
3893 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3894 bool &ReverseVEXT, unsigned &Imm) {
3895 unsigned NumElts = VT.getVectorNumElements();
3896 ReverseVEXT = false;
3898 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3904 // If this is a VEXT shuffle, the immediate value is the index of the first
3905 // element. The other shuffle indices must be the successive elements after
3907 unsigned ExpectedElt = Imm;
3908 for (unsigned i = 1; i < NumElts; ++i) {
3909 // Increment the expected index. If it wraps around, it may still be
3910 // a VEXT but the source vectors must be swapped.
3912 if (ExpectedElt == NumElts * 2) {
3917 if (M[i] < 0) continue; // ignore UNDEF indices
3918 if (ExpectedElt != static_cast<unsigned>(M[i]))
3922 // Adjust the index value if the source operands will be swapped.
3929 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3930 /// instruction with the specified blocksize. (The order of the elements
3931 /// within each block of the vector is reversed.)
3932 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3933 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3934 "Only possible block sizes for VREV are: 16, 32, 64");
3936 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3940 unsigned NumElts = VT.getVectorNumElements();
3941 unsigned BlockElts = M[0] + 1;
3942 // If the first shuffle index is UNDEF, be optimistic.
3944 BlockElts = BlockSize / EltSz;
3946 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3949 for (unsigned i = 0; i < NumElts; ++i) {
3950 if (M[i] < 0) continue; // ignore UNDEF indices
3951 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3958 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3959 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3960 // range, then 0 is placed into the resulting vector. So pretty much any mask
3961 // of 8 elements can work here.
3962 return VT == MVT::v8i8 && M.size() == 8;
3965 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3966 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3970 unsigned NumElts = VT.getVectorNumElements();
3971 WhichResult = (M[0] == 0 ? 0 : 1);
3972 for (unsigned i = 0; i < NumElts; i += 2) {
3973 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3974 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3980 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3981 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3982 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3983 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3984 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3988 unsigned NumElts = VT.getVectorNumElements();
3989 WhichResult = (M[0] == 0 ? 0 : 1);
3990 for (unsigned i = 0; i < NumElts; i += 2) {
3991 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3992 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3998 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3999 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4003 unsigned NumElts = VT.getVectorNumElements();
4004 WhichResult = (M[0] == 0 ? 0 : 1);
4005 for (unsigned i = 0; i != NumElts; ++i) {
4006 if (M[i] < 0) continue; // ignore UNDEF indices
4007 if ((unsigned) M[i] != 2 * i + WhichResult)
4011 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4012 if (VT.is64BitVector() && EltSz == 32)
4018 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4019 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4020 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4021 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4022 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4026 unsigned Half = VT.getVectorNumElements() / 2;
4027 WhichResult = (M[0] == 0 ? 0 : 1);
4028 for (unsigned j = 0; j != 2; ++j) {
4029 unsigned Idx = WhichResult;
4030 for (unsigned i = 0; i != Half; ++i) {
4031 int MIdx = M[i + j * Half];
4032 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4038 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4039 if (VT.is64BitVector() && EltSz == 32)
4045 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4046 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4050 unsigned NumElts = VT.getVectorNumElements();
4051 WhichResult = (M[0] == 0 ? 0 : 1);
4052 unsigned Idx = WhichResult * NumElts / 2;
4053 for (unsigned i = 0; i != NumElts; i += 2) {
4054 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4055 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4060 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4061 if (VT.is64BitVector() && EltSz == 32)
4067 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4068 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4069 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4070 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4071 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4075 unsigned NumElts = VT.getVectorNumElements();
4076 WhichResult = (M[0] == 0 ? 0 : 1);
4077 unsigned Idx = WhichResult * NumElts / 2;
4078 for (unsigned i = 0; i != NumElts; i += 2) {
4079 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4080 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4085 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4086 if (VT.is64BitVector() && EltSz == 32)
4092 // If N is an integer constant that can be moved into a register in one
4093 // instruction, return an SDValue of such a constant (will become a MOV
4094 // instruction). Otherwise return null.
4095 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4096 const ARMSubtarget *ST, DebugLoc dl) {
4098 if (!isa<ConstantSDNode>(N))
4100 Val = cast<ConstantSDNode>(N)->getZExtValue();
4102 if (ST->isThumb1Only()) {
4103 if (Val <= 255 || ~Val <= 255)
4104 return DAG.getConstant(Val, MVT::i32);
4106 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4107 return DAG.getConstant(Val, MVT::i32);
4112 // If this is a case we can't handle, return null and let the default
4113 // expansion code take care of it.
4114 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4115 const ARMSubtarget *ST) const {
4116 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4117 DebugLoc dl = Op.getDebugLoc();
4118 EVT VT = Op.getValueType();
4120 APInt SplatBits, SplatUndef;
4121 unsigned SplatBitSize;
4123 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4124 if (SplatBitSize <= 64) {
4125 // Check if an immediate VMOV works.
4127 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4128 SplatUndef.getZExtValue(), SplatBitSize,
4129 DAG, VmovVT, VT.is128BitVector(),
4131 if (Val.getNode()) {
4132 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4133 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4136 // Try an immediate VMVN.
4137 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4138 Val = isNEONModifiedImm(NegatedImm,
4139 SplatUndef.getZExtValue(), SplatBitSize,
4140 DAG, VmovVT, VT.is128BitVector(),
4142 if (Val.getNode()) {
4143 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4144 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4147 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4148 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4149 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4151 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4152 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4158 // Scan through the operands to see if only one value is used.
4159 unsigned NumElts = VT.getVectorNumElements();
4160 bool isOnlyLowElement = true;
4161 bool usesOnlyOneValue = true;
4162 bool isConstant = true;
4164 for (unsigned i = 0; i < NumElts; ++i) {
4165 SDValue V = Op.getOperand(i);
4166 if (V.getOpcode() == ISD::UNDEF)
4169 isOnlyLowElement = false;
4170 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4173 if (!Value.getNode())
4175 else if (V != Value)
4176 usesOnlyOneValue = false;
4179 if (!Value.getNode())
4180 return DAG.getUNDEF(VT);
4182 if (isOnlyLowElement)
4183 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4185 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4187 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4188 // i32 and try again.
4189 if (usesOnlyOneValue && EltSize <= 32) {
4191 return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4192 if (VT.getVectorElementType().isFloatingPoint()) {
4193 SmallVector<SDValue, 8> Ops;
4194 for (unsigned i = 0; i < NumElts; ++i)
4195 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4197 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4198 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4199 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4201 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4203 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4205 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4208 // If all elements are constants and the case above didn't get hit, fall back
4209 // to the default expansion, which will generate a load from the constant
4214 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4216 SDValue shuffle = ReconstructShuffle(Op, DAG);
4217 if (shuffle != SDValue())
4221 // Vectors with 32- or 64-bit elements can be built by directly assigning
4222 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4223 // will be legalized.
4224 if (EltSize >= 32) {
4225 // Do the expansion with floating-point types, since that is what the VFP
4226 // registers are defined to use, and since i64 is not legal.
4227 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4228 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4229 SmallVector<SDValue, 8> Ops;
4230 for (unsigned i = 0; i < NumElts; ++i)
4231 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4232 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4233 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4239 // Gather data to see if the operation can be modelled as a
4240 // shuffle in combination with VEXTs.
4241 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4242 SelectionDAG &DAG) const {
4243 DebugLoc dl = Op.getDebugLoc();
4244 EVT VT = Op.getValueType();
4245 unsigned NumElts = VT.getVectorNumElements();
4247 SmallVector<SDValue, 2> SourceVecs;
4248 SmallVector<unsigned, 2> MinElts;
4249 SmallVector<unsigned, 2> MaxElts;
4251 for (unsigned i = 0; i < NumElts; ++i) {
4252 SDValue V = Op.getOperand(i);
4253 if (V.getOpcode() == ISD::UNDEF)
4255 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4256 // A shuffle can only come from building a vector from various
4257 // elements of other vectors.
4259 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4260 VT.getVectorElementType()) {
4261 // This code doesn't know how to handle shuffles where the vector
4262 // element types do not match (this happens because type legalization
4263 // promotes the return type of EXTRACT_VECTOR_ELT).
4264 // FIXME: It might be appropriate to extend this code to handle
4265 // mismatched types.
4269 // Record this extraction against the appropriate vector if possible...
4270 SDValue SourceVec = V.getOperand(0);
4271 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4272 bool FoundSource = false;
4273 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4274 if (SourceVecs[j] == SourceVec) {
4275 if (MinElts[j] > EltNo)
4277 if (MaxElts[j] < EltNo)
4284 // Or record a new source if not...
4286 SourceVecs.push_back(SourceVec);
4287 MinElts.push_back(EltNo);
4288 MaxElts.push_back(EltNo);
4292 // Currently only do something sane when at most two source vectors
4294 if (SourceVecs.size() > 2)
4297 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4298 int VEXTOffsets[2] = {0, 0};
4300 // This loop extracts the usage patterns of the source vectors
4301 // and prepares appropriate SDValues for a shuffle if possible.
4302 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4303 if (SourceVecs[i].getValueType() == VT) {
4304 // No VEXT necessary
4305 ShuffleSrcs[i] = SourceVecs[i];
4308 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4309 // It probably isn't worth padding out a smaller vector just to
4310 // break it down again in a shuffle.
4314 // Since only 64-bit and 128-bit vectors are legal on ARM and
4315 // we've eliminated the other cases...
4316 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4317 "unexpected vector sizes in ReconstructShuffle");
4319 if (MaxElts[i] - MinElts[i] >= NumElts) {
4320 // Span too large for a VEXT to cope
4324 if (MinElts[i] >= NumElts) {
4325 // The extraction can just take the second half
4326 VEXTOffsets[i] = NumElts;
4327 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4329 DAG.getIntPtrConstant(NumElts));
4330 } else if (MaxElts[i] < NumElts) {
4331 // The extraction can just take the first half
4333 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4335 DAG.getIntPtrConstant(0));
4337 // An actual VEXT is needed
4338 VEXTOffsets[i] = MinElts[i];
4339 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4341 DAG.getIntPtrConstant(0));
4342 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4344 DAG.getIntPtrConstant(NumElts));
4345 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4346 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4350 SmallVector<int, 8> Mask;
4352 for (unsigned i = 0; i < NumElts; ++i) {
4353 SDValue Entry = Op.getOperand(i);
4354 if (Entry.getOpcode() == ISD::UNDEF) {
4359 SDValue ExtractVec = Entry.getOperand(0);
4360 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4361 .getOperand(1))->getSExtValue();
4362 if (ExtractVec == SourceVecs[0]) {
4363 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4365 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4369 // Final check before we try to produce nonsense...
4370 if (isShuffleMaskLegal(Mask, VT))
4371 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4377 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4378 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4379 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4380 /// are assumed to be legal.
4382 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4384 if (VT.getVectorNumElements() == 4 &&
4385 (VT.is128BitVector() || VT.is64BitVector())) {
4386 unsigned PFIndexes[4];
4387 for (unsigned i = 0; i != 4; ++i) {
4391 PFIndexes[i] = M[i];
4394 // Compute the index in the perfect shuffle table.
4395 unsigned PFTableIndex =
4396 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4397 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4398 unsigned Cost = (PFEntry >> 30);
4405 unsigned Imm, WhichResult;
4407 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4408 return (EltSize >= 32 ||
4409 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4410 isVREVMask(M, VT, 64) ||
4411 isVREVMask(M, VT, 32) ||
4412 isVREVMask(M, VT, 16) ||
4413 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4414 isVTBLMask(M, VT) ||
4415 isVTRNMask(M, VT, WhichResult) ||
4416 isVUZPMask(M, VT, WhichResult) ||
4417 isVZIPMask(M, VT, WhichResult) ||
4418 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4419 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4420 isVZIP_v_undef_Mask(M, VT, WhichResult));
4423 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4424 /// the specified operations to build the shuffle.
4425 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4426 SDValue RHS, SelectionDAG &DAG,
4428 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4429 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4430 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4433 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4442 OP_VUZPL, // VUZP, left result
4443 OP_VUZPR, // VUZP, right result
4444 OP_VZIPL, // VZIP, left result
4445 OP_VZIPR, // VZIP, right result
4446 OP_VTRNL, // VTRN, left result
4447 OP_VTRNR // VTRN, right result
4450 if (OpNum == OP_COPY) {
4451 if (LHSID == (1*9+2)*9+3) return LHS;
4452 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4456 SDValue OpLHS, OpRHS;
4457 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4458 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4459 EVT VT = OpLHS.getValueType();
4462 default: llvm_unreachable("Unknown shuffle opcode!");
4464 // VREV divides the vector in half and swaps within the half.
4465 if (VT.getVectorElementType() == MVT::i32 ||
4466 VT.getVectorElementType() == MVT::f32)
4467 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4468 // vrev <4 x i16> -> VREV32
4469 if (VT.getVectorElementType() == MVT::i16)
4470 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4471 // vrev <4 x i8> -> VREV16
4472 assert(VT.getVectorElementType() == MVT::i8);
4473 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4478 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4479 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4483 return DAG.getNode(ARMISD::VEXT, dl, VT,
4485 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4488 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4489 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4492 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4493 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4496 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4497 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4501 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4502 ArrayRef<int> ShuffleMask,
4503 SelectionDAG &DAG) {
4504 // Check to see if we can use the VTBL instruction.
4505 SDValue V1 = Op.getOperand(0);
4506 SDValue V2 = Op.getOperand(1);
4507 DebugLoc DL = Op.getDebugLoc();
4509 SmallVector<SDValue, 8> VTBLMask;
4510 for (ArrayRef<int>::iterator
4511 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4512 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4514 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4515 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4516 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4519 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4520 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4524 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4525 SDValue V1 = Op.getOperand(0);
4526 SDValue V2 = Op.getOperand(1);
4527 DebugLoc dl = Op.getDebugLoc();
4528 EVT VT = Op.getValueType();
4529 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4531 // Convert shuffles that are directly supported on NEON to target-specific
4532 // DAG nodes, instead of keeping them as shuffles and matching them again
4533 // during code selection. This is more efficient and avoids the possibility
4534 // of inconsistencies between legalization and selection.
4535 // FIXME: floating-point vectors should be canonicalized to integer vectors
4536 // of the same time so that they get CSEd properly.
4537 ArrayRef<int> ShuffleMask = SVN->getMask();
4539 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4540 if (EltSize <= 32) {
4541 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4542 int Lane = SVN->getSplatIndex();
4543 // If this is undef splat, generate it via "just" vdup, if possible.
4544 if (Lane == -1) Lane = 0;
4546 // Test if V1 is a SCALAR_TO_VECTOR.
4547 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4548 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4550 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4551 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4553 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4554 !isa<ConstantSDNode>(V1.getOperand(0))) {
4555 bool IsScalarToVector = true;
4556 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4557 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4558 IsScalarToVector = false;
4561 if (IsScalarToVector)
4562 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4564 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4565 DAG.getConstant(Lane, MVT::i32));
4570 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4573 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4574 DAG.getConstant(Imm, MVT::i32));
4577 if (isVREVMask(ShuffleMask, VT, 64))
4578 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4579 if (isVREVMask(ShuffleMask, VT, 32))
4580 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4581 if (isVREVMask(ShuffleMask, VT, 16))
4582 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4584 // Check for Neon shuffles that modify both input vectors in place.
4585 // If both results are used, i.e., if there are two shuffles with the same
4586 // source operands and with masks corresponding to both results of one of
4587 // these operations, DAG memoization will ensure that a single node is
4588 // used for both shuffles.
4589 unsigned WhichResult;
4590 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4591 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4592 V1, V2).getValue(WhichResult);
4593 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4594 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4595 V1, V2).getValue(WhichResult);
4596 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4597 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4598 V1, V2).getValue(WhichResult);
4600 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4601 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4602 V1, V1).getValue(WhichResult);
4603 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4604 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4605 V1, V1).getValue(WhichResult);
4606 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4607 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4608 V1, V1).getValue(WhichResult);
4611 // If the shuffle is not directly supported and it has 4 elements, use
4612 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4613 unsigned NumElts = VT.getVectorNumElements();
4615 unsigned PFIndexes[4];
4616 for (unsigned i = 0; i != 4; ++i) {
4617 if (ShuffleMask[i] < 0)
4620 PFIndexes[i] = ShuffleMask[i];
4623 // Compute the index in the perfect shuffle table.
4624 unsigned PFTableIndex =
4625 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4626 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4627 unsigned Cost = (PFEntry >> 30);
4630 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4633 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4634 if (EltSize >= 32) {
4635 // Do the expansion with floating-point types, since that is what the VFP
4636 // registers are defined to use, and since i64 is not legal.
4637 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4638 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4639 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4640 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4641 SmallVector<SDValue, 8> Ops;
4642 for (unsigned i = 0; i < NumElts; ++i) {
4643 if (ShuffleMask[i] < 0)
4644 Ops.push_back(DAG.getUNDEF(EltVT));
4646 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4647 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4648 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4651 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4652 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4655 if (VT == MVT::v8i8) {
4656 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4657 if (NewOp.getNode())
4664 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4665 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4666 SDValue Lane = Op.getOperand(2);
4667 if (!isa<ConstantSDNode>(Lane))
4673 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4674 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4675 SDValue Lane = Op.getOperand(1);
4676 if (!isa<ConstantSDNode>(Lane))
4679 SDValue Vec = Op.getOperand(0);
4680 if (Op.getValueType() == MVT::i32 &&
4681 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4682 DebugLoc dl = Op.getDebugLoc();
4683 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4689 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4690 // The only time a CONCAT_VECTORS operation can have legal types is when
4691 // two 64-bit vectors are concatenated to a 128-bit vector.
4692 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4693 "unexpected CONCAT_VECTORS");
4694 DebugLoc dl = Op.getDebugLoc();
4695 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4696 SDValue Op0 = Op.getOperand(0);
4697 SDValue Op1 = Op.getOperand(1);
4698 if (Op0.getOpcode() != ISD::UNDEF)
4699 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4700 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4701 DAG.getIntPtrConstant(0));
4702 if (Op1.getOpcode() != ISD::UNDEF)
4703 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4704 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4705 DAG.getIntPtrConstant(1));
4706 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4709 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4710 /// element has been zero/sign-extended, depending on the isSigned parameter,
4711 /// from an integer type half its size.
4712 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4714 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4715 EVT VT = N->getValueType(0);
4716 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4717 SDNode *BVN = N->getOperand(0).getNode();
4718 if (BVN->getValueType(0) != MVT::v4i32 ||
4719 BVN->getOpcode() != ISD::BUILD_VECTOR)
4721 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4722 unsigned HiElt = 1 - LoElt;
4723 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4724 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4725 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4726 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4727 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4730 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4731 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4734 if (Hi0->isNullValue() && Hi1->isNullValue())
4740 if (N->getOpcode() != ISD::BUILD_VECTOR)
4743 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4744 SDNode *Elt = N->getOperand(i).getNode();
4745 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4746 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4747 unsigned HalfSize = EltSize / 2;
4749 if (!isIntN(HalfSize, C->getSExtValue()))
4752 if (!isUIntN(HalfSize, C->getZExtValue()))
4763 /// isSignExtended - Check if a node is a vector value that is sign-extended
4764 /// or a constant BUILD_VECTOR with sign-extended elements.
4765 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4766 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4768 if (isExtendedBUILD_VECTOR(N, DAG, true))
4773 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4774 /// or a constant BUILD_VECTOR with zero-extended elements.
4775 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4776 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4778 if (isExtendedBUILD_VECTOR(N, DAG, false))
4783 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4784 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4785 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4786 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4787 return N->getOperand(0);
4788 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4789 return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4790 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4791 LD->isNonTemporal(), LD->isInvariant(),
4792 LD->getAlignment());
4793 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
4794 // have been legalized as a BITCAST from v4i32.
4795 if (N->getOpcode() == ISD::BITCAST) {
4796 SDNode *BVN = N->getOperand(0).getNode();
4797 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4798 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4799 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4800 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4801 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4803 // Construct a new BUILD_VECTOR with elements truncated to half the size.
4804 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4805 EVT VT = N->getValueType(0);
4806 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4807 unsigned NumElts = VT.getVectorNumElements();
4808 MVT TruncVT = MVT::getIntegerVT(EltSize);
4809 SmallVector<SDValue, 8> Ops;
4810 for (unsigned i = 0; i != NumElts; ++i) {
4811 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4812 const APInt &CInt = C->getAPIntValue();
4813 // Element types smaller than 32 bits are not legal, so use i32 elements.
4814 // The values are implicitly truncated so sext vs. zext doesn't matter.
4815 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4817 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4818 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4821 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4822 unsigned Opcode = N->getOpcode();
4823 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4824 SDNode *N0 = N->getOperand(0).getNode();
4825 SDNode *N1 = N->getOperand(1).getNode();
4826 return N0->hasOneUse() && N1->hasOneUse() &&
4827 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4832 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4833 unsigned Opcode = N->getOpcode();
4834 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4835 SDNode *N0 = N->getOperand(0).getNode();
4836 SDNode *N1 = N->getOperand(1).getNode();
4837 return N0->hasOneUse() && N1->hasOneUse() &&
4838 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4843 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4844 // Multiplications are only custom-lowered for 128-bit vectors so that
4845 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
4846 EVT VT = Op.getValueType();
4847 assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4848 SDNode *N0 = Op.getOperand(0).getNode();
4849 SDNode *N1 = Op.getOperand(1).getNode();
4850 unsigned NewOpc = 0;
4852 bool isN0SExt = isSignExtended(N0, DAG);
4853 bool isN1SExt = isSignExtended(N1, DAG);
4854 if (isN0SExt && isN1SExt)
4855 NewOpc = ARMISD::VMULLs;
4857 bool isN0ZExt = isZeroExtended(N0, DAG);
4858 bool isN1ZExt = isZeroExtended(N1, DAG);
4859 if (isN0ZExt && isN1ZExt)
4860 NewOpc = ARMISD::VMULLu;
4861 else if (isN1SExt || isN1ZExt) {
4862 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4863 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4864 if (isN1SExt && isAddSubSExt(N0, DAG)) {
4865 NewOpc = ARMISD::VMULLs;
4867 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4868 NewOpc = ARMISD::VMULLu;
4870 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4872 NewOpc = ARMISD::VMULLu;
4878 if (VT == MVT::v2i64)
4879 // Fall through to expand this. It is not legal.
4882 // Other vector multiplications are legal.
4887 // Legalize to a VMULL instruction.
4888 DebugLoc DL = Op.getDebugLoc();
4890 SDValue Op1 = SkipExtension(N1, DAG);
4892 Op0 = SkipExtension(N0, DAG);
4893 assert(Op0.getValueType().is64BitVector() &&
4894 Op1.getValueType().is64BitVector() &&
4895 "unexpected types for extended operands to VMULL");
4896 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4899 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4900 // isel lowering to take advantage of no-stall back to back vmul + vmla.
4907 SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4908 SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4909 EVT Op1VT = Op1.getValueType();
4910 return DAG.getNode(N0->getOpcode(), DL, VT,
4911 DAG.getNode(NewOpc, DL, VT,
4912 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4913 DAG.getNode(NewOpc, DL, VT,
4914 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4918 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4920 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4921 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4922 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4923 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4924 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4925 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4926 // Get reciprocal estimate.
4927 // float4 recip = vrecpeq_f32(yf);
4928 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4929 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4930 // Because char has a smaller range than uchar, we can actually get away
4931 // without any newton steps. This requires that we use a weird bias
4932 // of 0xb000, however (again, this has been exhaustively tested).
4933 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4934 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4935 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4936 Y = DAG.getConstant(0xb000, MVT::i32);
4937 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4938 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4939 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4940 // Convert back to short.
4941 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4942 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4947 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4949 // Convert to float.
4950 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4951 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4952 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4953 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4954 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4955 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4957 // Use reciprocal estimate and one refinement step.
4958 // float4 recip = vrecpeq_f32(yf);
4959 // recip *= vrecpsq_f32(yf, recip);
4960 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4961 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4962 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4963 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4965 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4966 // Because short has a smaller range than ushort, we can actually get away
4967 // with only a single newton step. This requires that we use a weird bias
4968 // of 89, however (again, this has been exhaustively tested).
4969 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4970 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4971 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4972 N1 = DAG.getConstant(0x89, MVT::i32);
4973 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4974 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4975 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4976 // Convert back to integer and return.
4977 // return vmovn_s32(vcvt_s32_f32(result));
4978 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4979 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4983 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4984 EVT VT = Op.getValueType();
4985 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4986 "unexpected type for custom-lowering ISD::SDIV");
4988 DebugLoc dl = Op.getDebugLoc();
4989 SDValue N0 = Op.getOperand(0);
4990 SDValue N1 = Op.getOperand(1);
4993 if (VT == MVT::v8i8) {
4994 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4995 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4997 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4998 DAG.getIntPtrConstant(4));
4999 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5000 DAG.getIntPtrConstant(4));
5001 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5002 DAG.getIntPtrConstant(0));
5003 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5004 DAG.getIntPtrConstant(0));
5006 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5007 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5009 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5010 N0 = LowerCONCAT_VECTORS(N0, DAG);
5012 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5015 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5018 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5019 EVT VT = Op.getValueType();
5020 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5021 "unexpected type for custom-lowering ISD::UDIV");
5023 DebugLoc dl = Op.getDebugLoc();
5024 SDValue N0 = Op.getOperand(0);
5025 SDValue N1 = Op.getOperand(1);
5028 if (VT == MVT::v8i8) {
5029 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5030 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5032 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5033 DAG.getIntPtrConstant(4));
5034 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5035 DAG.getIntPtrConstant(4));
5036 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5037 DAG.getIntPtrConstant(0));
5038 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5039 DAG.getIntPtrConstant(0));
5041 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5042 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5044 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5045 N0 = LowerCONCAT_VECTORS(N0, DAG);
5047 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5048 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5053 // v4i16 sdiv ... Convert to float.
5054 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5055 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5056 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5057 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5058 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5059 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5061 // Use reciprocal estimate and two refinement steps.
5062 // float4 recip = vrecpeq_f32(yf);
5063 // recip *= vrecpsq_f32(yf, recip);
5064 // recip *= vrecpsq_f32(yf, recip);
5065 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5066 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5067 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5068 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5070 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5071 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5072 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5074 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5075 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5076 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5077 // and that it will never cause us to return an answer too large).
5078 // float4 result = as_float4(as_int4(xf*recip) + 2);
5079 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5080 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5081 N1 = DAG.getConstant(2, MVT::i32);
5082 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5083 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5084 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5085 // Convert back to integer and return.
5086 // return vmovn_u32(vcvt_s32_f32(result));
5087 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5088 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5092 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5093 EVT VT = Op.getNode()->getValueType(0);
5094 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5097 bool ExtraOp = false;
5098 switch (Op.getOpcode()) {
5099 default: llvm_unreachable("Invalid code");
5100 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5101 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5102 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5103 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5107 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5109 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5110 Op.getOperand(1), Op.getOperand(2));
5113 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5114 // Monotonic load/store is legal for all targets
5115 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5118 // Aquire/Release load/store is not legal for targets without a
5119 // dmb or equivalent available.
5125 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5126 SelectionDAG &DAG, unsigned NewOp) {
5127 DebugLoc dl = Node->getDebugLoc();
5128 assert (Node->getValueType(0) == MVT::i64 &&
5129 "Only know how to expand i64 atomics");
5131 SmallVector<SDValue, 6> Ops;
5132 Ops.push_back(Node->getOperand(0)); // Chain
5133 Ops.push_back(Node->getOperand(1)); // Ptr
5135 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5136 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5137 // High part of Val1
5138 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5139 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5140 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5141 // High part of Val1
5142 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5143 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5144 // High part of Val2
5145 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5146 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5148 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5150 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5151 cast<MemSDNode>(Node)->getMemOperand());
5152 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5153 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5154 Results.push_back(Result.getValue(2));
5157 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5158 switch (Op.getOpcode()) {
5159 default: llvm_unreachable("Don't know how to custom lower this!");
5160 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5161 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5162 case ISD::GlobalAddress:
5163 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5164 LowerGlobalAddressELF(Op, DAG);
5165 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5166 case ISD::SELECT: return LowerSELECT(Op, DAG);
5167 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5168 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5169 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5170 case ISD::VASTART: return LowerVASTART(Op, DAG);
5171 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5172 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5173 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5174 case ISD::SINT_TO_FP:
5175 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5176 case ISD::FP_TO_SINT:
5177 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5178 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5179 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5180 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5181 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5182 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5183 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5184 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5186 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5189 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5190 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5191 case ISD::SRL_PARTS:
5192 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5193 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5194 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5195 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5196 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5197 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5198 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5199 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5200 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5201 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5202 case ISD::MUL: return LowerMUL(Op, DAG);
5203 case ISD::SDIV: return LowerSDIV(Op, DAG);
5204 case ISD::UDIV: return LowerUDIV(Op, DAG);
5208 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5209 case ISD::ATOMIC_LOAD:
5210 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5214 /// ReplaceNodeResults - Replace the results of node with an illegal result
5215 /// type with new values built out of custom code.
5216 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5217 SmallVectorImpl<SDValue>&Results,
5218 SelectionDAG &DAG) const {
5220 switch (N->getOpcode()) {
5222 llvm_unreachable("Don't know how to custom expand this!");
5224 Res = ExpandBITCAST(N, DAG);
5228 Res = Expand64BitShift(N, DAG, Subtarget);
5230 case ISD::ATOMIC_LOAD_ADD:
5231 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5233 case ISD::ATOMIC_LOAD_AND:
5234 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5236 case ISD::ATOMIC_LOAD_NAND:
5237 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5239 case ISD::ATOMIC_LOAD_OR:
5240 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5242 case ISD::ATOMIC_LOAD_SUB:
5243 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5245 case ISD::ATOMIC_LOAD_XOR:
5246 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5248 case ISD::ATOMIC_SWAP:
5249 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5251 case ISD::ATOMIC_CMP_SWAP:
5252 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5256 Results.push_back(Res);
5259 //===----------------------------------------------------------------------===//
5260 // ARM Scheduler Hooks
5261 //===----------------------------------------------------------------------===//
5264 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5265 MachineBasicBlock *BB,
5266 unsigned Size) const {
5267 unsigned dest = MI->getOperand(0).getReg();
5268 unsigned ptr = MI->getOperand(1).getReg();
5269 unsigned oldval = MI->getOperand(2).getReg();
5270 unsigned newval = MI->getOperand(3).getReg();
5271 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5272 DebugLoc dl = MI->getDebugLoc();
5273 bool isThumb2 = Subtarget->isThumb2();
5275 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5276 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5277 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5278 (const TargetRegisterClass*)&ARM::GPRRegClass);
5281 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5282 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5283 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5286 unsigned ldrOpc, strOpc;
5288 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5290 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5291 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5294 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5295 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5298 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5299 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5303 MachineFunction *MF = BB->getParent();
5304 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5305 MachineFunction::iterator It = BB;
5306 ++It; // insert the new blocks after the current block
5308 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5309 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5310 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5311 MF->insert(It, loop1MBB);
5312 MF->insert(It, loop2MBB);
5313 MF->insert(It, exitMBB);
5315 // Transfer the remainder of BB and its successor edges to exitMBB.
5316 exitMBB->splice(exitMBB->begin(), BB,
5317 llvm::next(MachineBasicBlock::iterator(MI)),
5319 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5323 // fallthrough --> loop1MBB
5324 BB->addSuccessor(loop1MBB);
5327 // ldrex dest, [ptr]
5331 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5332 if (ldrOpc == ARM::t2LDREX)
5334 AddDefaultPred(MIB);
5335 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5336 .addReg(dest).addReg(oldval));
5337 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5338 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5339 BB->addSuccessor(loop2MBB);
5340 BB->addSuccessor(exitMBB);
5343 // strex scratch, newval, [ptr]
5347 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5348 if (strOpc == ARM::t2STREX)
5350 AddDefaultPred(MIB);
5351 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5352 .addReg(scratch).addImm(0));
5353 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5354 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5355 BB->addSuccessor(loop1MBB);
5356 BB->addSuccessor(exitMBB);
5362 MI->eraseFromParent(); // The instruction is gone now.
5368 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5369 unsigned Size, unsigned BinOpcode) const {
5370 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5371 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5373 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5374 MachineFunction *MF = BB->getParent();
5375 MachineFunction::iterator It = BB;
5378 unsigned dest = MI->getOperand(0).getReg();
5379 unsigned ptr = MI->getOperand(1).getReg();
5380 unsigned incr = MI->getOperand(2).getReg();
5381 DebugLoc dl = MI->getDebugLoc();
5382 bool isThumb2 = Subtarget->isThumb2();
5384 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5386 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5387 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5390 unsigned ldrOpc, strOpc;
5392 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5394 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5395 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5398 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5399 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5402 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5403 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5407 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5408 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5409 MF->insert(It, loopMBB);
5410 MF->insert(It, exitMBB);
5412 // Transfer the remainder of BB and its successor edges to exitMBB.
5413 exitMBB->splice(exitMBB->begin(), BB,
5414 llvm::next(MachineBasicBlock::iterator(MI)),
5416 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5418 const TargetRegisterClass *TRC = isThumb2 ?
5419 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5420 (const TargetRegisterClass*)&ARM::GPRRegClass;
5421 unsigned scratch = MRI.createVirtualRegister(TRC);
5422 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5426 // fallthrough --> loopMBB
5427 BB->addSuccessor(loopMBB);
5431 // <binop> scratch2, dest, incr
5432 // strex scratch, scratch2, ptr
5435 // fallthrough --> exitMBB
5437 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5438 if (ldrOpc == ARM::t2LDREX)
5440 AddDefaultPred(MIB);
5442 // operand order needs to go the other way for NAND
5443 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5444 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5445 addReg(incr).addReg(dest)).addReg(0);
5447 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5448 addReg(dest).addReg(incr)).addReg(0);
5451 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5452 if (strOpc == ARM::t2STREX)
5454 AddDefaultPred(MIB);
5455 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5456 .addReg(scratch).addImm(0));
5457 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5458 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5460 BB->addSuccessor(loopMBB);
5461 BB->addSuccessor(exitMBB);
5467 MI->eraseFromParent(); // The instruction is gone now.
5473 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5474 MachineBasicBlock *BB,
5477 ARMCC::CondCodes Cond) const {
5478 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5480 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5481 MachineFunction *MF = BB->getParent();
5482 MachineFunction::iterator It = BB;
5485 unsigned dest = MI->getOperand(0).getReg();
5486 unsigned ptr = MI->getOperand(1).getReg();
5487 unsigned incr = MI->getOperand(2).getReg();
5488 unsigned oldval = dest;
5489 DebugLoc dl = MI->getDebugLoc();
5490 bool isThumb2 = Subtarget->isThumb2();
5492 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5494 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5495 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5498 unsigned ldrOpc, strOpc, extendOpc;
5500 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5502 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5503 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5504 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5507 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5508 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5509 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5512 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5513 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5518 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5519 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5520 MF->insert(It, loopMBB);
5521 MF->insert(It, exitMBB);
5523 // Transfer the remainder of BB and its successor edges to exitMBB.
5524 exitMBB->splice(exitMBB->begin(), BB,
5525 llvm::next(MachineBasicBlock::iterator(MI)),
5527 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5529 const TargetRegisterClass *TRC = isThumb2 ?
5530 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5531 (const TargetRegisterClass*)&ARM::GPRRegClass;
5532 unsigned scratch = MRI.createVirtualRegister(TRC);
5533 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5537 // fallthrough --> loopMBB
5538 BB->addSuccessor(loopMBB);
5542 // (sign extend dest, if required)
5544 // cmov.cond scratch2, dest, incr
5545 // strex scratch, scratch2, ptr
5548 // fallthrough --> exitMBB
5550 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5551 if (ldrOpc == ARM::t2LDREX)
5553 AddDefaultPred(MIB);
5555 // Sign extend the value, if necessary.
5556 if (signExtend && extendOpc) {
5557 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5558 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5563 // Build compare and cmov instructions.
5564 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5565 .addReg(oldval).addReg(incr));
5566 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5567 .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5569 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5570 if (strOpc == ARM::t2STREX)
5572 AddDefaultPred(MIB);
5573 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5574 .addReg(scratch).addImm(0));
5575 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5576 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5578 BB->addSuccessor(loopMBB);
5579 BB->addSuccessor(exitMBB);
5585 MI->eraseFromParent(); // The instruction is gone now.
5591 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5592 unsigned Op1, unsigned Op2,
5593 bool NeedsCarry, bool IsCmpxchg) const {
5594 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5595 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5597 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5598 MachineFunction *MF = BB->getParent();
5599 MachineFunction::iterator It = BB;
5602 unsigned destlo = MI->getOperand(0).getReg();
5603 unsigned desthi = MI->getOperand(1).getReg();
5604 unsigned ptr = MI->getOperand(2).getReg();
5605 unsigned vallo = MI->getOperand(3).getReg();
5606 unsigned valhi = MI->getOperand(4).getReg();
5607 DebugLoc dl = MI->getDebugLoc();
5608 bool isThumb2 = Subtarget->isThumb2();
5610 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5612 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5613 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5614 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5617 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5618 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5620 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5621 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5623 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5624 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5626 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5627 MF->insert(It, loopMBB);
5629 MF->insert(It, contBB);
5630 MF->insert(It, cont2BB);
5632 MF->insert(It, exitMBB);
5634 // Transfer the remainder of BB and its successor edges to exitMBB.
5635 exitMBB->splice(exitMBB->begin(), BB,
5636 llvm::next(MachineBasicBlock::iterator(MI)),
5638 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5640 const TargetRegisterClass *TRC = isThumb2 ?
5641 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5642 (const TargetRegisterClass*)&ARM::GPRRegClass;
5643 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5647 // fallthrough --> loopMBB
5648 BB->addSuccessor(loopMBB);
5651 // ldrexd r2, r3, ptr
5652 // <binopa> r0, r2, incr
5653 // <binopb> r1, r3, incr
5654 // strexd storesuccess, r0, r1, ptr
5655 // cmp storesuccess, #0
5657 // fallthrough --> exitMBB
5659 // Note that the registers are explicitly specified because there is not any
5660 // way to force the register allocator to allocate a register pair.
5662 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5663 // need to properly enforce the restriction that the two output registers
5664 // for ldrexd must be different.
5667 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5668 .addReg(ARM::R2, RegState::Define)
5669 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5670 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
5671 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5672 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5676 for (unsigned i = 0; i < 2; i++) {
5677 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5679 .addReg(i == 0 ? destlo : desthi)
5680 .addReg(i == 0 ? vallo : valhi));
5681 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5682 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5683 BB->addSuccessor(exitMBB);
5684 BB->addSuccessor(i == 0 ? contBB : cont2BB);
5685 BB = (i == 0 ? contBB : cont2BB);
5688 // Copy to physregs for strexd
5689 unsigned setlo = MI->getOperand(5).getReg();
5690 unsigned sethi = MI->getOperand(6).getReg();
5691 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5692 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5694 // Perform binary operation
5695 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5696 .addReg(destlo).addReg(vallo))
5697 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5698 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5699 .addReg(desthi).addReg(valhi)).addReg(0);
5701 // Copy to physregs for strexd
5702 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5703 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5707 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5708 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5710 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5711 .addReg(storesuccess).addImm(0));
5712 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5713 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5715 BB->addSuccessor(loopMBB);
5716 BB->addSuccessor(exitMBB);
5722 MI->eraseFromParent(); // The instruction is gone now.
5727 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5728 /// registers the function context.
5729 void ARMTargetLowering::
5730 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5731 MachineBasicBlock *DispatchBB, int FI) const {
5732 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5733 DebugLoc dl = MI->getDebugLoc();
5734 MachineFunction *MF = MBB->getParent();
5735 MachineRegisterInfo *MRI = &MF->getRegInfo();
5736 MachineConstantPool *MCP = MF->getConstantPool();
5737 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5738 const Function *F = MF->getFunction();
5740 bool isThumb = Subtarget->isThumb();
5741 bool isThumb2 = Subtarget->isThumb2();
5743 unsigned PCLabelId = AFI->createPICLabelUId();
5744 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5745 ARMConstantPoolValue *CPV =
5746 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5747 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5749 const TargetRegisterClass *TRC = isThumb ?
5750 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5751 (const TargetRegisterClass*)&ARM::GPRRegClass;
5753 // Grab constant pool and fixed stack memory operands.
5754 MachineMemOperand *CPMMO =
5755 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5756 MachineMemOperand::MOLoad, 4, 4);
5758 MachineMemOperand *FIMMOSt =
5759 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5760 MachineMemOperand::MOStore, 4, 4);
5762 // Load the address of the dispatch MBB into the jump buffer.
5764 // Incoming value: jbuf
5765 // ldr.n r5, LCPI1_1
5768 // str r5, [$jbuf, #+4] ; &jbuf[1]
5769 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5770 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5771 .addConstantPoolIndex(CPI)
5772 .addMemOperand(CPMMO));
5773 // Set the low bit because of thumb mode.
5774 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5776 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5777 .addReg(NewVReg1, RegState::Kill)
5779 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5780 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5781 .addReg(NewVReg2, RegState::Kill)
5783 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5784 .addReg(NewVReg3, RegState::Kill)
5786 .addImm(36) // &jbuf[1] :: pc
5787 .addMemOperand(FIMMOSt));
5788 } else if (isThumb) {
5789 // Incoming value: jbuf
5790 // ldr.n r1, LCPI1_4
5794 // add r2, $jbuf, #+4 ; &jbuf[1]
5796 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5797 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5798 .addConstantPoolIndex(CPI)
5799 .addMemOperand(CPMMO));
5800 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5801 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5802 .addReg(NewVReg1, RegState::Kill)
5804 // Set the low bit because of thumb mode.
5805 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5806 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5807 .addReg(ARM::CPSR, RegState::Define)
5809 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5810 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5811 .addReg(ARM::CPSR, RegState::Define)
5812 .addReg(NewVReg2, RegState::Kill)
5813 .addReg(NewVReg3, RegState::Kill));
5814 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5815 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5817 .addImm(36)); // &jbuf[1] :: pc
5818 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5819 .addReg(NewVReg4, RegState::Kill)
5820 .addReg(NewVReg5, RegState::Kill)
5822 .addMemOperand(FIMMOSt));
5824 // Incoming value: jbuf
5827 // str r1, [$jbuf, #+4] ; &jbuf[1]
5828 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5829 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
5830 .addConstantPoolIndex(CPI)
5832 .addMemOperand(CPMMO));
5833 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5834 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5835 .addReg(NewVReg1, RegState::Kill)
5836 .addImm(PCLabelId));
5837 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5838 .addReg(NewVReg2, RegState::Kill)
5840 .addImm(36) // &jbuf[1] :: pc
5841 .addMemOperand(FIMMOSt));
5845 MachineBasicBlock *ARMTargetLowering::
5846 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5847 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5848 DebugLoc dl = MI->getDebugLoc();
5849 MachineFunction *MF = MBB->getParent();
5850 MachineRegisterInfo *MRI = &MF->getRegInfo();
5851 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5852 MachineFrameInfo *MFI = MF->getFrameInfo();
5853 int FI = MFI->getFunctionContextIndex();
5855 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5856 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5857 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5859 // Get a mapping of the call site numbers to all of the landing pads they're
5861 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5862 unsigned MaxCSNum = 0;
5863 MachineModuleInfo &MMI = MF->getMMI();
5864 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5866 if (!BB->isLandingPad()) continue;
5868 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5870 for (MachineBasicBlock::iterator
5871 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5872 if (!II->isEHLabel()) continue;
5874 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5875 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5877 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5878 for (SmallVectorImpl<unsigned>::iterator
5879 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5880 CSI != CSE; ++CSI) {
5881 CallSiteNumToLPad[*CSI].push_back(BB);
5882 MaxCSNum = std::max(MaxCSNum, *CSI);
5888 // Get an ordered list of the machine basic blocks for the jump table.
5889 std::vector<MachineBasicBlock*> LPadList;
5890 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5891 LPadList.reserve(CallSiteNumToLPad.size());
5892 for (unsigned I = 1; I <= MaxCSNum; ++I) {
5893 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5894 for (SmallVectorImpl<MachineBasicBlock*>::iterator
5895 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5896 LPadList.push_back(*II);
5897 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5901 assert(!LPadList.empty() &&
5902 "No landing pad destinations for the dispatch jump table!");
5904 // Create the jump table and associated information.
5905 MachineJumpTableInfo *JTI =
5906 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5907 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5908 unsigned UId = AFI->createJumpTableUId();
5910 // Create the MBBs for the dispatch code.
5912 // Shove the dispatch's address into the return slot in the function context.
5913 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5914 DispatchBB->setIsLandingPad();
5916 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5917 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5918 DispatchBB->addSuccessor(TrapBB);
5920 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5921 DispatchBB->addSuccessor(DispContBB);
5924 MF->insert(MF->end(), DispatchBB);
5925 MF->insert(MF->end(), DispContBB);
5926 MF->insert(MF->end(), TrapBB);
5928 // Insert code into the entry block that creates and registers the function
5930 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5932 MachineMemOperand *FIMMOLd =
5933 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5934 MachineMemOperand::MOLoad |
5935 MachineMemOperand::MOVolatile, 4, 4);
5937 if (AFI->isThumb1OnlyFunction())
5938 BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5939 else if (!Subtarget->hasVFP2())
5940 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5942 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5944 unsigned NumLPads = LPadList.size();
5945 if (Subtarget->isThumb2()) {
5946 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5947 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5950 .addMemOperand(FIMMOLd));
5952 if (NumLPads < 256) {
5953 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5955 .addImm(LPadList.size()));
5957 unsigned VReg1 = MRI->createVirtualRegister(TRC);
5958 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5959 .addImm(NumLPads & 0xFFFF));
5961 unsigned VReg2 = VReg1;
5962 if ((NumLPads & 0xFFFF0000) != 0) {
5963 VReg2 = MRI->createVirtualRegister(TRC);
5964 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5966 .addImm(NumLPads >> 16));
5969 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5974 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5979 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5980 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5981 .addJumpTableIndex(MJTI)
5984 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5987 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5988 .addReg(NewVReg3, RegState::Kill)
5990 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5992 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5993 .addReg(NewVReg4, RegState::Kill)
5995 .addJumpTableIndex(MJTI)
5997 } else if (Subtarget->isThumb()) {
5998 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5999 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6002 .addMemOperand(FIMMOLd));
6004 if (NumLPads < 256) {
6005 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6009 MachineConstantPool *ConstantPool = MF->getConstantPool();
6010 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6011 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6013 // MachineConstantPool wants an explicit alignment.
6014 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6016 Align = getTargetData()->getTypeAllocSize(C->getType());
6017 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6019 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6020 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6021 .addReg(VReg1, RegState::Define)
6022 .addConstantPoolIndex(Idx));
6023 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6028 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6033 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6034 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6035 .addReg(ARM::CPSR, RegState::Define)
6039 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6040 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6041 .addJumpTableIndex(MJTI)
6044 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6045 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6046 .addReg(ARM::CPSR, RegState::Define)
6047 .addReg(NewVReg2, RegState::Kill)
6050 MachineMemOperand *JTMMOLd =
6051 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6052 MachineMemOperand::MOLoad, 4, 4);
6054 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6055 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6056 .addReg(NewVReg4, RegState::Kill)
6058 .addMemOperand(JTMMOLd));
6060 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6061 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6062 .addReg(ARM::CPSR, RegState::Define)
6063 .addReg(NewVReg5, RegState::Kill)
6066 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6067 .addReg(NewVReg6, RegState::Kill)
6068 .addJumpTableIndex(MJTI)
6071 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6072 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6075 .addMemOperand(FIMMOLd));
6077 if (NumLPads < 256) {
6078 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6081 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6082 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6083 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6084 .addImm(NumLPads & 0xFFFF));
6086 unsigned VReg2 = VReg1;
6087 if ((NumLPads & 0xFFFF0000) != 0) {
6088 VReg2 = MRI->createVirtualRegister(TRC);
6089 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6091 .addImm(NumLPads >> 16));
6094 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6098 MachineConstantPool *ConstantPool = MF->getConstantPool();
6099 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6100 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6102 // MachineConstantPool wants an explicit alignment.
6103 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6105 Align = getTargetData()->getTypeAllocSize(C->getType());
6106 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6108 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6109 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6110 .addReg(VReg1, RegState::Define)
6111 .addConstantPoolIndex(Idx)
6113 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6115 .addReg(VReg1, RegState::Kill));
6118 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6123 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6125 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6127 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6128 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6129 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6130 .addJumpTableIndex(MJTI)
6133 MachineMemOperand *JTMMOLd =
6134 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6135 MachineMemOperand::MOLoad, 4, 4);
6136 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6138 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6139 .addReg(NewVReg3, RegState::Kill)
6142 .addMemOperand(JTMMOLd));
6144 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6145 .addReg(NewVReg5, RegState::Kill)
6147 .addJumpTableIndex(MJTI)
6151 // Add the jump table entries as successors to the MBB.
6152 MachineBasicBlock *PrevMBB = 0;
6153 for (std::vector<MachineBasicBlock*>::iterator
6154 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6155 MachineBasicBlock *CurMBB = *I;
6156 if (PrevMBB != CurMBB)
6157 DispContBB->addSuccessor(CurMBB);
6161 // N.B. the order the invoke BBs are processed in doesn't matter here.
6162 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6163 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6164 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6165 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6166 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6167 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6168 MachineBasicBlock *BB = *I;
6170 // Remove the landing pad successor from the invoke block and replace it
6171 // with the new dispatch block.
6172 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6174 while (!Successors.empty()) {
6175 MachineBasicBlock *SMBB = Successors.pop_back_val();
6176 if (SMBB->isLandingPad()) {
6177 BB->removeSuccessor(SMBB);
6178 MBBLPads.push_back(SMBB);
6182 BB->addSuccessor(DispatchBB);
6184 // Find the invoke call and mark all of the callee-saved registers as
6185 // 'implicit defined' so that they're spilled. This prevents code from
6186 // moving instructions to before the EH block, where they will never be
6188 for (MachineBasicBlock::reverse_iterator
6189 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6190 if (!II->isCall()) continue;
6192 DenseMap<unsigned, bool> DefRegs;
6193 for (MachineInstr::mop_iterator
6194 OI = II->operands_begin(), OE = II->operands_end();
6196 if (!OI->isReg()) continue;
6197 DefRegs[OI->getReg()] = true;
6200 MachineInstrBuilder MIB(&*II);
6202 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6203 unsigned Reg = SavedRegs[i];
6204 if (Subtarget->isThumb2() &&
6205 !ARM::tGPRRegClass.contains(Reg) &&
6206 !ARM::hGPRRegClass.contains(Reg))
6208 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6210 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6213 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6220 // Mark all former landing pads as non-landing pads. The dispatch is the only
6222 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6223 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6224 (*I)->setIsLandingPad(false);
6226 // The instruction is gone now.
6227 MI->eraseFromParent();
6233 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6234 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6235 E = MBB->succ_end(); I != E; ++I)
6238 llvm_unreachable("Expecting a BB with two successors!");
6242 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6243 MachineBasicBlock *BB) const {
6244 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6245 DebugLoc dl = MI->getDebugLoc();
6246 bool isThumb2 = Subtarget->isThumb2();
6247 switch (MI->getOpcode()) {
6250 llvm_unreachable("Unexpected instr type to insert");
6252 // The Thumb2 pre-indexed stores have the same MI operands, they just
6253 // define them differently in the .td files from the isel patterns, so
6254 // they need pseudos.
6255 case ARM::t2STR_preidx:
6256 MI->setDesc(TII->get(ARM::t2STR_PRE));
6258 case ARM::t2STRB_preidx:
6259 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6261 case ARM::t2STRH_preidx:
6262 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6265 case ARM::STRi_preidx:
6266 case ARM::STRBi_preidx: {
6267 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6268 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6269 // Decode the offset.
6270 unsigned Offset = MI->getOperand(4).getImm();
6271 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6272 Offset = ARM_AM::getAM2Offset(Offset);
6276 MachineMemOperand *MMO = *MI->memoperands_begin();
6277 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6278 .addOperand(MI->getOperand(0)) // Rn_wb
6279 .addOperand(MI->getOperand(1)) // Rt
6280 .addOperand(MI->getOperand(2)) // Rn
6281 .addImm(Offset) // offset (skip GPR==zero_reg)
6282 .addOperand(MI->getOperand(5)) // pred
6283 .addOperand(MI->getOperand(6))
6284 .addMemOperand(MMO);
6285 MI->eraseFromParent();
6288 case ARM::STRr_preidx:
6289 case ARM::STRBr_preidx:
6290 case ARM::STRH_preidx: {
6292 switch (MI->getOpcode()) {
6293 default: llvm_unreachable("unexpected opcode!");
6294 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6295 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6296 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6298 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6299 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6300 MIB.addOperand(MI->getOperand(i));
6301 MI->eraseFromParent();
6304 case ARM::ATOMIC_LOAD_ADD_I8:
6305 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6306 case ARM::ATOMIC_LOAD_ADD_I16:
6307 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6308 case ARM::ATOMIC_LOAD_ADD_I32:
6309 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6311 case ARM::ATOMIC_LOAD_AND_I8:
6312 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6313 case ARM::ATOMIC_LOAD_AND_I16:
6314 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6315 case ARM::ATOMIC_LOAD_AND_I32:
6316 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6318 case ARM::ATOMIC_LOAD_OR_I8:
6319 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6320 case ARM::ATOMIC_LOAD_OR_I16:
6321 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6322 case ARM::ATOMIC_LOAD_OR_I32:
6323 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6325 case ARM::ATOMIC_LOAD_XOR_I8:
6326 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6327 case ARM::ATOMIC_LOAD_XOR_I16:
6328 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6329 case ARM::ATOMIC_LOAD_XOR_I32:
6330 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6332 case ARM::ATOMIC_LOAD_NAND_I8:
6333 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6334 case ARM::ATOMIC_LOAD_NAND_I16:
6335 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6336 case ARM::ATOMIC_LOAD_NAND_I32:
6337 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6339 case ARM::ATOMIC_LOAD_SUB_I8:
6340 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6341 case ARM::ATOMIC_LOAD_SUB_I16:
6342 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6343 case ARM::ATOMIC_LOAD_SUB_I32:
6344 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6346 case ARM::ATOMIC_LOAD_MIN_I8:
6347 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6348 case ARM::ATOMIC_LOAD_MIN_I16:
6349 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6350 case ARM::ATOMIC_LOAD_MIN_I32:
6351 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6353 case ARM::ATOMIC_LOAD_MAX_I8:
6354 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6355 case ARM::ATOMIC_LOAD_MAX_I16:
6356 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6357 case ARM::ATOMIC_LOAD_MAX_I32:
6358 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6360 case ARM::ATOMIC_LOAD_UMIN_I8:
6361 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6362 case ARM::ATOMIC_LOAD_UMIN_I16:
6363 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6364 case ARM::ATOMIC_LOAD_UMIN_I32:
6365 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6367 case ARM::ATOMIC_LOAD_UMAX_I8:
6368 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6369 case ARM::ATOMIC_LOAD_UMAX_I16:
6370 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6371 case ARM::ATOMIC_LOAD_UMAX_I32:
6372 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6374 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
6375 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6376 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6378 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
6379 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6380 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6383 case ARM::ATOMADD6432:
6384 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6385 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6386 /*NeedsCarry*/ true);
6387 case ARM::ATOMSUB6432:
6388 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6389 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6390 /*NeedsCarry*/ true);
6391 case ARM::ATOMOR6432:
6392 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6393 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6394 case ARM::ATOMXOR6432:
6395 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6396 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6397 case ARM::ATOMAND6432:
6398 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6399 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6400 case ARM::ATOMSWAP6432:
6401 return EmitAtomicBinary64(MI, BB, 0, 0, false);
6402 case ARM::ATOMCMPXCHG6432:
6403 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6404 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6405 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6407 case ARM::tMOVCCr_pseudo: {
6408 // To "insert" a SELECT_CC instruction, we actually have to insert the
6409 // diamond control-flow pattern. The incoming instruction knows the
6410 // destination vreg to set, the condition code register to branch on, the
6411 // true/false values to select between, and a branch opcode to use.
6412 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6413 MachineFunction::iterator It = BB;
6419 // cmpTY ccX, r1, r2
6421 // fallthrough --> copy0MBB
6422 MachineBasicBlock *thisMBB = BB;
6423 MachineFunction *F = BB->getParent();
6424 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6425 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6426 F->insert(It, copy0MBB);
6427 F->insert(It, sinkMBB);
6429 // Transfer the remainder of BB and its successor edges to sinkMBB.
6430 sinkMBB->splice(sinkMBB->begin(), BB,
6431 llvm::next(MachineBasicBlock::iterator(MI)),
6433 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6435 BB->addSuccessor(copy0MBB);
6436 BB->addSuccessor(sinkMBB);
6438 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6439 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6442 // %FalseValue = ...
6443 // # fallthrough to sinkMBB
6446 // Update machine-CFG edges
6447 BB->addSuccessor(sinkMBB);
6450 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6453 BuildMI(*BB, BB->begin(), dl,
6454 TII->get(ARM::PHI), MI->getOperand(0).getReg())
6455 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6456 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6458 MI->eraseFromParent(); // The pseudo instruction is gone now.
6463 case ARM::BCCZi64: {
6464 // If there is an unconditional branch to the other successor, remove it.
6465 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6467 // Compare both parts that make up the double comparison separately for
6469 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6471 unsigned LHS1 = MI->getOperand(1).getReg();
6472 unsigned LHS2 = MI->getOperand(2).getReg();
6474 AddDefaultPred(BuildMI(BB, dl,
6475 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6476 .addReg(LHS1).addImm(0));
6477 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6478 .addReg(LHS2).addImm(0)
6479 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6481 unsigned RHS1 = MI->getOperand(3).getReg();
6482 unsigned RHS2 = MI->getOperand(4).getReg();
6483 AddDefaultPred(BuildMI(BB, dl,
6484 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6485 .addReg(LHS1).addReg(RHS1));
6486 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6487 .addReg(LHS2).addReg(RHS2)
6488 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6491 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6492 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6493 if (MI->getOperand(0).getImm() == ARMCC::NE)
6494 std::swap(destMBB, exitMBB);
6496 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6497 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6499 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6501 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6503 MI->eraseFromParent(); // The pseudo instruction is gone now.
6507 case ARM::Int_eh_sjlj_setjmp:
6508 case ARM::Int_eh_sjlj_setjmp_nofp:
6509 case ARM::tInt_eh_sjlj_setjmp:
6510 case ARM::t2Int_eh_sjlj_setjmp:
6511 case ARM::t2Int_eh_sjlj_setjmp_nofp:
6512 EmitSjLjDispatchBlock(MI, BB);
6517 // To insert an ABS instruction, we have to insert the
6518 // diamond control-flow pattern. The incoming instruction knows the
6519 // source vreg to test against 0, the destination vreg to set,
6520 // the condition code register to branch on, the
6521 // true/false values to select between, and a branch opcode to use.
6526 // BCC (branch to SinkBB if V0 >= 0)
6527 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
6528 // SinkBB: V1 = PHI(V2, V3)
6529 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6530 MachineFunction::iterator BBI = BB;
6532 MachineFunction *Fn = BB->getParent();
6533 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6534 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6535 Fn->insert(BBI, RSBBB);
6536 Fn->insert(BBI, SinkBB);
6538 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6539 unsigned int ABSDstReg = MI->getOperand(0).getReg();
6540 bool isThumb2 = Subtarget->isThumb2();
6541 MachineRegisterInfo &MRI = Fn->getRegInfo();
6542 // In Thumb mode S must not be specified if source register is the SP or
6543 // PC and if destination register is the SP, so restrict register class
6544 unsigned NewMovDstReg = MRI.createVirtualRegister(isThumb2 ?
6545 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6546 (const TargetRegisterClass*)&ARM::GPRRegClass);
6547 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6548 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6549 (const TargetRegisterClass*)&ARM::GPRRegClass);
6551 // Transfer the remainder of BB and its successor edges to sinkMBB.
6552 SinkBB->splice(SinkBB->begin(), BB,
6553 llvm::next(MachineBasicBlock::iterator(MI)),
6555 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6557 BB->addSuccessor(RSBBB);
6558 BB->addSuccessor(SinkBB);
6560 // fall through to SinkMBB
6561 RSBBB->addSuccessor(SinkBB);
6563 // insert a movs at the end of BB
6564 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVr : ARM::MOVr),
6566 .addReg(ABSSrcReg, RegState::Kill)
6567 .addImm((unsigned)ARMCC::AL).addReg(0)
6568 .addReg(ARM::CPSR, RegState::Define);
6570 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6572 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6573 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6575 // insert rsbri in RSBBB
6576 // Note: BCC and rsbri will be converted into predicated rsbmi
6577 // by if-conversion pass
6578 BuildMI(*RSBBB, RSBBB->begin(), dl,
6579 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6580 .addReg(NewMovDstReg, RegState::Kill)
6581 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6583 // insert PHI in SinkBB,
6584 // reuse ABSDstReg to not change uses of ABS instruction
6585 BuildMI(*SinkBB, SinkBB->begin(), dl,
6586 TII->get(ARM::PHI), ABSDstReg)
6587 .addReg(NewRsbDstReg).addMBB(RSBBB)
6588 .addReg(NewMovDstReg).addMBB(BB);
6590 // remove ABS instruction
6591 MI->eraseFromParent();
6593 // return last added BB
6599 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6600 SDNode *Node) const {
6601 if (!MI->hasPostISelHook()) {
6602 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6603 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6607 const MCInstrDesc *MCID = &MI->getDesc();
6608 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6609 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6610 // operand is still set to noreg. If needed, set the optional operand's
6611 // register to CPSR, and remove the redundant implicit def.
6613 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6615 // Rename pseudo opcodes.
6616 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6618 const ARMBaseInstrInfo *TII =
6619 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6620 MCID = &TII->get(NewOpc);
6622 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6623 "converted opcode should be the same except for cc_out");
6627 // Add the optional cc_out operand
6628 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6630 unsigned ccOutIdx = MCID->getNumOperands() - 1;
6632 // Any ARM instruction that sets the 's' bit should specify an optional
6633 // "cc_out" operand in the last operand position.
6634 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6635 assert(!NewOpc && "Optional cc_out operand required");
6638 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6639 // since we already have an optional CPSR def.
6640 bool definesCPSR = false;
6641 bool deadCPSR = false;
6642 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6644 const MachineOperand &MO = MI->getOperand(i);
6645 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6649 MI->RemoveOperand(i);
6654 assert(!NewOpc && "Optional cc_out operand required");
6657 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6659 assert(!MI->getOperand(ccOutIdx).getReg() &&
6660 "expect uninitialized optional cc_out operand");
6664 // If this instruction was defined with an optional CPSR def and its dag node
6665 // had a live implicit CPSR def, then activate the optional CPSR def.
6666 MachineOperand &MO = MI->getOperand(ccOutIdx);
6667 MO.setReg(ARM::CPSR);
6671 //===----------------------------------------------------------------------===//
6672 // ARM Optimization Hooks
6673 //===----------------------------------------------------------------------===//
6676 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6677 TargetLowering::DAGCombinerInfo &DCI) {
6678 SelectionDAG &DAG = DCI.DAG;
6679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6680 EVT VT = N->getValueType(0);
6681 unsigned Opc = N->getOpcode();
6682 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6683 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6684 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6685 ISD::CondCode CC = ISD::SETCC_INVALID;
6688 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6690 SDValue CCOp = Slct.getOperand(0);
6691 if (CCOp.getOpcode() == ISD::SETCC)
6692 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6695 bool DoXform = false;
6697 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6700 if (LHS.getOpcode() == ISD::Constant &&
6701 cast<ConstantSDNode>(LHS)->isNullValue()) {
6703 } else if (CC != ISD::SETCC_INVALID &&
6704 RHS.getOpcode() == ISD::Constant &&
6705 cast<ConstantSDNode>(RHS)->isNullValue()) {
6706 std::swap(LHS, RHS);
6707 SDValue Op0 = Slct.getOperand(0);
6708 EVT OpVT = isSlctCC ? Op0.getValueType() :
6709 Op0.getOperand(0).getValueType();
6710 bool isInt = OpVT.isInteger();
6711 CC = ISD::getSetCCInverse(CC, isInt);
6713 if (!TLI.isCondCodeLegal(CC, OpVT))
6714 return SDValue(); // Inverse operator isn't legal.
6721 SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
6723 return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
6724 Slct.getOperand(0), Slct.getOperand(1), CC);
6725 SDValue CCOp = Slct.getOperand(0);
6727 CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
6728 CCOp.getOperand(0), CCOp.getOperand(1), CC);
6729 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
6730 CCOp, OtherOp, Result);
6735 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
6736 // (only after legalization).
6737 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
6738 TargetLowering::DAGCombinerInfo &DCI,
6739 const ARMSubtarget *Subtarget) {
6741 // Only perform optimization if after legalize, and if NEON is available. We
6742 // also expected both operands to be BUILD_VECTORs.
6743 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
6744 || N0.getOpcode() != ISD::BUILD_VECTOR
6745 || N1.getOpcode() != ISD::BUILD_VECTOR)
6748 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
6749 EVT VT = N->getValueType(0);
6750 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
6753 // Check that the vector operands are of the right form.
6754 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
6755 // operands, where N is the size of the formed vector.
6756 // Each EXTRACT_VECTOR should have the same input vector and odd or even
6757 // index such that we have a pair wise add pattern.
6759 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
6760 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6762 SDValue Vec = N0->getOperand(0)->getOperand(0);
6763 SDNode *V = Vec.getNode();
6764 unsigned nextIndex = 0;
6766 // For each operands to the ADD which are BUILD_VECTORs,
6767 // check to see if each of their operands are an EXTRACT_VECTOR with
6768 // the same vector and appropriate index.
6769 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
6770 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
6771 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6773 SDValue ExtVec0 = N0->getOperand(i);
6774 SDValue ExtVec1 = N1->getOperand(i);
6776 // First operand is the vector, verify its the same.
6777 if (V != ExtVec0->getOperand(0).getNode() ||
6778 V != ExtVec1->getOperand(0).getNode())
6781 // Second is the constant, verify its correct.
6782 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
6783 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
6785 // For the constant, we want to see all the even or all the odd.
6786 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
6787 || C1->getZExtValue() != nextIndex+1)
6796 // Create VPADDL node.
6797 SelectionDAG &DAG = DCI.DAG;
6798 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6800 // Build operand list.
6801 SmallVector<SDValue, 8> Ops;
6802 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
6803 TLI.getPointerTy()));
6805 // Input is the vector.
6808 // Get widened type and narrowed type.
6810 unsigned numElem = VT.getVectorNumElements();
6811 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
6812 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
6813 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
6814 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
6816 llvm_unreachable("Invalid vector element type for padd optimization.");
6819 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6820 widenType, &Ops[0], Ops.size());
6821 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
6824 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
6825 /// operands N0 and N1. This is a helper for PerformADDCombine that is
6826 /// called with the default operands, and if that fails, with commuted
6828 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
6829 TargetLowering::DAGCombinerInfo &DCI,
6830 const ARMSubtarget *Subtarget){
6832 // Attempt to create vpaddl for this add.
6833 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
6834 if (Result.getNode())
6837 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
6838 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
6839 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
6840 if (Result.getNode()) return Result;
6845 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6847 static SDValue PerformADDCombine(SDNode *N,
6848 TargetLowering::DAGCombinerInfo &DCI,
6849 const ARMSubtarget *Subtarget) {
6850 SDValue N0 = N->getOperand(0);
6851 SDValue N1 = N->getOperand(1);
6853 // First try with the default operand order.
6854 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
6855 if (Result.getNode())
6858 // If that didn't work, try again with the operands commuted.
6859 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
6862 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
6864 static SDValue PerformSUBCombine(SDNode *N,
6865 TargetLowering::DAGCombinerInfo &DCI) {
6866 SDValue N0 = N->getOperand(0);
6867 SDValue N1 = N->getOperand(1);
6869 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6870 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
6871 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
6872 if (Result.getNode()) return Result;
6878 /// PerformVMULCombine
6879 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
6880 /// special multiplier accumulator forwarding.
6886 static SDValue PerformVMULCombine(SDNode *N,
6887 TargetLowering::DAGCombinerInfo &DCI,
6888 const ARMSubtarget *Subtarget) {
6889 if (!Subtarget->hasVMLxForwarding())
6892 SelectionDAG &DAG = DCI.DAG;
6893 SDValue N0 = N->getOperand(0);
6894 SDValue N1 = N->getOperand(1);
6895 unsigned Opcode = N0.getOpcode();
6896 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6897 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
6898 Opcode = N1.getOpcode();
6899 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6900 Opcode != ISD::FADD && Opcode != ISD::FSUB)
6905 EVT VT = N->getValueType(0);
6906 DebugLoc DL = N->getDebugLoc();
6907 SDValue N00 = N0->getOperand(0);
6908 SDValue N01 = N0->getOperand(1);
6909 return DAG.getNode(Opcode, DL, VT,
6910 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
6911 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
6914 static SDValue PerformMULCombine(SDNode *N,
6915 TargetLowering::DAGCombinerInfo &DCI,
6916 const ARMSubtarget *Subtarget) {
6917 SelectionDAG &DAG = DCI.DAG;
6919 if (Subtarget->isThumb1Only())
6922 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6925 EVT VT = N->getValueType(0);
6926 if (VT.is64BitVector() || VT.is128BitVector())
6927 return PerformVMULCombine(N, DCI, Subtarget);
6931 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6935 int64_t MulAmt = C->getSExtValue();
6936 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
6938 ShiftAmt = ShiftAmt & (32 - 1);
6939 SDValue V = N->getOperand(0);
6940 DebugLoc DL = N->getDebugLoc();
6943 MulAmt >>= ShiftAmt;
6946 if (isPowerOf2_32(MulAmt - 1)) {
6947 // (mul x, 2^N + 1) => (add (shl x, N), x)
6948 Res = DAG.getNode(ISD::ADD, DL, VT,
6950 DAG.getNode(ISD::SHL, DL, VT,
6952 DAG.getConstant(Log2_32(MulAmt - 1),
6954 } else if (isPowerOf2_32(MulAmt + 1)) {
6955 // (mul x, 2^N - 1) => (sub (shl x, N), x)
6956 Res = DAG.getNode(ISD::SUB, DL, VT,
6957 DAG.getNode(ISD::SHL, DL, VT,
6959 DAG.getConstant(Log2_32(MulAmt + 1),
6965 uint64_t MulAmtAbs = -MulAmt;
6966 if (isPowerOf2_32(MulAmtAbs + 1)) {
6967 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
6968 Res = DAG.getNode(ISD::SUB, DL, VT,
6970 DAG.getNode(ISD::SHL, DL, VT,
6972 DAG.getConstant(Log2_32(MulAmtAbs + 1),
6974 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
6975 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
6976 Res = DAG.getNode(ISD::ADD, DL, VT,
6978 DAG.getNode(ISD::SHL, DL, VT,
6980 DAG.getConstant(Log2_32(MulAmtAbs-1),
6982 Res = DAG.getNode(ISD::SUB, DL, VT,
6983 DAG.getConstant(0, MVT::i32),Res);
6990 Res = DAG.getNode(ISD::SHL, DL, VT,
6991 Res, DAG.getConstant(ShiftAmt, MVT::i32));
6993 // Do not add new nodes to DAG combiner worklist.
6994 DCI.CombineTo(N, Res, false);
6998 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
6999 if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
7002 SDValue FalseVal = N.getOperand(0);
7003 ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
7007 return C->isAllOnesValue();
7008 return C->isNullValue();
7011 /// formConditionalOp - Combine an operation with a conditional move operand
7012 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7013 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7014 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7016 SDValue N0 = N->getOperand(0);
7017 SDValue N1 = N->getOperand(1);
7019 bool isAND = N->getOpcode() == ISD::AND;
7020 bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7021 if (!isCand && Commutable) {
7022 isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7030 switch (N->getOpcode()) {
7031 default: llvm_unreachable("Unexpected node");
7032 case ISD::AND: Opc = ARMISD::CAND; break;
7033 case ISD::OR: Opc = ARMISD::COR; break;
7034 case ISD::XOR: Opc = ARMISD::CXOR; break;
7036 return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7037 N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7041 static SDValue PerformANDCombine(SDNode *N,
7042 TargetLowering::DAGCombinerInfo &DCI,
7043 const ARMSubtarget *Subtarget) {
7045 // Attempt to use immediate-form VBIC
7046 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7047 DebugLoc dl = N->getDebugLoc();
7048 EVT VT = N->getValueType(0);
7049 SelectionDAG &DAG = DCI.DAG;
7051 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7054 APInt SplatBits, SplatUndef;
7055 unsigned SplatBitSize;
7058 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7059 if (SplatBitSize <= 64) {
7061 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7062 SplatUndef.getZExtValue(), SplatBitSize,
7063 DAG, VbicVT, VT.is128BitVector(),
7065 if (Val.getNode()) {
7067 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7068 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7069 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7074 if (!Subtarget->isThumb1Only()) {
7075 // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7076 SDValue CAND = formConditionalOp(N, DAG, true);
7084 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7085 static SDValue PerformORCombine(SDNode *N,
7086 TargetLowering::DAGCombinerInfo &DCI,
7087 const ARMSubtarget *Subtarget) {
7088 // Attempt to use immediate-form VORR
7089 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7090 DebugLoc dl = N->getDebugLoc();
7091 EVT VT = N->getValueType(0);
7092 SelectionDAG &DAG = DCI.DAG;
7094 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7097 APInt SplatBits, SplatUndef;
7098 unsigned SplatBitSize;
7100 if (BVN && Subtarget->hasNEON() &&
7101 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7102 if (SplatBitSize <= 64) {
7104 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7105 SplatUndef.getZExtValue(), SplatBitSize,
7106 DAG, VorrVT, VT.is128BitVector(),
7108 if (Val.getNode()) {
7110 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7111 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7112 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7117 if (!Subtarget->isThumb1Only()) {
7118 // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7119 SDValue COR = formConditionalOp(N, DAG, true);
7124 SDValue N0 = N->getOperand(0);
7125 if (N0.getOpcode() != ISD::AND)
7127 SDValue N1 = N->getOperand(1);
7129 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7130 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7131 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7133 unsigned SplatBitSize;
7136 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7138 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7139 HasAnyUndefs) && !HasAnyUndefs) {
7140 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7142 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7143 HasAnyUndefs) && !HasAnyUndefs &&
7144 SplatBits0 == ~SplatBits1) {
7145 // Canonicalize the vector type to make instruction selection simpler.
7146 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7147 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7148 N0->getOperand(1), N0->getOperand(0),
7150 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7155 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7158 // BFI is only available on V6T2+
7159 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7162 DebugLoc DL = N->getDebugLoc();
7163 // 1) or (and A, mask), val => ARMbfi A, val, mask
7164 // iff (val & mask) == val
7166 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7167 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7168 // && mask == ~mask2
7169 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7170 // && ~mask == mask2
7171 // (i.e., copy a bitfield value into another bitfield of the same width)
7176 SDValue N00 = N0.getOperand(0);
7178 // The value and the mask need to be constants so we can verify this is
7179 // actually a bitfield set. If the mask is 0xffff, we can do better
7180 // via a movt instruction, so don't use BFI in that case.
7181 SDValue MaskOp = N0.getOperand(1);
7182 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7185 unsigned Mask = MaskC->getZExtValue();
7189 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7190 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7192 unsigned Val = N1C->getZExtValue();
7193 if ((Val & ~Mask) != Val)
7196 if (ARM::isBitFieldInvertedMask(Mask)) {
7197 Val >>= CountTrailingZeros_32(~Mask);
7199 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7200 DAG.getConstant(Val, MVT::i32),
7201 DAG.getConstant(Mask, MVT::i32));
7203 // Do not add new nodes to DAG combiner worklist.
7204 DCI.CombineTo(N, Res, false);
7207 } else if (N1.getOpcode() == ISD::AND) {
7208 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7209 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7212 unsigned Mask2 = N11C->getZExtValue();
7214 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7216 if (ARM::isBitFieldInvertedMask(Mask) &&
7218 // The pack halfword instruction works better for masks that fit it,
7219 // so use that when it's available.
7220 if (Subtarget->hasT2ExtractPack() &&
7221 (Mask == 0xffff || Mask == 0xffff0000))
7224 unsigned amt = CountTrailingZeros_32(Mask2);
7225 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7226 DAG.getConstant(amt, MVT::i32));
7227 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7228 DAG.getConstant(Mask, MVT::i32));
7229 // Do not add new nodes to DAG combiner worklist.
7230 DCI.CombineTo(N, Res, false);
7232 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7234 // The pack halfword instruction works better for masks that fit it,
7235 // so use that when it's available.
7236 if (Subtarget->hasT2ExtractPack() &&
7237 (Mask2 == 0xffff || Mask2 == 0xffff0000))
7240 unsigned lsb = CountTrailingZeros_32(Mask);
7241 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7242 DAG.getConstant(lsb, MVT::i32));
7243 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7244 DAG.getConstant(Mask2, MVT::i32));
7245 // Do not add new nodes to DAG combiner worklist.
7246 DCI.CombineTo(N, Res, false);
7251 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7252 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7253 ARM::isBitFieldInvertedMask(~Mask)) {
7254 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7255 // where lsb(mask) == #shamt and masked bits of B are known zero.
7256 SDValue ShAmt = N00.getOperand(1);
7257 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7258 unsigned LSB = CountTrailingZeros_32(Mask);
7262 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7263 DAG.getConstant(~Mask, MVT::i32));
7265 // Do not add new nodes to DAG combiner worklist.
7266 DCI.CombineTo(N, Res, false);
7272 static SDValue PerformXORCombine(SDNode *N,
7273 TargetLowering::DAGCombinerInfo &DCI,
7274 const ARMSubtarget *Subtarget) {
7275 EVT VT = N->getValueType(0);
7276 SelectionDAG &DAG = DCI.DAG;
7278 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7281 if (!Subtarget->isThumb1Only()) {
7282 // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7283 SDValue CXOR = formConditionalOp(N, DAG, true);
7291 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7292 /// the bits being cleared by the AND are not demanded by the BFI.
7293 static SDValue PerformBFICombine(SDNode *N,
7294 TargetLowering::DAGCombinerInfo &DCI) {
7295 SDValue N1 = N->getOperand(1);
7296 if (N1.getOpcode() == ISD::AND) {
7297 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7300 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7301 unsigned LSB = CountTrailingZeros_32(~InvMask);
7302 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7303 unsigned Mask = (1 << Width)-1;
7304 unsigned Mask2 = N11C->getZExtValue();
7305 if ((Mask & (~Mask2)) == 0)
7306 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7307 N->getOperand(0), N1.getOperand(0),
7313 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7314 /// ARMISD::VMOVRRD.
7315 static SDValue PerformVMOVRRDCombine(SDNode *N,
7316 TargetLowering::DAGCombinerInfo &DCI) {
7317 // vmovrrd(vmovdrr x, y) -> x,y
7318 SDValue InDouble = N->getOperand(0);
7319 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7320 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7322 // vmovrrd(load f64) -> (load i32), (load i32)
7323 SDNode *InNode = InDouble.getNode();
7324 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7325 InNode->getValueType(0) == MVT::f64 &&
7326 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7327 !cast<LoadSDNode>(InNode)->isVolatile()) {
7328 // TODO: Should this be done for non-FrameIndex operands?
7329 LoadSDNode *LD = cast<LoadSDNode>(InNode);
7331 SelectionDAG &DAG = DCI.DAG;
7332 DebugLoc DL = LD->getDebugLoc();
7333 SDValue BasePtr = LD->getBasePtr();
7334 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7335 LD->getPointerInfo(), LD->isVolatile(),
7336 LD->isNonTemporal(), LD->isInvariant(),
7337 LD->getAlignment());
7339 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7340 DAG.getConstant(4, MVT::i32));
7341 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7342 LD->getPointerInfo(), LD->isVolatile(),
7343 LD->isNonTemporal(), LD->isInvariant(),
7344 std::min(4U, LD->getAlignment() / 2));
7346 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7347 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7348 DCI.RemoveFromWorklist(LD);
7356 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7357 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
7358 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7359 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7360 SDValue Op0 = N->getOperand(0);
7361 SDValue Op1 = N->getOperand(1);
7362 if (Op0.getOpcode() == ISD::BITCAST)
7363 Op0 = Op0.getOperand(0);
7364 if (Op1.getOpcode() == ISD::BITCAST)
7365 Op1 = Op1.getOperand(0);
7366 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7367 Op0.getNode() == Op1.getNode() &&
7368 Op0.getResNo() == 0 && Op1.getResNo() == 1)
7369 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7370 N->getValueType(0), Op0.getOperand(0));
7374 /// PerformSTORECombine - Target-specific dag combine xforms for
7376 static SDValue PerformSTORECombine(SDNode *N,
7377 TargetLowering::DAGCombinerInfo &DCI) {
7378 StoreSDNode *St = cast<StoreSDNode>(N);
7379 if (St->isVolatile())
7382 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
7383 // pack all of the elements in one place. Next, store to memory in fewer
7385 SDValue StVal = St->getValue();
7386 EVT VT = StVal.getValueType();
7387 if (St->isTruncatingStore() && VT.isVector()) {
7388 SelectionDAG &DAG = DCI.DAG;
7389 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7390 EVT StVT = St->getMemoryVT();
7391 unsigned NumElems = VT.getVectorNumElements();
7392 assert(StVT != VT && "Cannot truncate to the same type");
7393 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7394 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7396 // From, To sizes and ElemCount must be pow of two
7397 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7399 // We are going to use the original vector elt for storing.
7400 // Accumulated smaller vector elements must be a multiple of the store size.
7401 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7403 unsigned SizeRatio = FromEltSz / ToEltSz;
7404 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7406 // Create a type on which we perform the shuffle.
7407 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7408 NumElems*SizeRatio);
7409 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7411 DebugLoc DL = St->getDebugLoc();
7412 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7413 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7414 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7416 // Can't shuffle using an illegal type.
7417 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7419 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7420 DAG.getUNDEF(WideVec.getValueType()),
7422 // At this point all of the data is stored at the bottom of the
7423 // register. We now need to save it to mem.
7425 // Find the largest store unit
7426 MVT StoreType = MVT::i8;
7427 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7428 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7429 MVT Tp = (MVT::SimpleValueType)tp;
7430 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7433 // Didn't find a legal store type.
7434 if (!TLI.isTypeLegal(StoreType))
7437 // Bitcast the original vector into a vector of store-size units
7438 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7439 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7440 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7441 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7442 SmallVector<SDValue, 8> Chains;
7443 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7444 TLI.getPointerTy());
7445 SDValue BasePtr = St->getBasePtr();
7447 // Perform one or more big stores into memory.
7448 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7449 for (unsigned I = 0; I < E; I++) {
7450 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7451 StoreType, ShuffWide,
7452 DAG.getIntPtrConstant(I));
7453 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7454 St->getPointerInfo(), St->isVolatile(),
7455 St->isNonTemporal(), St->getAlignment());
7456 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7458 Chains.push_back(Ch);
7460 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7464 if (!ISD::isNormalStore(St))
7467 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7468 // ARM stores of arguments in the same cache line.
7469 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7470 StVal.getNode()->hasOneUse()) {
7471 SelectionDAG &DAG = DCI.DAG;
7472 DebugLoc DL = St->getDebugLoc();
7473 SDValue BasePtr = St->getBasePtr();
7474 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7475 StVal.getNode()->getOperand(0), BasePtr,
7476 St->getPointerInfo(), St->isVolatile(),
7477 St->isNonTemporal(), St->getAlignment());
7479 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7480 DAG.getConstant(4, MVT::i32));
7481 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7482 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7483 St->isNonTemporal(),
7484 std::min(4U, St->getAlignment() / 2));
7487 if (StVal.getValueType() != MVT::i64 ||
7488 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7491 // Bitcast an i64 store extracted from a vector to f64.
7492 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7493 SelectionDAG &DAG = DCI.DAG;
7494 DebugLoc dl = StVal.getDebugLoc();
7495 SDValue IntVec = StVal.getOperand(0);
7496 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7497 IntVec.getValueType().getVectorNumElements());
7498 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7499 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7500 Vec, StVal.getOperand(1));
7501 dl = N->getDebugLoc();
7502 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7503 // Make the DAGCombiner fold the bitcasts.
7504 DCI.AddToWorklist(Vec.getNode());
7505 DCI.AddToWorklist(ExtElt.getNode());
7506 DCI.AddToWorklist(V.getNode());
7507 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7508 St->getPointerInfo(), St->isVolatile(),
7509 St->isNonTemporal(), St->getAlignment(),
7513 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7514 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
7515 /// i64 vector to have f64 elements, since the value can then be loaded
7516 /// directly into a VFP register.
7517 static bool hasNormalLoadOperand(SDNode *N) {
7518 unsigned NumElts = N->getValueType(0).getVectorNumElements();
7519 for (unsigned i = 0; i < NumElts; ++i) {
7520 SDNode *Elt = N->getOperand(i).getNode();
7521 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7527 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7528 /// ISD::BUILD_VECTOR.
7529 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7530 TargetLowering::DAGCombinerInfo &DCI){
7531 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7532 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
7533 // into a pair of GPRs, which is fine when the value is used as a scalar,
7534 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7535 SelectionDAG &DAG = DCI.DAG;
7536 if (N->getNumOperands() == 2) {
7537 SDValue RV = PerformVMOVDRRCombine(N, DAG);
7542 // Load i64 elements as f64 values so that type legalization does not split
7543 // them up into i32 values.
7544 EVT VT = N->getValueType(0);
7545 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7547 DebugLoc dl = N->getDebugLoc();
7548 SmallVector<SDValue, 8> Ops;
7549 unsigned NumElts = VT.getVectorNumElements();
7550 for (unsigned i = 0; i < NumElts; ++i) {
7551 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7553 // Make the DAGCombiner fold the bitcast.
7554 DCI.AddToWorklist(V.getNode());
7556 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7557 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7558 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7561 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7562 /// ISD::INSERT_VECTOR_ELT.
7563 static SDValue PerformInsertEltCombine(SDNode *N,
7564 TargetLowering::DAGCombinerInfo &DCI) {
7565 // Bitcast an i64 load inserted into a vector to f64.
7566 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7567 EVT VT = N->getValueType(0);
7568 SDNode *Elt = N->getOperand(1).getNode();
7569 if (VT.getVectorElementType() != MVT::i64 ||
7570 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7573 SelectionDAG &DAG = DCI.DAG;
7574 DebugLoc dl = N->getDebugLoc();
7575 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7576 VT.getVectorNumElements());
7577 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7578 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7579 // Make the DAGCombiner fold the bitcasts.
7580 DCI.AddToWorklist(Vec.getNode());
7581 DCI.AddToWorklist(V.getNode());
7582 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7583 Vec, V, N->getOperand(2));
7584 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7587 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7588 /// ISD::VECTOR_SHUFFLE.
7589 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7590 // The LLVM shufflevector instruction does not require the shuffle mask
7591 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7592 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
7593 // operands do not match the mask length, they are extended by concatenating
7594 // them with undef vectors. That is probably the right thing for other
7595 // targets, but for NEON it is better to concatenate two double-register
7596 // size vector operands into a single quad-register size vector. Do that
7597 // transformation here:
7598 // shuffle(concat(v1, undef), concat(v2, undef)) ->
7599 // shuffle(concat(v1, v2), undef)
7600 SDValue Op0 = N->getOperand(0);
7601 SDValue Op1 = N->getOperand(1);
7602 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7603 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7604 Op0.getNumOperands() != 2 ||
7605 Op1.getNumOperands() != 2)
7607 SDValue Concat0Op1 = Op0.getOperand(1);
7608 SDValue Concat1Op1 = Op1.getOperand(1);
7609 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7610 Concat1Op1.getOpcode() != ISD::UNDEF)
7612 // Skip the transformation if any of the types are illegal.
7613 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7614 EVT VT = N->getValueType(0);
7615 if (!TLI.isTypeLegal(VT) ||
7616 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7617 !TLI.isTypeLegal(Concat1Op1.getValueType()))
7620 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7621 Op0.getOperand(0), Op1.getOperand(0));
7622 // Translate the shuffle mask.
7623 SmallVector<int, 16> NewMask;
7624 unsigned NumElts = VT.getVectorNumElements();
7625 unsigned HalfElts = NumElts/2;
7626 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7627 for (unsigned n = 0; n < NumElts; ++n) {
7628 int MaskElt = SVN->getMaskElt(n);
7630 if (MaskElt < (int)HalfElts)
7632 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7633 NewElt = HalfElts + MaskElt - NumElts;
7634 NewMask.push_back(NewElt);
7636 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7637 DAG.getUNDEF(VT), NewMask.data());
7640 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7641 /// NEON load/store intrinsics to merge base address updates.
7642 static SDValue CombineBaseUpdate(SDNode *N,
7643 TargetLowering::DAGCombinerInfo &DCI) {
7644 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7647 SelectionDAG &DAG = DCI.DAG;
7648 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7649 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7650 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7651 SDValue Addr = N->getOperand(AddrOpIdx);
7653 // Search for a use of the address operand that is an increment.
7654 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7655 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7657 if (User->getOpcode() != ISD::ADD ||
7658 UI.getUse().getResNo() != Addr.getResNo())
7661 // Check that the add is independent of the load/store. Otherwise, folding
7662 // it would create a cycle.
7663 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7666 // Find the new opcode for the updating load/store.
7668 bool isLaneOp = false;
7669 unsigned NewOpc = 0;
7670 unsigned NumVecs = 0;
7672 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7674 default: llvm_unreachable("unexpected intrinsic for Neon base update");
7675 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
7677 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
7679 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
7681 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
7683 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7684 NumVecs = 2; isLaneOp = true; break;
7685 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7686 NumVecs = 3; isLaneOp = true; break;
7687 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7688 NumVecs = 4; isLaneOp = true; break;
7689 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
7690 NumVecs = 1; isLoad = false; break;
7691 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
7692 NumVecs = 2; isLoad = false; break;
7693 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
7694 NumVecs = 3; isLoad = false; break;
7695 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
7696 NumVecs = 4; isLoad = false; break;
7697 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7698 NumVecs = 2; isLoad = false; isLaneOp = true; break;
7699 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7700 NumVecs = 3; isLoad = false; isLaneOp = true; break;
7701 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
7702 NumVecs = 4; isLoad = false; isLaneOp = true; break;
7706 switch (N->getOpcode()) {
7707 default: llvm_unreachable("unexpected opcode for Neon base update");
7708 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
7709 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
7710 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
7714 // Find the size of memory referenced by the load/store.
7717 VecTy = N->getValueType(0);
7719 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
7720 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7722 NumBytes /= VecTy.getVectorNumElements();
7724 // If the increment is a constant, it must match the memory ref size.
7725 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7726 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7727 uint64_t IncVal = CInc->getZExtValue();
7728 if (IncVal != NumBytes)
7730 } else if (NumBytes >= 3 * 16) {
7731 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
7732 // separate instructions that make it harder to use a non-constant update.
7736 // Create the new updating load/store node.
7738 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
7740 for (n = 0; n < NumResultVecs; ++n)
7742 Tys[n++] = MVT::i32;
7743 Tys[n] = MVT::Other;
7744 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
7745 SmallVector<SDValue, 8> Ops;
7746 Ops.push_back(N->getOperand(0)); // incoming chain
7747 Ops.push_back(N->getOperand(AddrOpIdx));
7749 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
7750 Ops.push_back(N->getOperand(i));
7752 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7753 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
7754 Ops.data(), Ops.size(),
7755 MemInt->getMemoryVT(),
7756 MemInt->getMemOperand());
7759 std::vector<SDValue> NewResults;
7760 for (unsigned i = 0; i < NumResultVecs; ++i) {
7761 NewResults.push_back(SDValue(UpdN.getNode(), i));
7763 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
7764 DCI.CombineTo(N, NewResults);
7765 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7772 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
7773 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
7774 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
7776 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
7777 SelectionDAG &DAG = DCI.DAG;
7778 EVT VT = N->getValueType(0);
7779 // vldN-dup instructions only support 64-bit vectors for N > 1.
7780 if (!VT.is64BitVector())
7783 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
7784 SDNode *VLD = N->getOperand(0).getNode();
7785 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
7787 unsigned NumVecs = 0;
7788 unsigned NewOpc = 0;
7789 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
7790 if (IntNo == Intrinsic::arm_neon_vld2lane) {
7792 NewOpc = ARMISD::VLD2DUP;
7793 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
7795 NewOpc = ARMISD::VLD3DUP;
7796 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
7798 NewOpc = ARMISD::VLD4DUP;
7803 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
7804 // numbers match the load.
7805 unsigned VLDLaneNo =
7806 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
7807 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7809 // Ignore uses of the chain result.
7810 if (UI.getUse().getResNo() == NumVecs)
7813 if (User->getOpcode() != ARMISD::VDUPLANE ||
7814 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
7818 // Create the vldN-dup node.
7821 for (n = 0; n < NumVecs; ++n)
7823 Tys[n] = MVT::Other;
7824 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
7825 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
7826 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
7827 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
7828 Ops, 2, VLDMemInt->getMemoryVT(),
7829 VLDMemInt->getMemOperand());
7832 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7834 unsigned ResNo = UI.getUse().getResNo();
7835 // Ignore uses of the chain result.
7836 if (ResNo == NumVecs)
7839 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
7842 // Now the vldN-lane intrinsic is dead except for its chain result.
7843 // Update uses of the chain.
7844 std::vector<SDValue> VLDDupResults;
7845 for (unsigned n = 0; n < NumVecs; ++n)
7846 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
7847 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
7848 DCI.CombineTo(VLD, VLDDupResults);
7853 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
7854 /// ARMISD::VDUPLANE.
7855 static SDValue PerformVDUPLANECombine(SDNode *N,
7856 TargetLowering::DAGCombinerInfo &DCI) {
7857 SDValue Op = N->getOperand(0);
7859 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
7860 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
7861 if (CombineVLDDUP(N, DCI))
7862 return SDValue(N, 0);
7864 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
7865 // redundant. Ignore bit_converts for now; element sizes are checked below.
7866 while (Op.getOpcode() == ISD::BITCAST)
7867 Op = Op.getOperand(0);
7868 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
7871 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
7872 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
7873 // The canonical VMOV for a zero vector uses a 32-bit element size.
7874 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7876 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
7878 EVT VT = N->getValueType(0);
7879 if (EltSize > VT.getVectorElementType().getSizeInBits())
7882 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
7885 // isConstVecPow2 - Return true if each vector element is a power of 2, all
7886 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
7887 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
7891 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
7893 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
7898 APFloat APF = C->getValueAPF();
7899 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
7900 != APFloat::opOK || !isExact)
7903 c0 = (I == 0) ? cN : c0;
7904 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
7911 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
7912 /// can replace combinations of VMUL and VCVT (floating-point to integer)
7913 /// when the VMUL has a constant operand that is a power of 2.
7915 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7916 /// vmul.f32 d16, d17, d16
7917 /// vcvt.s32.f32 d16, d16
7919 /// vcvt.s32.f32 d16, d16, #3
7920 static SDValue PerformVCVTCombine(SDNode *N,
7921 TargetLowering::DAGCombinerInfo &DCI,
7922 const ARMSubtarget *Subtarget) {
7923 SelectionDAG &DAG = DCI.DAG;
7924 SDValue Op = N->getOperand(0);
7926 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
7927 Op.getOpcode() != ISD::FMUL)
7931 SDValue N0 = Op->getOperand(0);
7932 SDValue ConstVec = Op->getOperand(1);
7933 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
7935 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7936 !isConstVecPow2(ConstVec, isSigned, C))
7939 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
7940 Intrinsic::arm_neon_vcvtfp2fxu;
7941 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7943 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
7944 DAG.getConstant(Log2_64(C), MVT::i32));
7947 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
7948 /// can replace combinations of VCVT (integer to floating-point) and VDIV
7949 /// when the VDIV has a constant operand that is a power of 2.
7951 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7952 /// vcvt.f32.s32 d16, d16
7953 /// vdiv.f32 d16, d17, d16
7955 /// vcvt.f32.s32 d16, d16, #3
7956 static SDValue PerformVDIVCombine(SDNode *N,
7957 TargetLowering::DAGCombinerInfo &DCI,
7958 const ARMSubtarget *Subtarget) {
7959 SelectionDAG &DAG = DCI.DAG;
7960 SDValue Op = N->getOperand(0);
7961 unsigned OpOpcode = Op.getNode()->getOpcode();
7963 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
7964 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
7968 SDValue ConstVec = N->getOperand(1);
7969 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
7971 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7972 !isConstVecPow2(ConstVec, isSigned, C))
7975 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
7976 Intrinsic::arm_neon_vcvtfxu2fp;
7977 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7979 DAG.getConstant(IntrinsicOpcode, MVT::i32),
7980 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
7983 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
7984 /// operand of a vector shift operation, where all the elements of the
7985 /// build_vector must have the same constant integer value.
7986 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7987 // Ignore bit_converts.
7988 while (Op.getOpcode() == ISD::BITCAST)
7989 Op = Op.getOperand(0);
7990 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7991 APInt SplatBits, SplatUndef;
7992 unsigned SplatBitSize;
7994 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7995 HasAnyUndefs, ElementBits) ||
7996 SplatBitSize > ElementBits)
7998 Cnt = SplatBits.getSExtValue();
8002 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8003 /// operand of a vector shift left operation. That value must be in the range:
8004 /// 0 <= Value < ElementBits for a left shift; or
8005 /// 0 <= Value <= ElementBits for a long left shift.
8006 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8007 assert(VT.isVector() && "vector shift count is not a vector type");
8008 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8009 if (! getVShiftImm(Op, ElementBits, Cnt))
8011 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8014 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8015 /// operand of a vector shift right operation. For a shift opcode, the value
8016 /// is positive, but for an intrinsic the value count must be negative. The
8017 /// absolute value must be in the range:
8018 /// 1 <= |Value| <= ElementBits for a right shift; or
8019 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8020 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8022 assert(VT.isVector() && "vector shift count is not a vector type");
8023 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8024 if (! getVShiftImm(Op, ElementBits, Cnt))
8028 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8031 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8032 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8033 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8036 // Don't do anything for most intrinsics.
8039 // Vector shifts: check for immediate versions and lower them.
8040 // Note: This is done during DAG combining instead of DAG legalizing because
8041 // the build_vectors for 64-bit vector element shift counts are generally
8042 // not legal, and it is hard to see their values after they get legalized to
8043 // loads from a constant pool.
8044 case Intrinsic::arm_neon_vshifts:
8045 case Intrinsic::arm_neon_vshiftu:
8046 case Intrinsic::arm_neon_vshiftls:
8047 case Intrinsic::arm_neon_vshiftlu:
8048 case Intrinsic::arm_neon_vshiftn:
8049 case Intrinsic::arm_neon_vrshifts:
8050 case Intrinsic::arm_neon_vrshiftu:
8051 case Intrinsic::arm_neon_vrshiftn:
8052 case Intrinsic::arm_neon_vqshifts:
8053 case Intrinsic::arm_neon_vqshiftu:
8054 case Intrinsic::arm_neon_vqshiftsu:
8055 case Intrinsic::arm_neon_vqshiftns:
8056 case Intrinsic::arm_neon_vqshiftnu:
8057 case Intrinsic::arm_neon_vqshiftnsu:
8058 case Intrinsic::arm_neon_vqrshiftns:
8059 case Intrinsic::arm_neon_vqrshiftnu:
8060 case Intrinsic::arm_neon_vqrshiftnsu: {
8061 EVT VT = N->getOperand(1).getValueType();
8063 unsigned VShiftOpc = 0;
8066 case Intrinsic::arm_neon_vshifts:
8067 case Intrinsic::arm_neon_vshiftu:
8068 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8069 VShiftOpc = ARMISD::VSHL;
8072 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8073 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8074 ARMISD::VSHRs : ARMISD::VSHRu);
8079 case Intrinsic::arm_neon_vshiftls:
8080 case Intrinsic::arm_neon_vshiftlu:
8081 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8083 llvm_unreachable("invalid shift count for vshll intrinsic");
8085 case Intrinsic::arm_neon_vrshifts:
8086 case Intrinsic::arm_neon_vrshiftu:
8087 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8091 case Intrinsic::arm_neon_vqshifts:
8092 case Intrinsic::arm_neon_vqshiftu:
8093 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8097 case Intrinsic::arm_neon_vqshiftsu:
8098 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8100 llvm_unreachable("invalid shift count for vqshlu intrinsic");
8102 case Intrinsic::arm_neon_vshiftn:
8103 case Intrinsic::arm_neon_vrshiftn:
8104 case Intrinsic::arm_neon_vqshiftns:
8105 case Intrinsic::arm_neon_vqshiftnu:
8106 case Intrinsic::arm_neon_vqshiftnsu:
8107 case Intrinsic::arm_neon_vqrshiftns:
8108 case Intrinsic::arm_neon_vqrshiftnu:
8109 case Intrinsic::arm_neon_vqrshiftnsu:
8110 // Narrowing shifts require an immediate right shift.
8111 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8113 llvm_unreachable("invalid shift count for narrowing vector shift "
8117 llvm_unreachable("unhandled vector shift");
8121 case Intrinsic::arm_neon_vshifts:
8122 case Intrinsic::arm_neon_vshiftu:
8123 // Opcode already set above.
8125 case Intrinsic::arm_neon_vshiftls:
8126 case Intrinsic::arm_neon_vshiftlu:
8127 if (Cnt == VT.getVectorElementType().getSizeInBits())
8128 VShiftOpc = ARMISD::VSHLLi;
8130 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8131 ARMISD::VSHLLs : ARMISD::VSHLLu);
8133 case Intrinsic::arm_neon_vshiftn:
8134 VShiftOpc = ARMISD::VSHRN; break;
8135 case Intrinsic::arm_neon_vrshifts:
8136 VShiftOpc = ARMISD::VRSHRs; break;
8137 case Intrinsic::arm_neon_vrshiftu:
8138 VShiftOpc = ARMISD::VRSHRu; break;
8139 case Intrinsic::arm_neon_vrshiftn:
8140 VShiftOpc = ARMISD::VRSHRN; break;
8141 case Intrinsic::arm_neon_vqshifts:
8142 VShiftOpc = ARMISD::VQSHLs; break;
8143 case Intrinsic::arm_neon_vqshiftu:
8144 VShiftOpc = ARMISD::VQSHLu; break;
8145 case Intrinsic::arm_neon_vqshiftsu:
8146 VShiftOpc = ARMISD::VQSHLsu; break;
8147 case Intrinsic::arm_neon_vqshiftns:
8148 VShiftOpc = ARMISD::VQSHRNs; break;
8149 case Intrinsic::arm_neon_vqshiftnu:
8150 VShiftOpc = ARMISD::VQSHRNu; break;
8151 case Intrinsic::arm_neon_vqshiftnsu:
8152 VShiftOpc = ARMISD::VQSHRNsu; break;
8153 case Intrinsic::arm_neon_vqrshiftns:
8154 VShiftOpc = ARMISD::VQRSHRNs; break;
8155 case Intrinsic::arm_neon_vqrshiftnu:
8156 VShiftOpc = ARMISD::VQRSHRNu; break;
8157 case Intrinsic::arm_neon_vqrshiftnsu:
8158 VShiftOpc = ARMISD::VQRSHRNsu; break;
8161 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8162 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8165 case Intrinsic::arm_neon_vshiftins: {
8166 EVT VT = N->getOperand(1).getValueType();
8168 unsigned VShiftOpc = 0;
8170 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8171 VShiftOpc = ARMISD::VSLI;
8172 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8173 VShiftOpc = ARMISD::VSRI;
8175 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8178 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8179 N->getOperand(1), N->getOperand(2),
8180 DAG.getConstant(Cnt, MVT::i32));
8183 case Intrinsic::arm_neon_vqrshifts:
8184 case Intrinsic::arm_neon_vqrshiftu:
8185 // No immediate versions of these to check for.
8192 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8193 /// lowers them. As with the vector shift intrinsics, this is done during DAG
8194 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8195 /// vector element shift counts are generally not legal, and it is hard to see
8196 /// their values after they get legalized to loads from a constant pool.
8197 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8198 const ARMSubtarget *ST) {
8199 EVT VT = N->getValueType(0);
8200 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8201 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8202 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8203 SDValue N1 = N->getOperand(1);
8204 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8205 SDValue N0 = N->getOperand(0);
8206 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8207 DAG.MaskedValueIsZero(N0.getOperand(0),
8208 APInt::getHighBitsSet(32, 16)))
8209 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8213 // Nothing to be done for scalar shifts.
8214 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8215 if (!VT.isVector() || !TLI.isTypeLegal(VT))
8218 assert(ST->hasNEON() && "unexpected vector shift");
8221 switch (N->getOpcode()) {
8222 default: llvm_unreachable("unexpected shift opcode");
8225 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8226 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8227 DAG.getConstant(Cnt, MVT::i32));
8232 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8233 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8234 ARMISD::VSHRs : ARMISD::VSHRu);
8235 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8236 DAG.getConstant(Cnt, MVT::i32));
8242 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8243 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8244 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8245 const ARMSubtarget *ST) {
8246 SDValue N0 = N->getOperand(0);
8248 // Check for sign- and zero-extensions of vector extract operations of 8-
8249 // and 16-bit vector elements. NEON supports these directly. They are
8250 // handled during DAG combining because type legalization will promote them
8251 // to 32-bit types and it is messy to recognize the operations after that.
8252 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8253 SDValue Vec = N0.getOperand(0);
8254 SDValue Lane = N0.getOperand(1);
8255 EVT VT = N->getValueType(0);
8256 EVT EltVT = N0.getValueType();
8257 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8259 if (VT == MVT::i32 &&
8260 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8261 TLI.isTypeLegal(Vec.getValueType()) &&
8262 isa<ConstantSDNode>(Lane)) {
8265 switch (N->getOpcode()) {
8266 default: llvm_unreachable("unexpected opcode");
8267 case ISD::SIGN_EXTEND:
8268 Opc = ARMISD::VGETLANEs;
8270 case ISD::ZERO_EXTEND:
8271 case ISD::ANY_EXTEND:
8272 Opc = ARMISD::VGETLANEu;
8275 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8282 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8283 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8284 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8285 const ARMSubtarget *ST) {
8286 // If the target supports NEON, try to use vmax/vmin instructions for f32
8287 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
8288 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
8289 // a NaN; only do the transformation when it matches that behavior.
8291 // For now only do this when using NEON for FP operations; if using VFP, it
8292 // is not obvious that the benefit outweighs the cost of switching to the
8294 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8295 N->getValueType(0) != MVT::f32)
8298 SDValue CondLHS = N->getOperand(0);
8299 SDValue CondRHS = N->getOperand(1);
8300 SDValue LHS = N->getOperand(2);
8301 SDValue RHS = N->getOperand(3);
8302 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8304 unsigned Opcode = 0;
8306 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8307 IsReversed = false; // x CC y ? x : y
8308 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8309 IsReversed = true ; // x CC y ? y : x
8323 // If LHS is NaN, an ordered comparison will be false and the result will
8324 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
8325 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8326 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8327 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8329 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8330 // will return -0, so vmin can only be used for unsafe math or if one of
8331 // the operands is known to be nonzero.
8332 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8333 !DAG.getTarget().Options.UnsafeFPMath &&
8334 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8336 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8345 // If LHS is NaN, an ordered comparison will be false and the result will
8346 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
8347 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8348 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8349 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8351 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8352 // will return +0, so vmax can only be used for unsafe math or if one of
8353 // the operands is known to be nonzero.
8354 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8355 !DAG.getTarget().Options.UnsafeFPMath &&
8356 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8358 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8364 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8367 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8369 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8370 SDValue Cmp = N->getOperand(4);
8371 if (Cmp.getOpcode() != ARMISD::CMPZ)
8372 // Only looking at EQ and NE cases.
8375 EVT VT = N->getValueType(0);
8376 DebugLoc dl = N->getDebugLoc();
8377 SDValue LHS = Cmp.getOperand(0);
8378 SDValue RHS = Cmp.getOperand(1);
8379 SDValue FalseVal = N->getOperand(0);
8380 SDValue TrueVal = N->getOperand(1);
8381 SDValue ARMcc = N->getOperand(2);
8382 ARMCC::CondCodes CC =
8383 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8401 /// FIXME: Turn this into a target neutral optimization?
8403 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8404 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8405 N->getOperand(3), Cmp);
8406 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8408 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8409 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8410 N->getOperand(3), NewCmp);
8413 if (Res.getNode()) {
8414 APInt KnownZero, KnownOne;
8415 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8416 // Capture demanded bits information that would be otherwise lost.
8417 if (KnownZero == 0xfffffffe)
8418 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8419 DAG.getValueType(MVT::i1));
8420 else if (KnownZero == 0xffffff00)
8421 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8422 DAG.getValueType(MVT::i8));
8423 else if (KnownZero == 0xffff0000)
8424 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8425 DAG.getValueType(MVT::i16));
8431 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8432 DAGCombinerInfo &DCI) const {
8433 switch (N->getOpcode()) {
8435 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
8436 case ISD::SUB: return PerformSUBCombine(N, DCI);
8437 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
8438 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
8439 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
8440 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
8441 case ARMISD::BFI: return PerformBFICombine(N, DCI);
8442 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8443 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8444 case ISD::STORE: return PerformSTORECombine(N, DCI);
8445 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8446 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8447 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8448 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8449 case ISD::FP_TO_SINT:
8450 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8451 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
8452 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8455 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
8456 case ISD::SIGN_EXTEND:
8457 case ISD::ZERO_EXTEND:
8458 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8459 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8460 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8461 case ARMISD::VLD2DUP:
8462 case ARMISD::VLD3DUP:
8463 case ARMISD::VLD4DUP:
8464 return CombineBaseUpdate(N, DCI);
8465 case ISD::INTRINSIC_VOID:
8466 case ISD::INTRINSIC_W_CHAIN:
8467 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8468 case Intrinsic::arm_neon_vld1:
8469 case Intrinsic::arm_neon_vld2:
8470 case Intrinsic::arm_neon_vld3:
8471 case Intrinsic::arm_neon_vld4:
8472 case Intrinsic::arm_neon_vld2lane:
8473 case Intrinsic::arm_neon_vld3lane:
8474 case Intrinsic::arm_neon_vld4lane:
8475 case Intrinsic::arm_neon_vst1:
8476 case Intrinsic::arm_neon_vst2:
8477 case Intrinsic::arm_neon_vst3:
8478 case Intrinsic::arm_neon_vst4:
8479 case Intrinsic::arm_neon_vst2lane:
8480 case Intrinsic::arm_neon_vst3lane:
8481 case Intrinsic::arm_neon_vst4lane:
8482 return CombineBaseUpdate(N, DCI);
8490 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8492 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8495 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8496 if (!Subtarget->allowsUnalignedMem())
8499 switch (VT.getSimpleVT().SimpleTy) {
8506 // FIXME: VLD1 etc with standard alignment is legal.
8510 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8511 unsigned AlignCheck) {
8512 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8513 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8516 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8517 unsigned DstAlign, unsigned SrcAlign,
8520 MachineFunction &MF) const {
8521 const Function *F = MF.getFunction();
8523 // See if we can use NEON instructions for this...
8525 !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8526 Subtarget->hasNEON()) {
8527 if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8529 } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8534 // Lowering to i32/i16 if the size permits.
8537 } else if (Size >= 2) {
8541 // Let the target-independent logic figure it out.
8545 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8550 switch (VT.getSimpleVT().SimpleTy) {
8551 default: return false;
8566 if ((V & (Scale - 1)) != 0)
8569 return V == (V & ((1LL << 5) - 1));
8572 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8573 const ARMSubtarget *Subtarget) {
8580 switch (VT.getSimpleVT().SimpleTy) {
8581 default: return false;
8586 // + imm12 or - imm8
8588 return V == (V & ((1LL << 8) - 1));
8589 return V == (V & ((1LL << 12) - 1));
8592 // Same as ARM mode. FIXME: NEON?
8593 if (!Subtarget->hasVFP2())
8598 return V == (V & ((1LL << 8) - 1));
8602 /// isLegalAddressImmediate - Return true if the integer value can be used
8603 /// as the offset of the target addressing mode for load / store of the
8605 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8606 const ARMSubtarget *Subtarget) {
8613 if (Subtarget->isThumb1Only())
8614 return isLegalT1AddressImmediate(V, VT);
8615 else if (Subtarget->isThumb2())
8616 return isLegalT2AddressImmediate(V, VT, Subtarget);
8621 switch (VT.getSimpleVT().SimpleTy) {
8622 default: return false;
8627 return V == (V & ((1LL << 12) - 1));
8630 return V == (V & ((1LL << 8) - 1));
8633 if (!Subtarget->hasVFP2()) // FIXME: NEON?
8638 return V == (V & ((1LL << 8) - 1));
8642 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8644 int Scale = AM.Scale;
8648 switch (VT.getSimpleVT().SimpleTy) {
8649 default: return false;
8658 return Scale == 2 || Scale == 4 || Scale == 8;
8661 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8665 // Note, we allow "void" uses (basically, uses that aren't loads or
8666 // stores), because arm allows folding a scale into many arithmetic
8667 // operations. This should be made more precise and revisited later.
8669 // Allow r << imm, but the imm has to be a multiple of two.
8670 if (Scale & 1) return false;
8671 return isPowerOf2_32(Scale);
8675 /// isLegalAddressingMode - Return true if the addressing mode represented
8676 /// by AM is legal for this target, for a load/store of the specified type.
8677 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8679 EVT VT = getValueType(Ty, true);
8680 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8683 // Can never fold addr of global into load/store.
8688 case 0: // no scale reg, must be "r+i" or "r", or "i".
8691 if (Subtarget->isThumb1Only())
8695 // ARM doesn't support any R+R*scale+imm addr modes.
8702 if (Subtarget->isThumb2())
8703 return isLegalT2ScaledAddressingMode(AM, VT);
8705 int Scale = AM.Scale;
8706 switch (VT.getSimpleVT().SimpleTy) {
8707 default: return false;
8711 if (Scale < 0) Scale = -Scale;
8715 return isPowerOf2_32(Scale & ~1);
8719 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8724 // Note, we allow "void" uses (basically, uses that aren't loads or
8725 // stores), because arm allows folding a scale into many arithmetic
8726 // operations. This should be made more precise and revisited later.
8728 // Allow r << imm, but the imm has to be a multiple of two.
8729 if (Scale & 1) return false;
8730 return isPowerOf2_32(Scale);
8736 /// isLegalICmpImmediate - Return true if the specified immediate is legal
8737 /// icmp immediate, that is the target has icmp instructions which can compare
8738 /// a register against the immediate without having to materialize the
8739 /// immediate into a register.
8740 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8741 // Thumb2 and ARM modes can use cmn for negative immediates.
8742 if (!Subtarget->isThumb())
8743 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
8744 if (Subtarget->isThumb2())
8745 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
8746 // Thumb1 doesn't have cmn, and only 8-bit immediates.
8747 return Imm >= 0 && Imm <= 255;
8750 /// isLegalAddImmediate - Return true if the specified immediate is legal
8751 /// add immediate, that is the target has add instructions which can add
8752 /// a register with the immediate without having to materialize the
8753 /// immediate into a register.
8754 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8755 return ARM_AM::getSOImmVal(Imm) != -1;
8758 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
8759 bool isSEXTLoad, SDValue &Base,
8760 SDValue &Offset, bool &isInc,
8761 SelectionDAG &DAG) {
8762 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8765 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
8767 Base = Ptr->getOperand(0);
8768 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8769 int RHSC = (int)RHS->getZExtValue();
8770 if (RHSC < 0 && RHSC > -256) {
8771 assert(Ptr->getOpcode() == ISD::ADD);
8773 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8777 isInc = (Ptr->getOpcode() == ISD::ADD);
8778 Offset = Ptr->getOperand(1);
8780 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
8782 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8783 int RHSC = (int)RHS->getZExtValue();
8784 if (RHSC < 0 && RHSC > -0x1000) {
8785 assert(Ptr->getOpcode() == ISD::ADD);
8787 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8788 Base = Ptr->getOperand(0);
8793 if (Ptr->getOpcode() == ISD::ADD) {
8795 ARM_AM::ShiftOpc ShOpcVal=
8796 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
8797 if (ShOpcVal != ARM_AM::no_shift) {
8798 Base = Ptr->getOperand(1);
8799 Offset = Ptr->getOperand(0);
8801 Base = Ptr->getOperand(0);
8802 Offset = Ptr->getOperand(1);
8807 isInc = (Ptr->getOpcode() == ISD::ADD);
8808 Base = Ptr->getOperand(0);
8809 Offset = Ptr->getOperand(1);
8813 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
8817 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
8818 bool isSEXTLoad, SDValue &Base,
8819 SDValue &Offset, bool &isInc,
8820 SelectionDAG &DAG) {
8821 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8824 Base = Ptr->getOperand(0);
8825 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8826 int RHSC = (int)RHS->getZExtValue();
8827 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
8828 assert(Ptr->getOpcode() == ISD::ADD);
8830 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8832 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
8833 isInc = Ptr->getOpcode() == ISD::ADD;
8834 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
8842 /// getPreIndexedAddressParts - returns true by value, base pointer and
8843 /// offset pointer and addressing mode by reference if the node's address
8844 /// can be legally represented as pre-indexed load / store address.
8846 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8848 ISD::MemIndexedMode &AM,
8849 SelectionDAG &DAG) const {
8850 if (Subtarget->isThumb1Only())
8855 bool isSEXTLoad = false;
8856 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8857 Ptr = LD->getBasePtr();
8858 VT = LD->getMemoryVT();
8859 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8860 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8861 Ptr = ST->getBasePtr();
8862 VT = ST->getMemoryVT();
8867 bool isLegal = false;
8868 if (Subtarget->isThumb2())
8869 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8870 Offset, isInc, DAG);
8872 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8873 Offset, isInc, DAG);
8877 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
8881 /// getPostIndexedAddressParts - returns true by value, base pointer and
8882 /// offset pointer and addressing mode by reference if this node can be
8883 /// combined with a load / store to form a post-indexed load / store.
8884 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
8887 ISD::MemIndexedMode &AM,
8888 SelectionDAG &DAG) const {
8889 if (Subtarget->isThumb1Only())
8894 bool isSEXTLoad = false;
8895 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8896 VT = LD->getMemoryVT();
8897 Ptr = LD->getBasePtr();
8898 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8899 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8900 VT = ST->getMemoryVT();
8901 Ptr = ST->getBasePtr();
8906 bool isLegal = false;
8907 if (Subtarget->isThumb2())
8908 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8911 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8917 // Swap base ptr and offset to catch more post-index load / store when
8918 // it's legal. In Thumb2 mode, offset must be an immediate.
8919 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
8920 !Subtarget->isThumb2())
8921 std::swap(Base, Offset);
8923 // Post-indexed load / store update the base pointer.
8928 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
8932 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8935 const SelectionDAG &DAG,
8936 unsigned Depth) const {
8937 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
8938 switch (Op.getOpcode()) {
8940 case ARMISD::CMOV: {
8941 // Bits are known zero/one if known on the LHS and RHS.
8942 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
8943 if (KnownZero == 0 && KnownOne == 0) return;
8945 APInt KnownZeroRHS, KnownOneRHS;
8946 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
8947 KnownZero &= KnownZeroRHS;
8948 KnownOne &= KnownOneRHS;
8954 //===----------------------------------------------------------------------===//
8955 // ARM Inline Assembly Support
8956 //===----------------------------------------------------------------------===//
8958 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
8959 // Looking for "rev" which is V6+.
8960 if (!Subtarget->hasV6Ops())
8963 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8964 std::string AsmStr = IA->getAsmString();
8965 SmallVector<StringRef, 4> AsmPieces;
8966 SplitString(AsmStr, AsmPieces, ";\n");
8968 switch (AsmPieces.size()) {
8969 default: return false;
8971 AsmStr = AsmPieces[0];
8973 SplitString(AsmStr, AsmPieces, " \t,");
8976 if (AsmPieces.size() == 3 &&
8977 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
8978 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
8979 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8980 if (Ty && Ty->getBitWidth() == 32)
8981 return IntrinsicLowering::LowerToByteSwap(CI);
8989 /// getConstraintType - Given a constraint letter, return the type of
8990 /// constraint it is for this target.
8991 ARMTargetLowering::ConstraintType
8992 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
8993 if (Constraint.size() == 1) {
8994 switch (Constraint[0]) {
8996 case 'l': return C_RegisterClass;
8997 case 'w': return C_RegisterClass;
8998 case 'h': return C_RegisterClass;
8999 case 'x': return C_RegisterClass;
9000 case 't': return C_RegisterClass;
9001 case 'j': return C_Other; // Constant for movw.
9002 // An address with a single base register. Due to the way we
9003 // currently handle addresses it is the same as an 'r' memory constraint.
9004 case 'Q': return C_Memory;
9006 } else if (Constraint.size() == 2) {
9007 switch (Constraint[0]) {
9009 // All 'U+' constraints are addresses.
9010 case 'U': return C_Memory;
9013 return TargetLowering::getConstraintType(Constraint);
9016 /// Examine constraint type and operand type and determine a weight value.
9017 /// This object must already have been set up with the operand type
9018 /// and the current alternative constraint selected.
9019 TargetLowering::ConstraintWeight
9020 ARMTargetLowering::getSingleConstraintMatchWeight(
9021 AsmOperandInfo &info, const char *constraint) const {
9022 ConstraintWeight weight = CW_Invalid;
9023 Value *CallOperandVal = info.CallOperandVal;
9024 // If we don't have a value, we can't do a match,
9025 // but allow it at the lowest weight.
9026 if (CallOperandVal == NULL)
9028 Type *type = CallOperandVal->getType();
9029 // Look at the constraint type.
9030 switch (*constraint) {
9032 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9035 if (type->isIntegerTy()) {
9036 if (Subtarget->isThumb())
9037 weight = CW_SpecificReg;
9039 weight = CW_Register;
9043 if (type->isFloatingPointTy())
9044 weight = CW_Register;
9050 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9052 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9054 if (Constraint.size() == 1) {
9055 // GCC ARM Constraint Letters
9056 switch (Constraint[0]) {
9057 case 'l': // Low regs or general regs.
9058 if (Subtarget->isThumb())
9059 return RCPair(0U, &ARM::tGPRRegClass);
9060 return RCPair(0U, &ARM::GPRRegClass);
9061 case 'h': // High regs or no regs.
9062 if (Subtarget->isThumb())
9063 return RCPair(0U, &ARM::hGPRRegClass);
9066 return RCPair(0U, &ARM::GPRRegClass);
9069 return RCPair(0U, &ARM::SPRRegClass);
9070 if (VT.getSizeInBits() == 64)
9071 return RCPair(0U, &ARM::DPRRegClass);
9072 if (VT.getSizeInBits() == 128)
9073 return RCPair(0U, &ARM::QPRRegClass);
9077 return RCPair(0U, &ARM::SPR_8RegClass);
9078 if (VT.getSizeInBits() == 64)
9079 return RCPair(0U, &ARM::DPR_8RegClass);
9080 if (VT.getSizeInBits() == 128)
9081 return RCPair(0U, &ARM::QPR_8RegClass);
9085 return RCPair(0U, &ARM::SPRRegClass);
9089 if (StringRef("{cc}").equals_lower(Constraint))
9090 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9092 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9095 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9096 /// vector. If it is invalid, don't add anything to Ops.
9097 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9098 std::string &Constraint,
9099 std::vector<SDValue>&Ops,
9100 SelectionDAG &DAG) const {
9101 SDValue Result(0, 0);
9103 // Currently only support length 1 constraints.
9104 if (Constraint.length() != 1) return;
9106 char ConstraintLetter = Constraint[0];
9107 switch (ConstraintLetter) {
9110 case 'I': case 'J': case 'K': case 'L':
9111 case 'M': case 'N': case 'O':
9112 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9116 int64_t CVal64 = C->getSExtValue();
9117 int CVal = (int) CVal64;
9118 // None of these constraints allow values larger than 32 bits. Check
9119 // that the value fits in an int.
9123 switch (ConstraintLetter) {
9125 // Constant suitable for movw, must be between 0 and
9127 if (Subtarget->hasV6T2Ops())
9128 if (CVal >= 0 && CVal <= 65535)
9132 if (Subtarget->isThumb1Only()) {
9133 // This must be a constant between 0 and 255, for ADD
9135 if (CVal >= 0 && CVal <= 255)
9137 } else if (Subtarget->isThumb2()) {
9138 // A constant that can be used as an immediate value in a
9139 // data-processing instruction.
9140 if (ARM_AM::getT2SOImmVal(CVal) != -1)
9143 // A constant that can be used as an immediate value in a
9144 // data-processing instruction.
9145 if (ARM_AM::getSOImmVal(CVal) != -1)
9151 if (Subtarget->isThumb()) { // FIXME thumb2
9152 // This must be a constant between -255 and -1, for negated ADD
9153 // immediates. This can be used in GCC with an "n" modifier that
9154 // prints the negated value, for use with SUB instructions. It is
9155 // not useful otherwise but is implemented for compatibility.
9156 if (CVal >= -255 && CVal <= -1)
9159 // This must be a constant between -4095 and 4095. It is not clear
9160 // what this constraint is intended for. Implemented for
9161 // compatibility with GCC.
9162 if (CVal >= -4095 && CVal <= 4095)
9168 if (Subtarget->isThumb1Only()) {
9169 // A 32-bit value where only one byte has a nonzero value. Exclude
9170 // zero to match GCC. This constraint is used by GCC internally for
9171 // constants that can be loaded with a move/shift combination.
9172 // It is not useful otherwise but is implemented for compatibility.
9173 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9175 } else if (Subtarget->isThumb2()) {
9176 // A constant whose bitwise inverse can be used as an immediate
9177 // value in a data-processing instruction. This can be used in GCC
9178 // with a "B" modifier that prints the inverted value, for use with
9179 // BIC and MVN instructions. It is not useful otherwise but is
9180 // implemented for compatibility.
9181 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9184 // A constant whose bitwise inverse can be used as an immediate
9185 // value in a data-processing instruction. This can be used in GCC
9186 // with a "B" modifier that prints the inverted value, for use with
9187 // BIC and MVN instructions. It is not useful otherwise but is
9188 // implemented for compatibility.
9189 if (ARM_AM::getSOImmVal(~CVal) != -1)
9195 if (Subtarget->isThumb1Only()) {
9196 // This must be a constant between -7 and 7,
9197 // for 3-operand ADD/SUB immediate instructions.
9198 if (CVal >= -7 && CVal < 7)
9200 } else if (Subtarget->isThumb2()) {
9201 // A constant whose negation can be used as an immediate value in a
9202 // data-processing instruction. This can be used in GCC with an "n"
9203 // modifier that prints the negated value, for use with SUB
9204 // instructions. It is not useful otherwise but is implemented for
9206 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9209 // A constant whose negation can be used as an immediate value in a
9210 // data-processing instruction. This can be used in GCC with an "n"
9211 // modifier that prints the negated value, for use with SUB
9212 // instructions. It is not useful otherwise but is implemented for
9214 if (ARM_AM::getSOImmVal(-CVal) != -1)
9220 if (Subtarget->isThumb()) { // FIXME thumb2
9221 // This must be a multiple of 4 between 0 and 1020, for
9222 // ADD sp + immediate.
9223 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9226 // A power of two or a constant between 0 and 32. This is used in
9227 // GCC for the shift amount on shifted register operands, but it is
9228 // useful in general for any shift amounts.
9229 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9235 if (Subtarget->isThumb()) { // FIXME thumb2
9236 // This must be a constant between 0 and 31, for shift amounts.
9237 if (CVal >= 0 && CVal <= 31)
9243 if (Subtarget->isThumb()) { // FIXME thumb2
9244 // This must be a multiple of 4 between -508 and 508, for
9245 // ADD/SUB sp = sp + immediate.
9246 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9251 Result = DAG.getTargetConstant(CVal, Op.getValueType());
9255 if (Result.getNode()) {
9256 Ops.push_back(Result);
9259 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9263 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9264 // The ARM target isn't yet aware of offsets.
9268 bool ARM::isBitFieldInvertedMask(unsigned v) {
9269 if (v == 0xffffffff)
9271 // there can be 1's on either or both "outsides", all the "inside"
9273 unsigned int lsb = 0, msb = 31;
9274 while (v & (1 << msb)) --msb;
9275 while (v & (1 << lsb)) ++lsb;
9276 for (unsigned int i = lsb; i <= msb; ++i) {
9283 /// isFPImmLegal - Returns true if the target can instruction select the
9284 /// specified FP immediate natively. If false, the legalizer will
9285 /// materialize the FP immediate as a load from a constant pool.
9286 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9287 if (!Subtarget->hasVFP3())
9290 return ARM_AM::getFP32Imm(Imm) != -1;
9292 return ARM_AM::getFP64Imm(Imm) != -1;
9296 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9297 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9298 /// specified in the intrinsic calls.
9299 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9301 unsigned Intrinsic) const {
9302 switch (Intrinsic) {
9303 case Intrinsic::arm_neon_vld1:
9304 case Intrinsic::arm_neon_vld2:
9305 case Intrinsic::arm_neon_vld3:
9306 case Intrinsic::arm_neon_vld4:
9307 case Intrinsic::arm_neon_vld2lane:
9308 case Intrinsic::arm_neon_vld3lane:
9309 case Intrinsic::arm_neon_vld4lane: {
9310 Info.opc = ISD::INTRINSIC_W_CHAIN;
9311 // Conservatively set memVT to the entire set of vectors loaded.
9312 uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9313 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9314 Info.ptrVal = I.getArgOperand(0);
9316 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9317 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9318 Info.vol = false; // volatile loads with NEON intrinsics not supported
9319 Info.readMem = true;
9320 Info.writeMem = false;
9323 case Intrinsic::arm_neon_vst1:
9324 case Intrinsic::arm_neon_vst2:
9325 case Intrinsic::arm_neon_vst3:
9326 case Intrinsic::arm_neon_vst4:
9327 case Intrinsic::arm_neon_vst2lane:
9328 case Intrinsic::arm_neon_vst3lane:
9329 case Intrinsic::arm_neon_vst4lane: {
9330 Info.opc = ISD::INTRINSIC_VOID;
9331 // Conservatively set memVT to the entire set of vectors stored.
9332 unsigned NumElts = 0;
9333 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9334 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9335 if (!ArgTy->isVectorTy())
9337 NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9339 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9340 Info.ptrVal = I.getArgOperand(0);
9342 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9343 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9344 Info.vol = false; // volatile stores with NEON intrinsics not supported
9345 Info.readMem = false;
9346 Info.writeMem = true;
9349 case Intrinsic::arm_strexd: {
9350 Info.opc = ISD::INTRINSIC_W_CHAIN;
9351 Info.memVT = MVT::i64;
9352 Info.ptrVal = I.getArgOperand(2);
9356 Info.readMem = false;
9357 Info.writeMem = true;
9360 case Intrinsic::arm_ldrexd: {
9361 Info.opc = ISD::INTRINSIC_W_CHAIN;
9362 Info.memVT = MVT::i64;
9363 Info.ptrVal = I.getArgOperand(0);
9367 Info.readMem = true;
9368 Info.writeMem = false;