1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <utility>
52 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57
58 // This option should go away when tail calls fully work.
59 static cl::opt<bool>
60 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
61 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
62 cl::init(false));
63
64 cl::opt<bool>
65 EnableARMLongCalls("arm-long-calls", cl::Hidden,
66 cl::desc("Generate calls via indirect call instructions"),
67 cl::init(false));
68
69 static cl::opt<bool>
70 ARMInterworking("arm-interworking", cl::Hidden,
71 cl::desc("Enable / disable ARM interworking (for debugging only)"),
72 cl::init(true));
73
74 namespace {
75 class ARMCCState : public CCState {
76 public:
ARMCCState(CallingConv::ID CC,bool isVarArg,MachineFunction & MF,const TargetMachine & TM,SmallVectorImpl<CCValAssign> & locs,LLVMContext & C,ParmContext PC)77 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
78 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
79 LLVMContext &C, ParmContext PC)
80 : CCState(CC, isVarArg, MF, TM, locs, C) {
81 assert(((PC == Call) || (PC == Prologue)) &&
82 "ARMCCState users must specify whether their context is call"
83 "or prologue generation.");
84 CallOrPrologue = PC;
85 }
86 };
87 }
88
89 // The APCS parameter registers.
90 static const uint16_t GPRArgRegs[] = {
91 ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 };
93
addTypeForNEON(MVT VT,MVT PromotedLdStVT,MVT PromotedBitwiseVT)94 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
95 MVT PromotedBitwiseVT) {
96 if (VT != PromotedLdStVT) {
97 setOperationAction(ISD::LOAD, VT, Promote);
98 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99
100 setOperationAction(ISD::STORE, VT, Promote);
101 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
102 }
103
104 MVT ElemTy = VT.getVectorElementType();
105 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106 setOperationAction(ISD::SETCC, VT, Custom);
107 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
108 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
109 if (ElemTy == MVT::i32) {
110 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
112 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
113 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114 } else {
115 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
117 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
118 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119 }
120 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
121 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
122 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
123 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
124 setOperationAction(ISD::SELECT, VT, Expand);
125 setOperationAction(ISD::SELECT_CC, VT, Expand);
126 setOperationAction(ISD::VSELECT, VT, Expand);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
128 if (VT.isInteger()) {
129 setOperationAction(ISD::SHL, VT, Custom);
130 setOperationAction(ISD::SRA, VT, Custom);
131 setOperationAction(ISD::SRL, VT, Custom);
132 }
133
134 // Promote all bit-wise operations.
135 if (VT.isInteger() && VT != PromotedBitwiseVT) {
136 setOperationAction(ISD::AND, VT, Promote);
137 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
138 setOperationAction(ISD::OR, VT, Promote);
139 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
140 setOperationAction(ISD::XOR, VT, Promote);
141 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
142 }
143
144 // Neon does not support vector divide/remainder operations.
145 setOperationAction(ISD::SDIV, VT, Expand);
146 setOperationAction(ISD::UDIV, VT, Expand);
147 setOperationAction(ISD::FDIV, VT, Expand);
148 setOperationAction(ISD::SREM, VT, Expand);
149 setOperationAction(ISD::UREM, VT, Expand);
150 setOperationAction(ISD::FREM, VT, Expand);
151 }
152
addDRTypeForNEON(MVT VT)153 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
154 addRegisterClass(VT, &ARM::DPRRegClass);
155 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
156 }
157
addQRTypeForNEON(MVT VT)158 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
159 addRegisterClass(VT, &ARM::DPairRegClass);
160 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
161 }
162
createTLOF(TargetMachine & TM)163 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
164 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
165 return new TargetLoweringObjectFileMachO();
166
167 return new ARMElfTargetObjectFile();
168 }
169
ARMTargetLowering(TargetMachine & TM)170 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
171 : TargetLowering(TM, createTLOF(TM)) {
172 Subtarget = &TM.getSubtarget<ARMSubtarget>();
173 RegInfo = TM.getRegisterInfo();
174 Itins = TM.getInstrItineraryData();
175
176 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177
178 if (Subtarget->isTargetIOS()) {
179 // Uses VFP for Thumb libfuncs if available.
180 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
181 Subtarget->hasARMOps()) {
182 // Single-precision floating-point arithmetic.
183 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
184 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
185 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
186 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
187
188 // Double-precision floating-point arithmetic.
189 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
190 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
191 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
192 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
193
194 // Single-precision comparisons.
195 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
196 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
197 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
198 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
199 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
200 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
201 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
202 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
203
204 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
210 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
211 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
212
213 // Double-precision comparisons.
214 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
215 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
216 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
217 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
218 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
219 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
220 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
221 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
222
223 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
229 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
230 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
231
232 // Floating-point to integer conversions.
233 // i64 conversions are done via library routines even when generating VFP
234 // instructions, so use the same ones.
235 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
236 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
237 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
238 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
239
240 // Conversions between floating types.
241 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
242 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
243
244 // Integer to floating-point conversions.
245 // i64 conversions are done via library routines even when generating VFP
246 // instructions, so use the same ones.
247 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
248 // e.g., __floatunsidf vs. __floatunssidfvfp.
249 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
250 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
251 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
252 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
253 }
254 }
255
256 // These libcalls are not available in 32-bit.
257 setLibcallName(RTLIB::SHL_I128, 0);
258 setLibcallName(RTLIB::SRL_I128, 0);
259 setLibcallName(RTLIB::SRA_I128, 0);
260
261 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
262 // Double-precision floating-point arithmetic helper functions
263 // RTABI chapter 4.1.2, Table 2
264 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
265 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
266 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
267 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
268 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
269 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
270 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
271 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
272
273 // Double-precision floating-point comparison helper functions
274 // RTABI chapter 4.1.2, Table 3
275 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
276 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
277 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
278 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
279 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
280 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
281 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
282 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
283 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
284 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
285 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
286 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
287 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
288 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
289 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
290 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
291 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
297 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
298 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
299
300 // Single-precision floating-point arithmetic helper functions
301 // RTABI chapter 4.1.2, Table 4
302 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
303 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
304 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
305 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
306 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
307 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
308 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
309 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
310
311 // Single-precision floating-point comparison helper functions
312 // RTABI chapter 4.1.2, Table 5
313 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
314 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
315 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
316 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
317 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
318 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
319 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
320 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
321 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
322 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
323 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
324 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
325 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
326 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
327 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
328 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
329 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
335 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
336 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
337
338 // Floating-point to integer conversions.
339 // RTABI chapter 4.1.2, Table 6
340 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
341 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
342 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
343 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
344 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
345 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
346 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
347 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
348 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
354 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
355 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
356
357 // Conversions between floating types.
358 // RTABI chapter 4.1.2, Table 7
359 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
360 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
361 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
362 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
363
364 // Integer to floating-point conversions.
365 // RTABI chapter 4.1.2, Table 8
366 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
367 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
368 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
369 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
370 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
371 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
372 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
373 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
374 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382
383 // Long long helper functions
384 // RTABI chapter 4.2, Table 9
385 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
386 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
387 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
388 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
389 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
395
396 // Integer division functions
397 // RTABI chapter 4.3.1
398 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
399 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
400 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
401 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
402 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
403 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
404 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
405 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
406 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
412 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
413 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
414
415 // Memory operations
416 // RTABI chapter 4.3.4
417 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
418 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
419 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
420 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
421 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
422 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
423 }
424
425 // Use divmod compiler-rt calls for iOS 5.0 and later.
426 if (Subtarget->getTargetTriple().isiOS() &&
427 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
428 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
429 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
430 }
431
432 if (Subtarget->isThumb1Only())
433 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
434 else
435 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
436 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
437 !Subtarget->isThumb1Only()) {
438 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
439 if (!Subtarget->isFPOnlySP())
440 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
441
442 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
443 }
444
445 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
447 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
449 setTruncStoreAction((MVT::SimpleValueType)VT,
450 (MVT::SimpleValueType)InnerVT, Expand);
451 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
452 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
454 }
455
456 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
458
459 if (Subtarget->hasNEON()) {
460 addDRTypeForNEON(MVT::v2f32);
461 addDRTypeForNEON(MVT::v8i8);
462 addDRTypeForNEON(MVT::v4i16);
463 addDRTypeForNEON(MVT::v2i32);
464 addDRTypeForNEON(MVT::v1i64);
465
466 addQRTypeForNEON(MVT::v4f32);
467 addQRTypeForNEON(MVT::v2f64);
468 addQRTypeForNEON(MVT::v16i8);
469 addQRTypeForNEON(MVT::v8i16);
470 addQRTypeForNEON(MVT::v4i32);
471 addQRTypeForNEON(MVT::v2i64);
472
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
486 // operands.
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);
510 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
511
512 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
527
528 // Mark v2f32 intrinsics.
529 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
544
545 // Neon does not support some operations on v1i64 and v2i64 types.
546 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547 // Custom handling for some quad-vector types to detect VMULL.
548 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551 // Custom handling for some vector types to avoid expensive expansions
552 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559 // a destination type that is wider than the source, and nor does
560 // it have a FP_TO_[SU]INT instruction with a narrower destination than
561 // source.
562 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
566
567 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
568 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
569
570 // NEON does not have single instruction CTPOP for vectors with element
571 // types wider than 8-bits. However, custom lowering can leverage the
572 // v8i8/v16i8 vcnt instruction.
573 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
574 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
575 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
576 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
577
578 // NEON only has FMA instructions as of VFP4.
579 if (!Subtarget->hasVFP4()) {
580 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
581 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
582 }
583
584 setTargetDAGCombine(ISD::INTRINSIC_VOID);
585 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
586 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
587 setTargetDAGCombine(ISD::SHL);
588 setTargetDAGCombine(ISD::SRL);
589 setTargetDAGCombine(ISD::SRA);
590 setTargetDAGCombine(ISD::SIGN_EXTEND);
591 setTargetDAGCombine(ISD::ZERO_EXTEND);
592 setTargetDAGCombine(ISD::ANY_EXTEND);
593 setTargetDAGCombine(ISD::SELECT_CC);
594 setTargetDAGCombine(ISD::BUILD_VECTOR);
595 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597 setTargetDAGCombine(ISD::STORE);
598 setTargetDAGCombine(ISD::FP_TO_SINT);
599 setTargetDAGCombine(ISD::FP_TO_UINT);
600 setTargetDAGCombine(ISD::FDIV);
601
602 // It is legal to extload from v4i8 to v4i16 or v4i32.
603 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
604 MVT::v4i16, MVT::v2i16,
605 MVT::v2i32};
606 for (unsigned i = 0; i < 6; ++i) {
607 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
608 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
609 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
610 }
611 }
612
613 // ARM and Thumb2 support UMLAL/SMLAL.
614 if (!Subtarget->isThumb1Only())
615 setTargetDAGCombine(ISD::ADDC);
616
617
618 computeRegisterProperties();
619
620 // ARM does not have f32 extending load.
621 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
622
623 // ARM does not have i1 sign extending load.
624 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
625
626 // ARM supports all 4 flavors of integer indexed load / store.
627 if (!Subtarget->isThumb1Only()) {
628 for (unsigned im = (unsigned)ISD::PRE_INC;
629 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
630 setIndexedLoadAction(im, MVT::i1, Legal);
631 setIndexedLoadAction(im, MVT::i8, Legal);
632 setIndexedLoadAction(im, MVT::i16, Legal);
633 setIndexedLoadAction(im, MVT::i32, Legal);
634 setIndexedStoreAction(im, MVT::i1, Legal);
635 setIndexedStoreAction(im, MVT::i8, Legal);
636 setIndexedStoreAction(im, MVT::i16, Legal);
637 setIndexedStoreAction(im, MVT::i32, Legal);
638 }
639 }
640
641 // i64 operation support.
642 setOperationAction(ISD::MUL, MVT::i64, Expand);
643 setOperationAction(ISD::MULHU, MVT::i32, Expand);
644 if (Subtarget->isThumb1Only()) {
645 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
646 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
647 }
648 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
649 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
650 setOperationAction(ISD::MULHS, MVT::i32, Expand);
651
652 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
653 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
654 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
655 setOperationAction(ISD::SRL, MVT::i64, Custom);
656 setOperationAction(ISD::SRA, MVT::i64, Custom);
657
658 if (!Subtarget->isThumb1Only()) {
659 // FIXME: We should do this for Thumb1 as well.
660 setOperationAction(ISD::ADDC, MVT::i32, Custom);
661 setOperationAction(ISD::ADDE, MVT::i32, Custom);
662 setOperationAction(ISD::SUBC, MVT::i32, Custom);
663 setOperationAction(ISD::SUBE, MVT::i32, Custom);
664 }
665
666 // ARM does not have ROTL.
667 setOperationAction(ISD::ROTL, MVT::i32, Expand);
668 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
669 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
670 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
671 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
672
673 // These just redirect to CTTZ and CTLZ on ARM.
674 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
675 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
676
677 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
678
679 // Only ARMv6 has BSWAP.
680 if (!Subtarget->hasV6Ops())
681 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
682
683 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
684 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
685 // These are expanded into libcalls if the cpu doesn't have HW divider.
686 setOperationAction(ISD::SDIV, MVT::i32, Expand);
687 setOperationAction(ISD::UDIV, MVT::i32, Expand);
688 }
689
690 // FIXME: Also set divmod for SREM on EABI
691 setOperationAction(ISD::SREM, MVT::i32, Expand);
692 setOperationAction(ISD::UREM, MVT::i32, Expand);
693 // Register based DivRem for AEABI (RTABI 4.2)
694 if (Subtarget->isTargetAEABI()) {
695 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
696 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
697 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
698 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
699 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
700 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
701 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
702 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
703
704 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
705 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
706 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
707 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
708 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
709 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
710 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
711 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
712
713 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
714 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
715 } else {
716 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
717 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
718 }
719
720 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
721 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
722 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
723 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
724 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
725
726 setOperationAction(ISD::TRAP, MVT::Other, Legal);
727
728 // Use the default implementation.
729 setOperationAction(ISD::VASTART, MVT::Other, Custom);
730 setOperationAction(ISD::VAARG, MVT::Other, Expand);
731 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
732 setOperationAction(ISD::VAEND, MVT::Other, Expand);
733 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
734 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
735
736 if (!Subtarget->isTargetDarwin()) {
737 // Non-Darwin platforms may return values in these registers via the
738 // personality function.
739 setExceptionPointerRegister(ARM::R0);
740 setExceptionSelectorRegister(ARM::R1);
741 }
742
743 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
744 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
745 // the default expansion.
746 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
747 // ATOMIC_FENCE needs custom lowering; the other 32-bit ones are legal and
748 // handled normally.
749 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
750 // Custom lowering for 64-bit ops
751 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
752 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
753 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
754 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
755 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
756 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
757 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
758 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
759 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
760 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
761 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
762 // On v8, we have particularly efficient implementations of atomic fences
763 // if they can be combined with nearby atomic loads and stores.
764 if (!Subtarget->hasV8Ops()) {
765 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
766 setInsertFencesForAtomic(true);
767 }
768 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
769 } else {
770 // If there's anything we can use as a barrier, go through custom lowering
771 // for ATOMIC_FENCE.
772 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
773 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
774
775 // Set them all for expansion, which will force libcalls.
776 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
777 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
778 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
779 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
780 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
781 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
782 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
783 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
784 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
785 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
786 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
787 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
788 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
789 // Unordered/Monotonic case.
790 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
791 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
792 }
793
794 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
795
796 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
797 if (!Subtarget->hasV6Ops()) {
798 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
799 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
800 }
801 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
802
803 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
804 !Subtarget->isThumb1Only()) {
805 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
806 // iff target supports vfp2.
807 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
808 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
809 }
810
811 // We want to custom lower some of our intrinsics.
812 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
813 if (Subtarget->isTargetDarwin()) {
814 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
815 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
816 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
817 }
818
819 setOperationAction(ISD::SETCC, MVT::i32, Expand);
820 setOperationAction(ISD::SETCC, MVT::f32, Expand);
821 setOperationAction(ISD::SETCC, MVT::f64, Expand);
822 setOperationAction(ISD::SELECT, MVT::i32, Custom);
823 setOperationAction(ISD::SELECT, MVT::f32, Custom);
824 setOperationAction(ISD::SELECT, MVT::f64, Custom);
825 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
826 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
827 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
828
829 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
830 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
831 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
832 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
833 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
834
835 // We don't support sin/cos/fmod/copysign/pow
836 setOperationAction(ISD::FSIN, MVT::f64, Expand);
837 setOperationAction(ISD::FSIN, MVT::f32, Expand);
838 setOperationAction(ISD::FCOS, MVT::f32, Expand);
839 setOperationAction(ISD::FCOS, MVT::f64, Expand);
840 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
841 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
842 setOperationAction(ISD::FREM, MVT::f64, Expand);
843 setOperationAction(ISD::FREM, MVT::f32, Expand);
844 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
845 !Subtarget->isThumb1Only()) {
846 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
847 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
848 }
849 setOperationAction(ISD::FPOW, MVT::f64, Expand);
850 setOperationAction(ISD::FPOW, MVT::f32, Expand);
851
852 if (!Subtarget->hasVFP4()) {
853 setOperationAction(ISD::FMA, MVT::f64, Expand);
854 setOperationAction(ISD::FMA, MVT::f32, Expand);
855 }
856
857 // Various VFP goodness
858 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
859 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
860 if (Subtarget->hasVFP2()) {
861 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
862 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
863 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
864 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
865 }
866 // Special handling for half-precision FP.
867 if (!Subtarget->hasFP16()) {
868 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
869 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
870 }
871 }
872
873 // Combine sin / cos into one node or libcall if possible.
874 if (Subtarget->hasSinCos()) {
875 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
876 setLibcallName(RTLIB::SINCOS_F64, "sincos");
877 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
878 // For iOS, we don't want to the normal expansion of a libcall to
879 // sincos. We want to issue a libcall to __sincos_stret.
880 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
881 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
882 }
883 }
884
885 // We have target-specific dag combine patterns for the following nodes:
886 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
887 setTargetDAGCombine(ISD::ADD);
888 setTargetDAGCombine(ISD::SUB);
889 setTargetDAGCombine(ISD::MUL);
890 setTargetDAGCombine(ISD::AND);
891 setTargetDAGCombine(ISD::OR);
892 setTargetDAGCombine(ISD::XOR);
893
894 if (Subtarget->hasV6Ops())
895 setTargetDAGCombine(ISD::SRL);
896
897 setStackPointerRegisterToSaveRestore(ARM::SP);
898
899 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
900 !Subtarget->hasVFP2())
901 setSchedulingPreference(Sched::RegPressure);
902 else
903 setSchedulingPreference(Sched::Hybrid);
904
905 //// temporary - rewrite interface to use type
906 MaxStoresPerMemset = 8;
907 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
908 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
909 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
910 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
911 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
912
913 // On ARM arguments smaller than 4 bytes are extended, so all arguments
914 // are at least 4 bytes aligned.
915 setMinStackArgumentAlignment(4);
916
917 // Prefer likely predicted branches to selects on out-of-order cores.
918 PredictableSelectIsExpensive = Subtarget->isLikeA9();
919
920 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
921 }
922
getExclusiveOperation(unsigned Size,AtomicOrdering Ord,bool isThumb2,unsigned & LdrOpc,unsigned & StrOpc)923 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
924 bool isThumb2, unsigned &LdrOpc,
925 unsigned &StrOpc) {
926 static const unsigned LoadBares[4][2] = {{ARM::LDREXB, ARM::t2LDREXB},
927 {ARM::LDREXH, ARM::t2LDREXH},
928 {ARM::LDREX, ARM::t2LDREX},
929 {ARM::LDREXD, ARM::t2LDREXD}};
930 static const unsigned LoadAcqs[4][2] = {{ARM::LDAEXB, ARM::t2LDAEXB},
931 {ARM::LDAEXH, ARM::t2LDAEXH},
932 {ARM::LDAEX, ARM::t2LDAEX},
933 {ARM::LDAEXD, ARM::t2LDAEXD}};
934 static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
935 {ARM::STREXH, ARM::t2STREXH},
936 {ARM::STREX, ARM::t2STREX},
937 {ARM::STREXD, ARM::t2STREXD}};
938 static const unsigned StoreRels[4][2] = {{ARM::STLEXB, ARM::t2STLEXB},
939 {ARM::STLEXH, ARM::t2STLEXH},
940 {ARM::STLEX, ARM::t2STLEX},
941 {ARM::STLEXD, ARM::t2STLEXD}};
942
943 const unsigned (*LoadOps)[2], (*StoreOps)[2];
944 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
945 LoadOps = LoadAcqs;
946 else
947 LoadOps = LoadBares;
948
949 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
950 StoreOps = StoreRels;
951 else
952 StoreOps = StoreBares;
953
954 assert(isPowerOf2_32(Size) && Size <= 8 &&
955 "unsupported size for atomic binary op!");
956
957 LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
958 StrOpc = StoreOps[Log2_32(Size)][isThumb2];
959 }
960
961 // FIXME: It might make sense to define the representative register class as the
962 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
963 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
964 // SPR's representative would be DPR_VFP2. This should work well if register
965 // pressure tracking were modified such that a register use would increment the
966 // pressure of the register class's representative and all of it's super
967 // classes' representatives transitively. We have not implemented this because
968 // of the difficulty prior to coalescing of modeling operand register classes
969 // due to the common occurrence of cross class copies and subregister insertions
970 // and extractions.
971 std::pair<const TargetRegisterClass*, uint8_t>
findRepresentativeClass(MVT VT) const972 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
973 const TargetRegisterClass *RRC = 0;
974 uint8_t Cost = 1;
975 switch (VT.SimpleTy) {
976 default:
977 return TargetLowering::findRepresentativeClass(VT);
978 // Use DPR as representative register class for all floating point
979 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
980 // the cost is 1 for both f32 and f64.
981 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
982 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
983 RRC = &ARM::DPRRegClass;
984 // When NEON is used for SP, only half of the register file is available
985 // because operations that define both SP and DP results will be constrained
986 // to the VFP2 class (D0-D15). We currently model this constraint prior to
987 // coalescing by double-counting the SP regs. See the FIXME above.
988 if (Subtarget->useNEONForSinglePrecisionFP())
989 Cost = 2;
990 break;
991 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
992 case MVT::v4f32: case MVT::v2f64:
993 RRC = &ARM::DPRRegClass;
994 Cost = 2;
995 break;
996 case MVT::v4i64:
997 RRC = &ARM::DPRRegClass;
998 Cost = 4;
999 break;
1000 case MVT::v8i64:
1001 RRC = &ARM::DPRRegClass;
1002 Cost = 8;
1003 break;
1004 }
1005 return std::make_pair(RRC, Cost);
1006 }
1007
getTargetNodeName(unsigned Opcode) const1008 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009 switch (Opcode) {
1010 default: return 0;
1011 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1012 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
1013 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1014 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1015 case ARMISD::CALL: return "ARMISD::CALL";
1016 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1017 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1018 case ARMISD::tCALL: return "ARMISD::tCALL";
1019 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1020 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1021 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1022 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1023 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1024 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1025 case ARMISD::CMP: return "ARMISD::CMP";
1026 case ARMISD::CMN: return "ARMISD::CMN";
1027 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1028 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1029 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1030 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1031 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1032
1033 case ARMISD::CMOV: return "ARMISD::CMOV";
1034
1035 case ARMISD::RBIT: return "ARMISD::RBIT";
1036
1037 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1038 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1039 case ARMISD::SITOF: return "ARMISD::SITOF";
1040 case ARMISD::UITOF: return "ARMISD::UITOF";
1041
1042 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1043 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1044 case ARMISD::RRX: return "ARMISD::RRX";
1045
1046 case ARMISD::ADDC: return "ARMISD::ADDC";
1047 case ARMISD::ADDE: return "ARMISD::ADDE";
1048 case ARMISD::SUBC: return "ARMISD::SUBC";
1049 case ARMISD::SUBE: return "ARMISD::SUBE";
1050
1051 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1052 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1053
1054 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1055 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1056
1057 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1058
1059 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1060
1061 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1062
1063 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1064
1065 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1066
1067 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1068 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1069 case ARMISD::VCGE: return "ARMISD::VCGE";
1070 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1071 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1072 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1073 case ARMISD::VCGT: return "ARMISD::VCGT";
1074 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1075 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1076 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1077 case ARMISD::VTST: return "ARMISD::VTST";
1078
1079 case ARMISD::VSHL: return "ARMISD::VSHL";
1080 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1081 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1082 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1083 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1084 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1085 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1086 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1087 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1088 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1089 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1090 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1091 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1092 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1093 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1094 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1095 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1096 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1097 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1098 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1099 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1100 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1101 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1102 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1103 case ARMISD::VDUP: return "ARMISD::VDUP";
1104 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1105 case ARMISD::VEXT: return "ARMISD::VEXT";
1106 case ARMISD::VREV64: return "ARMISD::VREV64";
1107 case ARMISD::VREV32: return "ARMISD::VREV32";
1108 case ARMISD::VREV16: return "ARMISD::VREV16";
1109 case ARMISD::VZIP: return "ARMISD::VZIP";
1110 case ARMISD::VUZP: return "ARMISD::VUZP";
1111 case ARMISD::VTRN: return "ARMISD::VTRN";
1112 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1113 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1114 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1115 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1116 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1117 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1118 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1119 case ARMISD::FMAX: return "ARMISD::FMAX";
1120 case ARMISD::FMIN: return "ARMISD::FMIN";
1121 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1122 case ARMISD::VMINNM: return "ARMISD::VMIN";
1123 case ARMISD::BFI: return "ARMISD::BFI";
1124 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1125 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1126 case ARMISD::VBSL: return "ARMISD::VBSL";
1127 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1128 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1129 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1130 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1131 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1132 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1133 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1134 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1135 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1136 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1137 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1138 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1139 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1140 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1141 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1142 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1143 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1144 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1145 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1146 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1147 }
1148 }
1149
getSetCCResultType(LLVMContext &,EVT VT) const1150 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1151 if (!VT.isVector()) return getPointerTy();
1152 return VT.changeVectorElementTypeToInteger();
1153 }
1154
1155 /// getRegClassFor - Return the register class that should be used for the
1156 /// specified value type.
getRegClassFor(MVT VT) const1157 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1158 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1159 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1160 // load / store 4 to 8 consecutive D registers.
1161 if (Subtarget->hasNEON()) {
1162 if (VT == MVT::v4i64)
1163 return &ARM::QQPRRegClass;
1164 if (VT == MVT::v8i64)
1165 return &ARM::QQQQPRRegClass;
1166 }
1167 return TargetLowering::getRegClassFor(VT);
1168 }
1169
1170 // Create a fast isel object.
1171 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const1172 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1173 const TargetLibraryInfo *libInfo) const {
1174 return ARM::createFastISel(funcInfo, libInfo);
1175 }
1176
1177 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1178 /// be used for loads / stores from the global.
getMaximalGlobalOffset() const1179 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1180 return (Subtarget->isThumb1Only() ? 127 : 4095);
1181 }
1182
getSchedulingPreference(SDNode * N) const1183 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1184 unsigned NumVals = N->getNumValues();
1185 if (!NumVals)
1186 return Sched::RegPressure;
1187
1188 for (unsigned i = 0; i != NumVals; ++i) {
1189 EVT VT = N->getValueType(i);
1190 if (VT == MVT::Glue || VT == MVT::Other)
1191 continue;
1192 if (VT.isFloatingPoint() || VT.isVector())
1193 return Sched::ILP;
1194 }
1195
1196 if (!N->isMachineOpcode())
1197 return Sched::RegPressure;
1198
1199 // Load are scheduled for latency even if there instruction itinerary
1200 // is not available.
1201 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1202 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1203
1204 if (MCID.getNumDefs() == 0)
1205 return Sched::RegPressure;
1206 if (!Itins->isEmpty() &&
1207 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1208 return Sched::ILP;
1209
1210 return Sched::RegPressure;
1211 }
1212
1213 //===----------------------------------------------------------------------===//
1214 // Lowering Code
1215 //===----------------------------------------------------------------------===//
1216
1217 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
IntCCToARMCC(ISD::CondCode CC)1218 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1219 switch (CC) {
1220 default: llvm_unreachable("Unknown condition code!");
1221 case ISD::SETNE: return ARMCC::NE;
1222 case ISD::SETEQ: return ARMCC::EQ;
1223 case ISD::SETGT: return ARMCC::GT;
1224 case ISD::SETGE: return ARMCC::GE;
1225 case ISD::SETLT: return ARMCC::LT;
1226 case ISD::SETLE: return ARMCC::LE;
1227 case ISD::SETUGT: return ARMCC::HI;
1228 case ISD::SETUGE: return ARMCC::HS;
1229 case ISD::SETULT: return ARMCC::LO;
1230 case ISD::SETULE: return ARMCC::LS;
1231 }
1232 }
1233
1234 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
FPCCToARMCC(ISD::CondCode CC,ARMCC::CondCodes & CondCode,ARMCC::CondCodes & CondCode2)1235 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1236 ARMCC::CondCodes &CondCode2) {
1237 CondCode2 = ARMCC::AL;
1238 switch (CC) {
1239 default: llvm_unreachable("Unknown FP condition!");
1240 case ISD::SETEQ:
1241 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1242 case ISD::SETGT:
1243 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1244 case ISD::SETGE:
1245 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1246 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1247 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1248 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1249 case ISD::SETO: CondCode = ARMCC::VC; break;
1250 case ISD::SETUO: CondCode = ARMCC::VS; break;
1251 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1252 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1253 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1254 case ISD::SETLT:
1255 case ISD::SETULT: CondCode = ARMCC::LT; break;
1256 case ISD::SETLE:
1257 case ISD::SETULE: CondCode = ARMCC::LE; break;
1258 case ISD::SETNE:
1259 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1260 }
1261 }
1262
1263 //===----------------------------------------------------------------------===//
1264 // Calling Convention Implementation
1265 //===----------------------------------------------------------------------===//
1266
1267 #include "ARMGenCallingConv.inc"
1268
1269 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1270 /// given CallingConvention value.
CCAssignFnForNode(CallingConv::ID CC,bool Return,bool isVarArg) const1271 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1272 bool Return,
1273 bool isVarArg) const {
1274 switch (CC) {
1275 default:
1276 llvm_unreachable("Unsupported calling convention");
1277 case CallingConv::Fast:
1278 if (Subtarget->hasVFP2() && !isVarArg) {
1279 if (!Subtarget->isAAPCS_ABI())
1280 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1281 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1282 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1283 }
1284 // Fallthrough
1285 case CallingConv::C: {
1286 // Use target triple & subtarget features to do actual dispatch.
1287 if (!Subtarget->isAAPCS_ABI())
1288 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1289 else if (Subtarget->hasVFP2() &&
1290 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1291 !isVarArg)
1292 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1294 }
1295 case CallingConv::ARM_AAPCS_VFP:
1296 if (!isVarArg)
1297 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1298 // Fallthrough
1299 case CallingConv::ARM_AAPCS:
1300 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1301 case CallingConv::ARM_APCS:
1302 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1303 case CallingConv::GHC:
1304 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1305 }
1306 }
1307
1308 /// LowerCallResult - Lower the result values of a call into the
1309 /// appropriate copies out of appropriate physical registers.
1310 SDValue
LowerCallResult(SDValue Chain,SDValue InFlag,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,SDLoc dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,bool isThisReturn,SDValue ThisVal) const1311 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1312 CallingConv::ID CallConv, bool isVarArg,
1313 const SmallVectorImpl<ISD::InputArg> &Ins,
1314 SDLoc dl, SelectionDAG &DAG,
1315 SmallVectorImpl<SDValue> &InVals,
1316 bool isThisReturn, SDValue ThisVal) const {
1317
1318 // Assign locations to each value returned by this call.
1319 SmallVector<CCValAssign, 16> RVLocs;
1320 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1321 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1322 CCInfo.AnalyzeCallResult(Ins,
1323 CCAssignFnForNode(CallConv, /* Return*/ true,
1324 isVarArg));
1325
1326 // Copy all of the result registers out of their specified physreg.
1327 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1328 CCValAssign VA = RVLocs[i];
1329
1330 // Pass 'this' value directly from the argument to return value, to avoid
1331 // reg unit interference
1332 if (i == 0 && isThisReturn) {
1333 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1334 "unexpected return calling convention register assignment");
1335 InVals.push_back(ThisVal);
1336 continue;
1337 }
1338
1339 SDValue Val;
1340 if (VA.needsCustom()) {
1341 // Handle f64 or half of a v2f64.
1342 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1343 InFlag);
1344 Chain = Lo.getValue(1);
1345 InFlag = Lo.getValue(2);
1346 VA = RVLocs[++i]; // skip ahead to next loc
1347 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1348 InFlag);
1349 Chain = Hi.getValue(1);
1350 InFlag = Hi.getValue(2);
1351 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1352
1353 if (VA.getLocVT() == MVT::v2f64) {
1354 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1355 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1356 DAG.getConstant(0, MVT::i32));
1357
1358 VA = RVLocs[++i]; // skip ahead to next loc
1359 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1360 Chain = Lo.getValue(1);
1361 InFlag = Lo.getValue(2);
1362 VA = RVLocs[++i]; // skip ahead to next loc
1363 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1364 Chain = Hi.getValue(1);
1365 InFlag = Hi.getValue(2);
1366 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1367 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1368 DAG.getConstant(1, MVT::i32));
1369 }
1370 } else {
1371 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1372 InFlag);
1373 Chain = Val.getValue(1);
1374 InFlag = Val.getValue(2);
1375 }
1376
1377 switch (VA.getLocInfo()) {
1378 default: llvm_unreachable("Unknown loc info!");
1379 case CCValAssign::Full: break;
1380 case CCValAssign::BCvt:
1381 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1382 break;
1383 }
1384
1385 InVals.push_back(Val);
1386 }
1387
1388 return Chain;
1389 }
1390
1391 /// LowerMemOpCallTo - Store the argument to the stack.
1392 SDValue
LowerMemOpCallTo(SDValue Chain,SDValue StackPtr,SDValue Arg,SDLoc dl,SelectionDAG & DAG,const CCValAssign & VA,ISD::ArgFlagsTy Flags) const1393 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1394 SDValue StackPtr, SDValue Arg,
1395 SDLoc dl, SelectionDAG &DAG,
1396 const CCValAssign &VA,
1397 ISD::ArgFlagsTy Flags) const {
1398 unsigned LocMemOffset = VA.getLocMemOffset();
1399 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1400 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1401 return DAG.getStore(Chain, dl, Arg, PtrOff,
1402 MachinePointerInfo::getStack(LocMemOffset),
1403 false, false, 0);
1404 }
1405
PassF64ArgInRegs(SDLoc dl,SelectionDAG & DAG,SDValue Chain,SDValue & Arg,RegsToPassVector & RegsToPass,CCValAssign & VA,CCValAssign & NextVA,SDValue & StackPtr,SmallVectorImpl<SDValue> & MemOpChains,ISD::ArgFlagsTy Flags) const1406 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1407 SDValue Chain, SDValue &Arg,
1408 RegsToPassVector &RegsToPass,
1409 CCValAssign &VA, CCValAssign &NextVA,
1410 SDValue &StackPtr,
1411 SmallVectorImpl<SDValue> &MemOpChains,
1412 ISD::ArgFlagsTy Flags) const {
1413
1414 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1415 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1416 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1417
1418 if (NextVA.isRegLoc())
1419 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1420 else {
1421 assert(NextVA.isMemLoc());
1422 if (StackPtr.getNode() == 0)
1423 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1424
1425 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1426 dl, DAG, NextVA,
1427 Flags));
1428 }
1429 }
1430
1431 /// LowerCall - Lowering a call into a callseq_start <-
1432 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1433 /// nodes.
1434 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const1435 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1436 SmallVectorImpl<SDValue> &InVals) const {
1437 SelectionDAG &DAG = CLI.DAG;
1438 SDLoc &dl = CLI.DL;
1439 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1440 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1441 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1442 SDValue Chain = CLI.Chain;
1443 SDValue Callee = CLI.Callee;
1444 bool &isTailCall = CLI.IsTailCall;
1445 CallingConv::ID CallConv = CLI.CallConv;
1446 bool doesNotRet = CLI.DoesNotReturn;
1447 bool isVarArg = CLI.IsVarArg;
1448
1449 MachineFunction &MF = DAG.getMachineFunction();
1450 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1451 bool isThisReturn = false;
1452 bool isSibCall = false;
1453 // Disable tail calls if they're not supported.
1454 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1455 isTailCall = false;
1456 if (isTailCall) {
1457 // Check if it's really possible to do a tail call.
1458 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1459 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1460 Outs, OutVals, Ins, DAG);
1461 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1462 // detected sibcalls.
1463 if (isTailCall) {
1464 ++NumTailCalls;
1465 isSibCall = true;
1466 }
1467 }
1468
1469 // Analyze operands of the call, assigning locations to each operand.
1470 SmallVector<CCValAssign, 16> ArgLocs;
1471 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1472 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1473 CCInfo.AnalyzeCallOperands(Outs,
1474 CCAssignFnForNode(CallConv, /* Return*/ false,
1475 isVarArg));
1476
1477 // Get a count of how many bytes are to be pushed on the stack.
1478 unsigned NumBytes = CCInfo.getNextStackOffset();
1479
1480 // For tail calls, memory operands are available in our caller's stack.
1481 if (isSibCall)
1482 NumBytes = 0;
1483
1484 // Adjust the stack pointer for the new arguments...
1485 // These operations are automatically eliminated by the prolog/epilog pass
1486 if (!isSibCall)
1487 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1488 dl);
1489
1490 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1491
1492 RegsToPassVector RegsToPass;
1493 SmallVector<SDValue, 8> MemOpChains;
1494
1495 // Walk the register/memloc assignments, inserting copies/loads. In the case
1496 // of tail call optimization, arguments are handled later.
1497 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1498 i != e;
1499 ++i, ++realArgIdx) {
1500 CCValAssign &VA = ArgLocs[i];
1501 SDValue Arg = OutVals[realArgIdx];
1502 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1503 bool isByVal = Flags.isByVal();
1504
1505 // Promote the value if needed.
1506 switch (VA.getLocInfo()) {
1507 default: llvm_unreachable("Unknown loc info!");
1508 case CCValAssign::Full: break;
1509 case CCValAssign::SExt:
1510 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1511 break;
1512 case CCValAssign::ZExt:
1513 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1514 break;
1515 case CCValAssign::AExt:
1516 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1517 break;
1518 case CCValAssign::BCvt:
1519 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1520 break;
1521 }
1522
1523 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1524 if (VA.needsCustom()) {
1525 if (VA.getLocVT() == MVT::v2f64) {
1526 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1527 DAG.getConstant(0, MVT::i32));
1528 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1529 DAG.getConstant(1, MVT::i32));
1530
1531 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1532 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1533
1534 VA = ArgLocs[++i]; // skip ahead to next loc
1535 if (VA.isRegLoc()) {
1536 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1537 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1538 } else {
1539 assert(VA.isMemLoc());
1540
1541 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1542 dl, DAG, VA, Flags));
1543 }
1544 } else {
1545 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1546 StackPtr, MemOpChains, Flags);
1547 }
1548 } else if (VA.isRegLoc()) {
1549 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1550 assert(VA.getLocVT() == MVT::i32 &&
1551 "unexpected calling convention register assignment");
1552 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1553 "unexpected use of 'returned'");
1554 isThisReturn = true;
1555 }
1556 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1557 } else if (isByVal) {
1558 assert(VA.isMemLoc());
1559 unsigned offset = 0;
1560
1561 // True if this byval aggregate will be split between registers
1562 // and memory.
1563 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1564 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1565
1566 if (CurByValIdx < ByValArgsCount) {
1567
1568 unsigned RegBegin, RegEnd;
1569 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1570
1571 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1572 unsigned int i, j;
1573 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1574 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1575 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1576 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1577 MachinePointerInfo(),
1578 false, false, false,
1579 DAG.InferPtrAlignment(AddArg));
1580 MemOpChains.push_back(Load.getValue(1));
1581 RegsToPass.push_back(std::make_pair(j, Load));
1582 }
1583
1584 // If parameter size outsides register area, "offset" value
1585 // helps us to calculate stack slot for remained part properly.
1586 offset = RegEnd - RegBegin;
1587
1588 CCInfo.nextInRegsParam();
1589 }
1590
1591 if (Flags.getByValSize() > 4*offset) {
1592 unsigned LocMemOffset = VA.getLocMemOffset();
1593 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1594 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1595 StkPtrOff);
1596 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1597 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1598 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1599 MVT::i32);
1600 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1601
1602 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1603 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1604 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1605 Ops, array_lengthof(Ops)));
1606 }
1607 } else if (!isSibCall) {
1608 assert(VA.isMemLoc());
1609
1610 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1611 dl, DAG, VA, Flags));
1612 }
1613 }
1614
1615 if (!MemOpChains.empty())
1616 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1617 &MemOpChains[0], MemOpChains.size());
1618
1619 // Build a sequence of copy-to-reg nodes chained together with token chain
1620 // and flag operands which copy the outgoing args into the appropriate regs.
1621 SDValue InFlag;
1622 // Tail call byval lowering might overwrite argument registers so in case of
1623 // tail call optimization the copies to registers are lowered later.
1624 if (!isTailCall)
1625 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1626 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1627 RegsToPass[i].second, InFlag);
1628 InFlag = Chain.getValue(1);
1629 }
1630
1631 // For tail calls lower the arguments to the 'real' stack slot.
1632 if (isTailCall) {
1633 // Force all the incoming stack arguments to be loaded from the stack
1634 // before any new outgoing arguments are stored to the stack, because the
1635 // outgoing stack slots may alias the incoming argument stack slots, and
1636 // the alias isn't otherwise explicit. This is slightly more conservative
1637 // than necessary, because it means that each store effectively depends
1638 // on every argument instead of just those arguments it would clobber.
1639
1640 // Do not flag preceding copytoreg stuff together with the following stuff.
1641 InFlag = SDValue();
1642 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1643 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1644 RegsToPass[i].second, InFlag);
1645 InFlag = Chain.getValue(1);
1646 }
1647 InFlag = SDValue();
1648 }
1649
1650 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1651 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1652 // node so that legalize doesn't hack it.
1653 bool isDirect = false;
1654 bool isARMFunc = false;
1655 bool isLocalARMFunc = false;
1656 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1657
1658 if (EnableARMLongCalls) {
1659 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1660 && "long-calls with non-static relocation model!");
1661 // Handle a global address or an external symbol. If it's not one of
1662 // those, the target's already in a register, so we don't need to do
1663 // anything extra.
1664 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1665 const GlobalValue *GV = G->getGlobal();
1666 // Create a constant pool entry for the callee address
1667 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1668 ARMConstantPoolValue *CPV =
1669 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1670
1671 // Get the address of the callee into a register
1672 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1673 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1674 Callee = DAG.getLoad(getPointerTy(), dl,
1675 DAG.getEntryNode(), CPAddr,
1676 MachinePointerInfo::getConstantPool(),
1677 false, false, false, 0);
1678 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1679 const char *Sym = S->getSymbol();
1680
1681 // Create a constant pool entry for the callee address
1682 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1683 ARMConstantPoolValue *CPV =
1684 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1685 ARMPCLabelIndex, 0);
1686 // Get the address of the callee into a register
1687 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1688 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1689 Callee = DAG.getLoad(getPointerTy(), dl,
1690 DAG.getEntryNode(), CPAddr,
1691 MachinePointerInfo::getConstantPool(),
1692 false, false, false, 0);
1693 }
1694 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1695 const GlobalValue *GV = G->getGlobal();
1696 isDirect = true;
1697 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1698 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1699 getTargetMachine().getRelocationModel() != Reloc::Static;
1700 isARMFunc = !Subtarget->isThumb() || isStub;
1701 // ARM call to a local ARM function is predicable.
1702 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1703 // tBX takes a register source operand.
1704 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1705 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1706 ARMConstantPoolValue *CPV =
1707 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1708 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1709 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1710 Callee = DAG.getLoad(getPointerTy(), dl,
1711 DAG.getEntryNode(), CPAddr,
1712 MachinePointerInfo::getConstantPool(),
1713 false, false, false, 0);
1714 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1715 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1716 getPointerTy(), Callee, PICLabel);
1717 } else {
1718 // On ELF targets for PIC code, direct calls should go through the PLT
1719 unsigned OpFlags = 0;
1720 if (Subtarget->isTargetELF() &&
1721 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1722 OpFlags = ARMII::MO_PLT;
1723 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1724 }
1725 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1726 isDirect = true;
1727 bool isStub = Subtarget->isTargetDarwin() &&
1728 getTargetMachine().getRelocationModel() != Reloc::Static;
1729 isARMFunc = !Subtarget->isThumb() || isStub;
1730 // tBX takes a register source operand.
1731 const char *Sym = S->getSymbol();
1732 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1733 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1734 ARMConstantPoolValue *CPV =
1735 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1736 ARMPCLabelIndex, 4);
1737 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1738 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1739 Callee = DAG.getLoad(getPointerTy(), dl,
1740 DAG.getEntryNode(), CPAddr,
1741 MachinePointerInfo::getConstantPool(),
1742 false, false, false, 0);
1743 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1744 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1745 getPointerTy(), Callee, PICLabel);
1746 } else {
1747 unsigned OpFlags = 0;
1748 // On ELF targets for PIC code, direct calls should go through the PLT
1749 if (Subtarget->isTargetELF() &&
1750 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1751 OpFlags = ARMII::MO_PLT;
1752 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1753 }
1754 }
1755
1756 // FIXME: handle tail calls differently.
1757 unsigned CallOpc;
1758 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1759 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1760 if (Subtarget->isThumb()) {
1761 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1762 CallOpc = ARMISD::CALL_NOLINK;
1763 else
1764 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1765 } else {
1766 if (!isDirect && !Subtarget->hasV5TOps())
1767 CallOpc = ARMISD::CALL_NOLINK;
1768 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1769 // Emit regular call when code size is the priority
1770 !HasMinSizeAttr)
1771 // "mov lr, pc; b _foo" to avoid confusing the RSP
1772 CallOpc = ARMISD::CALL_NOLINK;
1773 else
1774 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1775 }
1776
1777 std::vector<SDValue> Ops;
1778 Ops.push_back(Chain);
1779 Ops.push_back(Callee);
1780
1781 // Add argument registers to the end of the list so that they are known live
1782 // into the call.
1783 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1784 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1785 RegsToPass[i].second.getValueType()));
1786
1787 // Add a register mask operand representing the call-preserved registers.
1788 if (!isTailCall) {
1789 const uint32_t *Mask;
1790 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1791 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1792 if (isThisReturn) {
1793 // For 'this' returns, use the R0-preserving mask if applicable
1794 Mask = ARI->getThisReturnPreservedMask(CallConv);
1795 if (!Mask) {
1796 // Set isThisReturn to false if the calling convention is not one that
1797 // allows 'returned' to be modeled in this way, so LowerCallResult does
1798 // not try to pass 'this' straight through
1799 isThisReturn = false;
1800 Mask = ARI->getCallPreservedMask(CallConv);
1801 }
1802 } else
1803 Mask = ARI->getCallPreservedMask(CallConv);
1804
1805 assert(Mask && "Missing call preserved mask for calling convention");
1806 Ops.push_back(DAG.getRegisterMask(Mask));
1807 }
1808
1809 if (InFlag.getNode())
1810 Ops.push_back(InFlag);
1811
1812 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1813 if (isTailCall)
1814 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1815
1816 // Returns a chain and a flag for retval copy to use.
1817 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1818 InFlag = Chain.getValue(1);
1819
1820 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1821 DAG.getIntPtrConstant(0, true), InFlag, dl);
1822 if (!Ins.empty())
1823 InFlag = Chain.getValue(1);
1824
1825 // Handle result values, copying them out of physregs into vregs that we
1826 // return.
1827 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1828 InVals, isThisReturn,
1829 isThisReturn ? OutVals[0] : SDValue());
1830 }
1831
1832 /// HandleByVal - Every parameter *after* a byval parameter is passed
1833 /// on the stack. Remember the next parameter register to allocate,
1834 /// and then confiscate the rest of the parameter registers to insure
1835 /// this.
1836 void
HandleByVal(CCState * State,unsigned & size,unsigned Align) const1837 ARMTargetLowering::HandleByVal(
1838 CCState *State, unsigned &size, unsigned Align) const {
1839 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1840 assert((State->getCallOrPrologue() == Prologue ||
1841 State->getCallOrPrologue() == Call) &&
1842 "unhandled ParmContext");
1843
1844 // For in-prologue parameters handling, we also introduce stack offset
1845 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1846 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1847 // NSAA should be evaluted (NSAA means "next stacked argument address").
1848 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1849 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1850 unsigned NSAAOffset = State->getNextStackOffset();
1851 if (State->getCallOrPrologue() != Call) {
1852 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1853 unsigned RB, RE;
1854 State->getInRegsParamInfo(i, RB, RE);
1855 assert(NSAAOffset >= (RE-RB)*4 &&
1856 "Stack offset for byval regs doesn't introduced anymore?");
1857 NSAAOffset -= (RE-RB)*4;
1858 }
1859 }
1860 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1861 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1862 unsigned AlignInRegs = Align / 4;
1863 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1864 for (unsigned i = 0; i < Waste; ++i)
1865 reg = State->AllocateReg(GPRArgRegs, 4);
1866 }
1867 if (reg != 0) {
1868 unsigned excess = 4 * (ARM::R4 - reg);
1869
1870 // Special case when NSAA != SP and parameter size greater than size of
1871 // all remained GPR regs. In that case we can't split parameter, we must
1872 // send it to stack. We also must set NCRN to R4, so waste all
1873 // remained registers.
1874 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1875 while (State->AllocateReg(GPRArgRegs, 4))
1876 ;
1877 return;
1878 }
1879
1880 // First register for byval parameter is the first register that wasn't
1881 // allocated before this method call, so it would be "reg".
1882 // If parameter is small enough to be saved in range [reg, r4), then
1883 // the end (first after last) register would be reg + param-size-in-regs,
1884 // else parameter would be splitted between registers and stack,
1885 // end register would be r4 in this case.
1886 unsigned ByValRegBegin = reg;
1887 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1888 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1889 // Note, first register is allocated in the beginning of function already,
1890 // allocate remained amount of registers we need.
1891 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1892 State->AllocateReg(GPRArgRegs, 4);
1893 // At a call site, a byval parameter that is split between
1894 // registers and memory needs its size truncated here. In a
1895 // function prologue, such byval parameters are reassembled in
1896 // memory, and are not truncated.
1897 if (State->getCallOrPrologue() == Call) {
1898 // Make remained size equal to 0 in case, when
1899 // the whole structure may be stored into registers.
1900 if (size < excess)
1901 size = 0;
1902 else
1903 size -= excess;
1904 }
1905 }
1906 }
1907 }
1908
1909 /// MatchingStackOffset - Return true if the given stack call argument is
1910 /// already available in the same position (relatively) of the caller's
1911 /// incoming argument stack.
1912 static
MatchingStackOffset(SDValue Arg,unsigned Offset,ISD::ArgFlagsTy Flags,MachineFrameInfo * MFI,const MachineRegisterInfo * MRI,const TargetInstrInfo * TII)1913 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1914 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1915 const TargetInstrInfo *TII) {
1916 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1917 int FI = INT_MAX;
1918 if (Arg.getOpcode() == ISD::CopyFromReg) {
1919 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1920 if (!TargetRegisterInfo::isVirtualRegister(VR))
1921 return false;
1922 MachineInstr *Def = MRI->getVRegDef(VR);
1923 if (!Def)
1924 return false;
1925 if (!Flags.isByVal()) {
1926 if (!TII->isLoadFromStackSlot(Def, FI))
1927 return false;
1928 } else {
1929 return false;
1930 }
1931 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1932 if (Flags.isByVal())
1933 // ByVal argument is passed in as a pointer but it's now being
1934 // dereferenced. e.g.
1935 // define @foo(%struct.X* %A) {
1936 // tail call @bar(%struct.X* byval %A)
1937 // }
1938 return false;
1939 SDValue Ptr = Ld->getBasePtr();
1940 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1941 if (!FINode)
1942 return false;
1943 FI = FINode->getIndex();
1944 } else
1945 return false;
1946
1947 assert(FI != INT_MAX);
1948 if (!MFI->isFixedObjectIndex(FI))
1949 return false;
1950 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1951 }
1952
1953 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1954 /// for tail call optimization. Targets which want to do tail call
1955 /// optimization should implement this function.
1956 bool
IsEligibleForTailCallOptimization(SDValue Callee,CallingConv::ID CalleeCC,bool isVarArg,bool isCalleeStructRet,bool isCallerStructRet,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,SelectionDAG & DAG) const1957 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1958 CallingConv::ID CalleeCC,
1959 bool isVarArg,
1960 bool isCalleeStructRet,
1961 bool isCallerStructRet,
1962 const SmallVectorImpl<ISD::OutputArg> &Outs,
1963 const SmallVectorImpl<SDValue> &OutVals,
1964 const SmallVectorImpl<ISD::InputArg> &Ins,
1965 SelectionDAG& DAG) const {
1966 const Function *CallerF = DAG.getMachineFunction().getFunction();
1967 CallingConv::ID CallerCC = CallerF->getCallingConv();
1968 bool CCMatch = CallerCC == CalleeCC;
1969
1970 // Look for obvious safe cases to perform tail call optimization that do not
1971 // require ABI changes. This is what gcc calls sibcall.
1972
1973 // Do not sibcall optimize vararg calls unless the call site is not passing
1974 // any arguments.
1975 if (isVarArg && !Outs.empty())
1976 return false;
1977
1978 // Exception-handling functions need a special set of instructions to indicate
1979 // a return to the hardware. Tail-calling another function would probably
1980 // break this.
1981 if (CallerF->hasFnAttribute("interrupt"))
1982 return false;
1983
1984 // Also avoid sibcall optimization if either caller or callee uses struct
1985 // return semantics.
1986 if (isCalleeStructRet || isCallerStructRet)
1987 return false;
1988
1989 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1990 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1991 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1992 // support in the assembler and linker to be used. This would need to be
1993 // fixed to fully support tail calls in Thumb1.
1994 //
1995 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1996 // LR. This means if we need to reload LR, it takes an extra instructions,
1997 // which outweighs the value of the tail call; but here we don't know yet
1998 // whether LR is going to be used. Probably the right approach is to
1999 // generate the tail call here and turn it back into CALL/RET in
2000 // emitEpilogue if LR is used.
2001
2002 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2003 // but we need to make sure there are enough registers; the only valid
2004 // registers are the 4 used for parameters. We don't currently do this
2005 // case.
2006 if (Subtarget->isThumb1Only())
2007 return false;
2008
2009 // If the calling conventions do not match, then we'd better make sure the
2010 // results are returned in the same way as what the caller expects.
2011 if (!CCMatch) {
2012 SmallVector<CCValAssign, 16> RVLocs1;
2013 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2014 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2015 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2016
2017 SmallVector<CCValAssign, 16> RVLocs2;
2018 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2019 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2020 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2021
2022 if (RVLocs1.size() != RVLocs2.size())
2023 return false;
2024 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2025 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2026 return false;
2027 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2028 return false;
2029 if (RVLocs1[i].isRegLoc()) {
2030 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2031 return false;
2032 } else {
2033 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2034 return false;
2035 }
2036 }
2037 }
2038
2039 // If Caller's vararg or byval argument has been split between registers and
2040 // stack, do not perform tail call, since part of the argument is in caller's
2041 // local frame.
2042 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2043 getInfo<ARMFunctionInfo>();
2044 if (AFI_Caller->getArgRegsSaveSize())
2045 return false;
2046
2047 // If the callee takes no arguments then go on to check the results of the
2048 // call.
2049 if (!Outs.empty()) {
2050 // Check if stack adjustment is needed. For now, do not do this if any
2051 // argument is passed on the stack.
2052 SmallVector<CCValAssign, 16> ArgLocs;
2053 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2054 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2055 CCInfo.AnalyzeCallOperands(Outs,
2056 CCAssignFnForNode(CalleeCC, false, isVarArg));
2057 if (CCInfo.getNextStackOffset()) {
2058 MachineFunction &MF = DAG.getMachineFunction();
2059
2060 // Check if the arguments are already laid out in the right way as
2061 // the caller's fixed stack objects.
2062 MachineFrameInfo *MFI = MF.getFrameInfo();
2063 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2064 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2065 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2066 i != e;
2067 ++i, ++realArgIdx) {
2068 CCValAssign &VA = ArgLocs[i];
2069 EVT RegVT = VA.getLocVT();
2070 SDValue Arg = OutVals[realArgIdx];
2071 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2072 if (VA.getLocInfo() == CCValAssign::Indirect)
2073 return false;
2074 if (VA.needsCustom()) {
2075 // f64 and vector types are split into multiple registers or
2076 // register/stack-slot combinations. The types will not match
2077 // the registers; give up on memory f64 refs until we figure
2078 // out what to do about this.
2079 if (!VA.isRegLoc())
2080 return false;
2081 if (!ArgLocs[++i].isRegLoc())
2082 return false;
2083 if (RegVT == MVT::v2f64) {
2084 if (!ArgLocs[++i].isRegLoc())
2085 return false;
2086 if (!ArgLocs[++i].isRegLoc())
2087 return false;
2088 }
2089 } else if (!VA.isRegLoc()) {
2090 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2091 MFI, MRI, TII))
2092 return false;
2093 }
2094 }
2095 }
2096 }
2097
2098 return true;
2099 }
2100
2101 bool
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const2102 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2103 MachineFunction &MF, bool isVarArg,
2104 const SmallVectorImpl<ISD::OutputArg> &Outs,
2105 LLVMContext &Context) const {
2106 SmallVector<CCValAssign, 16> RVLocs;
2107 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2108 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2109 isVarArg));
2110 }
2111
LowerInterruptReturn(SmallVectorImpl<SDValue> & RetOps,SDLoc DL,SelectionDAG & DAG)2112 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2113 SDLoc DL, SelectionDAG &DAG) {
2114 const MachineFunction &MF = DAG.getMachineFunction();
2115 const Function *F = MF.getFunction();
2116
2117 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2118
2119 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2120 // version of the "preferred return address". These offsets affect the return
2121 // instruction if this is a return from PL1 without hypervisor extensions.
2122 // IRQ/FIQ: +4 "subs pc, lr, #4"
2123 // SWI: 0 "subs pc, lr, #0"
2124 // ABORT: +4 "subs pc, lr, #4"
2125 // UNDEF: +4/+2 "subs pc, lr, #0"
2126 // UNDEF varies depending on where the exception came from ARM or Thumb
2127 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2128
2129 int64_t LROffset;
2130 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2131 IntKind == "ABORT")
2132 LROffset = 4;
2133 else if (IntKind == "SWI" || IntKind == "UNDEF")
2134 LROffset = 0;
2135 else
2136 report_fatal_error("Unsupported interrupt attribute. If present, value "
2137 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2138
2139 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2140
2141 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2142 RetOps.data(), RetOps.size());
2143 }
2144
2145 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,SDLoc dl,SelectionDAG & DAG) const2146 ARMTargetLowering::LowerReturn(SDValue Chain,
2147 CallingConv::ID CallConv, bool isVarArg,
2148 const SmallVectorImpl<ISD::OutputArg> &Outs,
2149 const SmallVectorImpl<SDValue> &OutVals,
2150 SDLoc dl, SelectionDAG &DAG) const {
2151
2152 // CCValAssign - represent the assignment of the return value to a location.
2153 SmallVector<CCValAssign, 16> RVLocs;
2154
2155 // CCState - Info about the registers and stack slots.
2156 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2157 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2158
2159 // Analyze outgoing return values.
2160 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2161 isVarArg));
2162
2163 SDValue Flag;
2164 SmallVector<SDValue, 4> RetOps;
2165 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2166
2167 // Copy the result values into the output registers.
2168 for (unsigned i = 0, realRVLocIdx = 0;
2169 i != RVLocs.size();
2170 ++i, ++realRVLocIdx) {
2171 CCValAssign &VA = RVLocs[i];
2172 assert(VA.isRegLoc() && "Can only return in registers!");
2173
2174 SDValue Arg = OutVals[realRVLocIdx];
2175
2176 switch (VA.getLocInfo()) {
2177 default: llvm_unreachable("Unknown loc info!");
2178 case CCValAssign::Full: break;
2179 case CCValAssign::BCvt:
2180 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2181 break;
2182 }
2183
2184 if (VA.needsCustom()) {
2185 if (VA.getLocVT() == MVT::v2f64) {
2186 // Extract the first half and return it in two registers.
2187 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2188 DAG.getConstant(0, MVT::i32));
2189 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2190 DAG.getVTList(MVT::i32, MVT::i32), Half);
2191
2192 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2193 Flag = Chain.getValue(1);
2194 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2195 VA = RVLocs[++i]; // skip ahead to next loc
2196 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2197 HalfGPRs.getValue(1), Flag);
2198 Flag = Chain.getValue(1);
2199 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2200 VA = RVLocs[++i]; // skip ahead to next loc
2201
2202 // Extract the 2nd half and fall through to handle it as an f64 value.
2203 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2204 DAG.getConstant(1, MVT::i32));
2205 }
2206 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2207 // available.
2208 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2209 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2210 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2211 Flag = Chain.getValue(1);
2212 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2213 VA = RVLocs[++i]; // skip ahead to next loc
2214 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2215 Flag);
2216 } else
2217 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2218
2219 // Guarantee that all emitted copies are
2220 // stuck together, avoiding something bad.
2221 Flag = Chain.getValue(1);
2222 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2223 }
2224
2225 // Update chain and glue.
2226 RetOps[0] = Chain;
2227 if (Flag.getNode())
2228 RetOps.push_back(Flag);
2229
2230 // CPUs which aren't M-class use a special sequence to return from
2231 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2232 // though we use "subs pc, lr, #N").
2233 //
2234 // M-class CPUs actually use a normal return sequence with a special
2235 // (hardware-provided) value in LR, so the normal code path works.
2236 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2237 !Subtarget->isMClass()) {
2238 if (Subtarget->isThumb1Only())
2239 report_fatal_error("interrupt attribute is not supported in Thumb1");
2240 return LowerInterruptReturn(RetOps, dl, DAG);
2241 }
2242
2243 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2244 RetOps.data(), RetOps.size());
2245 }
2246
isUsedByReturnOnly(SDNode * N,SDValue & Chain) const2247 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2248 if (N->getNumValues() != 1)
2249 return false;
2250 if (!N->hasNUsesOfValue(1, 0))
2251 return false;
2252
2253 SDValue TCChain = Chain;
2254 SDNode *Copy = *N->use_begin();
2255 if (Copy->getOpcode() == ISD::CopyToReg) {
2256 // If the copy has a glue operand, we conservatively assume it isn't safe to
2257 // perform a tail call.
2258 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2259 return false;
2260 TCChain = Copy->getOperand(0);
2261 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2262 SDNode *VMov = Copy;
2263 // f64 returned in a pair of GPRs.
2264 SmallPtrSet<SDNode*, 2> Copies;
2265 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2266 UI != UE; ++UI) {
2267 if (UI->getOpcode() != ISD::CopyToReg)
2268 return false;
2269 Copies.insert(*UI);
2270 }
2271 if (Copies.size() > 2)
2272 return false;
2273
2274 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2275 UI != UE; ++UI) {
2276 SDValue UseChain = UI->getOperand(0);
2277 if (Copies.count(UseChain.getNode()))
2278 // Second CopyToReg
2279 Copy = *UI;
2280 else
2281 // First CopyToReg
2282 TCChain = UseChain;
2283 }
2284 } else if (Copy->getOpcode() == ISD::BITCAST) {
2285 // f32 returned in a single GPR.
2286 if (!Copy->hasOneUse())
2287 return false;
2288 Copy = *Copy->use_begin();
2289 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2290 return false;
2291 TCChain = Copy->getOperand(0);
2292 } else {
2293 return false;
2294 }
2295
2296 bool HasRet = false;
2297 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2298 UI != UE; ++UI) {
2299 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2300 UI->getOpcode() != ARMISD::INTRET_FLAG)
2301 return false;
2302 HasRet = true;
2303 }
2304
2305 if (!HasRet)
2306 return false;
2307
2308 Chain = TCChain;
2309 return true;
2310 }
2311
mayBeEmittedAsTailCall(CallInst * CI) const2312 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2313 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2314 return false;
2315
2316 if (!CI->isTailCall())
2317 return false;
2318
2319 return !Subtarget->isThumb1Only();
2320 }
2321
2322 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2323 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2324 // one of the above mentioned nodes. It has to be wrapped because otherwise
2325 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2326 // be used to form addressing mode. These wrapped nodes will be selected
2327 // into MOVi.
LowerConstantPool(SDValue Op,SelectionDAG & DAG)2328 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2329 EVT PtrVT = Op.getValueType();
2330 // FIXME there is no actual debug info here
2331 SDLoc dl(Op);
2332 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2333 SDValue Res;
2334 if (CP->isMachineConstantPoolEntry())
2335 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2336 CP->getAlignment());
2337 else
2338 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2339 CP->getAlignment());
2340 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2341 }
2342
getJumpTableEncoding() const2343 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2344 return MachineJumpTableInfo::EK_Inline;
2345 }
2346
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const2347 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2348 SelectionDAG &DAG) const {
2349 MachineFunction &MF = DAG.getMachineFunction();
2350 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2351 unsigned ARMPCLabelIndex = 0;
2352 SDLoc DL(Op);
2353 EVT PtrVT = getPointerTy();
2354 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2355 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2356 SDValue CPAddr;
2357 if (RelocM == Reloc::Static) {
2358 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2359 } else {
2360 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2361 ARMPCLabelIndex = AFI->createPICLabelUId();
2362 ARMConstantPoolValue *CPV =
2363 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2364 ARMCP::CPBlockAddress, PCAdj);
2365 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2366 }
2367 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2368 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2369 MachinePointerInfo::getConstantPool(),
2370 false, false, false, 0);
2371 if (RelocM == Reloc::Static)
2372 return Result;
2373 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2374 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2375 }
2376
2377 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2378 SDValue
LowerToTLSGeneralDynamicModel(GlobalAddressSDNode * GA,SelectionDAG & DAG) const2379 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2380 SelectionDAG &DAG) const {
2381 SDLoc dl(GA);
2382 EVT PtrVT = getPointerTy();
2383 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2384 MachineFunction &MF = DAG.getMachineFunction();
2385 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2386 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2387 ARMConstantPoolValue *CPV =
2388 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2389 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2390 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2391 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2392 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2393 MachinePointerInfo::getConstantPool(),
2394 false, false, false, 0);
2395 SDValue Chain = Argument.getValue(1);
2396
2397 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2398 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2399
2400 // call __tls_get_addr.
2401 ArgListTy Args;
2402 ArgListEntry Entry;
2403 Entry.Node = Argument;
2404 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2405 Args.push_back(Entry);
2406 // FIXME: is there useful debug info available here?
2407 TargetLowering::CallLoweringInfo CLI(Chain,
2408 (Type *) Type::getInt32Ty(*DAG.getContext()),
2409 false, false, false, false,
2410 0, CallingConv::C, /*isTailCall=*/false,
2411 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2412 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2413 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2414 return CallResult.first;
2415 }
2416
2417 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2418 // "local exec" model.
2419 SDValue
LowerToTLSExecModels(GlobalAddressSDNode * GA,SelectionDAG & DAG,TLSModel::Model model) const2420 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2421 SelectionDAG &DAG,
2422 TLSModel::Model model) const {
2423 const GlobalValue *GV = GA->getGlobal();
2424 SDLoc dl(GA);
2425 SDValue Offset;
2426 SDValue Chain = DAG.getEntryNode();
2427 EVT PtrVT = getPointerTy();
2428 // Get the Thread Pointer
2429 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2430
2431 if (model == TLSModel::InitialExec) {
2432 MachineFunction &MF = DAG.getMachineFunction();
2433 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2434 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2435 // Initial exec model.
2436 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2437 ARMConstantPoolValue *CPV =
2438 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2439 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2440 true);
2441 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2442 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2443 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2444 MachinePointerInfo::getConstantPool(),
2445 false, false, false, 0);
2446 Chain = Offset.getValue(1);
2447
2448 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2449 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2450
2451 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2452 MachinePointerInfo::getConstantPool(),
2453 false, false, false, 0);
2454 } else {
2455 // local exec model
2456 assert(model == TLSModel::LocalExec);
2457 ARMConstantPoolValue *CPV =
2458 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2459 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2460 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2461 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2462 MachinePointerInfo::getConstantPool(),
2463 false, false, false, 0);
2464 }
2465
2466 // The address of the thread local variable is the add of the thread
2467 // pointer with the offset of the variable.
2468 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2469 }
2470
2471 SDValue
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const2472 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2473 // TODO: implement the "local dynamic" model
2474 assert(Subtarget->isTargetELF() &&
2475 "TLS not implemented for non-ELF targets");
2476 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2477
2478 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2479
2480 switch (model) {
2481 case TLSModel::GeneralDynamic:
2482 case TLSModel::LocalDynamic:
2483 return LowerToTLSGeneralDynamicModel(GA, DAG);
2484 case TLSModel::InitialExec:
2485 case TLSModel::LocalExec:
2486 return LowerToTLSExecModels(GA, DAG, model);
2487 }
2488 llvm_unreachable("bogus TLS model");
2489 }
2490
LowerGlobalAddressELF(SDValue Op,SelectionDAG & DAG) const2491 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2492 SelectionDAG &DAG) const {
2493 EVT PtrVT = getPointerTy();
2494 SDLoc dl(Op);
2495 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2496 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2497 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2498 ARMConstantPoolValue *CPV =
2499 ARMConstantPoolConstant::Create(GV,
2500 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2501 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2502 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2503 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2504 CPAddr,
2505 MachinePointerInfo::getConstantPool(),
2506 false, false, false, 0);
2507 SDValue Chain = Result.getValue(1);
2508 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2509 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2510 if (!UseGOTOFF)
2511 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2512 MachinePointerInfo::getGOT(),
2513 false, false, false, 0);
2514 return Result;
2515 }
2516
2517 // If we have T2 ops, we can materialize the address directly via movt/movw
2518 // pair. This is always cheaper.
2519 if (Subtarget->useMovt()) {
2520 ++NumMovwMovt;
2521 // FIXME: Once remat is capable of dealing with instructions with register
2522 // operands, expand this into two nodes.
2523 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2524 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2525 } else {
2526 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2527 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2528 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2529 MachinePointerInfo::getConstantPool(),
2530 false, false, false, 0);
2531 }
2532 }
2533
LowerGlobalAddressDarwin(SDValue Op,SelectionDAG & DAG) const2534 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2535 SelectionDAG &DAG) const {
2536 EVT PtrVT = getPointerTy();
2537 SDLoc dl(Op);
2538 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2539 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2540
2541 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2542 // update ARMFastISel::ARMMaterializeGV.
2543 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2544 ++NumMovwMovt;
2545 // FIXME: Once remat is capable of dealing with instructions with register
2546 // operands, expand this into two nodes.
2547 if (RelocM == Reloc::Static)
2548 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2549 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2550
2551 unsigned Wrapper = (RelocM == Reloc::PIC_)
2552 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2553 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2554 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2555 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2556 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2557 MachinePointerInfo::getGOT(),
2558 false, false, false, 0);
2559 return Result;
2560 }
2561
2562 unsigned ARMPCLabelIndex = 0;
2563 SDValue CPAddr;
2564 if (RelocM == Reloc::Static) {
2565 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2566 } else {
2567 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2568 ARMPCLabelIndex = AFI->createPICLabelUId();
2569 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2570 ARMConstantPoolValue *CPV =
2571 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2572 PCAdj);
2573 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2574 }
2575 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2576
2577 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2578 MachinePointerInfo::getConstantPool(),
2579 false, false, false, 0);
2580 SDValue Chain = Result.getValue(1);
2581
2582 if (RelocM == Reloc::PIC_) {
2583 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2584 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2585 }
2586
2587 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2588 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2589 false, false, false, 0);
2590
2591 return Result;
2592 }
2593
LowerGLOBAL_OFFSET_TABLE(SDValue Op,SelectionDAG & DAG) const2594 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2595 SelectionDAG &DAG) const {
2596 assert(Subtarget->isTargetELF() &&
2597 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2598 MachineFunction &MF = DAG.getMachineFunction();
2599 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2600 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2601 EVT PtrVT = getPointerTy();
2602 SDLoc dl(Op);
2603 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2604 ARMConstantPoolValue *CPV =
2605 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2606 ARMPCLabelIndex, PCAdj);
2607 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2608 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2609 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2610 MachinePointerInfo::getConstantPool(),
2611 false, false, false, 0);
2612 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2613 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2614 }
2615
2616 SDValue
LowerEH_SJLJ_SETJMP(SDValue Op,SelectionDAG & DAG) const2617 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2618 SDLoc dl(Op);
2619 SDValue Val = DAG.getConstant(0, MVT::i32);
2620 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2621 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2622 Op.getOperand(1), Val);
2623 }
2624
2625 SDValue
LowerEH_SJLJ_LONGJMP(SDValue Op,SelectionDAG & DAG) const2626 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2627 SDLoc dl(Op);
2628 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2629 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2630 }
2631
2632 SDValue
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget) const2633 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2634 const ARMSubtarget *Subtarget) const {
2635 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2636 SDLoc dl(Op);
2637 switch (IntNo) {
2638 default: return SDValue(); // Don't custom lower most intrinsics.
2639 case Intrinsic::arm_thread_pointer: {
2640 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2641 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2642 }
2643 case Intrinsic::eh_sjlj_lsda: {
2644 MachineFunction &MF = DAG.getMachineFunction();
2645 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2646 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2647 EVT PtrVT = getPointerTy();
2648 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2649 SDValue CPAddr;
2650 unsigned PCAdj = (RelocM != Reloc::PIC_)
2651 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2652 ARMConstantPoolValue *CPV =
2653 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2654 ARMCP::CPLSDA, PCAdj);
2655 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2656 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2657 SDValue Result =
2658 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2659 MachinePointerInfo::getConstantPool(),
2660 false, false, false, 0);
2661
2662 if (RelocM == Reloc::PIC_) {
2663 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2664 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2665 }
2666 return Result;
2667 }
2668 case Intrinsic::arm_neon_vmulls:
2669 case Intrinsic::arm_neon_vmullu: {
2670 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2671 ? ARMISD::VMULLs : ARMISD::VMULLu;
2672 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2673 Op.getOperand(1), Op.getOperand(2));
2674 }
2675 }
2676 }
2677
LowerATOMIC_FENCE(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)2678 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2679 const ARMSubtarget *Subtarget) {
2680 // FIXME: handle "fence singlethread" more efficiently.
2681 SDLoc dl(Op);
2682 if (!Subtarget->hasDataBarrier()) {
2683 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2684 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2685 // here.
2686 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2687 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2688 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2689 DAG.getConstant(0, MVT::i32));
2690 }
2691
2692 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2693 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2694 unsigned Domain = ARM_MB::ISH;
2695 if (Subtarget->isMClass()) {
2696 // Only a full system barrier exists in the M-class architectures.
2697 Domain = ARM_MB::SY;
2698 } else if (Subtarget->isSwift() && Ord == Release) {
2699 // Swift happens to implement ISHST barriers in a way that's compatible with
2700 // Release semantics but weaker than ISH so we'd be fools not to use
2701 // it. Beware: other processors probably don't!
2702 Domain = ARM_MB::ISHST;
2703 }
2704
2705 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2706 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2707 DAG.getConstant(Domain, MVT::i32));
2708 }
2709
LowerPREFETCH(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)2710 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2711 const ARMSubtarget *Subtarget) {
2712 // ARM pre v5TE and Thumb1 does not have preload instructions.
2713 if (!(Subtarget->isThumb2() ||
2714 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2715 // Just preserve the chain.
2716 return Op.getOperand(0);
2717
2718 SDLoc dl(Op);
2719 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2720 if (!isRead &&
2721 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2722 // ARMv7 with MP extension has PLDW.
2723 return Op.getOperand(0);
2724
2725 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2726 if (Subtarget->isThumb()) {
2727 // Invert the bits.
2728 isRead = ~isRead & 1;
2729 isData = ~isData & 1;
2730 }
2731
2732 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2733 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2734 DAG.getConstant(isData, MVT::i32));
2735 }
2736
LowerVASTART(SDValue Op,SelectionDAG & DAG)2737 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2738 MachineFunction &MF = DAG.getMachineFunction();
2739 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2740
2741 // vastart just stores the address of the VarArgsFrameIndex slot into the
2742 // memory location argument.
2743 SDLoc dl(Op);
2744 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2745 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2746 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2747 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2748 MachinePointerInfo(SV), false, false, 0);
2749 }
2750
2751 SDValue
GetF64FormalArgument(CCValAssign & VA,CCValAssign & NextVA,SDValue & Root,SelectionDAG & DAG,SDLoc dl) const2752 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2753 SDValue &Root, SelectionDAG &DAG,
2754 SDLoc dl) const {
2755 MachineFunction &MF = DAG.getMachineFunction();
2756 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2757
2758 const TargetRegisterClass *RC;
2759 if (AFI->isThumb1OnlyFunction())
2760 RC = &ARM::tGPRRegClass;
2761 else
2762 RC = &ARM::GPRRegClass;
2763
2764 // Transform the arguments stored in physical registers into virtual ones.
2765 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2766 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2767
2768 SDValue ArgValue2;
2769 if (NextVA.isMemLoc()) {
2770 MachineFrameInfo *MFI = MF.getFrameInfo();
2771 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2772
2773 // Create load node to retrieve arguments from the stack.
2774 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2775 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2776 MachinePointerInfo::getFixedStack(FI),
2777 false, false, false, 0);
2778 } else {
2779 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2780 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2781 }
2782
2783 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2784 }
2785
2786 void
computeRegArea(CCState & CCInfo,MachineFunction & MF,unsigned InRegsParamRecordIdx,unsigned ArgSize,unsigned & ArgRegsSize,unsigned & ArgRegsSaveSize) const2787 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2788 unsigned InRegsParamRecordIdx,
2789 unsigned ArgSize,
2790 unsigned &ArgRegsSize,
2791 unsigned &ArgRegsSaveSize)
2792 const {
2793 unsigned NumGPRs;
2794 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2795 unsigned RBegin, REnd;
2796 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2797 NumGPRs = REnd - RBegin;
2798 } else {
2799 unsigned int firstUnalloced;
2800 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2801 sizeof(GPRArgRegs) /
2802 sizeof(GPRArgRegs[0]));
2803 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2804 }
2805
2806 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2807 ArgRegsSize = NumGPRs * 4;
2808
2809 // If parameter is split between stack and GPRs...
2810 if (NumGPRs && Align == 8 &&
2811 (ArgRegsSize < ArgSize ||
2812 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2813 // Add padding for part of param recovered from GPRs, so
2814 // its last byte must be at address K*8 - 1.
2815 // We need to do it, since remained (stack) part of parameter has
2816 // stack alignment, and we need to "attach" "GPRs head" without gaps
2817 // to it:
2818 // Stack:
2819 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2820 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2821 //
2822 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2823 unsigned Padding =
2824 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2825 (ArgRegsSize + AFI->getArgRegsSaveSize());
2826 ArgRegsSaveSize = ArgRegsSize + Padding;
2827 } else
2828 // We don't need to extend regs save size for byval parameters if they
2829 // are passed via GPRs only.
2830 ArgRegsSaveSize = ArgRegsSize;
2831 }
2832
2833 // The remaining GPRs hold either the beginning of variable-argument
2834 // data, or the beginning of an aggregate passed by value (usually
2835 // byval). Either way, we allocate stack slots adjacent to the data
2836 // provided by our caller, and store the unallocated registers there.
2837 // If this is a variadic function, the va_list pointer will begin with
2838 // these values; otherwise, this reassembles a (byval) structure that
2839 // was split between registers and memory.
2840 // Return: The frame index registers were stored into.
2841 int
StoreByValRegs(CCState & CCInfo,SelectionDAG & DAG,SDLoc dl,SDValue & Chain,const Value * OrigArg,unsigned InRegsParamRecordIdx,unsigned OffsetFromOrigArg,unsigned ArgOffset,unsigned ArgSize,bool ForceMutable) const2842 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2843 SDLoc dl, SDValue &Chain,
2844 const Value *OrigArg,
2845 unsigned InRegsParamRecordIdx,
2846 unsigned OffsetFromOrigArg,
2847 unsigned ArgOffset,
2848 unsigned ArgSize,
2849 bool ForceMutable) const {
2850
2851 // Currently, two use-cases possible:
2852 // Case #1. Non var-args function, and we meet first byval parameter.
2853 // Setup first unallocated register as first byval register;
2854 // eat all remained registers
2855 // (these two actions are performed by HandleByVal method).
2856 // Then, here, we initialize stack frame with
2857 // "store-reg" instructions.
2858 // Case #2. Var-args function, that doesn't contain byval parameters.
2859 // The same: eat all remained unallocated registers,
2860 // initialize stack frame.
2861
2862 MachineFunction &MF = DAG.getMachineFunction();
2863 MachineFrameInfo *MFI = MF.getFrameInfo();
2864 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2865 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2866 unsigned RBegin, REnd;
2867 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2868 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2869 firstRegToSaveIndex = RBegin - ARM::R0;
2870 lastRegToSaveIndex = REnd - ARM::R0;
2871 } else {
2872 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2873 (GPRArgRegs, array_lengthof(GPRArgRegs));
2874 lastRegToSaveIndex = 4;
2875 }
2876
2877 unsigned ArgRegsSize, ArgRegsSaveSize;
2878 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2879 ArgRegsSize, ArgRegsSaveSize);
2880
2881 // Store any by-val regs to their spots on the stack so that they may be
2882 // loaded by deferencing the result of formal parameter pointer or va_next.
2883 // Note: once stack area for byval/varargs registers
2884 // was initialized, it can't be initialized again.
2885 if (ArgRegsSaveSize) {
2886
2887 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2888
2889 if (Padding) {
2890 assert(AFI->getStoredByValParamsPadding() == 0 &&
2891 "The only parameter may be padded.");
2892 AFI->setStoredByValParamsPadding(Padding);
2893 }
2894
2895 int FrameIndex = MFI->CreateFixedObject(
2896 ArgRegsSaveSize,
2897 Padding + ArgOffset,
2898 false);
2899 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2900
2901 SmallVector<SDValue, 4> MemOps;
2902 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2903 ++firstRegToSaveIndex, ++i) {
2904 const TargetRegisterClass *RC;
2905 if (AFI->isThumb1OnlyFunction())
2906 RC = &ARM::tGPRRegClass;
2907 else
2908 RC = &ARM::GPRRegClass;
2909
2910 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2911 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2912 SDValue Store =
2913 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2914 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2915 false, false, 0);
2916 MemOps.push_back(Store);
2917 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2918 DAG.getConstant(4, getPointerTy()));
2919 }
2920
2921 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2922
2923 if (!MemOps.empty())
2924 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2925 &MemOps[0], MemOps.size());
2926 return FrameIndex;
2927 } else
2928 // This will point to the next argument passed via stack.
2929 return MFI->CreateFixedObject(
2930 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2931 }
2932
2933 // Setup stack frame, the va_list pointer will start from.
2934 void
VarArgStyleRegisters(CCState & CCInfo,SelectionDAG & DAG,SDLoc dl,SDValue & Chain,unsigned ArgOffset,bool ForceMutable) const2935 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2936 SDLoc dl, SDValue &Chain,
2937 unsigned ArgOffset,
2938 bool ForceMutable) const {
2939 MachineFunction &MF = DAG.getMachineFunction();
2940 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2941
2942 // Try to store any remaining integer argument regs
2943 // to their spots on the stack so that they may be loaded by deferencing
2944 // the result of va_next.
2945 // If there is no regs to be stored, just point address after last
2946 // argument passed via stack.
2947 int FrameIndex =
2948 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2949 0, ArgOffset, 0, ForceMutable);
2950
2951 AFI->setVarArgsFrameIndex(FrameIndex);
2952 }
2953
2954 SDValue
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,SDLoc dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const2955 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2956 CallingConv::ID CallConv, bool isVarArg,
2957 const SmallVectorImpl<ISD::InputArg>
2958 &Ins,
2959 SDLoc dl, SelectionDAG &DAG,
2960 SmallVectorImpl<SDValue> &InVals)
2961 const {
2962 MachineFunction &MF = DAG.getMachineFunction();
2963 MachineFrameInfo *MFI = MF.getFrameInfo();
2964
2965 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2966
2967 // Assign locations to all of the incoming arguments.
2968 SmallVector<CCValAssign, 16> ArgLocs;
2969 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2970 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2971 CCInfo.AnalyzeFormalArguments(Ins,
2972 CCAssignFnForNode(CallConv, /* Return*/ false,
2973 isVarArg));
2974
2975 SmallVector<SDValue, 16> ArgValues;
2976 int lastInsIndex = -1;
2977 SDValue ArgValue;
2978 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2979 unsigned CurArgIdx = 0;
2980
2981 // Initially ArgRegsSaveSize is zero.
2982 // Then we increase this value each time we meet byval parameter.
2983 // We also increase this value in case of varargs function.
2984 AFI->setArgRegsSaveSize(0);
2985
2986 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2987 CCValAssign &VA = ArgLocs[i];
2988 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2989 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2990 // Arguments stored in registers.
2991 if (VA.isRegLoc()) {
2992 EVT RegVT = VA.getLocVT();
2993
2994 if (VA.needsCustom()) {
2995 // f64 and vector types are split up into multiple registers or
2996 // combinations of registers and stack slots.
2997 if (VA.getLocVT() == MVT::v2f64) {
2998 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2999 Chain, DAG, dl);
3000 VA = ArgLocs[++i]; // skip ahead to next loc
3001 SDValue ArgValue2;
3002 if (VA.isMemLoc()) {
3003 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3004 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3005 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3006 MachinePointerInfo::getFixedStack(FI),
3007 false, false, false, 0);
3008 } else {
3009 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3010 Chain, DAG, dl);
3011 }
3012 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3013 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3014 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3015 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3016 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3017 } else
3018 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3019
3020 } else {
3021 const TargetRegisterClass *RC;
3022
3023 if (RegVT == MVT::f32)
3024 RC = &ARM::SPRRegClass;
3025 else if (RegVT == MVT::f64)
3026 RC = &ARM::DPRRegClass;
3027 else if (RegVT == MVT::v2f64)
3028 RC = &ARM::QPRRegClass;
3029 else if (RegVT == MVT::i32)
3030 RC = AFI->isThumb1OnlyFunction() ?
3031 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3032 (const TargetRegisterClass*)&ARM::GPRRegClass;
3033 else
3034 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3035
3036 // Transform the arguments in physical registers into virtual ones.
3037 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3038 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3039 }
3040
3041 // If this is an 8 or 16-bit value, it is really passed promoted
3042 // to 32 bits. Insert an assert[sz]ext to capture this, then
3043 // truncate to the right size.
3044 switch (VA.getLocInfo()) {
3045 default: llvm_unreachable("Unknown loc info!");
3046 case CCValAssign::Full: break;
3047 case CCValAssign::BCvt:
3048 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3049 break;
3050 case CCValAssign::SExt:
3051 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3052 DAG.getValueType(VA.getValVT()));
3053 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3054 break;
3055 case CCValAssign::ZExt:
3056 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3057 DAG.getValueType(VA.getValVT()));
3058 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3059 break;
3060 }
3061
3062 InVals.push_back(ArgValue);
3063
3064 } else { // VA.isRegLoc()
3065
3066 // sanity check
3067 assert(VA.isMemLoc());
3068 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3069
3070 int index = ArgLocs[i].getValNo();
3071
3072 // Some Ins[] entries become multiple ArgLoc[] entries.
3073 // Process them only once.
3074 if (index != lastInsIndex)
3075 {
3076 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3077 // FIXME: For now, all byval parameter objects are marked mutable.
3078 // This can be changed with more analysis.
3079 // In case of tail call optimization mark all arguments mutable.
3080 // Since they could be overwritten by lowering of arguments in case of
3081 // a tail call.
3082 if (Flags.isByVal()) {
3083 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3084 int FrameIndex = StoreByValRegs(
3085 CCInfo, DAG, dl, Chain, CurOrigArg,
3086 CurByValIndex,
3087 Ins[VA.getValNo()].PartOffset,
3088 VA.getLocMemOffset(),
3089 Flags.getByValSize(),
3090 true /*force mutable frames*/);
3091 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3092 CCInfo.nextInRegsParam();
3093 } else {
3094 unsigned FIOffset = VA.getLocMemOffset() +
3095 AFI->getStoredByValParamsPadding();
3096 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3097 FIOffset, true);
3098
3099 // Create load nodes to retrieve arguments from the stack.
3100 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3101 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3102 MachinePointerInfo::getFixedStack(FI),
3103 false, false, false, 0));
3104 }
3105 lastInsIndex = index;
3106 }
3107 }
3108 }
3109
3110 // varargs
3111 if (isVarArg)
3112 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3113 CCInfo.getNextStackOffset());
3114
3115 return Chain;
3116 }
3117
3118 /// isFloatingPointZero - Return true if this is +0.0.
isFloatingPointZero(SDValue Op)3119 static bool isFloatingPointZero(SDValue Op) {
3120 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3121 return CFP->getValueAPF().isPosZero();
3122 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3123 // Maybe this has already been legalized into the constant pool?
3124 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3125 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3126 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3127 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3128 return CFP->getValueAPF().isPosZero();
3129 }
3130 }
3131 return false;
3132 }
3133
3134 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3135 /// the given operands.
3136 SDValue
getARMCmp(SDValue LHS,SDValue RHS,ISD::CondCode CC,SDValue & ARMcc,SelectionDAG & DAG,SDLoc dl) const3137 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3138 SDValue &ARMcc, SelectionDAG &DAG,
3139 SDLoc dl) const {
3140 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3141 unsigned C = RHSC->getZExtValue();
3142 if (!isLegalICmpImmediate(C)) {
3143 // Constant does not fit, try adjusting it by one?
3144 switch (CC) {
3145 default: break;
3146 case ISD::SETLT:
3147 case ISD::SETGE:
3148 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3149 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3150 RHS = DAG.getConstant(C-1, MVT::i32);
3151 }
3152 break;
3153 case ISD::SETULT:
3154 case ISD::SETUGE:
3155 if (C != 0 && isLegalICmpImmediate(C-1)) {
3156 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3157 RHS = DAG.getConstant(C-1, MVT::i32);
3158 }
3159 break;
3160 case ISD::SETLE:
3161 case ISD::SETGT:
3162 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3163 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3164 RHS = DAG.getConstant(C+1, MVT::i32);
3165 }
3166 break;
3167 case ISD::SETULE:
3168 case ISD::SETUGT:
3169 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3170 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3171 RHS = DAG.getConstant(C+1, MVT::i32);
3172 }
3173 break;
3174 }
3175 }
3176 }
3177
3178 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3179 ARMISD::NodeType CompareType;
3180 switch (CondCode) {
3181 default:
3182 CompareType = ARMISD::CMP;
3183 break;
3184 case ARMCC::EQ:
3185 case ARMCC::NE:
3186 // Uses only Z Flag
3187 CompareType = ARMISD::CMPZ;
3188 break;
3189 }
3190 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3191 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3192 }
3193
3194 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3195 SDValue
getVFPCmp(SDValue LHS,SDValue RHS,SelectionDAG & DAG,SDLoc dl) const3196 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3197 SDLoc dl) const {
3198 SDValue Cmp;
3199 if (!isFloatingPointZero(RHS))
3200 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3201 else
3202 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3203 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3204 }
3205
3206 /// duplicateCmp - Glue values can have only one use, so this function
3207 /// duplicates a comparison node.
3208 SDValue
duplicateCmp(SDValue Cmp,SelectionDAG & DAG) const3209 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3210 unsigned Opc = Cmp.getOpcode();
3211 SDLoc DL(Cmp);
3212 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3213 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3214
3215 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3216 Cmp = Cmp.getOperand(0);
3217 Opc = Cmp.getOpcode();
3218 if (Opc == ARMISD::CMPFP)
3219 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3220 else {
3221 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3222 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3223 }
3224 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3225 }
3226
LowerSELECT(SDValue Op,SelectionDAG & DAG) const3227 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3228 SDValue Cond = Op.getOperand(0);
3229 SDValue SelectTrue = Op.getOperand(1);
3230 SDValue SelectFalse = Op.getOperand(2);
3231 SDLoc dl(Op);
3232
3233 // Convert:
3234 //
3235 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3236 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3237 //
3238 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3239 const ConstantSDNode *CMOVTrue =
3240 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3241 const ConstantSDNode *CMOVFalse =
3242 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3243
3244 if (CMOVTrue && CMOVFalse) {
3245 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3246 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3247
3248 SDValue True;
3249 SDValue False;
3250 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3251 True = SelectTrue;
3252 False = SelectFalse;
3253 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3254 True = SelectFalse;
3255 False = SelectTrue;
3256 }
3257
3258 if (True.getNode() && False.getNode()) {
3259 EVT VT = Op.getValueType();
3260 SDValue ARMcc = Cond.getOperand(2);
3261 SDValue CCR = Cond.getOperand(3);
3262 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3263 assert(True.getValueType() == VT);
3264 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3265 }
3266 }
3267 }
3268
3269 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3270 // undefined bits before doing a full-word comparison with zero.
3271 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3272 DAG.getConstant(1, Cond.getValueType()));
3273
3274 return DAG.getSelectCC(dl, Cond,
3275 DAG.getConstant(0, Cond.getValueType()),
3276 SelectTrue, SelectFalse, ISD::SETNE);
3277 }
3278
getInverseCCForVSEL(ISD::CondCode CC)3279 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3280 if (CC == ISD::SETNE)
3281 return ISD::SETEQ;
3282 return ISD::getSetCCSwappedOperands(CC);
3283 }
3284
checkVSELConstraints(ISD::CondCode CC,ARMCC::CondCodes & CondCode,bool & swpCmpOps,bool & swpVselOps)3285 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3286 bool &swpCmpOps, bool &swpVselOps) {
3287 // Start by selecting the GE condition code for opcodes that return true for
3288 // 'equality'
3289 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3290 CC == ISD::SETULE)
3291 CondCode = ARMCC::GE;
3292
3293 // and GT for opcodes that return false for 'equality'.
3294 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3295 CC == ISD::SETULT)
3296 CondCode = ARMCC::GT;
3297
3298 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3299 // to swap the compare operands.
3300 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3301 CC == ISD::SETULT)
3302 swpCmpOps = true;
3303
3304 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3305 // If we have an unordered opcode, we need to swap the operands to the VSEL
3306 // instruction (effectively negating the condition).
3307 //
3308 // This also has the effect of swapping which one of 'less' or 'greater'
3309 // returns true, so we also swap the compare operands. It also switches
3310 // whether we return true for 'equality', so we compensate by picking the
3311 // opposite condition code to our original choice.
3312 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3313 CC == ISD::SETUGT) {
3314 swpCmpOps = !swpCmpOps;
3315 swpVselOps = !swpVselOps;
3316 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3317 }
3318
3319 // 'ordered' is 'anything but unordered', so use the VS condition code and
3320 // swap the VSEL operands.
3321 if (CC == ISD::SETO) {
3322 CondCode = ARMCC::VS;
3323 swpVselOps = true;
3324 }
3325
3326 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3327 // code and swap the VSEL operands.
3328 if (CC == ISD::SETUNE) {
3329 CondCode = ARMCC::EQ;
3330 swpVselOps = true;
3331 }
3332 }
3333
LowerSELECT_CC(SDValue Op,SelectionDAG & DAG) const3334 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3335 EVT VT = Op.getValueType();
3336 SDValue LHS = Op.getOperand(0);
3337 SDValue RHS = Op.getOperand(1);
3338 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3339 SDValue TrueVal = Op.getOperand(2);
3340 SDValue FalseVal = Op.getOperand(3);
3341 SDLoc dl(Op);
3342
3343 if (LHS.getValueType() == MVT::i32) {
3344 // Try to generate VSEL on ARMv8.
3345 // The VSEL instruction can't use all the usual ARM condition
3346 // codes: it only has two bits to select the condition code, so it's
3347 // constrained to use only GE, GT, VS and EQ.
3348 //
3349 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3350 // swap the operands of the previous compare instruction (effectively
3351 // inverting the compare condition, swapping 'less' and 'greater') and
3352 // sometimes need to swap the operands to the VSEL (which inverts the
3353 // condition in the sense of firing whenever the previous condition didn't)
3354 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3355 TrueVal.getValueType() == MVT::f64)) {
3356 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3357 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3358 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3359 CC = getInverseCCForVSEL(CC);
3360 std::swap(TrueVal, FalseVal);
3361 }
3362 }
3363
3364 SDValue ARMcc;
3365 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3366 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3367 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3368 Cmp);
3369 }
3370
3371 ARMCC::CondCodes CondCode, CondCode2;
3372 FPCCToARMCC(CC, CondCode, CondCode2);
3373
3374 // Try to generate VSEL on ARMv8.
3375 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3376 TrueVal.getValueType() == MVT::f64)) {
3377 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3378 // same operands, as follows:
3379 // c = fcmp [ogt, olt, ugt, ult] a, b
3380 // select c, a, b
3381 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3382 // handled differently than the original code sequence.
3383 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3384 RHS == FalseVal) {
3385 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3386 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3387 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3388 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3389 }
3390
3391 bool swpCmpOps = false;
3392 bool swpVselOps = false;
3393 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3394
3395 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3396 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3397 if (swpCmpOps)
3398 std::swap(LHS, RHS);
3399 if (swpVselOps)
3400 std::swap(TrueVal, FalseVal);
3401 }
3402 }
3403
3404 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3405 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3406 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3407 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3408 ARMcc, CCR, Cmp);
3409 if (CondCode2 != ARMCC::AL) {
3410 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3411 // FIXME: Needs another CMP because flag can have but one use.
3412 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3413 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3414 Result, TrueVal, ARMcc2, CCR, Cmp2);
3415 }
3416 return Result;
3417 }
3418
3419 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3420 /// to morph to an integer compare sequence.
canChangeToInt(SDValue Op,bool & SeenZero,const ARMSubtarget * Subtarget)3421 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3422 const ARMSubtarget *Subtarget) {
3423 SDNode *N = Op.getNode();
3424 if (!N->hasOneUse())
3425 // Otherwise it requires moving the value from fp to integer registers.
3426 return false;
3427 if (!N->getNumValues())
3428 return false;
3429 EVT VT = Op.getValueType();
3430 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3431 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3432 // vmrs are very slow, e.g. cortex-a8.
3433 return false;
3434
3435 if (isFloatingPointZero(Op)) {
3436 SeenZero = true;
3437 return true;
3438 }
3439 return ISD::isNormalLoad(N);
3440 }
3441
bitcastf32Toi32(SDValue Op,SelectionDAG & DAG)3442 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3443 if (isFloatingPointZero(Op))
3444 return DAG.getConstant(0, MVT::i32);
3445
3446 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3447 return DAG.getLoad(MVT::i32, SDLoc(Op),
3448 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3449 Ld->isVolatile(), Ld->isNonTemporal(),
3450 Ld->isInvariant(), Ld->getAlignment());
3451
3452 llvm_unreachable("Unknown VFP cmp argument!");
3453 }
3454
expandf64Toi32(SDValue Op,SelectionDAG & DAG,SDValue & RetVal1,SDValue & RetVal2)3455 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3456 SDValue &RetVal1, SDValue &RetVal2) {
3457 if (isFloatingPointZero(Op)) {
3458 RetVal1 = DAG.getConstant(0, MVT::i32);
3459 RetVal2 = DAG.getConstant(0, MVT::i32);
3460 return;
3461 }
3462
3463 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3464 SDValue Ptr = Ld->getBasePtr();
3465 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3466 Ld->getChain(), Ptr,
3467 Ld->getPointerInfo(),
3468 Ld->isVolatile(), Ld->isNonTemporal(),
3469 Ld->isInvariant(), Ld->getAlignment());
3470
3471 EVT PtrType = Ptr.getValueType();
3472 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3473 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3474 PtrType, Ptr, DAG.getConstant(4, PtrType));
3475 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3476 Ld->getChain(), NewPtr,
3477 Ld->getPointerInfo().getWithOffset(4),
3478 Ld->isVolatile(), Ld->isNonTemporal(),
3479 Ld->isInvariant(), NewAlign);
3480 return;
3481 }
3482
3483 llvm_unreachable("Unknown VFP cmp argument!");
3484 }
3485
3486 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3487 /// f32 and even f64 comparisons to integer ones.
3488 SDValue
OptimizeVFPBrcond(SDValue Op,SelectionDAG & DAG) const3489 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3490 SDValue Chain = Op.getOperand(0);
3491 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3492 SDValue LHS = Op.getOperand(2);
3493 SDValue RHS = Op.getOperand(3);
3494 SDValue Dest = Op.getOperand(4);
3495 SDLoc dl(Op);
3496
3497 bool LHSSeenZero = false;
3498 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3499 bool RHSSeenZero = false;
3500 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3501 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3502 // If unsafe fp math optimization is enabled and there are no other uses of
3503 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3504 // to an integer comparison.
3505 if (CC == ISD::SETOEQ)
3506 CC = ISD::SETEQ;
3507 else if (CC == ISD::SETUNE)
3508 CC = ISD::SETNE;
3509
3510 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3511 SDValue ARMcc;
3512 if (LHS.getValueType() == MVT::f32) {
3513 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3514 bitcastf32Toi32(LHS, DAG), Mask);
3515 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3516 bitcastf32Toi32(RHS, DAG), Mask);
3517 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3518 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3519 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3520 Chain, Dest, ARMcc, CCR, Cmp);
3521 }
3522
3523 SDValue LHS1, LHS2;
3524 SDValue RHS1, RHS2;
3525 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3526 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3527 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3528 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3529 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3530 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3531 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3532 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3533 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3534 }
3535
3536 return SDValue();
3537 }
3538
LowerBR_CC(SDValue Op,SelectionDAG & DAG) const3539 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3540 SDValue Chain = Op.getOperand(0);
3541 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3542 SDValue LHS = Op.getOperand(2);
3543 SDValue RHS = Op.getOperand(3);
3544 SDValue Dest = Op.getOperand(4);
3545 SDLoc dl(Op);
3546
3547 if (LHS.getValueType() == MVT::i32) {
3548 SDValue ARMcc;
3549 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3550 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3551 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3552 Chain, Dest, ARMcc, CCR, Cmp);
3553 }
3554
3555 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3556
3557 if (getTargetMachine().Options.UnsafeFPMath &&
3558 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3559 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3560 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3561 if (Result.getNode())
3562 return Result;
3563 }
3564
3565 ARMCC::CondCodes CondCode, CondCode2;
3566 FPCCToARMCC(CC, CondCode, CondCode2);
3567
3568 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3569 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3570 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3571 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3572 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3573 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3574 if (CondCode2 != ARMCC::AL) {
3575 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3576 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3577 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3578 }
3579 return Res;
3580 }
3581
LowerBR_JT(SDValue Op,SelectionDAG & DAG) const3582 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3583 SDValue Chain = Op.getOperand(0);
3584 SDValue Table = Op.getOperand(1);
3585 SDValue Index = Op.getOperand(2);
3586 SDLoc dl(Op);
3587
3588 EVT PTy = getPointerTy();
3589 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3590 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3591 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3592 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3593 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3594 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3595 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3596 if (Subtarget->isThumb2()) {
3597 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3598 // which does another jump to the destination. This also makes it easier
3599 // to translate it to TBB / TBH later.
3600 // FIXME: This might not work if the function is extremely large.
3601 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3602 Addr, Op.getOperand(2), JTI, UId);
3603 }
3604 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3605 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3606 MachinePointerInfo::getJumpTable(),
3607 false, false, false, 0);
3608 Chain = Addr.getValue(1);
3609 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3610 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3611 } else {
3612 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3613 MachinePointerInfo::getJumpTable(),
3614 false, false, false, 0);
3615 Chain = Addr.getValue(1);
3616 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3617 }
3618 }
3619
LowerVectorFP_TO_INT(SDValue Op,SelectionDAG & DAG)3620 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3621 EVT VT = Op.getValueType();
3622 SDLoc dl(Op);
3623
3624 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3625 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3626 return Op;
3627 return DAG.UnrollVectorOp(Op.getNode());
3628 }
3629
3630 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3631 "Invalid type for custom lowering!");
3632 if (VT != MVT::v4i16)
3633 return DAG.UnrollVectorOp(Op.getNode());
3634
3635 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3636 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3637 }
3638
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG)3639 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3640 EVT VT = Op.getValueType();
3641 if (VT.isVector())
3642 return LowerVectorFP_TO_INT(Op, DAG);
3643
3644 SDLoc dl(Op);
3645 unsigned Opc;
3646
3647 switch (Op.getOpcode()) {
3648 default: llvm_unreachable("Invalid opcode!");
3649 case ISD::FP_TO_SINT:
3650 Opc = ARMISD::FTOSI;
3651 break;
3652 case ISD::FP_TO_UINT:
3653 Opc = ARMISD::FTOUI;
3654 break;
3655 }
3656 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3657 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3658 }
3659
LowerVectorINT_TO_FP(SDValue Op,SelectionDAG & DAG)3660 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3661 EVT VT = Op.getValueType();
3662 SDLoc dl(Op);
3663
3664 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3665 if (VT.getVectorElementType() == MVT::f32)
3666 return Op;
3667 return DAG.UnrollVectorOp(Op.getNode());
3668 }
3669
3670 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3671 "Invalid type for custom lowering!");
3672 if (VT != MVT::v4f32)
3673 return DAG.UnrollVectorOp(Op.getNode());
3674
3675 unsigned CastOpc;
3676 unsigned Opc;
3677 switch (Op.getOpcode()) {
3678 default: llvm_unreachable("Invalid opcode!");
3679 case ISD::SINT_TO_FP:
3680 CastOpc = ISD::SIGN_EXTEND;
3681 Opc = ISD::SINT_TO_FP;
3682 break;
3683 case ISD::UINT_TO_FP:
3684 CastOpc = ISD::ZERO_EXTEND;
3685 Opc = ISD::UINT_TO_FP;
3686 break;
3687 }
3688
3689 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3690 return DAG.getNode(Opc, dl, VT, Op);
3691 }
3692
LowerINT_TO_FP(SDValue Op,SelectionDAG & DAG)3693 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3694 EVT VT = Op.getValueType();
3695 if (VT.isVector())
3696 return LowerVectorINT_TO_FP(Op, DAG);
3697
3698 SDLoc dl(Op);
3699 unsigned Opc;
3700
3701 switch (Op.getOpcode()) {
3702 default: llvm_unreachable("Invalid opcode!");
3703 case ISD::SINT_TO_FP:
3704 Opc = ARMISD::SITOF;
3705 break;
3706 case ISD::UINT_TO_FP:
3707 Opc = ARMISD::UITOF;
3708 break;
3709 }
3710
3711 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3712 return DAG.getNode(Opc, dl, VT, Op);
3713 }
3714
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG) const3715 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3716 // Implement fcopysign with a fabs and a conditional fneg.
3717 SDValue Tmp0 = Op.getOperand(0);
3718 SDValue Tmp1 = Op.getOperand(1);
3719 SDLoc dl(Op);
3720 EVT VT = Op.getValueType();
3721 EVT SrcVT = Tmp1.getValueType();
3722 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3723 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3724 bool UseNEON = !InGPR && Subtarget->hasNEON();
3725
3726 if (UseNEON) {
3727 // Use VBSL to copy the sign bit.
3728 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3729 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3730 DAG.getTargetConstant(EncodedVal, MVT::i32));
3731 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3732 if (VT == MVT::f64)
3733 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3734 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3735 DAG.getConstant(32, MVT::i32));
3736 else /*if (VT == MVT::f32)*/
3737 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3738 if (SrcVT == MVT::f32) {
3739 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3740 if (VT == MVT::f64)
3741 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3742 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3743 DAG.getConstant(32, MVT::i32));
3744 } else if (VT == MVT::f32)
3745 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3746 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3747 DAG.getConstant(32, MVT::i32));
3748 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3749 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3750
3751 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3752 MVT::i32);
3753 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3754 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3755 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3756
3757 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3758 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3759 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3760 if (VT == MVT::f32) {
3761 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3762 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3763 DAG.getConstant(0, MVT::i32));
3764 } else {
3765 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3766 }
3767
3768 return Res;
3769 }
3770
3771 // Bitcast operand 1 to i32.
3772 if (SrcVT == MVT::f64)
3773 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3774 &Tmp1, 1).getValue(1);
3775 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3776
3777 // Or in the signbit with integer operations.
3778 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3779 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3780 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3781 if (VT == MVT::f32) {
3782 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3783 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3784 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3785 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3786 }
3787
3788 // f64: Or the high part with signbit and then combine two parts.
3789 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3790 &Tmp0, 1);
3791 SDValue Lo = Tmp0.getValue(0);
3792 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3793 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3794 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3795 }
3796
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const3797 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3798 MachineFunction &MF = DAG.getMachineFunction();
3799 MachineFrameInfo *MFI = MF.getFrameInfo();
3800 MFI->setReturnAddressIsTaken(true);
3801
3802 EVT VT = Op.getValueType();
3803 SDLoc dl(Op);
3804 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3805 if (Depth) {
3806 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3807 SDValue Offset = DAG.getConstant(4, MVT::i32);
3808 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3809 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3810 MachinePointerInfo(), false, false, false, 0);
3811 }
3812
3813 // Return LR, which contains the return address. Mark it an implicit live-in.
3814 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3815 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3816 }
3817
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const3818 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3819 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3820 MFI->setFrameAddressIsTaken(true);
3821
3822 EVT VT = Op.getValueType();
3823 SDLoc dl(Op); // FIXME probably not meaningful
3824 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3825 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3826 ? ARM::R7 : ARM::R11;
3827 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3828 while (Depth--)
3829 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3830 MachinePointerInfo(),
3831 false, false, false, 0);
3832 return FrameAddr;
3833 }
3834
3835 /// ExpandBITCAST - If the target supports VFP, this function is called to
3836 /// expand a bit convert where either the source or destination type is i64 to
3837 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3838 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3839 /// vectors), since the legalizer won't know what to do with that.
ExpandBITCAST(SDNode * N,SelectionDAG & DAG)3840 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3841 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3842 SDLoc dl(N);
3843 SDValue Op = N->getOperand(0);
3844
3845 // This function is only supposed to be called for i64 types, either as the
3846 // source or destination of the bit convert.
3847 EVT SrcVT = Op.getValueType();
3848 EVT DstVT = N->getValueType(0);
3849 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3850 "ExpandBITCAST called for non-i64 type");
3851
3852 // Turn i64->f64 into VMOVDRR.
3853 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3854 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3855 DAG.getConstant(0, MVT::i32));
3856 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3857 DAG.getConstant(1, MVT::i32));
3858 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3859 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3860 }
3861
3862 // Turn f64->i64 into VMOVRRD.
3863 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3864 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3865 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3866 // Merge the pieces into a single i64 value.
3867 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3868 }
3869
3870 return SDValue();
3871 }
3872
3873 /// getZeroVector - Returns a vector of specified type with all zero elements.
3874 /// Zero vectors are used to represent vector negation and in those cases
3875 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3876 /// not support i64 elements, so sometimes the zero vectors will need to be
3877 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3878 /// zero vector.
getZeroVector(EVT VT,SelectionDAG & DAG,SDLoc dl)3879 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3880 assert(VT.isVector() && "Expected a vector type");
3881 // The canonical modified immediate encoding of a zero vector is....0!
3882 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3883 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3884 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3885 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3886 }
3887
3888 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3889 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
LowerShiftRightParts(SDValue Op,SelectionDAG & DAG) const3890 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3891 SelectionDAG &DAG) const {
3892 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3893 EVT VT = Op.getValueType();
3894 unsigned VTBits = VT.getSizeInBits();
3895 SDLoc dl(Op);
3896 SDValue ShOpLo = Op.getOperand(0);
3897 SDValue ShOpHi = Op.getOperand(1);
3898 SDValue ShAmt = Op.getOperand(2);
3899 SDValue ARMcc;
3900 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3901
3902 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3903
3904 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3905 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3906 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3907 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3908 DAG.getConstant(VTBits, MVT::i32));
3909 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3910 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3911 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3912
3913 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3914 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3915 ARMcc, DAG, dl);
3916 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3917 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3918 CCR, Cmp);
3919
3920 SDValue Ops[2] = { Lo, Hi };
3921 return DAG.getMergeValues(Ops, 2, dl);
3922 }
3923
3924 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3925 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
LowerShiftLeftParts(SDValue Op,SelectionDAG & DAG) const3926 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3927 SelectionDAG &DAG) const {
3928 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3929 EVT VT = Op.getValueType();
3930 unsigned VTBits = VT.getSizeInBits();
3931 SDLoc dl(Op);
3932 SDValue ShOpLo = Op.getOperand(0);
3933 SDValue ShOpHi = Op.getOperand(1);
3934 SDValue ShAmt = Op.getOperand(2);
3935 SDValue ARMcc;
3936
3937 assert(Op.getOpcode() == ISD::SHL_PARTS);
3938 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3939 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3940 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3941 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3942 DAG.getConstant(VTBits, MVT::i32));
3943 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3944 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3945
3946 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3947 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3948 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3949 ARMcc, DAG, dl);
3950 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3951 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3952 CCR, Cmp);
3953
3954 SDValue Ops[2] = { Lo, Hi };
3955 return DAG.getMergeValues(Ops, 2, dl);
3956 }
3957
LowerFLT_ROUNDS_(SDValue Op,SelectionDAG & DAG) const3958 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3959 SelectionDAG &DAG) const {
3960 // The rounding mode is in bits 23:22 of the FPSCR.
3961 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3962 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3963 // so that the shift + and get folded into a bitfield extract.
3964 SDLoc dl(Op);
3965 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3966 DAG.getConstant(Intrinsic::arm_get_fpscr,
3967 MVT::i32));
3968 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3969 DAG.getConstant(1U << 22, MVT::i32));
3970 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3971 DAG.getConstant(22, MVT::i32));
3972 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3973 DAG.getConstant(3, MVT::i32));
3974 }
3975
LowerCTTZ(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)3976 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3977 const ARMSubtarget *ST) {
3978 EVT VT = N->getValueType(0);
3979 SDLoc dl(N);
3980
3981 if (!ST->hasV6T2Ops())
3982 return SDValue();
3983
3984 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3985 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3986 }
3987
3988 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3989 /// for each 16-bit element from operand, repeated. The basic idea is to
3990 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3991 ///
3992 /// Trace for v4i16:
3993 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3994 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3995 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3996 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3997 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3998 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3999 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4000 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
getCTPOP16BitCounts(SDNode * N,SelectionDAG & DAG)4001 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4002 EVT VT = N->getValueType(0);
4003 SDLoc DL(N);
4004
4005 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4006 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4007 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4008 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4009 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4010 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4011 }
4012
4013 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4014 /// bit-count for each 16-bit element from the operand. We need slightly
4015 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4016 /// 64/128-bit registers.
4017 ///
4018 /// Trace for v4i16:
4019 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4020 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4021 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4022 /// v4i16:Extracted = [k0 k1 k2 k3 ]
lowerCTPOP16BitElements(SDNode * N,SelectionDAG & DAG)4023 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4024 EVT VT = N->getValueType(0);
4025 SDLoc DL(N);
4026
4027 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4028 if (VT.is64BitVector()) {
4029 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4030 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4031 DAG.getIntPtrConstant(0));
4032 } else {
4033 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4034 BitCounts, DAG.getIntPtrConstant(0));
4035 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4036 }
4037 }
4038
4039 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4040 /// bit-count for each 32-bit element from the operand. The idea here is
4041 /// to split the vector into 16-bit elements, leverage the 16-bit count
4042 /// routine, and then combine the results.
4043 ///
4044 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4045 /// input = [v0 v1 ] (vi: 32-bit elements)
4046 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4047 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4048 /// vrev: N0 = [k1 k0 k3 k2 ]
4049 /// [k0 k1 k2 k3 ]
4050 /// N1 =+[k1 k0 k3 k2 ]
4051 /// [k0 k2 k1 k3 ]
4052 /// N2 =+[k1 k3 k0 k2 ]
4053 /// [k0 k2 k1 k3 ]
4054 /// Extended =+[k1 k3 k0 k2 ]
4055 /// [k0 k2 ]
4056 /// Extracted=+[k1 k3 ]
4057 ///
lowerCTPOP32BitElements(SDNode * N,SelectionDAG & DAG)4058 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4059 EVT VT = N->getValueType(0);
4060 SDLoc DL(N);
4061
4062 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4063
4064 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4065 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4066 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4067 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4068 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4069
4070 if (VT.is64BitVector()) {
4071 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4072 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4073 DAG.getIntPtrConstant(0));
4074 } else {
4075 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4076 DAG.getIntPtrConstant(0));
4077 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4078 }
4079 }
4080
LowerCTPOP(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)4081 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4082 const ARMSubtarget *ST) {
4083 EVT VT = N->getValueType(0);
4084
4085 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4086 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4087 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4088 "Unexpected type for custom ctpop lowering");
4089
4090 if (VT.getVectorElementType() == MVT::i32)
4091 return lowerCTPOP32BitElements(N, DAG);
4092 else
4093 return lowerCTPOP16BitElements(N, DAG);
4094 }
4095
LowerShift(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)4096 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4097 const ARMSubtarget *ST) {
4098 EVT VT = N->getValueType(0);
4099 SDLoc dl(N);
4100
4101 if (!VT.isVector())
4102 return SDValue();
4103
4104 // Lower vector shifts on NEON to use VSHL.
4105 assert(ST->hasNEON() && "unexpected vector shift");
4106
4107 // Left shifts translate directly to the vshiftu intrinsic.
4108 if (N->getOpcode() == ISD::SHL)
4109 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4110 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4111 N->getOperand(0), N->getOperand(1));
4112
4113 assert((N->getOpcode() == ISD::SRA ||
4114 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4115
4116 // NEON uses the same intrinsics for both left and right shifts. For
4117 // right shifts, the shift amounts are negative, so negate the vector of
4118 // shift amounts.
4119 EVT ShiftVT = N->getOperand(1).getValueType();
4120 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4121 getZeroVector(ShiftVT, DAG, dl),
4122 N->getOperand(1));
4123 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4124 Intrinsic::arm_neon_vshifts :
4125 Intrinsic::arm_neon_vshiftu);
4126 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4127 DAG.getConstant(vshiftInt, MVT::i32),
4128 N->getOperand(0), NegatedCount);
4129 }
4130
Expand64BitShift(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)4131 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4132 const ARMSubtarget *ST) {
4133 EVT VT = N->getValueType(0);
4134 SDLoc dl(N);
4135
4136 // We can get here for a node like i32 = ISD::SHL i32, i64
4137 if (VT != MVT::i64)
4138 return SDValue();
4139
4140 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4141 "Unknown shift to lower!");
4142
4143 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4144 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4145 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4146 return SDValue();
4147
4148 // If we are in thumb mode, we don't have RRX.
4149 if (ST->isThumb1Only()) return SDValue();
4150
4151 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4152 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4153 DAG.getConstant(0, MVT::i32));
4154 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4155 DAG.getConstant(1, MVT::i32));
4156
4157 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4158 // captures the result into a carry flag.
4159 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4160 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4161
4162 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4163 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4164
4165 // Merge the pieces into a single i64 value.
4166 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4167 }
4168
LowerVSETCC(SDValue Op,SelectionDAG & DAG)4169 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4170 SDValue TmpOp0, TmpOp1;
4171 bool Invert = false;
4172 bool Swap = false;
4173 unsigned Opc = 0;
4174
4175 SDValue Op0 = Op.getOperand(0);
4176 SDValue Op1 = Op.getOperand(1);
4177 SDValue CC = Op.getOperand(2);
4178 EVT VT = Op.getValueType();
4179 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4180 SDLoc dl(Op);
4181
4182 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4183 switch (SetCCOpcode) {
4184 default: llvm_unreachable("Illegal FP comparison");
4185 case ISD::SETUNE:
4186 case ISD::SETNE: Invert = true; // Fallthrough
4187 case ISD::SETOEQ:
4188 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4189 case ISD::SETOLT:
4190 case ISD::SETLT: Swap = true; // Fallthrough
4191 case ISD::SETOGT:
4192 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4193 case ISD::SETOLE:
4194 case ISD::SETLE: Swap = true; // Fallthrough
4195 case ISD::SETOGE:
4196 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4197 case ISD::SETUGE: Swap = true; // Fallthrough
4198 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4199 case ISD::SETUGT: Swap = true; // Fallthrough
4200 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4201 case ISD::SETUEQ: Invert = true; // Fallthrough
4202 case ISD::SETONE:
4203 // Expand this to (OLT | OGT).
4204 TmpOp0 = Op0;
4205 TmpOp1 = Op1;
4206 Opc = ISD::OR;
4207 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4208 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4209 break;
4210 case ISD::SETUO: Invert = true; // Fallthrough
4211 case ISD::SETO:
4212 // Expand this to (OLT | OGE).
4213 TmpOp0 = Op0;
4214 TmpOp1 = Op1;
4215 Opc = ISD::OR;
4216 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4217 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4218 break;
4219 }
4220 } else {
4221 // Integer comparisons.
4222 switch (SetCCOpcode) {
4223 default: llvm_unreachable("Illegal integer comparison");
4224 case ISD::SETNE: Invert = true;
4225 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4226 case ISD::SETLT: Swap = true;
4227 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4228 case ISD::SETLE: Swap = true;
4229 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4230 case ISD::SETULT: Swap = true;
4231 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4232 case ISD::SETULE: Swap = true;
4233 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4234 }
4235
4236 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4237 if (Opc == ARMISD::VCEQ) {
4238
4239 SDValue AndOp;
4240 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4241 AndOp = Op0;
4242 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4243 AndOp = Op1;
4244
4245 // Ignore bitconvert.
4246 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4247 AndOp = AndOp.getOperand(0);
4248
4249 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4250 Opc = ARMISD::VTST;
4251 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4252 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4253 Invert = !Invert;
4254 }
4255 }
4256 }
4257
4258 if (Swap)
4259 std::swap(Op0, Op1);
4260
4261 // If one of the operands is a constant vector zero, attempt to fold the
4262 // comparison to a specialized compare-against-zero form.
4263 SDValue SingleOp;
4264 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4265 SingleOp = Op0;
4266 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4267 if (Opc == ARMISD::VCGE)
4268 Opc = ARMISD::VCLEZ;
4269 else if (Opc == ARMISD::VCGT)
4270 Opc = ARMISD::VCLTZ;
4271 SingleOp = Op1;
4272 }
4273
4274 SDValue Result;
4275 if (SingleOp.getNode()) {
4276 switch (Opc) {
4277 case ARMISD::VCEQ:
4278 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4279 case ARMISD::VCGE:
4280 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4281 case ARMISD::VCLEZ:
4282 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4283 case ARMISD::VCGT:
4284 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4285 case ARMISD::VCLTZ:
4286 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4287 default:
4288 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4289 }
4290 } else {
4291 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4292 }
4293
4294 if (Invert)
4295 Result = DAG.getNOT(dl, Result, VT);
4296
4297 return Result;
4298 }
4299
4300 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4301 /// valid vector constant for a NEON instruction with a "modified immediate"
4302 /// operand (e.g., VMOV). If so, return the encoded value.
isNEONModifiedImm(uint64_t SplatBits,uint64_t SplatUndef,unsigned SplatBitSize,SelectionDAG & DAG,EVT & VT,bool is128Bits,NEONModImmType type)4303 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4304 unsigned SplatBitSize, SelectionDAG &DAG,
4305 EVT &VT, bool is128Bits, NEONModImmType type) {
4306 unsigned OpCmode, Imm;
4307
4308 // SplatBitSize is set to the smallest size that splats the vector, so a
4309 // zero vector will always have SplatBitSize == 8. However, NEON modified
4310 // immediate instructions others than VMOV do not support the 8-bit encoding
4311 // of a zero vector, and the default encoding of zero is supposed to be the
4312 // 32-bit version.
4313 if (SplatBits == 0)
4314 SplatBitSize = 32;
4315
4316 switch (SplatBitSize) {
4317 case 8:
4318 if (type != VMOVModImm)
4319 return SDValue();
4320 // Any 1-byte value is OK. Op=0, Cmode=1110.
4321 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4322 OpCmode = 0xe;
4323 Imm = SplatBits;
4324 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4325 break;
4326
4327 case 16:
4328 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4329 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4330 if ((SplatBits & ~0xff) == 0) {
4331 // Value = 0x00nn: Op=x, Cmode=100x.
4332 OpCmode = 0x8;
4333 Imm = SplatBits;
4334 break;
4335 }
4336 if ((SplatBits & ~0xff00) == 0) {
4337 // Value = 0xnn00: Op=x, Cmode=101x.
4338 OpCmode = 0xa;
4339 Imm = SplatBits >> 8;
4340 break;
4341 }
4342 return SDValue();
4343
4344 case 32:
4345 // NEON's 32-bit VMOV supports splat values where:
4346 // * only one byte is nonzero, or
4347 // * the least significant byte is 0xff and the second byte is nonzero, or
4348 // * the least significant 2 bytes are 0xff and the third is nonzero.
4349 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4350 if ((SplatBits & ~0xff) == 0) {
4351 // Value = 0x000000nn: Op=x, Cmode=000x.
4352 OpCmode = 0;
4353 Imm = SplatBits;
4354 break;
4355 }
4356 if ((SplatBits & ~0xff00) == 0) {
4357 // Value = 0x0000nn00: Op=x, Cmode=001x.
4358 OpCmode = 0x2;
4359 Imm = SplatBits >> 8;
4360 break;
4361 }
4362 if ((SplatBits & ~0xff0000) == 0) {
4363 // Value = 0x00nn0000: Op=x, Cmode=010x.
4364 OpCmode = 0x4;
4365 Imm = SplatBits >> 16;
4366 break;
4367 }
4368 if ((SplatBits & ~0xff000000) == 0) {
4369 // Value = 0xnn000000: Op=x, Cmode=011x.
4370 OpCmode = 0x6;
4371 Imm = SplatBits >> 24;
4372 break;
4373 }
4374
4375 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4376 if (type == OtherModImm) return SDValue();
4377
4378 if ((SplatBits & ~0xffff) == 0 &&
4379 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4380 // Value = 0x0000nnff: Op=x, Cmode=1100.
4381 OpCmode = 0xc;
4382 Imm = SplatBits >> 8;
4383 SplatBits |= 0xff;
4384 break;
4385 }
4386
4387 if ((SplatBits & ~0xffffff) == 0 &&
4388 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4389 // Value = 0x00nnffff: Op=x, Cmode=1101.
4390 OpCmode = 0xd;
4391 Imm = SplatBits >> 16;
4392 SplatBits |= 0xffff;
4393 break;
4394 }
4395
4396 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4397 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4398 // VMOV.I32. A (very) minor optimization would be to replicate the value
4399 // and fall through here to test for a valid 64-bit splat. But, then the
4400 // caller would also need to check and handle the change in size.
4401 return SDValue();
4402
4403 case 64: {
4404 if (type != VMOVModImm)
4405 return SDValue();
4406 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4407 uint64_t BitMask = 0xff;
4408 uint64_t Val = 0;
4409 unsigned ImmMask = 1;
4410 Imm = 0;
4411 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4412 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4413 Val |= BitMask;
4414 Imm |= ImmMask;
4415 } else if ((SplatBits & BitMask) != 0) {
4416 return SDValue();
4417 }
4418 BitMask <<= 8;
4419 ImmMask <<= 1;
4420 }
4421 // Op=1, Cmode=1110.
4422 OpCmode = 0x1e;
4423 SplatBits = Val;
4424 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4425 break;
4426 }
4427
4428 default:
4429 llvm_unreachable("unexpected size for isNEONModifiedImm");
4430 }
4431
4432 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4433 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4434 }
4435
LowerConstantFP(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST) const4436 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4437 const ARMSubtarget *ST) const {
4438 if (!ST->hasVFP3())
4439 return SDValue();
4440
4441 bool IsDouble = Op.getValueType() == MVT::f64;
4442 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4443
4444 // Try splatting with a VMOV.f32...
4445 APFloat FPVal = CFP->getValueAPF();
4446 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4447
4448 if (ImmVal != -1) {
4449 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4450 // We have code in place to select a valid ConstantFP already, no need to
4451 // do any mangling.
4452 return Op;
4453 }
4454
4455 // It's a float and we are trying to use NEON operations where
4456 // possible. Lower it to a splat followed by an extract.
4457 SDLoc DL(Op);
4458 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4459 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4460 NewVal);
4461 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4462 DAG.getConstant(0, MVT::i32));
4463 }
4464
4465 // The rest of our options are NEON only, make sure that's allowed before
4466 // proceeding..
4467 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4468 return SDValue();
4469
4470 EVT VMovVT;
4471 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4472
4473 // It wouldn't really be worth bothering for doubles except for one very
4474 // important value, which does happen to match: 0.0. So make sure we don't do
4475 // anything stupid.
4476 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4477 return SDValue();
4478
4479 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4480 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4481 false, VMOVModImm);
4482 if (NewVal != SDValue()) {
4483 SDLoc DL(Op);
4484 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4485 NewVal);
4486 if (IsDouble)
4487 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4488
4489 // It's a float: cast and extract a vector element.
4490 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4491 VecConstant);
4492 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4493 DAG.getConstant(0, MVT::i32));
4494 }
4495
4496 // Finally, try a VMVN.i32
4497 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4498 false, VMVNModImm);
4499 if (NewVal != SDValue()) {
4500 SDLoc DL(Op);
4501 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4502
4503 if (IsDouble)
4504 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4505
4506 // It's a float: cast and extract a vector element.
4507 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4508 VecConstant);
4509 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4510 DAG.getConstant(0, MVT::i32));
4511 }
4512
4513 return SDValue();
4514 }
4515
4516 // check if an VEXT instruction can handle the shuffle mask when the
4517 // vector sources of the shuffle are the same.
isSingletonVEXTMask(ArrayRef<int> M,EVT VT,unsigned & Imm)4518 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4519 unsigned NumElts = VT.getVectorNumElements();
4520
4521 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4522 if (M[0] < 0)
4523 return false;
4524
4525 Imm = M[0];
4526
4527 // If this is a VEXT shuffle, the immediate value is the index of the first
4528 // element. The other shuffle indices must be the successive elements after
4529 // the first one.
4530 unsigned ExpectedElt = Imm;
4531 for (unsigned i = 1; i < NumElts; ++i) {
4532 // Increment the expected index. If it wraps around, just follow it
4533 // back to index zero and keep going.
4534 ++ExpectedElt;
4535 if (ExpectedElt == NumElts)
4536 ExpectedElt = 0;
4537
4538 if (M[i] < 0) continue; // ignore UNDEF indices
4539 if (ExpectedElt != static_cast<unsigned>(M[i]))
4540 return false;
4541 }
4542
4543 return true;
4544 }
4545
4546
isVEXTMask(ArrayRef<int> M,EVT VT,bool & ReverseVEXT,unsigned & Imm)4547 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4548 bool &ReverseVEXT, unsigned &Imm) {
4549 unsigned NumElts = VT.getVectorNumElements();
4550 ReverseVEXT = false;
4551
4552 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4553 if (M[0] < 0)
4554 return false;
4555
4556 Imm = M[0];
4557
4558 // If this is a VEXT shuffle, the immediate value is the index of the first
4559 // element. The other shuffle indices must be the successive elements after
4560 // the first one.
4561 unsigned ExpectedElt = Imm;
4562 for (unsigned i = 1; i < NumElts; ++i) {
4563 // Increment the expected index. If it wraps around, it may still be
4564 // a VEXT but the source vectors must be swapped.
4565 ExpectedElt += 1;
4566 if (ExpectedElt == NumElts * 2) {
4567 ExpectedElt = 0;
4568 ReverseVEXT = true;
4569 }
4570
4571 if (M[i] < 0) continue; // ignore UNDEF indices
4572 if (ExpectedElt != static_cast<unsigned>(M[i]))
4573 return false;
4574 }
4575
4576 // Adjust the index value if the source operands will be swapped.
4577 if (ReverseVEXT)
4578 Imm -= NumElts;
4579
4580 return true;
4581 }
4582
4583 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4584 /// instruction with the specified blocksize. (The order of the elements
4585 /// within each block of the vector is reversed.)
isVREVMask(ArrayRef<int> M,EVT VT,unsigned BlockSize)4586 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4587 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4588 "Only possible block sizes for VREV are: 16, 32, 64");
4589
4590 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4591 if (EltSz == 64)
4592 return false;
4593
4594 unsigned NumElts = VT.getVectorNumElements();
4595 unsigned BlockElts = M[0] + 1;
4596 // If the first shuffle index is UNDEF, be optimistic.
4597 if (M[0] < 0)
4598 BlockElts = BlockSize / EltSz;
4599
4600 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4601 return false;
4602
4603 for (unsigned i = 0; i < NumElts; ++i) {
4604 if (M[i] < 0) continue; // ignore UNDEF indices
4605 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4606 return false;
4607 }
4608
4609 return true;
4610 }
4611
isVTBLMask(ArrayRef<int> M,EVT VT)4612 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4613 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4614 // range, then 0 is placed into the resulting vector. So pretty much any mask
4615 // of 8 elements can work here.
4616 return VT == MVT::v8i8 && M.size() == 8;
4617 }
4618
isVTRNMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4619 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4620 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4621 if (EltSz == 64)
4622 return false;
4623
4624 unsigned NumElts = VT.getVectorNumElements();
4625 WhichResult = (M[0] == 0 ? 0 : 1);
4626 for (unsigned i = 0; i < NumElts; i += 2) {
4627 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4628 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4629 return false;
4630 }
4631 return true;
4632 }
4633
4634 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4635 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4636 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
isVTRN_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4637 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4638 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4639 if (EltSz == 64)
4640 return false;
4641
4642 unsigned NumElts = VT.getVectorNumElements();
4643 WhichResult = (M[0] == 0 ? 0 : 1);
4644 for (unsigned i = 0; i < NumElts; i += 2) {
4645 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4646 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4647 return false;
4648 }
4649 return true;
4650 }
4651
isVUZPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4652 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4653 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4654 if (EltSz == 64)
4655 return false;
4656
4657 unsigned NumElts = VT.getVectorNumElements();
4658 WhichResult = (M[0] == 0 ? 0 : 1);
4659 for (unsigned i = 0; i != NumElts; ++i) {
4660 if (M[i] < 0) continue; // ignore UNDEF indices
4661 if ((unsigned) M[i] != 2 * i + WhichResult)
4662 return false;
4663 }
4664
4665 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4666 if (VT.is64BitVector() && EltSz == 32)
4667 return false;
4668
4669 return true;
4670 }
4671
4672 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4673 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4674 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
isVUZP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4675 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4676 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4677 if (EltSz == 64)
4678 return false;
4679
4680 unsigned Half = VT.getVectorNumElements() / 2;
4681 WhichResult = (M[0] == 0 ? 0 : 1);
4682 for (unsigned j = 0; j != 2; ++j) {
4683 unsigned Idx = WhichResult;
4684 for (unsigned i = 0; i != Half; ++i) {
4685 int MIdx = M[i + j * Half];
4686 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4687 return false;
4688 Idx += 2;
4689 }
4690 }
4691
4692 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4693 if (VT.is64BitVector() && EltSz == 32)
4694 return false;
4695
4696 return true;
4697 }
4698
isVZIPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4699 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4700 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4701 if (EltSz == 64)
4702 return false;
4703
4704 unsigned NumElts = VT.getVectorNumElements();
4705 WhichResult = (M[0] == 0 ? 0 : 1);
4706 unsigned Idx = WhichResult * NumElts / 2;
4707 for (unsigned i = 0; i != NumElts; i += 2) {
4708 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4709 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4710 return false;
4711 Idx += 1;
4712 }
4713
4714 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4715 if (VT.is64BitVector() && EltSz == 32)
4716 return false;
4717
4718 return true;
4719 }
4720
4721 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4722 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4723 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
isVZIP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)4724 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4725 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4726 if (EltSz == 64)
4727 return false;
4728
4729 unsigned NumElts = VT.getVectorNumElements();
4730 WhichResult = (M[0] == 0 ? 0 : 1);
4731 unsigned Idx = WhichResult * NumElts / 2;
4732 for (unsigned i = 0; i != NumElts; i += 2) {
4733 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4734 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4735 return false;
4736 Idx += 1;
4737 }
4738
4739 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4740 if (VT.is64BitVector() && EltSz == 32)
4741 return false;
4742
4743 return true;
4744 }
4745
4746 /// \return true if this is a reverse operation on an vector.
isReverseMask(ArrayRef<int> M,EVT VT)4747 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4748 unsigned NumElts = VT.getVectorNumElements();
4749 // Make sure the mask has the right size.
4750 if (NumElts != M.size())
4751 return false;
4752
4753 // Look for <15, ..., 3, -1, 1, 0>.
4754 for (unsigned i = 0; i != NumElts; ++i)
4755 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4756 return false;
4757
4758 return true;
4759 }
4760
4761 // If N is an integer constant that can be moved into a register in one
4762 // instruction, return an SDValue of such a constant (will become a MOV
4763 // instruction). Otherwise return null.
IsSingleInstrConstant(SDValue N,SelectionDAG & DAG,const ARMSubtarget * ST,SDLoc dl)4764 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4765 const ARMSubtarget *ST, SDLoc dl) {
4766 uint64_t Val;
4767 if (!isa<ConstantSDNode>(N))
4768 return SDValue();
4769 Val = cast<ConstantSDNode>(N)->getZExtValue();
4770
4771 if (ST->isThumb1Only()) {
4772 if (Val <= 255 || ~Val <= 255)
4773 return DAG.getConstant(Val, MVT::i32);
4774 } else {
4775 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4776 return DAG.getConstant(Val, MVT::i32);
4777 }
4778 return SDValue();
4779 }
4780
4781 // If this is a case we can't handle, return null and let the default
4782 // expansion code take care of it.
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST) const4783 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4784 const ARMSubtarget *ST) const {
4785 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4786 SDLoc dl(Op);
4787 EVT VT = Op.getValueType();
4788
4789 APInt SplatBits, SplatUndef;
4790 unsigned SplatBitSize;
4791 bool HasAnyUndefs;
4792 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4793 if (SplatBitSize <= 64) {
4794 // Check if an immediate VMOV works.
4795 EVT VmovVT;
4796 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4797 SplatUndef.getZExtValue(), SplatBitSize,
4798 DAG, VmovVT, VT.is128BitVector(),
4799 VMOVModImm);
4800 if (Val.getNode()) {
4801 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4802 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4803 }
4804
4805 // Try an immediate VMVN.
4806 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4807 Val = isNEONModifiedImm(NegatedImm,
4808 SplatUndef.getZExtValue(), SplatBitSize,
4809 DAG, VmovVT, VT.is128BitVector(),
4810 VMVNModImm);
4811 if (Val.getNode()) {
4812 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4813 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4814 }
4815
4816 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4817 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4818 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4819 if (ImmVal != -1) {
4820 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4821 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4822 }
4823 }
4824 }
4825 }
4826
4827 // Scan through the operands to see if only one value is used.
4828 //
4829 // As an optimisation, even if more than one value is used it may be more
4830 // profitable to splat with one value then change some lanes.
4831 //
4832 // Heuristically we decide to do this if the vector has a "dominant" value,
4833 // defined as splatted to more than half of the lanes.
4834 unsigned NumElts = VT.getVectorNumElements();
4835 bool isOnlyLowElement = true;
4836 bool usesOnlyOneValue = true;
4837 bool hasDominantValue = false;
4838 bool isConstant = true;
4839
4840 // Map of the number of times a particular SDValue appears in the
4841 // element list.
4842 DenseMap<SDValue, unsigned> ValueCounts;
4843 SDValue Value;
4844 for (unsigned i = 0; i < NumElts; ++i) {
4845 SDValue V = Op.getOperand(i);
4846 if (V.getOpcode() == ISD::UNDEF)
4847 continue;
4848 if (i > 0)
4849 isOnlyLowElement = false;
4850 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4851 isConstant = false;
4852
4853 ValueCounts.insert(std::make_pair(V, 0));
4854 unsigned &Count = ValueCounts[V];
4855
4856 // Is this value dominant? (takes up more than half of the lanes)
4857 if (++Count > (NumElts / 2)) {
4858 hasDominantValue = true;
4859 Value = V;
4860 }
4861 }
4862 if (ValueCounts.size() != 1)
4863 usesOnlyOneValue = false;
4864 if (!Value.getNode() && ValueCounts.size() > 0)
4865 Value = ValueCounts.begin()->first;
4866
4867 if (ValueCounts.size() == 0)
4868 return DAG.getUNDEF(VT);
4869
4870 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4871 // Keep going if we are hitting this case.
4872 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4873 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4874
4875 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4876
4877 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4878 // i32 and try again.
4879 if (hasDominantValue && EltSize <= 32) {
4880 if (!isConstant) {
4881 SDValue N;
4882
4883 // If we are VDUPing a value that comes directly from a vector, that will
4884 // cause an unnecessary move to and from a GPR, where instead we could
4885 // just use VDUPLANE. We can only do this if the lane being extracted
4886 // is at a constant index, as the VDUP from lane instructions only have
4887 // constant-index forms.
4888 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4889 isa<ConstantSDNode>(Value->getOperand(1))) {
4890 // We need to create a new undef vector to use for the VDUPLANE if the
4891 // size of the vector from which we get the value is different than the
4892 // size of the vector that we need to create. We will insert the element
4893 // such that the register coalescer will remove unnecessary copies.
4894 if (VT != Value->getOperand(0).getValueType()) {
4895 ConstantSDNode *constIndex;
4896 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4897 assert(constIndex && "The index is not a constant!");
4898 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4899 VT.getVectorNumElements();
4900 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4901 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4902 Value, DAG.getConstant(index, MVT::i32)),
4903 DAG.getConstant(index, MVT::i32));
4904 } else
4905 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4906 Value->getOperand(0), Value->getOperand(1));
4907 } else
4908 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4909
4910 if (!usesOnlyOneValue) {
4911 // The dominant value was splatted as 'N', but we now have to insert
4912 // all differing elements.
4913 for (unsigned I = 0; I < NumElts; ++I) {
4914 if (Op.getOperand(I) == Value)
4915 continue;
4916 SmallVector<SDValue, 3> Ops;
4917 Ops.push_back(N);
4918 Ops.push_back(Op.getOperand(I));
4919 Ops.push_back(DAG.getConstant(I, MVT::i32));
4920 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4921 }
4922 }
4923 return N;
4924 }
4925 if (VT.getVectorElementType().isFloatingPoint()) {
4926 SmallVector<SDValue, 8> Ops;
4927 for (unsigned i = 0; i < NumElts; ++i)
4928 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4929 Op.getOperand(i)));
4930 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4931 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4932 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4933 if (Val.getNode())
4934 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4935 }
4936 if (usesOnlyOneValue) {
4937 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4938 if (isConstant && Val.getNode())
4939 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4940 }
4941 }
4942
4943 // If all elements are constants and the case above didn't get hit, fall back
4944 // to the default expansion, which will generate a load from the constant
4945 // pool.
4946 if (isConstant)
4947 return SDValue();
4948
4949 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4950 if (NumElts >= 4) {
4951 SDValue shuffle = ReconstructShuffle(Op, DAG);
4952 if (shuffle != SDValue())
4953 return shuffle;
4954 }
4955
4956 // Vectors with 32- or 64-bit elements can be built by directly assigning
4957 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4958 // will be legalized.
4959 if (EltSize >= 32) {
4960 // Do the expansion with floating-point types, since that is what the VFP
4961 // registers are defined to use, and since i64 is not legal.
4962 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4963 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4964 SmallVector<SDValue, 8> Ops;
4965 for (unsigned i = 0; i < NumElts; ++i)
4966 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4967 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4968 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4969 }
4970
4971 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4972 // know the default expansion would otherwise fall back on something even
4973 // worse. For a vector with one or two non-undef values, that's
4974 // scalar_to_vector for the elements followed by a shuffle (provided the
4975 // shuffle is valid for the target) and materialization element by element
4976 // on the stack followed by a load for everything else.
4977 if (!isConstant && !usesOnlyOneValue) {
4978 SDValue Vec = DAG.getUNDEF(VT);
4979 for (unsigned i = 0 ; i < NumElts; ++i) {
4980 SDValue V = Op.getOperand(i);
4981 if (V.getOpcode() == ISD::UNDEF)
4982 continue;
4983 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4984 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4985 }
4986 return Vec;
4987 }
4988
4989 return SDValue();
4990 }
4991
4992 // Gather data to see if the operation can be modelled as a
4993 // shuffle in combination with VEXTs.
ReconstructShuffle(SDValue Op,SelectionDAG & DAG) const4994 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4995 SelectionDAG &DAG) const {
4996 SDLoc dl(Op);
4997 EVT VT = Op.getValueType();
4998 unsigned NumElts = VT.getVectorNumElements();
4999
5000 SmallVector<SDValue, 2> SourceVecs;
5001 SmallVector<unsigned, 2> MinElts;
5002 SmallVector<unsigned, 2> MaxElts;
5003
5004 for (unsigned i = 0; i < NumElts; ++i) {
5005 SDValue V = Op.getOperand(i);
5006 if (V.getOpcode() == ISD::UNDEF)
5007 continue;
5008 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5009 // A shuffle can only come from building a vector from various
5010 // elements of other vectors.
5011 return SDValue();
5012 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5013 VT.getVectorElementType()) {
5014 // This code doesn't know how to handle shuffles where the vector
5015 // element types do not match (this happens because type legalization
5016 // promotes the return type of EXTRACT_VECTOR_ELT).
5017 // FIXME: It might be appropriate to extend this code to handle
5018 // mismatched types.
5019 return SDValue();
5020 }
5021
5022 // Record this extraction against the appropriate vector if possible...
5023 SDValue SourceVec = V.getOperand(0);
5024 // If the element number isn't a constant, we can't effectively
5025 // analyze what's going on.
5026 if (!isa<ConstantSDNode>(V.getOperand(1)))
5027 return SDValue();
5028 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5029 bool FoundSource = false;
5030 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5031 if (SourceVecs[j] == SourceVec) {
5032 if (MinElts[j] > EltNo)
5033 MinElts[j] = EltNo;
5034 if (MaxElts[j] < EltNo)
5035 MaxElts[j] = EltNo;
5036 FoundSource = true;
5037 break;
5038 }
5039 }
5040
5041 // Or record a new source if not...
5042 if (!FoundSource) {
5043 SourceVecs.push_back(SourceVec);
5044 MinElts.push_back(EltNo);
5045 MaxElts.push_back(EltNo);
5046 }
5047 }
5048
5049 // Currently only do something sane when at most two source vectors
5050 // involved.
5051 if (SourceVecs.size() > 2)
5052 return SDValue();
5053
5054 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5055 int VEXTOffsets[2] = {0, 0};
5056
5057 // This loop extracts the usage patterns of the source vectors
5058 // and prepares appropriate SDValues for a shuffle if possible.
5059 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5060 if (SourceVecs[i].getValueType() == VT) {
5061 // No VEXT necessary
5062 ShuffleSrcs[i] = SourceVecs[i];
5063 VEXTOffsets[i] = 0;
5064 continue;
5065 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5066 // It probably isn't worth padding out a smaller vector just to
5067 // break it down again in a shuffle.
5068 return SDValue();
5069 }
5070
5071 // Since only 64-bit and 128-bit vectors are legal on ARM and
5072 // we've eliminated the other cases...
5073 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5074 "unexpected vector sizes in ReconstructShuffle");
5075
5076 if (MaxElts[i] - MinElts[i] >= NumElts) {
5077 // Span too large for a VEXT to cope
5078 return SDValue();
5079 }
5080
5081 if (MinElts[i] >= NumElts) {
5082 // The extraction can just take the second half
5083 VEXTOffsets[i] = NumElts;
5084 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5085 SourceVecs[i],
5086 DAG.getIntPtrConstant(NumElts));
5087 } else if (MaxElts[i] < NumElts) {
5088 // The extraction can just take the first half
5089 VEXTOffsets[i] = 0;
5090 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5091 SourceVecs[i],
5092 DAG.getIntPtrConstant(0));
5093 } else {
5094 // An actual VEXT is needed
5095 VEXTOffsets[i] = MinElts[i];
5096 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5097 SourceVecs[i],
5098 DAG.getIntPtrConstant(0));
5099 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5100 SourceVecs[i],
5101 DAG.getIntPtrConstant(NumElts));
5102 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5103 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5104 }
5105 }
5106
5107 SmallVector<int, 8> Mask;
5108
5109 for (unsigned i = 0; i < NumElts; ++i) {
5110 SDValue Entry = Op.getOperand(i);
5111 if (Entry.getOpcode() == ISD::UNDEF) {
5112 Mask.push_back(-1);
5113 continue;
5114 }
5115
5116 SDValue ExtractVec = Entry.getOperand(0);
5117 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5118 .getOperand(1))->getSExtValue();
5119 if (ExtractVec == SourceVecs[0]) {
5120 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5121 } else {
5122 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5123 }
5124 }
5125
5126 // Final check before we try to produce nonsense...
5127 if (isShuffleMaskLegal(Mask, VT))
5128 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5129 &Mask[0]);
5130
5131 return SDValue();
5132 }
5133
5134 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5135 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5136 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5137 /// are assumed to be legal.
5138 bool
isShuffleMaskLegal(const SmallVectorImpl<int> & M,EVT VT) const5139 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5140 EVT VT) const {
5141 if (VT.getVectorNumElements() == 4 &&
5142 (VT.is128BitVector() || VT.is64BitVector())) {
5143 unsigned PFIndexes[4];
5144 for (unsigned i = 0; i != 4; ++i) {
5145 if (M[i] < 0)
5146 PFIndexes[i] = 8;
5147 else
5148 PFIndexes[i] = M[i];
5149 }
5150
5151 // Compute the index in the perfect shuffle table.
5152 unsigned PFTableIndex =
5153 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5154 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5155 unsigned Cost = (PFEntry >> 30);
5156
5157 if (Cost <= 4)
5158 return true;
5159 }
5160
5161 bool ReverseVEXT;
5162 unsigned Imm, WhichResult;
5163
5164 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5165 return (EltSize >= 32 ||
5166 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5167 isVREVMask(M, VT, 64) ||
5168 isVREVMask(M, VT, 32) ||
5169 isVREVMask(M, VT, 16) ||
5170 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5171 isVTBLMask(M, VT) ||
5172 isVTRNMask(M, VT, WhichResult) ||
5173 isVUZPMask(M, VT, WhichResult) ||
5174 isVZIPMask(M, VT, WhichResult) ||
5175 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5176 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5177 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5178 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5179 }
5180
5181 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5182 /// the specified operations to build the shuffle.
GeneratePerfectShuffle(unsigned PFEntry,SDValue LHS,SDValue RHS,SelectionDAG & DAG,SDLoc dl)5183 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5184 SDValue RHS, SelectionDAG &DAG,
5185 SDLoc dl) {
5186 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5187 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5188 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5189
5190 enum {
5191 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5192 OP_VREV,
5193 OP_VDUP0,
5194 OP_VDUP1,
5195 OP_VDUP2,
5196 OP_VDUP3,
5197 OP_VEXT1,
5198 OP_VEXT2,
5199 OP_VEXT3,
5200 OP_VUZPL, // VUZP, left result
5201 OP_VUZPR, // VUZP, right result
5202 OP_VZIPL, // VZIP, left result
5203 OP_VZIPR, // VZIP, right result
5204 OP_VTRNL, // VTRN, left result
5205 OP_VTRNR // VTRN, right result
5206 };
5207
5208 if (OpNum == OP_COPY) {
5209 if (LHSID == (1*9+2)*9+3) return LHS;
5210 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5211 return RHS;
5212 }
5213
5214 SDValue OpLHS, OpRHS;
5215 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5216 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5217 EVT VT = OpLHS.getValueType();
5218
5219 switch (OpNum) {
5220 default: llvm_unreachable("Unknown shuffle opcode!");
5221 case OP_VREV:
5222 // VREV divides the vector in half and swaps within the half.
5223 if (VT.getVectorElementType() == MVT::i32 ||
5224 VT.getVectorElementType() == MVT::f32)
5225 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5226 // vrev <4 x i16> -> VREV32
5227 if (VT.getVectorElementType() == MVT::i16)
5228 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5229 // vrev <4 x i8> -> VREV16
5230 assert(VT.getVectorElementType() == MVT::i8);
5231 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5232 case OP_VDUP0:
5233 case OP_VDUP1:
5234 case OP_VDUP2:
5235 case OP_VDUP3:
5236 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5237 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5238 case OP_VEXT1:
5239 case OP_VEXT2:
5240 case OP_VEXT3:
5241 return DAG.getNode(ARMISD::VEXT, dl, VT,
5242 OpLHS, OpRHS,
5243 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5244 case OP_VUZPL:
5245 case OP_VUZPR:
5246 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5247 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5248 case OP_VZIPL:
5249 case OP_VZIPR:
5250 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5251 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5252 case OP_VTRNL:
5253 case OP_VTRNR:
5254 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5255 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5256 }
5257 }
5258
LowerVECTOR_SHUFFLEv8i8(SDValue Op,ArrayRef<int> ShuffleMask,SelectionDAG & DAG)5259 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5260 ArrayRef<int> ShuffleMask,
5261 SelectionDAG &DAG) {
5262 // Check to see if we can use the VTBL instruction.
5263 SDValue V1 = Op.getOperand(0);
5264 SDValue V2 = Op.getOperand(1);
5265 SDLoc DL(Op);
5266
5267 SmallVector<SDValue, 8> VTBLMask;
5268 for (ArrayRef<int>::iterator
5269 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5270 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5271
5272 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5273 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5274 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5275 &VTBLMask[0], 8));
5276
5277 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5278 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5279 &VTBLMask[0], 8));
5280 }
5281
LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,SelectionDAG & DAG)5282 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5283 SelectionDAG &DAG) {
5284 SDLoc DL(Op);
5285 SDValue OpLHS = Op.getOperand(0);
5286 EVT VT = OpLHS.getValueType();
5287
5288 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5289 "Expect an v8i16/v16i8 type");
5290 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5291 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5292 // extract the first 8 bytes into the top double word and the last 8 bytes
5293 // into the bottom double word. The v8i16 case is similar.
5294 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5295 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5296 DAG.getConstant(ExtractNum, MVT::i32));
5297 }
5298
LowerVECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG)5299 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5300 SDValue V1 = Op.getOperand(0);
5301 SDValue V2 = Op.getOperand(1);
5302 SDLoc dl(Op);
5303 EVT VT = Op.getValueType();
5304 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5305
5306 // Convert shuffles that are directly supported on NEON to target-specific
5307 // DAG nodes, instead of keeping them as shuffles and matching them again
5308 // during code selection. This is more efficient and avoids the possibility
5309 // of inconsistencies between legalization and selection.
5310 // FIXME: floating-point vectors should be canonicalized to integer vectors
5311 // of the same time so that they get CSEd properly.
5312 ArrayRef<int> ShuffleMask = SVN->getMask();
5313
5314 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5315 if (EltSize <= 32) {
5316 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5317 int Lane = SVN->getSplatIndex();
5318 // If this is undef splat, generate it via "just" vdup, if possible.
5319 if (Lane == -1) Lane = 0;
5320
5321 // Test if V1 is a SCALAR_TO_VECTOR.
5322 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5323 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5324 }
5325 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5326 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5327 // reaches it).
5328 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5329 !isa<ConstantSDNode>(V1.getOperand(0))) {
5330 bool IsScalarToVector = true;
5331 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5332 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5333 IsScalarToVector = false;
5334 break;
5335 }
5336 if (IsScalarToVector)
5337 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5338 }
5339 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5340 DAG.getConstant(Lane, MVT::i32));
5341 }
5342
5343 bool ReverseVEXT;
5344 unsigned Imm;
5345 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5346 if (ReverseVEXT)
5347 std::swap(V1, V2);
5348 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5349 DAG.getConstant(Imm, MVT::i32));
5350 }
5351
5352 if (isVREVMask(ShuffleMask, VT, 64))
5353 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5354 if (isVREVMask(ShuffleMask, VT, 32))
5355 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5356 if (isVREVMask(ShuffleMask, VT, 16))
5357 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5358
5359 if (V2->getOpcode() == ISD::UNDEF &&
5360 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5361 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5362 DAG.getConstant(Imm, MVT::i32));
5363 }
5364
5365 // Check for Neon shuffles that modify both input vectors in place.
5366 // If both results are used, i.e., if there are two shuffles with the same
5367 // source operands and with masks corresponding to both results of one of
5368 // these operations, DAG memoization will ensure that a single node is
5369 // used for both shuffles.
5370 unsigned WhichResult;
5371 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5372 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5373 V1, V2).getValue(WhichResult);
5374 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5375 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5376 V1, V2).getValue(WhichResult);
5377 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5378 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5379 V1, V2).getValue(WhichResult);
5380
5381 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5382 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5383 V1, V1).getValue(WhichResult);
5384 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5385 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5386 V1, V1).getValue(WhichResult);
5387 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5388 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5389 V1, V1).getValue(WhichResult);
5390 }
5391
5392 // If the shuffle is not directly supported and it has 4 elements, use
5393 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5394 unsigned NumElts = VT.getVectorNumElements();
5395 if (NumElts == 4) {
5396 unsigned PFIndexes[4];
5397 for (unsigned i = 0; i != 4; ++i) {
5398 if (ShuffleMask[i] < 0)
5399 PFIndexes[i] = 8;
5400 else
5401 PFIndexes[i] = ShuffleMask[i];
5402 }
5403
5404 // Compute the index in the perfect shuffle table.
5405 unsigned PFTableIndex =
5406 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5407 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5408 unsigned Cost = (PFEntry >> 30);
5409
5410 if (Cost <= 4)
5411 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5412 }
5413
5414 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5415 if (EltSize >= 32) {
5416 // Do the expansion with floating-point types, since that is what the VFP
5417 // registers are defined to use, and since i64 is not legal.
5418 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5419 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5420 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5421 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5422 SmallVector<SDValue, 8> Ops;
5423 for (unsigned i = 0; i < NumElts; ++i) {
5424 if (ShuffleMask[i] < 0)
5425 Ops.push_back(DAG.getUNDEF(EltVT));
5426 else
5427 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5428 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5429 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5430 MVT::i32)));
5431 }
5432 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5433 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5434 }
5435
5436 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5437 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5438
5439 if (VT == MVT::v8i8) {
5440 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5441 if (NewOp.getNode())
5442 return NewOp;
5443 }
5444
5445 return SDValue();
5446 }
5447
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG)5448 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5449 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5450 SDValue Lane = Op.getOperand(2);
5451 if (!isa<ConstantSDNode>(Lane))
5452 return SDValue();
5453
5454 return Op;
5455 }
5456
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG)5457 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5458 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5459 SDValue Lane = Op.getOperand(1);
5460 if (!isa<ConstantSDNode>(Lane))
5461 return SDValue();
5462
5463 SDValue Vec = Op.getOperand(0);
5464 if (Op.getValueType() == MVT::i32 &&
5465 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5466 SDLoc dl(Op);
5467 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5468 }
5469
5470 return Op;
5471 }
5472
LowerCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG)5473 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5474 // The only time a CONCAT_VECTORS operation can have legal types is when
5475 // two 64-bit vectors are concatenated to a 128-bit vector.
5476 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5477 "unexpected CONCAT_VECTORS");
5478 SDLoc dl(Op);
5479 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5480 SDValue Op0 = Op.getOperand(0);
5481 SDValue Op1 = Op.getOperand(1);
5482 if (Op0.getOpcode() != ISD::UNDEF)
5483 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5484 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5485 DAG.getIntPtrConstant(0));
5486 if (Op1.getOpcode() != ISD::UNDEF)
5487 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5488 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5489 DAG.getIntPtrConstant(1));
5490 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5491 }
5492
5493 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5494 /// element has been zero/sign-extended, depending on the isSigned parameter,
5495 /// from an integer type half its size.
isExtendedBUILD_VECTOR(SDNode * N,SelectionDAG & DAG,bool isSigned)5496 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5497 bool isSigned) {
5498 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5499 EVT VT = N->getValueType(0);
5500 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5501 SDNode *BVN = N->getOperand(0).getNode();
5502 if (BVN->getValueType(0) != MVT::v4i32 ||
5503 BVN->getOpcode() != ISD::BUILD_VECTOR)
5504 return false;
5505 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5506 unsigned HiElt = 1 - LoElt;
5507 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5508 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5509 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5510 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5511 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5512 return false;
5513 if (isSigned) {
5514 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5515 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5516 return true;
5517 } else {
5518 if (Hi0->isNullValue() && Hi1->isNullValue())
5519 return true;
5520 }
5521 return false;
5522 }
5523
5524 if (N->getOpcode() != ISD::BUILD_VECTOR)
5525 return false;
5526
5527 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5528 SDNode *Elt = N->getOperand(i).getNode();
5529 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5530 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5531 unsigned HalfSize = EltSize / 2;
5532 if (isSigned) {
5533 if (!isIntN(HalfSize, C->getSExtValue()))
5534 return false;
5535 } else {
5536 if (!isUIntN(HalfSize, C->getZExtValue()))
5537 return false;
5538 }
5539 continue;
5540 }
5541 return false;
5542 }
5543
5544 return true;
5545 }
5546
5547 /// isSignExtended - Check if a node is a vector value that is sign-extended
5548 /// or a constant BUILD_VECTOR with sign-extended elements.
isSignExtended(SDNode * N,SelectionDAG & DAG)5549 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5550 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5551 return true;
5552 if (isExtendedBUILD_VECTOR(N, DAG, true))
5553 return true;
5554 return false;
5555 }
5556
5557 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5558 /// or a constant BUILD_VECTOR with zero-extended elements.
isZeroExtended(SDNode * N,SelectionDAG & DAG)5559 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5560 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5561 return true;
5562 if (isExtendedBUILD_VECTOR(N, DAG, false))
5563 return true;
5564 return false;
5565 }
5566
getExtensionTo64Bits(const EVT & OrigVT)5567 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5568 if (OrigVT.getSizeInBits() >= 64)
5569 return OrigVT;
5570
5571 assert(OrigVT.isSimple() && "Expecting a simple value type");
5572
5573 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5574 switch (OrigSimpleTy) {
5575 default: llvm_unreachable("Unexpected Vector Type");
5576 case MVT::v2i8:
5577 case MVT::v2i16:
5578 return MVT::v2i32;
5579 case MVT::v4i8:
5580 return MVT::v4i16;
5581 }
5582 }
5583
5584 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5585 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5586 /// We insert the required extension here to get the vector to fill a D register.
AddRequiredExtensionForVMULL(SDValue N,SelectionDAG & DAG,const EVT & OrigTy,const EVT & ExtTy,unsigned ExtOpcode)5587 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5588 const EVT &OrigTy,
5589 const EVT &ExtTy,
5590 unsigned ExtOpcode) {
5591 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5592 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5593 // 64-bits we need to insert a new extension so that it will be 64-bits.
5594 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5595 if (OrigTy.getSizeInBits() >= 64)
5596 return N;
5597
5598 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5599 EVT NewVT = getExtensionTo64Bits(OrigTy);
5600
5601 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5602 }
5603
5604 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5605 /// does not do any sign/zero extension. If the original vector is less
5606 /// than 64 bits, an appropriate extension will be added after the load to
5607 /// reach a total size of 64 bits. We have to add the extension separately
5608 /// because ARM does not have a sign/zero extending load for vectors.
SkipLoadExtensionForVMULL(LoadSDNode * LD,SelectionDAG & DAG)5609 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5610 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5611
5612 // The load already has the right type.
5613 if (ExtendedTy == LD->getMemoryVT())
5614 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5615 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5616 LD->isNonTemporal(), LD->isInvariant(),
5617 LD->getAlignment());
5618
5619 // We need to create a zextload/sextload. We cannot just create a load
5620 // followed by a zext/zext node because LowerMUL is also run during normal
5621 // operation legalization where we can't create illegal types.
5622 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5623 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5624 LD->getMemoryVT(), LD->isVolatile(),
5625 LD->isNonTemporal(), LD->getAlignment());
5626 }
5627
5628 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5629 /// extending load, or BUILD_VECTOR with extended elements, return the
5630 /// unextended value. The unextended vector should be 64 bits so that it can
5631 /// be used as an operand to a VMULL instruction. If the original vector size
5632 /// before extension is less than 64 bits we add a an extension to resize
5633 /// the vector to 64 bits.
SkipExtensionForVMULL(SDNode * N,SelectionDAG & DAG)5634 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5635 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5636 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5637 N->getOperand(0)->getValueType(0),
5638 N->getValueType(0),
5639 N->getOpcode());
5640
5641 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5642 return SkipLoadExtensionForVMULL(LD, DAG);
5643
5644 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5645 // have been legalized as a BITCAST from v4i32.
5646 if (N->getOpcode() == ISD::BITCAST) {
5647 SDNode *BVN = N->getOperand(0).getNode();
5648 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5649 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5650 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5651 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5652 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5653 }
5654 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5655 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5656 EVT VT = N->getValueType(0);
5657 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5658 unsigned NumElts = VT.getVectorNumElements();
5659 MVT TruncVT = MVT::getIntegerVT(EltSize);
5660 SmallVector<SDValue, 8> Ops;
5661 for (unsigned i = 0; i != NumElts; ++i) {
5662 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5663 const APInt &CInt = C->getAPIntValue();
5664 // Element types smaller than 32 bits are not legal, so use i32 elements.
5665 // The values are implicitly truncated so sext vs. zext doesn't matter.
5666 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5667 }
5668 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5669 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5670 }
5671
isAddSubSExt(SDNode * N,SelectionDAG & DAG)5672 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5673 unsigned Opcode = N->getOpcode();
5674 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5675 SDNode *N0 = N->getOperand(0).getNode();
5676 SDNode *N1 = N->getOperand(1).getNode();
5677 return N0->hasOneUse() && N1->hasOneUse() &&
5678 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5679 }
5680 return false;
5681 }
5682
isAddSubZExt(SDNode * N,SelectionDAG & DAG)5683 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5684 unsigned Opcode = N->getOpcode();
5685 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5686 SDNode *N0 = N->getOperand(0).getNode();
5687 SDNode *N1 = N->getOperand(1).getNode();
5688 return N0->hasOneUse() && N1->hasOneUse() &&
5689 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5690 }
5691 return false;
5692 }
5693
LowerMUL(SDValue Op,SelectionDAG & DAG)5694 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5695 // Multiplications are only custom-lowered for 128-bit vectors so that
5696 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5697 EVT VT = Op.getValueType();
5698 assert(VT.is128BitVector() && VT.isInteger() &&
5699 "unexpected type for custom-lowering ISD::MUL");
5700 SDNode *N0 = Op.getOperand(0).getNode();
5701 SDNode *N1 = Op.getOperand(1).getNode();
5702 unsigned NewOpc = 0;
5703 bool isMLA = false;
5704 bool isN0SExt = isSignExtended(N0, DAG);
5705 bool isN1SExt = isSignExtended(N1, DAG);
5706 if (isN0SExt && isN1SExt)
5707 NewOpc = ARMISD::VMULLs;
5708 else {
5709 bool isN0ZExt = isZeroExtended(N0, DAG);
5710 bool isN1ZExt = isZeroExtended(N1, DAG);
5711 if (isN0ZExt && isN1ZExt)
5712 NewOpc = ARMISD::VMULLu;
5713 else if (isN1SExt || isN1ZExt) {
5714 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5715 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5716 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5717 NewOpc = ARMISD::VMULLs;
5718 isMLA = true;
5719 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5720 NewOpc = ARMISD::VMULLu;
5721 isMLA = true;
5722 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5723 std::swap(N0, N1);
5724 NewOpc = ARMISD::VMULLu;
5725 isMLA = true;
5726 }
5727 }
5728
5729 if (!NewOpc) {
5730 if (VT == MVT::v2i64)
5731 // Fall through to expand this. It is not legal.
5732 return SDValue();
5733 else
5734 // Other vector multiplications are legal.
5735 return Op;
5736 }
5737 }
5738
5739 // Legalize to a VMULL instruction.
5740 SDLoc DL(Op);
5741 SDValue Op0;
5742 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5743 if (!isMLA) {
5744 Op0 = SkipExtensionForVMULL(N0, DAG);
5745 assert(Op0.getValueType().is64BitVector() &&
5746 Op1.getValueType().is64BitVector() &&
5747 "unexpected types for extended operands to VMULL");
5748 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5749 }
5750
5751 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5752 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5753 // vmull q0, d4, d6
5754 // vmlal q0, d5, d6
5755 // is faster than
5756 // vaddl q0, d4, d5
5757 // vmovl q1, d6
5758 // vmul q0, q0, q1
5759 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5760 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5761 EVT Op1VT = Op1.getValueType();
5762 return DAG.getNode(N0->getOpcode(), DL, VT,
5763 DAG.getNode(NewOpc, DL, VT,
5764 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5765 DAG.getNode(NewOpc, DL, VT,
5766 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5767 }
5768
5769 static SDValue
LowerSDIV_v4i8(SDValue X,SDValue Y,SDLoc dl,SelectionDAG & DAG)5770 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5771 // Convert to float
5772 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5773 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5774 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5775 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5776 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5777 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5778 // Get reciprocal estimate.
5779 // float4 recip = vrecpeq_f32(yf);
5780 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5781 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5782 // Because char has a smaller range than uchar, we can actually get away
5783 // without any newton steps. This requires that we use a weird bias
5784 // of 0xb000, however (again, this has been exhaustively tested).
5785 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5786 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5787 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5788 Y = DAG.getConstant(0xb000, MVT::i32);
5789 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5790 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5791 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5792 // Convert back to short.
5793 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5794 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5795 return X;
5796 }
5797
5798 static SDValue
LowerSDIV_v4i16(SDValue N0,SDValue N1,SDLoc dl,SelectionDAG & DAG)5799 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5800 SDValue N2;
5801 // Convert to float.
5802 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5803 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5804 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5805 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5806 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5807 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5808
5809 // Use reciprocal estimate and one refinement step.
5810 // float4 recip = vrecpeq_f32(yf);
5811 // recip *= vrecpsq_f32(yf, recip);
5812 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5813 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5814 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5815 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5816 N1, N2);
5817 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5818 // Because short has a smaller range than ushort, we can actually get away
5819 // with only a single newton step. This requires that we use a weird bias
5820 // of 89, however (again, this has been exhaustively tested).
5821 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5822 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5823 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5824 N1 = DAG.getConstant(0x89, MVT::i32);
5825 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5826 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5827 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5828 // Convert back to integer and return.
5829 // return vmovn_s32(vcvt_s32_f32(result));
5830 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5831 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5832 return N0;
5833 }
5834
LowerSDIV(SDValue Op,SelectionDAG & DAG)5835 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5836 EVT VT = Op.getValueType();
5837 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5838 "unexpected type for custom-lowering ISD::SDIV");
5839
5840 SDLoc dl(Op);
5841 SDValue N0 = Op.getOperand(0);
5842 SDValue N1 = Op.getOperand(1);
5843 SDValue N2, N3;
5844
5845 if (VT == MVT::v8i8) {
5846 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5847 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5848
5849 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5850 DAG.getIntPtrConstant(4));
5851 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5852 DAG.getIntPtrConstant(4));
5853 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5854 DAG.getIntPtrConstant(0));
5855 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5856 DAG.getIntPtrConstant(0));
5857
5858 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5859 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5860
5861 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5862 N0 = LowerCONCAT_VECTORS(N0, DAG);
5863
5864 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5865 return N0;
5866 }
5867 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5868 }
5869
LowerUDIV(SDValue Op,SelectionDAG & DAG)5870 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5871 EVT VT = Op.getValueType();
5872 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5873 "unexpected type for custom-lowering ISD::UDIV");
5874
5875 SDLoc dl(Op);
5876 SDValue N0 = Op.getOperand(0);
5877 SDValue N1 = Op.getOperand(1);
5878 SDValue N2, N3;
5879
5880 if (VT == MVT::v8i8) {
5881 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5882 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5883
5884 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5885 DAG.getIntPtrConstant(4));
5886 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5887 DAG.getIntPtrConstant(4));
5888 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5889 DAG.getIntPtrConstant(0));
5890 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5891 DAG.getIntPtrConstant(0));
5892
5893 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5894 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5895
5896 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5897 N0 = LowerCONCAT_VECTORS(N0, DAG);
5898
5899 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5900 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5901 N0);
5902 return N0;
5903 }
5904
5905 // v4i16 sdiv ... Convert to float.
5906 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5907 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5908 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5909 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5910 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5911 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5912
5913 // Use reciprocal estimate and two refinement steps.
5914 // float4 recip = vrecpeq_f32(yf);
5915 // recip *= vrecpsq_f32(yf, recip);
5916 // recip *= vrecpsq_f32(yf, recip);
5917 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5918 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5919 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5920 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5921 BN1, N2);
5922 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5923 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5924 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5925 BN1, N2);
5926 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5927 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5928 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5929 // and that it will never cause us to return an answer too large).
5930 // float4 result = as_float4(as_int4(xf*recip) + 2);
5931 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5932 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5933 N1 = DAG.getConstant(2, MVT::i32);
5934 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5935 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5936 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5937 // Convert back to integer and return.
5938 // return vmovn_u32(vcvt_s32_f32(result));
5939 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5940 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5941 return N0;
5942 }
5943
LowerADDC_ADDE_SUBC_SUBE(SDValue Op,SelectionDAG & DAG)5944 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5945 EVT VT = Op.getNode()->getValueType(0);
5946 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5947
5948 unsigned Opc;
5949 bool ExtraOp = false;
5950 switch (Op.getOpcode()) {
5951 default: llvm_unreachable("Invalid code");
5952 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5953 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5954 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5955 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5956 }
5957
5958 if (!ExtraOp)
5959 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5960 Op.getOperand(1));
5961 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5962 Op.getOperand(1), Op.getOperand(2));
5963 }
5964
LowerFSINCOS(SDValue Op,SelectionDAG & DAG) const5965 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5966 assert(Subtarget->isTargetDarwin());
5967
5968 // For iOS, we want to call an alternative entry point: __sincos_stret,
5969 // return values are passed via sret.
5970 SDLoc dl(Op);
5971 SDValue Arg = Op.getOperand(0);
5972 EVT ArgVT = Arg.getValueType();
5973 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5974
5975 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5976 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5977
5978 // Pair of floats / doubles used to pass the result.
5979 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5980
5981 // Create stack object for sret.
5982 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5983 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5984 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5985 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5986
5987 ArgListTy Args;
5988 ArgListEntry Entry;
5989
5990 Entry.Node = SRet;
5991 Entry.Ty = RetTy->getPointerTo();
5992 Entry.isSExt = false;
5993 Entry.isZExt = false;
5994 Entry.isSRet = true;
5995 Args.push_back(Entry);
5996
5997 Entry.Node = Arg;
5998 Entry.Ty = ArgTy;
5999 Entry.isSExt = false;
6000 Entry.isZExt = false;
6001 Args.push_back(Entry);
6002
6003 const char *LibcallName = (ArgVT == MVT::f64)
6004 ? "__sincos_stret" : "__sincosf_stret";
6005 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6006
6007 TargetLowering::
6008 CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6009 false, false, false, false, 0,
6010 CallingConv::C, /*isTaillCall=*/false,
6011 /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6012 Callee, Args, DAG, dl);
6013 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6014
6015 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6016 MachinePointerInfo(), false, false, false, 0);
6017
6018 // Address of cos field.
6019 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6020 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6021 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6022 MachinePointerInfo(), false, false, false, 0);
6023
6024 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6025 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6026 LoadSin.getValue(0), LoadCos.getValue(0));
6027 }
6028
LowerAtomicLoadStore(SDValue Op,SelectionDAG & DAG)6029 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6030 // Monotonic load/store is legal for all targets
6031 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6032 return Op;
6033
6034 // Aquire/Release load/store is not legal for targets without a
6035 // dmb or equivalent available.
6036 return SDValue();
6037 }
6038
6039 static void
ReplaceATOMIC_OP_64(SDNode * Node,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG)6040 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6041 SelectionDAG &DAG) {
6042 SDLoc dl(Node);
6043 assert (Node->getValueType(0) == MVT::i64 &&
6044 "Only know how to expand i64 atomics");
6045 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6046
6047 SmallVector<SDValue, 6> Ops;
6048 Ops.push_back(Node->getOperand(0)); // Chain
6049 Ops.push_back(Node->getOperand(1)); // Ptr
6050 for(unsigned i=2; i<Node->getNumOperands(); i++) {
6051 // Low part
6052 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6053 Node->getOperand(i), DAG.getIntPtrConstant(0)));
6054 // High part
6055 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6056 Node->getOperand(i), DAG.getIntPtrConstant(1)));
6057 }
6058 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6059 SDValue Result =
6060 DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6061 cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6062 AN->getSynchScope());
6063 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6064 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6065 Results.push_back(Result.getValue(2));
6066 }
6067
ReplaceREADCYCLECOUNTER(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG,const ARMSubtarget * Subtarget)6068 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6069 SmallVectorImpl<SDValue> &Results,
6070 SelectionDAG &DAG,
6071 const ARMSubtarget *Subtarget) {
6072 SDLoc DL(N);
6073 SDValue Cycles32, OutChain;
6074
6075 if (Subtarget->hasPerfMon()) {
6076 // Under Power Management extensions, the cycle-count is:
6077 // mrc p15, #0, <Rt>, c9, c13, #0
6078 SDValue Ops[] = { N->getOperand(0), // Chain
6079 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6080 DAG.getConstant(15, MVT::i32),
6081 DAG.getConstant(0, MVT::i32),
6082 DAG.getConstant(9, MVT::i32),
6083 DAG.getConstant(13, MVT::i32),
6084 DAG.getConstant(0, MVT::i32)
6085 };
6086
6087 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6088 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6089 array_lengthof(Ops));
6090 OutChain = Cycles32.getValue(1);
6091 } else {
6092 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6093 // there are older ARM CPUs that have implementation-specific ways of
6094 // obtaining this information (FIXME!).
6095 Cycles32 = DAG.getConstant(0, MVT::i32);
6096 OutChain = DAG.getEntryNode();
6097 }
6098
6099
6100 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6101 Cycles32, DAG.getConstant(0, MVT::i32));
6102 Results.push_back(Cycles64);
6103 Results.push_back(OutChain);
6104 }
6105
LowerOperation(SDValue Op,SelectionDAG & DAG) const6106 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6107 switch (Op.getOpcode()) {
6108 default: llvm_unreachable("Don't know how to custom lower this!");
6109 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6110 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6111 case ISD::GlobalAddress:
6112 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6113 LowerGlobalAddressELF(Op, DAG);
6114 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6115 case ISD::SELECT: return LowerSELECT(Op, DAG);
6116 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6117 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6118 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6119 case ISD::VASTART: return LowerVASTART(Op, DAG);
6120 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6121 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6122 case ISD::SINT_TO_FP:
6123 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6124 case ISD::FP_TO_SINT:
6125 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6126 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6127 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6128 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6129 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6130 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6131 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6132 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6133 Subtarget);
6134 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6135 case ISD::SHL:
6136 case ISD::SRL:
6137 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6138 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6139 case ISD::SRL_PARTS:
6140 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6141 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6142 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6143 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6144 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6145 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6146 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6147 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6148 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6149 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6150 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6151 case ISD::MUL: return LowerMUL(Op, DAG);
6152 case ISD::SDIV: return LowerSDIV(Op, DAG);
6153 case ISD::UDIV: return LowerUDIV(Op, DAG);
6154 case ISD::ADDC:
6155 case ISD::ADDE:
6156 case ISD::SUBC:
6157 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6158 case ISD::ATOMIC_LOAD:
6159 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6160 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6161 case ISD::SDIVREM:
6162 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6163 }
6164 }
6165
6166 /// ReplaceNodeResults - Replace the results of node with an illegal result
6167 /// type with new values built out of custom code.
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const6168 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6169 SmallVectorImpl<SDValue>&Results,
6170 SelectionDAG &DAG) const {
6171 SDValue Res;
6172 switch (N->getOpcode()) {
6173 default:
6174 llvm_unreachable("Don't know how to custom expand this!");
6175 case ISD::BITCAST:
6176 Res = ExpandBITCAST(N, DAG);
6177 break;
6178 case ISD::SRL:
6179 case ISD::SRA:
6180 Res = Expand64BitShift(N, DAG, Subtarget);
6181 break;
6182 case ISD::READCYCLECOUNTER:
6183 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6184 return;
6185 case ISD::ATOMIC_STORE:
6186 case ISD::ATOMIC_LOAD:
6187 case ISD::ATOMIC_LOAD_ADD:
6188 case ISD::ATOMIC_LOAD_AND:
6189 case ISD::ATOMIC_LOAD_NAND:
6190 case ISD::ATOMIC_LOAD_OR:
6191 case ISD::ATOMIC_LOAD_SUB:
6192 case ISD::ATOMIC_LOAD_XOR:
6193 case ISD::ATOMIC_SWAP:
6194 case ISD::ATOMIC_CMP_SWAP:
6195 case ISD::ATOMIC_LOAD_MIN:
6196 case ISD::ATOMIC_LOAD_UMIN:
6197 case ISD::ATOMIC_LOAD_MAX:
6198 case ISD::ATOMIC_LOAD_UMAX:
6199 ReplaceATOMIC_OP_64(N, Results, DAG);
6200 return;
6201 }
6202 if (Res.getNode())
6203 Results.push_back(Res);
6204 }
6205
6206 //===----------------------------------------------------------------------===//
6207 // ARM Scheduler Hooks
6208 //===----------------------------------------------------------------------===//
6209
6210 MachineBasicBlock *
EmitAtomicCmpSwap(MachineInstr * MI,MachineBasicBlock * BB,unsigned Size) const6211 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6212 MachineBasicBlock *BB,
6213 unsigned Size) const {
6214 unsigned dest = MI->getOperand(0).getReg();
6215 unsigned ptr = MI->getOperand(1).getReg();
6216 unsigned oldval = MI->getOperand(2).getReg();
6217 unsigned newval = MI->getOperand(3).getReg();
6218 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6219 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6220 DebugLoc dl = MI->getDebugLoc();
6221 bool isThumb2 = Subtarget->isThumb2();
6222
6223 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6224 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6225 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6226 (const TargetRegisterClass*)&ARM::GPRRegClass);
6227
6228 if (isThumb2) {
6229 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6230 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6231 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6232 }
6233
6234 unsigned ldrOpc, strOpc;
6235 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6236
6237 MachineFunction *MF = BB->getParent();
6238 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6239 MachineFunction::iterator It = BB;
6240 ++It; // insert the new blocks after the current block
6241
6242 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6243 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6244 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6245 MF->insert(It, loop1MBB);
6246 MF->insert(It, loop2MBB);
6247 MF->insert(It, exitMBB);
6248
6249 // Transfer the remainder of BB and its successor edges to exitMBB.
6250 exitMBB->splice(exitMBB->begin(), BB,
6251 llvm::next(MachineBasicBlock::iterator(MI)),
6252 BB->end());
6253 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6254
6255 // thisMBB:
6256 // ...
6257 // fallthrough --> loop1MBB
6258 BB->addSuccessor(loop1MBB);
6259
6260 // loop1MBB:
6261 // ldrex dest, [ptr]
6262 // cmp dest, oldval
6263 // bne exitMBB
6264 BB = loop1MBB;
6265 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6266 if (ldrOpc == ARM::t2LDREX)
6267 MIB.addImm(0);
6268 AddDefaultPred(MIB);
6269 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6270 .addReg(dest).addReg(oldval));
6271 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6272 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6273 BB->addSuccessor(loop2MBB);
6274 BB->addSuccessor(exitMBB);
6275
6276 // loop2MBB:
6277 // strex scratch, newval, [ptr]
6278 // cmp scratch, #0
6279 // bne loop1MBB
6280 BB = loop2MBB;
6281 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6282 if (strOpc == ARM::t2STREX)
6283 MIB.addImm(0);
6284 AddDefaultPred(MIB);
6285 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6286 .addReg(scratch).addImm(0));
6287 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6288 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6289 BB->addSuccessor(loop1MBB);
6290 BB->addSuccessor(exitMBB);
6291
6292 // exitMBB:
6293 // ...
6294 BB = exitMBB;
6295
6296 MI->eraseFromParent(); // The instruction is gone now.
6297
6298 return BB;
6299 }
6300
6301 MachineBasicBlock *
EmitAtomicBinary(MachineInstr * MI,MachineBasicBlock * BB,unsigned Size,unsigned BinOpcode) const6302 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6303 unsigned Size, unsigned BinOpcode) const {
6304 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6305 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6306
6307 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6308 MachineFunction *MF = BB->getParent();
6309 MachineFunction::iterator It = BB;
6310 ++It;
6311
6312 unsigned dest = MI->getOperand(0).getReg();
6313 unsigned ptr = MI->getOperand(1).getReg();
6314 unsigned incr = MI->getOperand(2).getReg();
6315 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6316 DebugLoc dl = MI->getDebugLoc();
6317 bool isThumb2 = Subtarget->isThumb2();
6318
6319 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6320 if (isThumb2) {
6321 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6322 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6323 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6324 }
6325
6326 unsigned ldrOpc, strOpc;
6327 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6328
6329 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6330 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6331 MF->insert(It, loopMBB);
6332 MF->insert(It, exitMBB);
6333
6334 // Transfer the remainder of BB and its successor edges to exitMBB.
6335 exitMBB->splice(exitMBB->begin(), BB,
6336 llvm::next(MachineBasicBlock::iterator(MI)),
6337 BB->end());
6338 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6339
6340 const TargetRegisterClass *TRC = isThumb2 ?
6341 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6342 (const TargetRegisterClass*)&ARM::GPRRegClass;
6343 unsigned scratch = MRI.createVirtualRegister(TRC);
6344 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6345
6346 // thisMBB:
6347 // ...
6348 // fallthrough --> loopMBB
6349 BB->addSuccessor(loopMBB);
6350
6351 // loopMBB:
6352 // ldrex dest, ptr
6353 // <binop> scratch2, dest, incr
6354 // strex scratch, scratch2, ptr
6355 // cmp scratch, #0
6356 // bne- loopMBB
6357 // fallthrough --> exitMBB
6358 BB = loopMBB;
6359 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6360 if (ldrOpc == ARM::t2LDREX)
6361 MIB.addImm(0);
6362 AddDefaultPred(MIB);
6363 if (BinOpcode) {
6364 // operand order needs to go the other way for NAND
6365 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6366 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6367 addReg(incr).addReg(dest)).addReg(0);
6368 else
6369 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6370 addReg(dest).addReg(incr)).addReg(0);
6371 }
6372
6373 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6374 if (strOpc == ARM::t2STREX)
6375 MIB.addImm(0);
6376 AddDefaultPred(MIB);
6377 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6378 .addReg(scratch).addImm(0));
6379 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6380 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6381
6382 BB->addSuccessor(loopMBB);
6383 BB->addSuccessor(exitMBB);
6384
6385 // exitMBB:
6386 // ...
6387 BB = exitMBB;
6388
6389 MI->eraseFromParent(); // The instruction is gone now.
6390
6391 return BB;
6392 }
6393
6394 MachineBasicBlock *
EmitAtomicBinaryMinMax(MachineInstr * MI,MachineBasicBlock * BB,unsigned Size,bool signExtend,ARMCC::CondCodes Cond) const6395 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6396 MachineBasicBlock *BB,
6397 unsigned Size,
6398 bool signExtend,
6399 ARMCC::CondCodes Cond) const {
6400 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6401
6402 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6403 MachineFunction *MF = BB->getParent();
6404 MachineFunction::iterator It = BB;
6405 ++It;
6406
6407 unsigned dest = MI->getOperand(0).getReg();
6408 unsigned ptr = MI->getOperand(1).getReg();
6409 unsigned incr = MI->getOperand(2).getReg();
6410 unsigned oldval = dest;
6411 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6412 DebugLoc dl = MI->getDebugLoc();
6413 bool isThumb2 = Subtarget->isThumb2();
6414
6415 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6416 if (isThumb2) {
6417 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6418 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6419 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6420 }
6421
6422 unsigned ldrOpc, strOpc, extendOpc;
6423 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6424 switch (Size) {
6425 default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6426 case 1:
6427 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6428 break;
6429 case 2:
6430 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6431 break;
6432 case 4:
6433 extendOpc = 0;
6434 break;
6435 }
6436
6437 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6438 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6439 MF->insert(It, loopMBB);
6440 MF->insert(It, exitMBB);
6441
6442 // Transfer the remainder of BB and its successor edges to exitMBB.
6443 exitMBB->splice(exitMBB->begin(), BB,
6444 llvm::next(MachineBasicBlock::iterator(MI)),
6445 BB->end());
6446 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6447
6448 const TargetRegisterClass *TRC = isThumb2 ?
6449 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6450 (const TargetRegisterClass*)&ARM::GPRRegClass;
6451 unsigned scratch = MRI.createVirtualRegister(TRC);
6452 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6453
6454 // thisMBB:
6455 // ...
6456 // fallthrough --> loopMBB
6457 BB->addSuccessor(loopMBB);
6458
6459 // loopMBB:
6460 // ldrex dest, ptr
6461 // (sign extend dest, if required)
6462 // cmp dest, incr
6463 // cmov.cond scratch2, incr, dest
6464 // strex scratch, scratch2, ptr
6465 // cmp scratch, #0
6466 // bne- loopMBB
6467 // fallthrough --> exitMBB
6468 BB = loopMBB;
6469 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6470 if (ldrOpc == ARM::t2LDREX)
6471 MIB.addImm(0);
6472 AddDefaultPred(MIB);
6473
6474 // Sign extend the value, if necessary.
6475 if (signExtend && extendOpc) {
6476 oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6477 : &ARM::GPRnopcRegClass);
6478 if (!isThumb2)
6479 MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6480 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6481 .addReg(dest)
6482 .addImm(0));
6483 }
6484
6485 // Build compare and cmov instructions.
6486 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6487 .addReg(oldval).addReg(incr));
6488 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6489 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6490
6491 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6492 if (strOpc == ARM::t2STREX)
6493 MIB.addImm(0);
6494 AddDefaultPred(MIB);
6495 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6496 .addReg(scratch).addImm(0));
6497 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6498 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6499
6500 BB->addSuccessor(loopMBB);
6501 BB->addSuccessor(exitMBB);
6502
6503 // exitMBB:
6504 // ...
6505 BB = exitMBB;
6506
6507 MI->eraseFromParent(); // The instruction is gone now.
6508
6509 return BB;
6510 }
6511
6512 MachineBasicBlock *
EmitAtomicBinary64(MachineInstr * MI,MachineBasicBlock * BB,unsigned Op1,unsigned Op2,bool NeedsCarry,bool IsCmpxchg,bool IsMinMax,ARMCC::CondCodes CC) const6513 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6514 unsigned Op1, unsigned Op2,
6515 bool NeedsCarry, bool IsCmpxchg,
6516 bool IsMinMax, ARMCC::CondCodes CC) const {
6517 // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6518 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6519
6520 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6521 MachineFunction *MF = BB->getParent();
6522 MachineFunction::iterator It = BB;
6523 ++It;
6524
6525 bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6526 unsigned offset = (isStore ? -2 : 0);
6527 unsigned destlo = MI->getOperand(0).getReg();
6528 unsigned desthi = MI->getOperand(1).getReg();
6529 unsigned ptr = MI->getOperand(offset+2).getReg();
6530 unsigned vallo = MI->getOperand(offset+3).getReg();
6531 unsigned valhi = MI->getOperand(offset+4).getReg();
6532 unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6533 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6534 DebugLoc dl = MI->getDebugLoc();
6535 bool isThumb2 = Subtarget->isThumb2();
6536
6537 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6538 if (isThumb2) {
6539 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6540 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6541 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6542 MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6543 MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6544 }
6545
6546 unsigned ldrOpc, strOpc;
6547 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6548
6549 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6550 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6551 if (IsCmpxchg || IsMinMax)
6552 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6553 if (IsCmpxchg)
6554 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6555 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6556
6557 MF->insert(It, loopMBB);
6558 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6559 if (IsCmpxchg) MF->insert(It, cont2BB);
6560 MF->insert(It, exitMBB);
6561
6562 // Transfer the remainder of BB and its successor edges to exitMBB.
6563 exitMBB->splice(exitMBB->begin(), BB,
6564 llvm::next(MachineBasicBlock::iterator(MI)),
6565 BB->end());
6566 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6567
6568 const TargetRegisterClass *TRC = isThumb2 ?
6569 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6570 (const TargetRegisterClass*)&ARM::GPRRegClass;
6571 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6572
6573 // thisMBB:
6574 // ...
6575 // fallthrough --> loopMBB
6576 BB->addSuccessor(loopMBB);
6577
6578 // loopMBB:
6579 // ldrexd r2, r3, ptr
6580 // <binopa> r0, r2, incr
6581 // <binopb> r1, r3, incr
6582 // strexd storesuccess, r0, r1, ptr
6583 // cmp storesuccess, #0
6584 // bne- loopMBB
6585 // fallthrough --> exitMBB
6586 BB = loopMBB;
6587
6588 if (!isStore) {
6589 // Load
6590 if (isThumb2) {
6591 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6592 .addReg(destlo, RegState::Define)
6593 .addReg(desthi, RegState::Define)
6594 .addReg(ptr));
6595 } else {
6596 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6597 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6598 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6599 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6600 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6601 .addReg(GPRPair0, 0, ARM::gsub_0);
6602 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6603 .addReg(GPRPair0, 0, ARM::gsub_1);
6604 }
6605 }
6606
6607 unsigned StoreLo, StoreHi;
6608 if (IsCmpxchg) {
6609 // Add early exit
6610 for (unsigned i = 0; i < 2; i++) {
6611 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6612 ARM::CMPrr))
6613 .addReg(i == 0 ? destlo : desthi)
6614 .addReg(i == 0 ? vallo : valhi));
6615 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6616 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6617 BB->addSuccessor(exitMBB);
6618 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6619 BB = (i == 0 ? contBB : cont2BB);
6620 }
6621
6622 // Copy to physregs for strexd
6623 StoreLo = MI->getOperand(5).getReg();
6624 StoreHi = MI->getOperand(6).getReg();
6625 } else if (Op1) {
6626 // Perform binary operation
6627 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6628 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6629 .addReg(destlo).addReg(vallo))
6630 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6631 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6632 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6633 .addReg(desthi).addReg(valhi))
6634 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6635
6636 StoreLo = tmpRegLo;
6637 StoreHi = tmpRegHi;
6638 } else {
6639 // Copy to physregs for strexd
6640 StoreLo = vallo;
6641 StoreHi = valhi;
6642 }
6643 if (IsMinMax) {
6644 // Compare and branch to exit block.
6645 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6646 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6647 BB->addSuccessor(exitMBB);
6648 BB->addSuccessor(contBB);
6649 BB = contBB;
6650 StoreLo = vallo;
6651 StoreHi = valhi;
6652 }
6653
6654 // Store
6655 if (isThumb2) {
6656 MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6657 MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6658 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6659 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6660 } else {
6661 // Marshal a pair...
6662 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6663 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6664 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6665 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6666 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6667 .addReg(UndefPair)
6668 .addReg(StoreLo)
6669 .addImm(ARM::gsub_0);
6670 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6671 .addReg(r1)
6672 .addReg(StoreHi)
6673 .addImm(ARM::gsub_1);
6674
6675 // ...and store it
6676 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6677 .addReg(StorePair).addReg(ptr));
6678 }
6679 // Cmp+jump
6680 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6681 .addReg(storesuccess).addImm(0));
6682 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6683 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6684
6685 BB->addSuccessor(loopMBB);
6686 BB->addSuccessor(exitMBB);
6687
6688 // exitMBB:
6689 // ...
6690 BB = exitMBB;
6691
6692 MI->eraseFromParent(); // The instruction is gone now.
6693
6694 return BB;
6695 }
6696
6697 MachineBasicBlock *
EmitAtomicLoad64(MachineInstr * MI,MachineBasicBlock * BB) const6698 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6699
6700 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6701
6702 unsigned destlo = MI->getOperand(0).getReg();
6703 unsigned desthi = MI->getOperand(1).getReg();
6704 unsigned ptr = MI->getOperand(2).getReg();
6705 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6706 DebugLoc dl = MI->getDebugLoc();
6707 bool isThumb2 = Subtarget->isThumb2();
6708
6709 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6710 if (isThumb2) {
6711 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6712 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6713 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6714 }
6715 unsigned ldrOpc, strOpc;
6716 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6717
6718 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6719
6720 if (isThumb2) {
6721 MIB.addReg(destlo, RegState::Define)
6722 .addReg(desthi, RegState::Define)
6723 .addReg(ptr);
6724
6725 } else {
6726 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6727 MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6728
6729 // Copy GPRPair0 into dest. (This copy will normally be coalesced.)
6730 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6731 .addReg(GPRPair0, 0, ARM::gsub_0);
6732 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6733 .addReg(GPRPair0, 0, ARM::gsub_1);
6734 }
6735 AddDefaultPred(MIB);
6736
6737 MI->eraseFromParent(); // The instruction is gone now.
6738
6739 return BB;
6740 }
6741
6742 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6743 /// registers the function context.
6744 void ARMTargetLowering::
SetupEntryBlockForSjLj(MachineInstr * MI,MachineBasicBlock * MBB,MachineBasicBlock * DispatchBB,int FI) const6745 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6746 MachineBasicBlock *DispatchBB, int FI) const {
6747 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6748 DebugLoc dl = MI->getDebugLoc();
6749 MachineFunction *MF = MBB->getParent();
6750 MachineRegisterInfo *MRI = &MF->getRegInfo();
6751 MachineConstantPool *MCP = MF->getConstantPool();
6752 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6753 const Function *F = MF->getFunction();
6754
6755 bool isThumb = Subtarget->isThumb();
6756 bool isThumb2 = Subtarget->isThumb2();
6757
6758 unsigned PCLabelId = AFI->createPICLabelUId();
6759 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6760 ARMConstantPoolValue *CPV =
6761 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6762 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6763
6764 const TargetRegisterClass *TRC = isThumb ?
6765 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6766 (const TargetRegisterClass*)&ARM::GPRRegClass;
6767
6768 // Grab constant pool and fixed stack memory operands.
6769 MachineMemOperand *CPMMO =
6770 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6771 MachineMemOperand::MOLoad, 4, 4);
6772
6773 MachineMemOperand *FIMMOSt =
6774 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6775 MachineMemOperand::MOStore, 4, 4);
6776
6777 // Load the address of the dispatch MBB into the jump buffer.
6778 if (isThumb2) {
6779 // Incoming value: jbuf
6780 // ldr.n r5, LCPI1_1
6781 // orr r5, r5, #1
6782 // add r5, pc
6783 // str r5, [$jbuf, #+4] ; &jbuf[1]
6784 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6785 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6786 .addConstantPoolIndex(CPI)
6787 .addMemOperand(CPMMO));
6788 // Set the low bit because of thumb mode.
6789 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6790 AddDefaultCC(
6791 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6792 .addReg(NewVReg1, RegState::Kill)
6793 .addImm(0x01)));
6794 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6795 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6796 .addReg(NewVReg2, RegState::Kill)
6797 .addImm(PCLabelId);
6798 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6799 .addReg(NewVReg3, RegState::Kill)
6800 .addFrameIndex(FI)
6801 .addImm(36) // &jbuf[1] :: pc
6802 .addMemOperand(FIMMOSt));
6803 } else if (isThumb) {
6804 // Incoming value: jbuf
6805 // ldr.n r1, LCPI1_4
6806 // add r1, pc
6807 // mov r2, #1
6808 // orrs r1, r2
6809 // add r2, $jbuf, #+4 ; &jbuf[1]
6810 // str r1, [r2]
6811 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6812 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6813 .addConstantPoolIndex(CPI)
6814 .addMemOperand(CPMMO));
6815 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6816 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6817 .addReg(NewVReg1, RegState::Kill)
6818 .addImm(PCLabelId);
6819 // Set the low bit because of thumb mode.
6820 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6821 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6822 .addReg(ARM::CPSR, RegState::Define)
6823 .addImm(1));
6824 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6825 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6826 .addReg(ARM::CPSR, RegState::Define)
6827 .addReg(NewVReg2, RegState::Kill)
6828 .addReg(NewVReg3, RegState::Kill));
6829 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6830 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6831 .addFrameIndex(FI)
6832 .addImm(36)); // &jbuf[1] :: pc
6833 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6834 .addReg(NewVReg4, RegState::Kill)
6835 .addReg(NewVReg5, RegState::Kill)
6836 .addImm(0)
6837 .addMemOperand(FIMMOSt));
6838 } else {
6839 // Incoming value: jbuf
6840 // ldr r1, LCPI1_1
6841 // add r1, pc, r1
6842 // str r1, [$jbuf, #+4] ; &jbuf[1]
6843 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6844 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6845 .addConstantPoolIndex(CPI)
6846 .addImm(0)
6847 .addMemOperand(CPMMO));
6848 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6849 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6850 .addReg(NewVReg1, RegState::Kill)
6851 .addImm(PCLabelId));
6852 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6853 .addReg(NewVReg2, RegState::Kill)
6854 .addFrameIndex(FI)
6855 .addImm(36) // &jbuf[1] :: pc
6856 .addMemOperand(FIMMOSt));
6857 }
6858 }
6859
6860 MachineBasicBlock *ARMTargetLowering::
EmitSjLjDispatchBlock(MachineInstr * MI,MachineBasicBlock * MBB) const6861 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6862 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6863 DebugLoc dl = MI->getDebugLoc();
6864 MachineFunction *MF = MBB->getParent();
6865 MachineRegisterInfo *MRI = &MF->getRegInfo();
6866 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6867 MachineFrameInfo *MFI = MF->getFrameInfo();
6868 int FI = MFI->getFunctionContextIndex();
6869
6870 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6871 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6872 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6873
6874 // Get a mapping of the call site numbers to all of the landing pads they're
6875 // associated with.
6876 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6877 unsigned MaxCSNum = 0;
6878 MachineModuleInfo &MMI = MF->getMMI();
6879 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6880 ++BB) {
6881 if (!BB->isLandingPad()) continue;
6882
6883 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6884 // pad.
6885 for (MachineBasicBlock::iterator
6886 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6887 if (!II->isEHLabel()) continue;
6888
6889 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6890 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6891
6892 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6893 for (SmallVectorImpl<unsigned>::iterator
6894 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6895 CSI != CSE; ++CSI) {
6896 CallSiteNumToLPad[*CSI].push_back(BB);
6897 MaxCSNum = std::max(MaxCSNum, *CSI);
6898 }
6899 break;
6900 }
6901 }
6902
6903 // Get an ordered list of the machine basic blocks for the jump table.
6904 std::vector<MachineBasicBlock*> LPadList;
6905 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6906 LPadList.reserve(CallSiteNumToLPad.size());
6907 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6908 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6909 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6910 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6911 LPadList.push_back(*II);
6912 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6913 }
6914 }
6915
6916 assert(!LPadList.empty() &&
6917 "No landing pad destinations for the dispatch jump table!");
6918
6919 // Create the jump table and associated information.
6920 MachineJumpTableInfo *JTI =
6921 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6922 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6923 unsigned UId = AFI->createJumpTableUId();
6924 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6925
6926 // Create the MBBs for the dispatch code.
6927
6928 // Shove the dispatch's address into the return slot in the function context.
6929 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6930 DispatchBB->setIsLandingPad();
6931
6932 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6933 unsigned trap_opcode;
6934 if (Subtarget->isThumb())
6935 trap_opcode = ARM::tTRAP;
6936 else
6937 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6938
6939 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6940 DispatchBB->addSuccessor(TrapBB);
6941
6942 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6943 DispatchBB->addSuccessor(DispContBB);
6944
6945 // Insert and MBBs.
6946 MF->insert(MF->end(), DispatchBB);
6947 MF->insert(MF->end(), DispContBB);
6948 MF->insert(MF->end(), TrapBB);
6949
6950 // Insert code into the entry block that creates and registers the function
6951 // context.
6952 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6953
6954 MachineMemOperand *FIMMOLd =
6955 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6956 MachineMemOperand::MOLoad |
6957 MachineMemOperand::MOVolatile, 4, 4);
6958
6959 MachineInstrBuilder MIB;
6960 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6961
6962 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6963 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6964
6965 // Add a register mask with no preserved registers. This results in all
6966 // registers being marked as clobbered.
6967 MIB.addRegMask(RI.getNoPreservedMask());
6968
6969 unsigned NumLPads = LPadList.size();
6970 if (Subtarget->isThumb2()) {
6971 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6972 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6973 .addFrameIndex(FI)
6974 .addImm(4)
6975 .addMemOperand(FIMMOLd));
6976
6977 if (NumLPads < 256) {
6978 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6979 .addReg(NewVReg1)
6980 .addImm(LPadList.size()));
6981 } else {
6982 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6983 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6984 .addImm(NumLPads & 0xFFFF));
6985
6986 unsigned VReg2 = VReg1;
6987 if ((NumLPads & 0xFFFF0000) != 0) {
6988 VReg2 = MRI->createVirtualRegister(TRC);
6989 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6990 .addReg(VReg1)
6991 .addImm(NumLPads >> 16));
6992 }
6993
6994 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6995 .addReg(NewVReg1)
6996 .addReg(VReg2));
6997 }
6998
6999 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7000 .addMBB(TrapBB)
7001 .addImm(ARMCC::HI)
7002 .addReg(ARM::CPSR);
7003
7004 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7005 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7006 .addJumpTableIndex(MJTI)
7007 .addImm(UId));
7008
7009 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7010 AddDefaultCC(
7011 AddDefaultPred(
7012 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7013 .addReg(NewVReg3, RegState::Kill)
7014 .addReg(NewVReg1)
7015 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7016
7017 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7018 .addReg(NewVReg4, RegState::Kill)
7019 .addReg(NewVReg1)
7020 .addJumpTableIndex(MJTI)
7021 .addImm(UId);
7022 } else if (Subtarget->isThumb()) {
7023 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7024 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7025 .addFrameIndex(FI)
7026 .addImm(1)
7027 .addMemOperand(FIMMOLd));
7028
7029 if (NumLPads < 256) {
7030 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7031 .addReg(NewVReg1)
7032 .addImm(NumLPads));
7033 } else {
7034 MachineConstantPool *ConstantPool = MF->getConstantPool();
7035 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7036 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7037
7038 // MachineConstantPool wants an explicit alignment.
7039 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7040 if (Align == 0)
7041 Align = getDataLayout()->getTypeAllocSize(C->getType());
7042 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7043
7044 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7045 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7046 .addReg(VReg1, RegState::Define)
7047 .addConstantPoolIndex(Idx));
7048 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7049 .addReg(NewVReg1)
7050 .addReg(VReg1));
7051 }
7052
7053 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7054 .addMBB(TrapBB)
7055 .addImm(ARMCC::HI)
7056 .addReg(ARM::CPSR);
7057
7058 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7059 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7060 .addReg(ARM::CPSR, RegState::Define)
7061 .addReg(NewVReg1)
7062 .addImm(2));
7063
7064 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7065 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7066 .addJumpTableIndex(MJTI)
7067 .addImm(UId));
7068
7069 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7070 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7071 .addReg(ARM::CPSR, RegState::Define)
7072 .addReg(NewVReg2, RegState::Kill)
7073 .addReg(NewVReg3));
7074
7075 MachineMemOperand *JTMMOLd =
7076 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7077 MachineMemOperand::MOLoad, 4, 4);
7078
7079 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7080 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7081 .addReg(NewVReg4, RegState::Kill)
7082 .addImm(0)
7083 .addMemOperand(JTMMOLd));
7084
7085 unsigned NewVReg6 = NewVReg5;
7086 if (RelocM == Reloc::PIC_) {
7087 NewVReg6 = MRI->createVirtualRegister(TRC);
7088 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7089 .addReg(ARM::CPSR, RegState::Define)
7090 .addReg(NewVReg5, RegState::Kill)
7091 .addReg(NewVReg3));
7092 }
7093
7094 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7095 .addReg(NewVReg6, RegState::Kill)
7096 .addJumpTableIndex(MJTI)
7097 .addImm(UId);
7098 } else {
7099 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7100 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7101 .addFrameIndex(FI)
7102 .addImm(4)
7103 .addMemOperand(FIMMOLd));
7104
7105 if (NumLPads < 256) {
7106 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7107 .addReg(NewVReg1)
7108 .addImm(NumLPads));
7109 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7110 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7111 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7112 .addImm(NumLPads & 0xFFFF));
7113
7114 unsigned VReg2 = VReg1;
7115 if ((NumLPads & 0xFFFF0000) != 0) {
7116 VReg2 = MRI->createVirtualRegister(TRC);
7117 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7118 .addReg(VReg1)
7119 .addImm(NumLPads >> 16));
7120 }
7121
7122 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7123 .addReg(NewVReg1)
7124 .addReg(VReg2));
7125 } else {
7126 MachineConstantPool *ConstantPool = MF->getConstantPool();
7127 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7128 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7129
7130 // MachineConstantPool wants an explicit alignment.
7131 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7132 if (Align == 0)
7133 Align = getDataLayout()->getTypeAllocSize(C->getType());
7134 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7135
7136 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7137 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7138 .addReg(VReg1, RegState::Define)
7139 .addConstantPoolIndex(Idx)
7140 .addImm(0));
7141 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7142 .addReg(NewVReg1)
7143 .addReg(VReg1, RegState::Kill));
7144 }
7145
7146 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7147 .addMBB(TrapBB)
7148 .addImm(ARMCC::HI)
7149 .addReg(ARM::CPSR);
7150
7151 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7152 AddDefaultCC(
7153 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7154 .addReg(NewVReg1)
7155 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7156 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7157 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7158 .addJumpTableIndex(MJTI)
7159 .addImm(UId));
7160
7161 MachineMemOperand *JTMMOLd =
7162 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7163 MachineMemOperand::MOLoad, 4, 4);
7164 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7165 AddDefaultPred(
7166 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7167 .addReg(NewVReg3, RegState::Kill)
7168 .addReg(NewVReg4)
7169 .addImm(0)
7170 .addMemOperand(JTMMOLd));
7171
7172 if (RelocM == Reloc::PIC_) {
7173 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7174 .addReg(NewVReg5, RegState::Kill)
7175 .addReg(NewVReg4)
7176 .addJumpTableIndex(MJTI)
7177 .addImm(UId);
7178 } else {
7179 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7180 .addReg(NewVReg5, RegState::Kill)
7181 .addJumpTableIndex(MJTI)
7182 .addImm(UId);
7183 }
7184 }
7185
7186 // Add the jump table entries as successors to the MBB.
7187 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7188 for (std::vector<MachineBasicBlock*>::iterator
7189 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7190 MachineBasicBlock *CurMBB = *I;
7191 if (SeenMBBs.insert(CurMBB))
7192 DispContBB->addSuccessor(CurMBB);
7193 }
7194
7195 // N.B. the order the invoke BBs are processed in doesn't matter here.
7196 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7197 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7198 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7199 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7200 MachineBasicBlock *BB = *I;
7201
7202 // Remove the landing pad successor from the invoke block and replace it
7203 // with the new dispatch block.
7204 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7205 BB->succ_end());
7206 while (!Successors.empty()) {
7207 MachineBasicBlock *SMBB = Successors.pop_back_val();
7208 if (SMBB->isLandingPad()) {
7209 BB->removeSuccessor(SMBB);
7210 MBBLPads.push_back(SMBB);
7211 }
7212 }
7213
7214 BB->addSuccessor(DispatchBB);
7215
7216 // Find the invoke call and mark all of the callee-saved registers as
7217 // 'implicit defined' so that they're spilled. This prevents code from
7218 // moving instructions to before the EH block, where they will never be
7219 // executed.
7220 for (MachineBasicBlock::reverse_iterator
7221 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7222 if (!II->isCall()) continue;
7223
7224 DenseMap<unsigned, bool> DefRegs;
7225 for (MachineInstr::mop_iterator
7226 OI = II->operands_begin(), OE = II->operands_end();
7227 OI != OE; ++OI) {
7228 if (!OI->isReg()) continue;
7229 DefRegs[OI->getReg()] = true;
7230 }
7231
7232 MachineInstrBuilder MIB(*MF, &*II);
7233
7234 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7235 unsigned Reg = SavedRegs[i];
7236 if (Subtarget->isThumb2() &&
7237 !ARM::tGPRRegClass.contains(Reg) &&
7238 !ARM::hGPRRegClass.contains(Reg))
7239 continue;
7240 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7241 continue;
7242 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7243 continue;
7244 if (!DefRegs[Reg])
7245 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7246 }
7247
7248 break;
7249 }
7250 }
7251
7252 // Mark all former landing pads as non-landing pads. The dispatch is the only
7253 // landing pad now.
7254 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7255 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7256 (*I)->setIsLandingPad(false);
7257
7258 // The instruction is gone now.
7259 MI->eraseFromParent();
7260
7261 return MBB;
7262 }
7263
7264 static
OtherSucc(MachineBasicBlock * MBB,MachineBasicBlock * Succ)7265 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7266 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7267 E = MBB->succ_end(); I != E; ++I)
7268 if (*I != Succ)
7269 return *I;
7270 llvm_unreachable("Expecting a BB with two successors!");
7271 }
7272
7273 /// Return the load opcode for a given load size. If load size >= 8,
7274 /// neon opcode will be returned.
getLdOpcode(unsigned LdSize,bool IsThumb1,bool IsThumb2)7275 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7276 if (LdSize >= 8)
7277 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7278 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7279 if (IsThumb1)
7280 return LdSize == 4 ? ARM::tLDRi
7281 : LdSize == 2 ? ARM::tLDRHi
7282 : LdSize == 1 ? ARM::tLDRBi : 0;
7283 if (IsThumb2)
7284 return LdSize == 4 ? ARM::t2LDR_POST
7285 : LdSize == 2 ? ARM::t2LDRH_POST
7286 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7287 return LdSize == 4 ? ARM::LDR_POST_IMM
7288 : LdSize == 2 ? ARM::LDRH_POST
7289 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7290 }
7291
7292 /// Return the store opcode for a given store size. If store size >= 8,
7293 /// neon opcode will be returned.
getStOpcode(unsigned StSize,bool IsThumb1,bool IsThumb2)7294 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7295 if (StSize >= 8)
7296 return StSize == 16 ? ARM::VST1q32wb_fixed
7297 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7298 if (IsThumb1)
7299 return StSize == 4 ? ARM::tSTRi
7300 : StSize == 2 ? ARM::tSTRHi
7301 : StSize == 1 ? ARM::tSTRBi : 0;
7302 if (IsThumb2)
7303 return StSize == 4 ? ARM::t2STR_POST
7304 : StSize == 2 ? ARM::t2STRH_POST
7305 : StSize == 1 ? ARM::t2STRB_POST : 0;
7306 return StSize == 4 ? ARM::STR_POST_IMM
7307 : StSize == 2 ? ARM::STRH_POST
7308 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7309 }
7310
7311 /// Emit a post-increment load operation with given size. The instructions
7312 /// will be added to BB at Pos.
emitPostLd(MachineBasicBlock * BB,MachineInstr * Pos,const TargetInstrInfo * TII,DebugLoc dl,unsigned LdSize,unsigned Data,unsigned AddrIn,unsigned AddrOut,bool IsThumb1,bool IsThumb2)7313 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7314 const TargetInstrInfo *TII, DebugLoc dl,
7315 unsigned LdSize, unsigned Data, unsigned AddrIn,
7316 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7317 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7318 assert(LdOpc != 0 && "Should have a load opcode");
7319 if (LdSize >= 8) {
7320 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7321 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7322 .addImm(0));
7323 } else if (IsThumb1) {
7324 // load + update AddrIn
7325 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7326 .addReg(AddrIn).addImm(0));
7327 MachineInstrBuilder MIB =
7328 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7329 MIB = AddDefaultT1CC(MIB);
7330 MIB.addReg(AddrIn).addImm(LdSize);
7331 AddDefaultPred(MIB);
7332 } else if (IsThumb2) {
7333 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7334 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7335 .addImm(LdSize));
7336 } else { // arm
7337 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7338 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7339 .addReg(0).addImm(LdSize));
7340 }
7341 }
7342
7343 /// Emit a post-increment store operation with given size. The instructions
7344 /// will be added to BB at Pos.
emitPostSt(MachineBasicBlock * BB,MachineInstr * Pos,const TargetInstrInfo * TII,DebugLoc dl,unsigned StSize,unsigned Data,unsigned AddrIn,unsigned AddrOut,bool IsThumb1,bool IsThumb2)7345 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7346 const TargetInstrInfo *TII, DebugLoc dl,
7347 unsigned StSize, unsigned Data, unsigned AddrIn,
7348 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7349 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7350 assert(StOpc != 0 && "Should have a store opcode");
7351 if (StSize >= 8) {
7352 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7353 .addReg(AddrIn).addImm(0).addReg(Data));
7354 } else if (IsThumb1) {
7355 // store + update AddrIn
7356 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7357 .addReg(AddrIn).addImm(0));
7358 MachineInstrBuilder MIB =
7359 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7360 MIB = AddDefaultT1CC(MIB);
7361 MIB.addReg(AddrIn).addImm(StSize);
7362 AddDefaultPred(MIB);
7363 } else if (IsThumb2) {
7364 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7365 .addReg(Data).addReg(AddrIn).addImm(StSize));
7366 } else { // arm
7367 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7368 .addReg(Data).addReg(AddrIn).addReg(0)
7369 .addImm(StSize));
7370 }
7371 }
7372
7373 MachineBasicBlock *
EmitStructByval(MachineInstr * MI,MachineBasicBlock * BB) const7374 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7375 MachineBasicBlock *BB) const {
7376 // This pseudo instruction has 3 operands: dst, src, size
7377 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7378 // Otherwise, we will generate unrolled scalar copies.
7379 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7380 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7381 MachineFunction::iterator It = BB;
7382 ++It;
7383
7384 unsigned dest = MI->getOperand(0).getReg();
7385 unsigned src = MI->getOperand(1).getReg();
7386 unsigned SizeVal = MI->getOperand(2).getImm();
7387 unsigned Align = MI->getOperand(3).getImm();
7388 DebugLoc dl = MI->getDebugLoc();
7389
7390 MachineFunction *MF = BB->getParent();
7391 MachineRegisterInfo &MRI = MF->getRegInfo();
7392 unsigned UnitSize = 0;
7393 const TargetRegisterClass *TRC = 0;
7394 const TargetRegisterClass *VecTRC = 0;
7395
7396 bool IsThumb1 = Subtarget->isThumb1Only();
7397 bool IsThumb2 = Subtarget->isThumb2();
7398
7399 if (Align & 1) {
7400 UnitSize = 1;
7401 } else if (Align & 2) {
7402 UnitSize = 2;
7403 } else {
7404 // Check whether we can use NEON instructions.
7405 if (!MF->getFunction()->getAttributes().
7406 hasAttribute(AttributeSet::FunctionIndex,
7407 Attribute::NoImplicitFloat) &&
7408 Subtarget->hasNEON()) {
7409 if ((Align % 16 == 0) && SizeVal >= 16)
7410 UnitSize = 16;
7411 else if ((Align % 8 == 0) && SizeVal >= 8)
7412 UnitSize = 8;
7413 }
7414 // Can't use NEON instructions.
7415 if (UnitSize == 0)
7416 UnitSize = 4;
7417 }
7418
7419 // Select the correct opcode and register class for unit size load/store
7420 bool IsNeon = UnitSize >= 8;
7421 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7422 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7423 if (IsNeon)
7424 VecTRC = UnitSize == 16
7425 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7426 : UnitSize == 8
7427 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7428 : 0;
7429
7430 unsigned BytesLeft = SizeVal % UnitSize;
7431 unsigned LoopSize = SizeVal - BytesLeft;
7432
7433 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7434 // Use LDR and STR to copy.
7435 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7436 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7437 unsigned srcIn = src;
7438 unsigned destIn = dest;
7439 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7440 unsigned srcOut = MRI.createVirtualRegister(TRC);
7441 unsigned destOut = MRI.createVirtualRegister(TRC);
7442 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7443 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7444 IsThumb1, IsThumb2);
7445 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7446 IsThumb1, IsThumb2);
7447 srcIn = srcOut;
7448 destIn = destOut;
7449 }
7450
7451 // Handle the leftover bytes with LDRB and STRB.
7452 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7453 // [destOut] = STRB_POST(scratch, destIn, 1)
7454 for (unsigned i = 0; i < BytesLeft; i++) {
7455 unsigned srcOut = MRI.createVirtualRegister(TRC);
7456 unsigned destOut = MRI.createVirtualRegister(TRC);
7457 unsigned scratch = MRI.createVirtualRegister(TRC);
7458 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7459 IsThumb1, IsThumb2);
7460 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7461 IsThumb1, IsThumb2);
7462 srcIn = srcOut;
7463 destIn = destOut;
7464 }
7465 MI->eraseFromParent(); // The instruction is gone now.
7466 return BB;
7467 }
7468
7469 // Expand the pseudo op to a loop.
7470 // thisMBB:
7471 // ...
7472 // movw varEnd, # --> with thumb2
7473 // movt varEnd, #
7474 // ldrcp varEnd, idx --> without thumb2
7475 // fallthrough --> loopMBB
7476 // loopMBB:
7477 // PHI varPhi, varEnd, varLoop
7478 // PHI srcPhi, src, srcLoop
7479 // PHI destPhi, dst, destLoop
7480 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7481 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7482 // subs varLoop, varPhi, #UnitSize
7483 // bne loopMBB
7484 // fallthrough --> exitMBB
7485 // exitMBB:
7486 // epilogue to handle left-over bytes
7487 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7488 // [destOut] = STRB_POST(scratch, destLoop, 1)
7489 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7490 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7491 MF->insert(It, loopMBB);
7492 MF->insert(It, exitMBB);
7493
7494 // Transfer the remainder of BB and its successor edges to exitMBB.
7495 exitMBB->splice(exitMBB->begin(), BB,
7496 llvm::next(MachineBasicBlock::iterator(MI)),
7497 BB->end());
7498 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7499
7500 // Load an immediate to varEnd.
7501 unsigned varEnd = MRI.createVirtualRegister(TRC);
7502 if (IsThumb2) {
7503 unsigned Vtmp = varEnd;
7504 if ((LoopSize & 0xFFFF0000) != 0)
7505 Vtmp = MRI.createVirtualRegister(TRC);
7506 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7507 .addImm(LoopSize & 0xFFFF));
7508
7509 if ((LoopSize & 0xFFFF0000) != 0)
7510 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7511 .addReg(Vtmp).addImm(LoopSize >> 16));
7512 } else {
7513 MachineConstantPool *ConstantPool = MF->getConstantPool();
7514 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7515 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7516
7517 // MachineConstantPool wants an explicit alignment.
7518 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7519 if (Align == 0)
7520 Align = getDataLayout()->getTypeAllocSize(C->getType());
7521 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7522
7523 if (IsThumb1)
7524 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7525 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7526 else
7527 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7528 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7529 }
7530 BB->addSuccessor(loopMBB);
7531
7532 // Generate the loop body:
7533 // varPhi = PHI(varLoop, varEnd)
7534 // srcPhi = PHI(srcLoop, src)
7535 // destPhi = PHI(destLoop, dst)
7536 MachineBasicBlock *entryBB = BB;
7537 BB = loopMBB;
7538 unsigned varLoop = MRI.createVirtualRegister(TRC);
7539 unsigned varPhi = MRI.createVirtualRegister(TRC);
7540 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7541 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7542 unsigned destLoop = MRI.createVirtualRegister(TRC);
7543 unsigned destPhi = MRI.createVirtualRegister(TRC);
7544
7545 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7546 .addReg(varLoop).addMBB(loopMBB)
7547 .addReg(varEnd).addMBB(entryBB);
7548 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7549 .addReg(srcLoop).addMBB(loopMBB)
7550 .addReg(src).addMBB(entryBB);
7551 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7552 .addReg(destLoop).addMBB(loopMBB)
7553 .addReg(dest).addMBB(entryBB);
7554
7555 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7556 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7557 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7558 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7559 IsThumb1, IsThumb2);
7560 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7561 IsThumb1, IsThumb2);
7562
7563 // Decrement loop variable by UnitSize.
7564 if (IsThumb1) {
7565 MachineInstrBuilder MIB =
7566 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7567 MIB = AddDefaultT1CC(MIB);
7568 MIB.addReg(varPhi).addImm(UnitSize);
7569 AddDefaultPred(MIB);
7570 } else {
7571 MachineInstrBuilder MIB =
7572 BuildMI(*BB, BB->end(), dl,
7573 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7574 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7575 MIB->getOperand(5).setReg(ARM::CPSR);
7576 MIB->getOperand(5).setIsDef(true);
7577 }
7578 BuildMI(*BB, BB->end(), dl,
7579 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7580 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7581
7582 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7583 BB->addSuccessor(loopMBB);
7584 BB->addSuccessor(exitMBB);
7585
7586 // Add epilogue to handle BytesLeft.
7587 BB = exitMBB;
7588 MachineInstr *StartOfExit = exitMBB->begin();
7589
7590 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7591 // [destOut] = STRB_POST(scratch, destLoop, 1)
7592 unsigned srcIn = srcLoop;
7593 unsigned destIn = destLoop;
7594 for (unsigned i = 0; i < BytesLeft; i++) {
7595 unsigned srcOut = MRI.createVirtualRegister(TRC);
7596 unsigned destOut = MRI.createVirtualRegister(TRC);
7597 unsigned scratch = MRI.createVirtualRegister(TRC);
7598 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7599 IsThumb1, IsThumb2);
7600 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7601 IsThumb1, IsThumb2);
7602 srcIn = srcOut;
7603 destIn = destOut;
7604 }
7605
7606 MI->eraseFromParent(); // The instruction is gone now.
7607 return BB;
7608 }
7609
7610 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr * MI,MachineBasicBlock * BB) const7611 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7612 MachineBasicBlock *BB) const {
7613 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7614 DebugLoc dl = MI->getDebugLoc();
7615 bool isThumb2 = Subtarget->isThumb2();
7616 switch (MI->getOpcode()) {
7617 default: {
7618 MI->dump();
7619 llvm_unreachable("Unexpected instr type to insert");
7620 }
7621 // The Thumb2 pre-indexed stores have the same MI operands, they just
7622 // define them differently in the .td files from the isel patterns, so
7623 // they need pseudos.
7624 case ARM::t2STR_preidx:
7625 MI->setDesc(TII->get(ARM::t2STR_PRE));
7626 return BB;
7627 case ARM::t2STRB_preidx:
7628 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7629 return BB;
7630 case ARM::t2STRH_preidx:
7631 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7632 return BB;
7633
7634 case ARM::STRi_preidx:
7635 case ARM::STRBi_preidx: {
7636 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7637 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7638 // Decode the offset.
7639 unsigned Offset = MI->getOperand(4).getImm();
7640 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7641 Offset = ARM_AM::getAM2Offset(Offset);
7642 if (isSub)
7643 Offset = -Offset;
7644
7645 MachineMemOperand *MMO = *MI->memoperands_begin();
7646 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7647 .addOperand(MI->getOperand(0)) // Rn_wb
7648 .addOperand(MI->getOperand(1)) // Rt
7649 .addOperand(MI->getOperand(2)) // Rn
7650 .addImm(Offset) // offset (skip GPR==zero_reg)
7651 .addOperand(MI->getOperand(5)) // pred
7652 .addOperand(MI->getOperand(6))
7653 .addMemOperand(MMO);
7654 MI->eraseFromParent();
7655 return BB;
7656 }
7657 case ARM::STRr_preidx:
7658 case ARM::STRBr_preidx:
7659 case ARM::STRH_preidx: {
7660 unsigned NewOpc;
7661 switch (MI->getOpcode()) {
7662 default: llvm_unreachable("unexpected opcode!");
7663 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7664 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7665 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7666 }
7667 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7668 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7669 MIB.addOperand(MI->getOperand(i));
7670 MI->eraseFromParent();
7671 return BB;
7672 }
7673 case ARM::ATOMIC_LOAD_ADD_I8:
7674 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7675 case ARM::ATOMIC_LOAD_ADD_I16:
7676 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7677 case ARM::ATOMIC_LOAD_ADD_I32:
7678 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7679
7680 case ARM::ATOMIC_LOAD_AND_I8:
7681 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7682 case ARM::ATOMIC_LOAD_AND_I16:
7683 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7684 case ARM::ATOMIC_LOAD_AND_I32:
7685 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7686
7687 case ARM::ATOMIC_LOAD_OR_I8:
7688 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7689 case ARM::ATOMIC_LOAD_OR_I16:
7690 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7691 case ARM::ATOMIC_LOAD_OR_I32:
7692 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7693
7694 case ARM::ATOMIC_LOAD_XOR_I8:
7695 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7696 case ARM::ATOMIC_LOAD_XOR_I16:
7697 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7698 case ARM::ATOMIC_LOAD_XOR_I32:
7699 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7700
7701 case ARM::ATOMIC_LOAD_NAND_I8:
7702 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7703 case ARM::ATOMIC_LOAD_NAND_I16:
7704 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7705 case ARM::ATOMIC_LOAD_NAND_I32:
7706 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7707
7708 case ARM::ATOMIC_LOAD_SUB_I8:
7709 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7710 case ARM::ATOMIC_LOAD_SUB_I16:
7711 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7712 case ARM::ATOMIC_LOAD_SUB_I32:
7713 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7714
7715 case ARM::ATOMIC_LOAD_MIN_I8:
7716 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7717 case ARM::ATOMIC_LOAD_MIN_I16:
7718 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7719 case ARM::ATOMIC_LOAD_MIN_I32:
7720 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7721
7722 case ARM::ATOMIC_LOAD_MAX_I8:
7723 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7724 case ARM::ATOMIC_LOAD_MAX_I16:
7725 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7726 case ARM::ATOMIC_LOAD_MAX_I32:
7727 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7728
7729 case ARM::ATOMIC_LOAD_UMIN_I8:
7730 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7731 case ARM::ATOMIC_LOAD_UMIN_I16:
7732 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7733 case ARM::ATOMIC_LOAD_UMIN_I32:
7734 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7735
7736 case ARM::ATOMIC_LOAD_UMAX_I8:
7737 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7738 case ARM::ATOMIC_LOAD_UMAX_I16:
7739 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7740 case ARM::ATOMIC_LOAD_UMAX_I32:
7741 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7742
7743 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7744 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7745 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7746
7747 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7748 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7749 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7750
7751 case ARM::ATOMIC_LOAD_I64:
7752 return EmitAtomicLoad64(MI, BB);
7753
7754 case ARM::ATOMIC_LOAD_ADD_I64:
7755 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7756 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7757 /*NeedsCarry*/ true);
7758 case ARM::ATOMIC_LOAD_SUB_I64:
7759 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7760 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7761 /*NeedsCarry*/ true);
7762 case ARM::ATOMIC_LOAD_OR_I64:
7763 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7764 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7765 case ARM::ATOMIC_LOAD_XOR_I64:
7766 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7767 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7768 case ARM::ATOMIC_LOAD_AND_I64:
7769 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7770 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7771 case ARM::ATOMIC_STORE_I64:
7772 case ARM::ATOMIC_SWAP_I64:
7773 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7774 case ARM::ATOMIC_CMP_SWAP_I64:
7775 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7776 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7777 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7778 case ARM::ATOMIC_LOAD_MIN_I64:
7779 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7780 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7781 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7782 /*IsMinMax*/ true, ARMCC::LT);
7783 case ARM::ATOMIC_LOAD_MAX_I64:
7784 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7785 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7786 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7787 /*IsMinMax*/ true, ARMCC::GE);
7788 case ARM::ATOMIC_LOAD_UMIN_I64:
7789 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7790 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7791 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7792 /*IsMinMax*/ true, ARMCC::LO);
7793 case ARM::ATOMIC_LOAD_UMAX_I64:
7794 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7795 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7796 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7797 /*IsMinMax*/ true, ARMCC::HS);
7798
7799 case ARM::tMOVCCr_pseudo: {
7800 // To "insert" a SELECT_CC instruction, we actually have to insert the
7801 // diamond control-flow pattern. The incoming instruction knows the
7802 // destination vreg to set, the condition code register to branch on, the
7803 // true/false values to select between, and a branch opcode to use.
7804 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7805 MachineFunction::iterator It = BB;
7806 ++It;
7807
7808 // thisMBB:
7809 // ...
7810 // TrueVal = ...
7811 // cmpTY ccX, r1, r2
7812 // bCC copy1MBB
7813 // fallthrough --> copy0MBB
7814 MachineBasicBlock *thisMBB = BB;
7815 MachineFunction *F = BB->getParent();
7816 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7817 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7818 F->insert(It, copy0MBB);
7819 F->insert(It, sinkMBB);
7820
7821 // Transfer the remainder of BB and its successor edges to sinkMBB.
7822 sinkMBB->splice(sinkMBB->begin(), BB,
7823 llvm::next(MachineBasicBlock::iterator(MI)),
7824 BB->end());
7825 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7826
7827 BB->addSuccessor(copy0MBB);
7828 BB->addSuccessor(sinkMBB);
7829
7830 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7831 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7832
7833 // copy0MBB:
7834 // %FalseValue = ...
7835 // # fallthrough to sinkMBB
7836 BB = copy0MBB;
7837
7838 // Update machine-CFG edges
7839 BB->addSuccessor(sinkMBB);
7840
7841 // sinkMBB:
7842 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7843 // ...
7844 BB = sinkMBB;
7845 BuildMI(*BB, BB->begin(), dl,
7846 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7847 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7848 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7849
7850 MI->eraseFromParent(); // The pseudo instruction is gone now.
7851 return BB;
7852 }
7853
7854 case ARM::BCCi64:
7855 case ARM::BCCZi64: {
7856 // If there is an unconditional branch to the other successor, remove it.
7857 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7858
7859 // Compare both parts that make up the double comparison separately for
7860 // equality.
7861 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7862
7863 unsigned LHS1 = MI->getOperand(1).getReg();
7864 unsigned LHS2 = MI->getOperand(2).getReg();
7865 if (RHSisZero) {
7866 AddDefaultPred(BuildMI(BB, dl,
7867 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7868 .addReg(LHS1).addImm(0));
7869 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7870 .addReg(LHS2).addImm(0)
7871 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7872 } else {
7873 unsigned RHS1 = MI->getOperand(3).getReg();
7874 unsigned RHS2 = MI->getOperand(4).getReg();
7875 AddDefaultPred(BuildMI(BB, dl,
7876 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7877 .addReg(LHS1).addReg(RHS1));
7878 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7879 .addReg(LHS2).addReg(RHS2)
7880 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7881 }
7882
7883 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7884 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7885 if (MI->getOperand(0).getImm() == ARMCC::NE)
7886 std::swap(destMBB, exitMBB);
7887
7888 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7889 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7890 if (isThumb2)
7891 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7892 else
7893 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7894
7895 MI->eraseFromParent(); // The pseudo instruction is gone now.
7896 return BB;
7897 }
7898
7899 case ARM::Int_eh_sjlj_setjmp:
7900 case ARM::Int_eh_sjlj_setjmp_nofp:
7901 case ARM::tInt_eh_sjlj_setjmp:
7902 case ARM::t2Int_eh_sjlj_setjmp:
7903 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7904 EmitSjLjDispatchBlock(MI, BB);
7905 return BB;
7906
7907 case ARM::ABS:
7908 case ARM::t2ABS: {
7909 // To insert an ABS instruction, we have to insert the
7910 // diamond control-flow pattern. The incoming instruction knows the
7911 // source vreg to test against 0, the destination vreg to set,
7912 // the condition code register to branch on, the
7913 // true/false values to select between, and a branch opcode to use.
7914 // It transforms
7915 // V1 = ABS V0
7916 // into
7917 // V2 = MOVS V0
7918 // BCC (branch to SinkBB if V0 >= 0)
7919 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7920 // SinkBB: V1 = PHI(V2, V3)
7921 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7922 MachineFunction::iterator BBI = BB;
7923 ++BBI;
7924 MachineFunction *Fn = BB->getParent();
7925 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7926 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7927 Fn->insert(BBI, RSBBB);
7928 Fn->insert(BBI, SinkBB);
7929
7930 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7931 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7932 bool isThumb2 = Subtarget->isThumb2();
7933 MachineRegisterInfo &MRI = Fn->getRegInfo();
7934 // In Thumb mode S must not be specified if source register is the SP or
7935 // PC and if destination register is the SP, so restrict register class
7936 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7937 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7938 (const TargetRegisterClass*)&ARM::GPRRegClass);
7939
7940 // Transfer the remainder of BB and its successor edges to sinkMBB.
7941 SinkBB->splice(SinkBB->begin(), BB,
7942 llvm::next(MachineBasicBlock::iterator(MI)),
7943 BB->end());
7944 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7945
7946 BB->addSuccessor(RSBBB);
7947 BB->addSuccessor(SinkBB);
7948
7949 // fall through to SinkMBB
7950 RSBBB->addSuccessor(SinkBB);
7951
7952 // insert a cmp at the end of BB
7953 AddDefaultPred(BuildMI(BB, dl,
7954 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7955 .addReg(ABSSrcReg).addImm(0));
7956
7957 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7958 BuildMI(BB, dl,
7959 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7960 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7961
7962 // insert rsbri in RSBBB
7963 // Note: BCC and rsbri will be converted into predicated rsbmi
7964 // by if-conversion pass
7965 BuildMI(*RSBBB, RSBBB->begin(), dl,
7966 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7967 .addReg(ABSSrcReg, RegState::Kill)
7968 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7969
7970 // insert PHI in SinkBB,
7971 // reuse ABSDstReg to not change uses of ABS instruction
7972 BuildMI(*SinkBB, SinkBB->begin(), dl,
7973 TII->get(ARM::PHI), ABSDstReg)
7974 .addReg(NewRsbDstReg).addMBB(RSBBB)
7975 .addReg(ABSSrcReg).addMBB(BB);
7976
7977 // remove ABS instruction
7978 MI->eraseFromParent();
7979
7980 // return last added BB
7981 return SinkBB;
7982 }
7983 case ARM::COPY_STRUCT_BYVAL_I32:
7984 ++NumLoopByVals;
7985 return EmitStructByval(MI, BB);
7986 }
7987 }
7988
AdjustInstrPostInstrSelection(MachineInstr * MI,SDNode * Node) const7989 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7990 SDNode *Node) const {
7991 if (!MI->hasPostISelHook()) {
7992 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7993 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7994 return;
7995 }
7996
7997 const MCInstrDesc *MCID = &MI->getDesc();
7998 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7999 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8000 // operand is still set to noreg. If needed, set the optional operand's
8001 // register to CPSR, and remove the redundant implicit def.
8002 //
8003 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8004
8005 // Rename pseudo opcodes.
8006 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8007 if (NewOpc) {
8008 const ARMBaseInstrInfo *TII =
8009 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
8010 MCID = &TII->get(NewOpc);
8011
8012 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8013 "converted opcode should be the same except for cc_out");
8014
8015 MI->setDesc(*MCID);
8016
8017 // Add the optional cc_out operand
8018 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8019 }
8020 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8021
8022 // Any ARM instruction that sets the 's' bit should specify an optional
8023 // "cc_out" operand in the last operand position.
8024 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8025 assert(!NewOpc && "Optional cc_out operand required");
8026 return;
8027 }
8028 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8029 // since we already have an optional CPSR def.
8030 bool definesCPSR = false;
8031 bool deadCPSR = false;
8032 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8033 i != e; ++i) {
8034 const MachineOperand &MO = MI->getOperand(i);
8035 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8036 definesCPSR = true;
8037 if (MO.isDead())
8038 deadCPSR = true;
8039 MI->RemoveOperand(i);
8040 break;
8041 }
8042 }
8043 if (!definesCPSR) {
8044 assert(!NewOpc && "Optional cc_out operand required");
8045 return;
8046 }
8047 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8048 if (deadCPSR) {
8049 assert(!MI->getOperand(ccOutIdx).getReg() &&
8050 "expect uninitialized optional cc_out operand");
8051 return;
8052 }
8053
8054 // If this instruction was defined with an optional CPSR def and its dag node
8055 // had a live implicit CPSR def, then activate the optional CPSR def.
8056 MachineOperand &MO = MI->getOperand(ccOutIdx);
8057 MO.setReg(ARM::CPSR);
8058 MO.setIsDef(true);
8059 }
8060
8061 //===----------------------------------------------------------------------===//
8062 // ARM Optimization Hooks
8063 //===----------------------------------------------------------------------===//
8064
8065 // Helper function that checks if N is a null or all ones constant.
isZeroOrAllOnes(SDValue N,bool AllOnes)8066 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8067 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8068 if (!C)
8069 return false;
8070 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8071 }
8072
8073 // Return true if N is conditionally 0 or all ones.
8074 // Detects these expressions where cc is an i1 value:
8075 //
8076 // (select cc 0, y) [AllOnes=0]
8077 // (select cc y, 0) [AllOnes=0]
8078 // (zext cc) [AllOnes=0]
8079 // (sext cc) [AllOnes=0/1]
8080 // (select cc -1, y) [AllOnes=1]
8081 // (select cc y, -1) [AllOnes=1]
8082 //
8083 // Invert is set when N is the null/all ones constant when CC is false.
8084 // OtherOp is set to the alternative value of N.
isConditionalZeroOrAllOnes(SDNode * N,bool AllOnes,SDValue & CC,bool & Invert,SDValue & OtherOp,SelectionDAG & DAG)8085 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8086 SDValue &CC, bool &Invert,
8087 SDValue &OtherOp,
8088 SelectionDAG &DAG) {
8089 switch (N->getOpcode()) {
8090 default: return false;
8091 case ISD::SELECT: {
8092 CC = N->getOperand(0);
8093 SDValue N1 = N->getOperand(1);
8094 SDValue N2 = N->getOperand(2);
8095 if (isZeroOrAllOnes(N1, AllOnes)) {
8096 Invert = false;
8097 OtherOp = N2;
8098 return true;
8099 }
8100 if (isZeroOrAllOnes(N2, AllOnes)) {
8101 Invert = true;
8102 OtherOp = N1;
8103 return true;
8104 }
8105 return false;
8106 }
8107 case ISD::ZERO_EXTEND:
8108 // (zext cc) can never be the all ones value.
8109 if (AllOnes)
8110 return false;
8111 // Fall through.
8112 case ISD::SIGN_EXTEND: {
8113 EVT VT = N->getValueType(0);
8114 CC = N->getOperand(0);
8115 if (CC.getValueType() != MVT::i1)
8116 return false;
8117 Invert = !AllOnes;
8118 if (AllOnes)
8119 // When looking for an AllOnes constant, N is an sext, and the 'other'
8120 // value is 0.
8121 OtherOp = DAG.getConstant(0, VT);
8122 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8123 // When looking for a 0 constant, N can be zext or sext.
8124 OtherOp = DAG.getConstant(1, VT);
8125 else
8126 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8127 return true;
8128 }
8129 }
8130 }
8131
8132 // Combine a constant select operand into its use:
8133 //
8134 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8135 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8136 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8137 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8138 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8139 //
8140 // The transform is rejected if the select doesn't have a constant operand that
8141 // is null, or all ones when AllOnes is set.
8142 //
8143 // Also recognize sext/zext from i1:
8144 //
8145 // (add (zext cc), x) -> (select cc (add x, 1), x)
8146 // (add (sext cc), x) -> (select cc (add x, -1), x)
8147 //
8148 // These transformations eventually create predicated instructions.
8149 //
8150 // @param N The node to transform.
8151 // @param Slct The N operand that is a select.
8152 // @param OtherOp The other N operand (x above).
8153 // @param DCI Context.
8154 // @param AllOnes Require the select constant to be all ones instead of null.
8155 // @returns The new node, or SDValue() on failure.
8156 static
combineSelectAndUse(SDNode * N,SDValue Slct,SDValue OtherOp,TargetLowering::DAGCombinerInfo & DCI,bool AllOnes=false)8157 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8158 TargetLowering::DAGCombinerInfo &DCI,
8159 bool AllOnes = false) {
8160 SelectionDAG &DAG = DCI.DAG;
8161 EVT VT = N->getValueType(0);
8162 SDValue NonConstantVal;
8163 SDValue CCOp;
8164 bool SwapSelectOps;
8165 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8166 NonConstantVal, DAG))
8167 return SDValue();
8168
8169 // Slct is now know to be the desired identity constant when CC is true.
8170 SDValue TrueVal = OtherOp;
8171 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8172 OtherOp, NonConstantVal);
8173 // Unless SwapSelectOps says CC should be false.
8174 if (SwapSelectOps)
8175 std::swap(TrueVal, FalseVal);
8176
8177 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8178 CCOp, TrueVal, FalseVal);
8179 }
8180
8181 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8182 static
combineSelectAndUseCommutative(SDNode * N,bool AllOnes,TargetLowering::DAGCombinerInfo & DCI)8183 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8184 TargetLowering::DAGCombinerInfo &DCI) {
8185 SDValue N0 = N->getOperand(0);
8186 SDValue N1 = N->getOperand(1);
8187 if (N0.getNode()->hasOneUse()) {
8188 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8189 if (Result.getNode())
8190 return Result;
8191 }
8192 if (N1.getNode()->hasOneUse()) {
8193 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8194 if (Result.getNode())
8195 return Result;
8196 }
8197 return SDValue();
8198 }
8199
8200 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8201 // (only after legalization).
AddCombineToVPADDL(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8202 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8203 TargetLowering::DAGCombinerInfo &DCI,
8204 const ARMSubtarget *Subtarget) {
8205
8206 // Only perform optimization if after legalize, and if NEON is available. We
8207 // also expected both operands to be BUILD_VECTORs.
8208 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8209 || N0.getOpcode() != ISD::BUILD_VECTOR
8210 || N1.getOpcode() != ISD::BUILD_VECTOR)
8211 return SDValue();
8212
8213 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8214 EVT VT = N->getValueType(0);
8215 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8216 return SDValue();
8217
8218 // Check that the vector operands are of the right form.
8219 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8220 // operands, where N is the size of the formed vector.
8221 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8222 // index such that we have a pair wise add pattern.
8223
8224 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8225 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8226 return SDValue();
8227 SDValue Vec = N0->getOperand(0)->getOperand(0);
8228 SDNode *V = Vec.getNode();
8229 unsigned nextIndex = 0;
8230
8231 // For each operands to the ADD which are BUILD_VECTORs,
8232 // check to see if each of their operands are an EXTRACT_VECTOR with
8233 // the same vector and appropriate index.
8234 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8235 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8236 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8237
8238 SDValue ExtVec0 = N0->getOperand(i);
8239 SDValue ExtVec1 = N1->getOperand(i);
8240
8241 // First operand is the vector, verify its the same.
8242 if (V != ExtVec0->getOperand(0).getNode() ||
8243 V != ExtVec1->getOperand(0).getNode())
8244 return SDValue();
8245
8246 // Second is the constant, verify its correct.
8247 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8248 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8249
8250 // For the constant, we want to see all the even or all the odd.
8251 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8252 || C1->getZExtValue() != nextIndex+1)
8253 return SDValue();
8254
8255 // Increment index.
8256 nextIndex+=2;
8257 } else
8258 return SDValue();
8259 }
8260
8261 // Create VPADDL node.
8262 SelectionDAG &DAG = DCI.DAG;
8263 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8264
8265 // Build operand list.
8266 SmallVector<SDValue, 8> Ops;
8267 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8268 TLI.getPointerTy()));
8269
8270 // Input is the vector.
8271 Ops.push_back(Vec);
8272
8273 // Get widened type and narrowed type.
8274 MVT widenType;
8275 unsigned numElem = VT.getVectorNumElements();
8276 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8277 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8278 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8279 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8280 default:
8281 llvm_unreachable("Invalid vector element type for padd optimization.");
8282 }
8283
8284 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8285 widenType, &Ops[0], Ops.size());
8286 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8287 }
8288
findMUL_LOHI(SDValue V)8289 static SDValue findMUL_LOHI(SDValue V) {
8290 if (V->getOpcode() == ISD::UMUL_LOHI ||
8291 V->getOpcode() == ISD::SMUL_LOHI)
8292 return V;
8293 return SDValue();
8294 }
8295
AddCombineTo64bitMLAL(SDNode * AddcNode,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8296 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8297 TargetLowering::DAGCombinerInfo &DCI,
8298 const ARMSubtarget *Subtarget) {
8299
8300 if (Subtarget->isThumb1Only()) return SDValue();
8301
8302 // Only perform the checks after legalize when the pattern is available.
8303 if (DCI.isBeforeLegalize()) return SDValue();
8304
8305 // Look for multiply add opportunities.
8306 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8307 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8308 // a glue link from the first add to the second add.
8309 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8310 // a S/UMLAL instruction.
8311 // loAdd UMUL_LOHI
8312 // \ / :lo \ :hi
8313 // \ / \ [no multiline comment]
8314 // ADDC | hiAdd
8315 // \ :glue / /
8316 // \ / /
8317 // ADDE
8318 //
8319 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8320 SDValue AddcOp0 = AddcNode->getOperand(0);
8321 SDValue AddcOp1 = AddcNode->getOperand(1);
8322
8323 // Check if the two operands are from the same mul_lohi node.
8324 if (AddcOp0.getNode() == AddcOp1.getNode())
8325 return SDValue();
8326
8327 assert(AddcNode->getNumValues() == 2 &&
8328 AddcNode->getValueType(0) == MVT::i32 &&
8329 "Expect ADDC with two result values. First: i32");
8330
8331 // Check that we have a glued ADDC node.
8332 if (AddcNode->getValueType(1) != MVT::Glue)
8333 return SDValue();
8334
8335 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8336 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8337 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8338 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8339 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8340 return SDValue();
8341
8342 // Look for the glued ADDE.
8343 SDNode* AddeNode = AddcNode->getGluedUser();
8344 if (AddeNode == NULL)
8345 return SDValue();
8346
8347 // Make sure it is really an ADDE.
8348 if (AddeNode->getOpcode() != ISD::ADDE)
8349 return SDValue();
8350
8351 assert(AddeNode->getNumOperands() == 3 &&
8352 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8353 "ADDE node has the wrong inputs");
8354
8355 // Check for the triangle shape.
8356 SDValue AddeOp0 = AddeNode->getOperand(0);
8357 SDValue AddeOp1 = AddeNode->getOperand(1);
8358
8359 // Make sure that the ADDE operands are not coming from the same node.
8360 if (AddeOp0.getNode() == AddeOp1.getNode())
8361 return SDValue();
8362
8363 // Find the MUL_LOHI node walking up ADDE's operands.
8364 bool IsLeftOperandMUL = false;
8365 SDValue MULOp = findMUL_LOHI(AddeOp0);
8366 if (MULOp == SDValue())
8367 MULOp = findMUL_LOHI(AddeOp1);
8368 else
8369 IsLeftOperandMUL = true;
8370 if (MULOp == SDValue())
8371 return SDValue();
8372
8373 // Figure out the right opcode.
8374 unsigned Opc = MULOp->getOpcode();
8375 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8376
8377 // Figure out the high and low input values to the MLAL node.
8378 SDValue* HiMul = &MULOp;
8379 SDValue* HiAdd = NULL;
8380 SDValue* LoMul = NULL;
8381 SDValue* LowAdd = NULL;
8382
8383 if (IsLeftOperandMUL)
8384 HiAdd = &AddeOp1;
8385 else
8386 HiAdd = &AddeOp0;
8387
8388
8389 if (AddcOp0->getOpcode() == Opc) {
8390 LoMul = &AddcOp0;
8391 LowAdd = &AddcOp1;
8392 }
8393 if (AddcOp1->getOpcode() == Opc) {
8394 LoMul = &AddcOp1;
8395 LowAdd = &AddcOp0;
8396 }
8397
8398 if (LoMul == NULL)
8399 return SDValue();
8400
8401 if (LoMul->getNode() != HiMul->getNode())
8402 return SDValue();
8403
8404 // Create the merged node.
8405 SelectionDAG &DAG = DCI.DAG;
8406
8407 // Build operand list.
8408 SmallVector<SDValue, 8> Ops;
8409 Ops.push_back(LoMul->getOperand(0));
8410 Ops.push_back(LoMul->getOperand(1));
8411 Ops.push_back(*LowAdd);
8412 Ops.push_back(*HiAdd);
8413
8414 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8415 DAG.getVTList(MVT::i32, MVT::i32),
8416 &Ops[0], Ops.size());
8417
8418 // Replace the ADDs' nodes uses by the MLA node's values.
8419 SDValue HiMLALResult(MLALNode.getNode(), 1);
8420 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8421
8422 SDValue LoMLALResult(MLALNode.getNode(), 0);
8423 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8424
8425 // Return original node to notify the driver to stop replacing.
8426 SDValue resNode(AddcNode, 0);
8427 return resNode;
8428 }
8429
8430 /// PerformADDCCombine - Target-specific dag combine transform from
8431 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
PerformADDCCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8432 static SDValue PerformADDCCombine(SDNode *N,
8433 TargetLowering::DAGCombinerInfo &DCI,
8434 const ARMSubtarget *Subtarget) {
8435
8436 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8437
8438 }
8439
8440 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8441 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8442 /// called with the default operands, and if that fails, with commuted
8443 /// operands.
PerformADDCombineWithOperands(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8444 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8445 TargetLowering::DAGCombinerInfo &DCI,
8446 const ARMSubtarget *Subtarget){
8447
8448 // Attempt to create vpaddl for this add.
8449 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8450 if (Result.getNode())
8451 return Result;
8452
8453 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8454 if (N0.getNode()->hasOneUse()) {
8455 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8456 if (Result.getNode()) return Result;
8457 }
8458 return SDValue();
8459 }
8460
8461 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8462 ///
PerformADDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8463 static SDValue PerformADDCombine(SDNode *N,
8464 TargetLowering::DAGCombinerInfo &DCI,
8465 const ARMSubtarget *Subtarget) {
8466 SDValue N0 = N->getOperand(0);
8467 SDValue N1 = N->getOperand(1);
8468
8469 // First try with the default operand order.
8470 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8471 if (Result.getNode())
8472 return Result;
8473
8474 // If that didn't work, try again with the operands commuted.
8475 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8476 }
8477
8478 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8479 ///
PerformSUBCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8480 static SDValue PerformSUBCombine(SDNode *N,
8481 TargetLowering::DAGCombinerInfo &DCI) {
8482 SDValue N0 = N->getOperand(0);
8483 SDValue N1 = N->getOperand(1);
8484
8485 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8486 if (N1.getNode()->hasOneUse()) {
8487 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8488 if (Result.getNode()) return Result;
8489 }
8490
8491 return SDValue();
8492 }
8493
8494 /// PerformVMULCombine
8495 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8496 /// special multiplier accumulator forwarding.
8497 /// vmul d3, d0, d2
8498 /// vmla d3, d1, d2
8499 /// is faster than
8500 /// vadd d3, d0, d1
8501 /// vmul d3, d3, d2
8502 // However, for (A + B) * (A + B),
8503 // vadd d2, d0, d1
8504 // vmul d3, d0, d2
8505 // vmla d3, d1, d2
8506 // is slower than
8507 // vadd d2, d0, d1
8508 // vmul d3, d2, d2
PerformVMULCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8509 static SDValue PerformVMULCombine(SDNode *N,
8510 TargetLowering::DAGCombinerInfo &DCI,
8511 const ARMSubtarget *Subtarget) {
8512 if (!Subtarget->hasVMLxForwarding())
8513 return SDValue();
8514
8515 SelectionDAG &DAG = DCI.DAG;
8516 SDValue N0 = N->getOperand(0);
8517 SDValue N1 = N->getOperand(1);
8518 unsigned Opcode = N0.getOpcode();
8519 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8520 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8521 Opcode = N1.getOpcode();
8522 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8523 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8524 return SDValue();
8525 std::swap(N0, N1);
8526 }
8527
8528 if (N0 == N1)
8529 return SDValue();
8530
8531 EVT VT = N->getValueType(0);
8532 SDLoc DL(N);
8533 SDValue N00 = N0->getOperand(0);
8534 SDValue N01 = N0->getOperand(1);
8535 return DAG.getNode(Opcode, DL, VT,
8536 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8537 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8538 }
8539
PerformMULCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8540 static SDValue PerformMULCombine(SDNode *N,
8541 TargetLowering::DAGCombinerInfo &DCI,
8542 const ARMSubtarget *Subtarget) {
8543 SelectionDAG &DAG = DCI.DAG;
8544
8545 if (Subtarget->isThumb1Only())
8546 return SDValue();
8547
8548 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8549 return SDValue();
8550
8551 EVT VT = N->getValueType(0);
8552 if (VT.is64BitVector() || VT.is128BitVector())
8553 return PerformVMULCombine(N, DCI, Subtarget);
8554 if (VT != MVT::i32)
8555 return SDValue();
8556
8557 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8558 if (!C)
8559 return SDValue();
8560
8561 int64_t MulAmt = C->getSExtValue();
8562 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8563
8564 ShiftAmt = ShiftAmt & (32 - 1);
8565 SDValue V = N->getOperand(0);
8566 SDLoc DL(N);
8567
8568 SDValue Res;
8569 MulAmt >>= ShiftAmt;
8570
8571 if (MulAmt >= 0) {
8572 if (isPowerOf2_32(MulAmt - 1)) {
8573 // (mul x, 2^N + 1) => (add (shl x, N), x)
8574 Res = DAG.getNode(ISD::ADD, DL, VT,
8575 V,
8576 DAG.getNode(ISD::SHL, DL, VT,
8577 V,
8578 DAG.getConstant(Log2_32(MulAmt - 1),
8579 MVT::i32)));
8580 } else if (isPowerOf2_32(MulAmt + 1)) {
8581 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8582 Res = DAG.getNode(ISD::SUB, DL, VT,
8583 DAG.getNode(ISD::SHL, DL, VT,
8584 V,
8585 DAG.getConstant(Log2_32(MulAmt + 1),
8586 MVT::i32)),
8587 V);
8588 } else
8589 return SDValue();
8590 } else {
8591 uint64_t MulAmtAbs = -MulAmt;
8592 if (isPowerOf2_32(MulAmtAbs + 1)) {
8593 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8594 Res = DAG.getNode(ISD::SUB, DL, VT,
8595 V,
8596 DAG.getNode(ISD::SHL, DL, VT,
8597 V,
8598 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8599 MVT::i32)));
8600 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8601 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8602 Res = DAG.getNode(ISD::ADD, DL, VT,
8603 V,
8604 DAG.getNode(ISD::SHL, DL, VT,
8605 V,
8606 DAG.getConstant(Log2_32(MulAmtAbs-1),
8607 MVT::i32)));
8608 Res = DAG.getNode(ISD::SUB, DL, VT,
8609 DAG.getConstant(0, MVT::i32),Res);
8610
8611 } else
8612 return SDValue();
8613 }
8614
8615 if (ShiftAmt != 0)
8616 Res = DAG.getNode(ISD::SHL, DL, VT,
8617 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8618
8619 // Do not add new nodes to DAG combiner worklist.
8620 DCI.CombineTo(N, Res, false);
8621 return SDValue();
8622 }
8623
PerformANDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8624 static SDValue PerformANDCombine(SDNode *N,
8625 TargetLowering::DAGCombinerInfo &DCI,
8626 const ARMSubtarget *Subtarget) {
8627
8628 // Attempt to use immediate-form VBIC
8629 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8630 SDLoc dl(N);
8631 EVT VT = N->getValueType(0);
8632 SelectionDAG &DAG = DCI.DAG;
8633
8634 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8635 return SDValue();
8636
8637 APInt SplatBits, SplatUndef;
8638 unsigned SplatBitSize;
8639 bool HasAnyUndefs;
8640 if (BVN &&
8641 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8642 if (SplatBitSize <= 64) {
8643 EVT VbicVT;
8644 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8645 SplatUndef.getZExtValue(), SplatBitSize,
8646 DAG, VbicVT, VT.is128BitVector(),
8647 OtherModImm);
8648 if (Val.getNode()) {
8649 SDValue Input =
8650 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8651 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8652 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8653 }
8654 }
8655 }
8656
8657 if (!Subtarget->isThumb1Only()) {
8658 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8659 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8660 if (Result.getNode())
8661 return Result;
8662 }
8663
8664 return SDValue();
8665 }
8666
8667 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
PerformORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8668 static SDValue PerformORCombine(SDNode *N,
8669 TargetLowering::DAGCombinerInfo &DCI,
8670 const ARMSubtarget *Subtarget) {
8671 // Attempt to use immediate-form VORR
8672 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8673 SDLoc dl(N);
8674 EVT VT = N->getValueType(0);
8675 SelectionDAG &DAG = DCI.DAG;
8676
8677 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8678 return SDValue();
8679
8680 APInt SplatBits, SplatUndef;
8681 unsigned SplatBitSize;
8682 bool HasAnyUndefs;
8683 if (BVN && Subtarget->hasNEON() &&
8684 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8685 if (SplatBitSize <= 64) {
8686 EVT VorrVT;
8687 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8688 SplatUndef.getZExtValue(), SplatBitSize,
8689 DAG, VorrVT, VT.is128BitVector(),
8690 OtherModImm);
8691 if (Val.getNode()) {
8692 SDValue Input =
8693 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8694 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8695 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8696 }
8697 }
8698 }
8699
8700 if (!Subtarget->isThumb1Only()) {
8701 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8702 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8703 if (Result.getNode())
8704 return Result;
8705 }
8706
8707 // The code below optimizes (or (and X, Y), Z).
8708 // The AND operand needs to have a single user to make these optimizations
8709 // profitable.
8710 SDValue N0 = N->getOperand(0);
8711 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8712 return SDValue();
8713 SDValue N1 = N->getOperand(1);
8714
8715 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8716 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8717 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8718 APInt SplatUndef;
8719 unsigned SplatBitSize;
8720 bool HasAnyUndefs;
8721
8722 APInt SplatBits0, SplatBits1;
8723 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8724 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8725 // Ensure that the second operand of both ands are constants
8726 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8727 HasAnyUndefs) && !HasAnyUndefs) {
8728 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8729 HasAnyUndefs) && !HasAnyUndefs) {
8730 // Ensure that the bit width of the constants are the same and that
8731 // the splat arguments are logical inverses as per the pattern we
8732 // are trying to simplify.
8733 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8734 SplatBits0 == ~SplatBits1) {
8735 // Canonicalize the vector type to make instruction selection
8736 // simpler.
8737 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8738 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8739 N0->getOperand(1),
8740 N0->getOperand(0),
8741 N1->getOperand(0));
8742 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8743 }
8744 }
8745 }
8746 }
8747
8748 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8749 // reasonable.
8750
8751 // BFI is only available on V6T2+
8752 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8753 return SDValue();
8754
8755 SDLoc DL(N);
8756 // 1) or (and A, mask), val => ARMbfi A, val, mask
8757 // iff (val & mask) == val
8758 //
8759 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8760 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8761 // && mask == ~mask2
8762 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8763 // && ~mask == mask2
8764 // (i.e., copy a bitfield value into another bitfield of the same width)
8765
8766 if (VT != MVT::i32)
8767 return SDValue();
8768
8769 SDValue N00 = N0.getOperand(0);
8770
8771 // The value and the mask need to be constants so we can verify this is
8772 // actually a bitfield set. If the mask is 0xffff, we can do better
8773 // via a movt instruction, so don't use BFI in that case.
8774 SDValue MaskOp = N0.getOperand(1);
8775 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8776 if (!MaskC)
8777 return SDValue();
8778 unsigned Mask = MaskC->getZExtValue();
8779 if (Mask == 0xffff)
8780 return SDValue();
8781 SDValue Res;
8782 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8783 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8784 if (N1C) {
8785 unsigned Val = N1C->getZExtValue();
8786 if ((Val & ~Mask) != Val)
8787 return SDValue();
8788
8789 if (ARM::isBitFieldInvertedMask(Mask)) {
8790 Val >>= countTrailingZeros(~Mask);
8791
8792 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8793 DAG.getConstant(Val, MVT::i32),
8794 DAG.getConstant(Mask, MVT::i32));
8795
8796 // Do not add new nodes to DAG combiner worklist.
8797 DCI.CombineTo(N, Res, false);
8798 return SDValue();
8799 }
8800 } else if (N1.getOpcode() == ISD::AND) {
8801 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8802 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8803 if (!N11C)
8804 return SDValue();
8805 unsigned Mask2 = N11C->getZExtValue();
8806
8807 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8808 // as is to match.
8809 if (ARM::isBitFieldInvertedMask(Mask) &&
8810 (Mask == ~Mask2)) {
8811 // The pack halfword instruction works better for masks that fit it,
8812 // so use that when it's available.
8813 if (Subtarget->hasT2ExtractPack() &&
8814 (Mask == 0xffff || Mask == 0xffff0000))
8815 return SDValue();
8816 // 2a
8817 unsigned amt = countTrailingZeros(Mask2);
8818 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8819 DAG.getConstant(amt, MVT::i32));
8820 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8821 DAG.getConstant(Mask, MVT::i32));
8822 // Do not add new nodes to DAG combiner worklist.
8823 DCI.CombineTo(N, Res, false);
8824 return SDValue();
8825 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8826 (~Mask == Mask2)) {
8827 // The pack halfword instruction works better for masks that fit it,
8828 // so use that when it's available.
8829 if (Subtarget->hasT2ExtractPack() &&
8830 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8831 return SDValue();
8832 // 2b
8833 unsigned lsb = countTrailingZeros(Mask);
8834 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8835 DAG.getConstant(lsb, MVT::i32));
8836 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8837 DAG.getConstant(Mask2, MVT::i32));
8838 // Do not add new nodes to DAG combiner worklist.
8839 DCI.CombineTo(N, Res, false);
8840 return SDValue();
8841 }
8842 }
8843
8844 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8845 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8846 ARM::isBitFieldInvertedMask(~Mask)) {
8847 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8848 // where lsb(mask) == #shamt and masked bits of B are known zero.
8849 SDValue ShAmt = N00.getOperand(1);
8850 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8851 unsigned LSB = countTrailingZeros(Mask);
8852 if (ShAmtC != LSB)
8853 return SDValue();
8854
8855 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8856 DAG.getConstant(~Mask, MVT::i32));
8857
8858 // Do not add new nodes to DAG combiner worklist.
8859 DCI.CombineTo(N, Res, false);
8860 }
8861
8862 return SDValue();
8863 }
8864
PerformXORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)8865 static SDValue PerformXORCombine(SDNode *N,
8866 TargetLowering::DAGCombinerInfo &DCI,
8867 const ARMSubtarget *Subtarget) {
8868 EVT VT = N->getValueType(0);
8869 SelectionDAG &DAG = DCI.DAG;
8870
8871 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8872 return SDValue();
8873
8874 if (!Subtarget->isThumb1Only()) {
8875 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8876 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8877 if (Result.getNode())
8878 return Result;
8879 }
8880
8881 return SDValue();
8882 }
8883
8884 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8885 /// the bits being cleared by the AND are not demanded by the BFI.
PerformBFICombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8886 static SDValue PerformBFICombine(SDNode *N,
8887 TargetLowering::DAGCombinerInfo &DCI) {
8888 SDValue N1 = N->getOperand(1);
8889 if (N1.getOpcode() == ISD::AND) {
8890 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8891 if (!N11C)
8892 return SDValue();
8893 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8894 unsigned LSB = countTrailingZeros(~InvMask);
8895 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8896 unsigned Mask = (1 << Width)-1;
8897 unsigned Mask2 = N11C->getZExtValue();
8898 if ((Mask & (~Mask2)) == 0)
8899 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8900 N->getOperand(0), N1.getOperand(0),
8901 N->getOperand(2));
8902 }
8903 return SDValue();
8904 }
8905
8906 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8907 /// ARMISD::VMOVRRD.
PerformVMOVRRDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8908 static SDValue PerformVMOVRRDCombine(SDNode *N,
8909 TargetLowering::DAGCombinerInfo &DCI) {
8910 // vmovrrd(vmovdrr x, y) -> x,y
8911 SDValue InDouble = N->getOperand(0);
8912 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8913 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8914
8915 // vmovrrd(load f64) -> (load i32), (load i32)
8916 SDNode *InNode = InDouble.getNode();
8917 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8918 InNode->getValueType(0) == MVT::f64 &&
8919 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8920 !cast<LoadSDNode>(InNode)->isVolatile()) {
8921 // TODO: Should this be done for non-FrameIndex operands?
8922 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8923
8924 SelectionDAG &DAG = DCI.DAG;
8925 SDLoc DL(LD);
8926 SDValue BasePtr = LD->getBasePtr();
8927 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8928 LD->getPointerInfo(), LD->isVolatile(),
8929 LD->isNonTemporal(), LD->isInvariant(),
8930 LD->getAlignment());
8931
8932 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8933 DAG.getConstant(4, MVT::i32));
8934 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8935 LD->getPointerInfo(), LD->isVolatile(),
8936 LD->isNonTemporal(), LD->isInvariant(),
8937 std::min(4U, LD->getAlignment() / 2));
8938
8939 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8940 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8941 DCI.RemoveFromWorklist(LD);
8942 DAG.DeleteNode(LD);
8943 return Result;
8944 }
8945
8946 return SDValue();
8947 }
8948
8949 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8950 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
PerformVMOVDRRCombine(SDNode * N,SelectionDAG & DAG)8951 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8952 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8953 SDValue Op0 = N->getOperand(0);
8954 SDValue Op1 = N->getOperand(1);
8955 if (Op0.getOpcode() == ISD::BITCAST)
8956 Op0 = Op0.getOperand(0);
8957 if (Op1.getOpcode() == ISD::BITCAST)
8958 Op1 = Op1.getOperand(0);
8959 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8960 Op0.getNode() == Op1.getNode() &&
8961 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8962 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8963 N->getValueType(0), Op0.getOperand(0));
8964 return SDValue();
8965 }
8966
8967 /// PerformSTORECombine - Target-specific dag combine xforms for
8968 /// ISD::STORE.
PerformSTORECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)8969 static SDValue PerformSTORECombine(SDNode *N,
8970 TargetLowering::DAGCombinerInfo &DCI) {
8971 StoreSDNode *St = cast<StoreSDNode>(N);
8972 if (St->isVolatile())
8973 return SDValue();
8974
8975 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8976 // pack all of the elements in one place. Next, store to memory in fewer
8977 // chunks.
8978 SDValue StVal = St->getValue();
8979 EVT VT = StVal.getValueType();
8980 if (St->isTruncatingStore() && VT.isVector()) {
8981 SelectionDAG &DAG = DCI.DAG;
8982 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8983 EVT StVT = St->getMemoryVT();
8984 unsigned NumElems = VT.getVectorNumElements();
8985 assert(StVT != VT && "Cannot truncate to the same type");
8986 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8987 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8988
8989 // From, To sizes and ElemCount must be pow of two
8990 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8991
8992 // We are going to use the original vector elt for storing.
8993 // Accumulated smaller vector elements must be a multiple of the store size.
8994 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8995
8996 unsigned SizeRatio = FromEltSz / ToEltSz;
8997 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8998
8999 // Create a type on which we perform the shuffle.
9000 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9001 NumElems*SizeRatio);
9002 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9003
9004 SDLoc DL(St);
9005 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9006 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9007 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
9008
9009 // Can't shuffle using an illegal type.
9010 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9011
9012 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9013 DAG.getUNDEF(WideVec.getValueType()),
9014 ShuffleVec.data());
9015 // At this point all of the data is stored at the bottom of the
9016 // register. We now need to save it to mem.
9017
9018 // Find the largest store unit
9019 MVT StoreType = MVT::i8;
9020 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
9021 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9022 MVT Tp = (MVT::SimpleValueType)tp;
9023 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9024 StoreType = Tp;
9025 }
9026 // Didn't find a legal store type.
9027 if (!TLI.isTypeLegal(StoreType))
9028 return SDValue();
9029
9030 // Bitcast the original vector into a vector of store-size units
9031 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9032 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9033 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9034 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9035 SmallVector<SDValue, 8> Chains;
9036 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9037 TLI.getPointerTy());
9038 SDValue BasePtr = St->getBasePtr();
9039
9040 // Perform one or more big stores into memory.
9041 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9042 for (unsigned I = 0; I < E; I++) {
9043 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9044 StoreType, ShuffWide,
9045 DAG.getIntPtrConstant(I));
9046 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9047 St->getPointerInfo(), St->isVolatile(),
9048 St->isNonTemporal(), St->getAlignment());
9049 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9050 Increment);
9051 Chains.push_back(Ch);
9052 }
9053 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9054 Chains.size());
9055 }
9056
9057 if (!ISD::isNormalStore(St))
9058 return SDValue();
9059
9060 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9061 // ARM stores of arguments in the same cache line.
9062 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9063 StVal.getNode()->hasOneUse()) {
9064 SelectionDAG &DAG = DCI.DAG;
9065 SDLoc DL(St);
9066 SDValue BasePtr = St->getBasePtr();
9067 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9068 StVal.getNode()->getOperand(0), BasePtr,
9069 St->getPointerInfo(), St->isVolatile(),
9070 St->isNonTemporal(), St->getAlignment());
9071
9072 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9073 DAG.getConstant(4, MVT::i32));
9074 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9075 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9076 St->isNonTemporal(),
9077 std::min(4U, St->getAlignment() / 2));
9078 }
9079
9080 if (StVal.getValueType() != MVT::i64 ||
9081 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9082 return SDValue();
9083
9084 // Bitcast an i64 store extracted from a vector to f64.
9085 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9086 SelectionDAG &DAG = DCI.DAG;
9087 SDLoc dl(StVal);
9088 SDValue IntVec = StVal.getOperand(0);
9089 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9090 IntVec.getValueType().getVectorNumElements());
9091 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9092 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9093 Vec, StVal.getOperand(1));
9094 dl = SDLoc(N);
9095 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9096 // Make the DAGCombiner fold the bitcasts.
9097 DCI.AddToWorklist(Vec.getNode());
9098 DCI.AddToWorklist(ExtElt.getNode());
9099 DCI.AddToWorklist(V.getNode());
9100 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9101 St->getPointerInfo(), St->isVolatile(),
9102 St->isNonTemporal(), St->getAlignment(),
9103 St->getTBAAInfo());
9104 }
9105
9106 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9107 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9108 /// i64 vector to have f64 elements, since the value can then be loaded
9109 /// directly into a VFP register.
hasNormalLoadOperand(SDNode * N)9110 static bool hasNormalLoadOperand(SDNode *N) {
9111 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9112 for (unsigned i = 0; i < NumElts; ++i) {
9113 SDNode *Elt = N->getOperand(i).getNode();
9114 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9115 return true;
9116 }
9117 return false;
9118 }
9119
9120 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9121 /// ISD::BUILD_VECTOR.
PerformBUILD_VECTORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)9122 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9123 TargetLowering::DAGCombinerInfo &DCI){
9124 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9125 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9126 // into a pair of GPRs, which is fine when the value is used as a scalar,
9127 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9128 SelectionDAG &DAG = DCI.DAG;
9129 if (N->getNumOperands() == 2) {
9130 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9131 if (RV.getNode())
9132 return RV;
9133 }
9134
9135 // Load i64 elements as f64 values so that type legalization does not split
9136 // them up into i32 values.
9137 EVT VT = N->getValueType(0);
9138 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9139 return SDValue();
9140 SDLoc dl(N);
9141 SmallVector<SDValue, 8> Ops;
9142 unsigned NumElts = VT.getVectorNumElements();
9143 for (unsigned i = 0; i < NumElts; ++i) {
9144 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9145 Ops.push_back(V);
9146 // Make the DAGCombiner fold the bitcast.
9147 DCI.AddToWorklist(V.getNode());
9148 }
9149 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9150 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9151 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9152 }
9153
9154 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9155 static SDValue
PerformARMBUILD_VECTORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)9156 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9157 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9158 // At that time, we may have inserted bitcasts from integer to float.
9159 // If these bitcasts have survived DAGCombine, change the lowering of this
9160 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9161 // force to use floating point types.
9162
9163 // Make sure we can change the type of the vector.
9164 // This is possible iff:
9165 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9166 // 1.1. Vector is used only once.
9167 // 1.2. Use is a bit convert to an integer type.
9168 // 2. The size of its operands are 32-bits (64-bits are not legal).
9169 EVT VT = N->getValueType(0);
9170 EVT EltVT = VT.getVectorElementType();
9171
9172 // Check 1.1. and 2.
9173 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9174 return SDValue();
9175
9176 // By construction, the input type must be float.
9177 assert(EltVT == MVT::f32 && "Unexpected type!");
9178
9179 // Check 1.2.
9180 SDNode *Use = *N->use_begin();
9181 if (Use->getOpcode() != ISD::BITCAST ||
9182 Use->getValueType(0).isFloatingPoint())
9183 return SDValue();
9184
9185 // Check profitability.
9186 // Model is, if more than half of the relevant operands are bitcast from
9187 // i32, turn the build_vector into a sequence of insert_vector_elt.
9188 // Relevant operands are everything that is not statically
9189 // (i.e., at compile time) bitcasted.
9190 unsigned NumOfBitCastedElts = 0;
9191 unsigned NumElts = VT.getVectorNumElements();
9192 unsigned NumOfRelevantElts = NumElts;
9193 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9194 SDValue Elt = N->getOperand(Idx);
9195 if (Elt->getOpcode() == ISD::BITCAST) {
9196 // Assume only bit cast to i32 will go away.
9197 if (Elt->getOperand(0).getValueType() == MVT::i32)
9198 ++NumOfBitCastedElts;
9199 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9200 // Constants are statically casted, thus do not count them as
9201 // relevant operands.
9202 --NumOfRelevantElts;
9203 }
9204
9205 // Check if more than half of the elements require a non-free bitcast.
9206 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9207 return SDValue();
9208
9209 SelectionDAG &DAG = DCI.DAG;
9210 // Create the new vector type.
9211 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9212 // Check if the type is legal.
9213 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9214 if (!TLI.isTypeLegal(VecVT))
9215 return SDValue();
9216
9217 // Combine:
9218 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9219 // => BITCAST INSERT_VECTOR_ELT
9220 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9221 // (BITCAST EN), N.
9222 SDValue Vec = DAG.getUNDEF(VecVT);
9223 SDLoc dl(N);
9224 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9225 SDValue V = N->getOperand(Idx);
9226 if (V.getOpcode() == ISD::UNDEF)
9227 continue;
9228 if (V.getOpcode() == ISD::BITCAST &&
9229 V->getOperand(0).getValueType() == MVT::i32)
9230 // Fold obvious case.
9231 V = V.getOperand(0);
9232 else {
9233 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9234 // Make the DAGCombiner fold the bitcasts.
9235 DCI.AddToWorklist(V.getNode());
9236 }
9237 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9238 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9239 }
9240 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9241 // Make the DAGCombiner fold the bitcasts.
9242 DCI.AddToWorklist(Vec.getNode());
9243 return Vec;
9244 }
9245
9246 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9247 /// ISD::INSERT_VECTOR_ELT.
PerformInsertEltCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)9248 static SDValue PerformInsertEltCombine(SDNode *N,
9249 TargetLowering::DAGCombinerInfo &DCI) {
9250 // Bitcast an i64 load inserted into a vector to f64.
9251 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9252 EVT VT = N->getValueType(0);
9253 SDNode *Elt = N->getOperand(1).getNode();
9254 if (VT.getVectorElementType() != MVT::i64 ||
9255 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9256 return SDValue();
9257
9258 SelectionDAG &DAG = DCI.DAG;
9259 SDLoc dl(N);
9260 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9261 VT.getVectorNumElements());
9262 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9263 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9264 // Make the DAGCombiner fold the bitcasts.
9265 DCI.AddToWorklist(Vec.getNode());
9266 DCI.AddToWorklist(V.getNode());
9267 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9268 Vec, V, N->getOperand(2));
9269 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9270 }
9271
9272 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9273 /// ISD::VECTOR_SHUFFLE.
PerformVECTOR_SHUFFLECombine(SDNode * N,SelectionDAG & DAG)9274 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9275 // The LLVM shufflevector instruction does not require the shuffle mask
9276 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9277 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9278 // operands do not match the mask length, they are extended by concatenating
9279 // them with undef vectors. That is probably the right thing for other
9280 // targets, but for NEON it is better to concatenate two double-register
9281 // size vector operands into a single quad-register size vector. Do that
9282 // transformation here:
9283 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9284 // shuffle(concat(v1, v2), undef)
9285 SDValue Op0 = N->getOperand(0);
9286 SDValue Op1 = N->getOperand(1);
9287 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9288 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9289 Op0.getNumOperands() != 2 ||
9290 Op1.getNumOperands() != 2)
9291 return SDValue();
9292 SDValue Concat0Op1 = Op0.getOperand(1);
9293 SDValue Concat1Op1 = Op1.getOperand(1);
9294 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9295 Concat1Op1.getOpcode() != ISD::UNDEF)
9296 return SDValue();
9297 // Skip the transformation if any of the types are illegal.
9298 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9299 EVT VT = N->getValueType(0);
9300 if (!TLI.isTypeLegal(VT) ||
9301 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9302 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9303 return SDValue();
9304
9305 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9306 Op0.getOperand(0), Op1.getOperand(0));
9307 // Translate the shuffle mask.
9308 SmallVector<int, 16> NewMask;
9309 unsigned NumElts = VT.getVectorNumElements();
9310 unsigned HalfElts = NumElts/2;
9311 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9312 for (unsigned n = 0; n < NumElts; ++n) {
9313 int MaskElt = SVN->getMaskElt(n);
9314 int NewElt = -1;
9315 if (MaskElt < (int)HalfElts)
9316 NewElt = MaskElt;
9317 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9318 NewElt = HalfElts + MaskElt - NumElts;
9319 NewMask.push_back(NewElt);
9320 }
9321 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9322 DAG.getUNDEF(VT), NewMask.data());
9323 }
9324
9325 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9326 /// NEON load/store intrinsics to merge base address updates.
CombineBaseUpdate(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)9327 static SDValue CombineBaseUpdate(SDNode *N,
9328 TargetLowering::DAGCombinerInfo &DCI) {
9329 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9330 return SDValue();
9331
9332 SelectionDAG &DAG = DCI.DAG;
9333 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9334 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9335 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9336 SDValue Addr = N->getOperand(AddrOpIdx);
9337
9338 // Search for a use of the address operand that is an increment.
9339 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9340 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9341 SDNode *User = *UI;
9342 if (User->getOpcode() != ISD::ADD ||
9343 UI.getUse().getResNo() != Addr.getResNo())
9344 continue;
9345
9346 // Check that the add is independent of the load/store. Otherwise, folding
9347 // it would create a cycle.
9348 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9349 continue;
9350
9351 // Find the new opcode for the updating load/store.
9352 bool isLoad = true;
9353 bool isLaneOp = false;
9354 unsigned NewOpc = 0;
9355 unsigned NumVecs = 0;
9356 if (isIntrinsic) {
9357 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9358 switch (IntNo) {
9359 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9360 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9361 NumVecs = 1; break;
9362 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9363 NumVecs = 2; break;
9364 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9365 NumVecs = 3; break;
9366 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9367 NumVecs = 4; break;
9368 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9369 NumVecs = 2; isLaneOp = true; break;
9370 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9371 NumVecs = 3; isLaneOp = true; break;
9372 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9373 NumVecs = 4; isLaneOp = true; break;
9374 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9375 NumVecs = 1; isLoad = false; break;
9376 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9377 NumVecs = 2; isLoad = false; break;
9378 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9379 NumVecs = 3; isLoad = false; break;
9380 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9381 NumVecs = 4; isLoad = false; break;
9382 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9383 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9384 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9385 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9386 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9387 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9388 }
9389 } else {
9390 isLaneOp = true;
9391 switch (N->getOpcode()) {
9392 default: llvm_unreachable("unexpected opcode for Neon base update");
9393 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9394 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9395 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9396 }
9397 }
9398
9399 // Find the size of memory referenced by the load/store.
9400 EVT VecTy;
9401 if (isLoad)
9402 VecTy = N->getValueType(0);
9403 else
9404 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9405 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9406 if (isLaneOp)
9407 NumBytes /= VecTy.getVectorNumElements();
9408
9409 // If the increment is a constant, it must match the memory ref size.
9410 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9411 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9412 uint64_t IncVal = CInc->getZExtValue();
9413 if (IncVal != NumBytes)
9414 continue;
9415 } else if (NumBytes >= 3 * 16) {
9416 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9417 // separate instructions that make it harder to use a non-constant update.
9418 continue;
9419 }
9420
9421 // Create the new updating load/store node.
9422 EVT Tys[6];
9423 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9424 unsigned n;
9425 for (n = 0; n < NumResultVecs; ++n)
9426 Tys[n] = VecTy;
9427 Tys[n++] = MVT::i32;
9428 Tys[n] = MVT::Other;
9429 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9430 SmallVector<SDValue, 8> Ops;
9431 Ops.push_back(N->getOperand(0)); // incoming chain
9432 Ops.push_back(N->getOperand(AddrOpIdx));
9433 Ops.push_back(Inc);
9434 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9435 Ops.push_back(N->getOperand(i));
9436 }
9437 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9438 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9439 Ops.data(), Ops.size(),
9440 MemInt->getMemoryVT(),
9441 MemInt->getMemOperand());
9442
9443 // Update the uses.
9444 std::vector<SDValue> NewResults;
9445 for (unsigned i = 0; i < NumResultVecs; ++i) {
9446 NewResults.push_back(SDValue(UpdN.getNode(), i));
9447 }
9448 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9449 DCI.CombineTo(N, NewResults);
9450 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9451
9452 break;
9453 }
9454 return SDValue();
9455 }
9456
9457 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9458 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9459 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9460 /// return true.
CombineVLDDUP(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)9461 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9462 SelectionDAG &DAG = DCI.DAG;
9463 EVT VT = N->getValueType(0);
9464 // vldN-dup instructions only support 64-bit vectors for N > 1.
9465 if (!VT.is64BitVector())
9466 return false;
9467
9468 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9469 SDNode *VLD = N->getOperand(0).getNode();
9470 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9471 return false;
9472 unsigned NumVecs = 0;
9473 unsigned NewOpc = 0;
9474 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9475 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9476 NumVecs = 2;
9477 NewOpc = ARMISD::VLD2DUP;
9478 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9479 NumVecs = 3;
9480 NewOpc = ARMISD::VLD3DUP;
9481 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9482 NumVecs = 4;
9483 NewOpc = ARMISD::VLD4DUP;
9484 } else {
9485 return false;
9486 }
9487
9488 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9489 // numbers match the load.
9490 unsigned VLDLaneNo =
9491 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9492 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9493 UI != UE; ++UI) {
9494 // Ignore uses of the chain result.
9495 if (UI.getUse().getResNo() == NumVecs)
9496 continue;
9497 SDNode *User = *UI;
9498 if (User->getOpcode() != ARMISD::VDUPLANE ||
9499 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9500 return false;
9501 }
9502
9503 // Create the vldN-dup node.
9504 EVT Tys[5];
9505 unsigned n;
9506 for (n = 0; n < NumVecs; ++n)
9507 Tys[n] = VT;
9508 Tys[n] = MVT::Other;
9509 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9510 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9511 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9512 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9513 Ops, 2, VLDMemInt->getMemoryVT(),
9514 VLDMemInt->getMemOperand());
9515
9516 // Update the uses.
9517 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9518 UI != UE; ++UI) {
9519 unsigned ResNo = UI.getUse().getResNo();
9520 // Ignore uses of the chain result.
9521 if (ResNo == NumVecs)
9522 continue;
9523 SDNode *User = *UI;
9524 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9525 }
9526
9527 // Now the vldN-lane intrinsic is dead except for its chain result.
9528 // Update uses of the chain.
9529 std::vector<SDValue> VLDDupResults;
9530 for (unsigned n = 0; n < NumVecs; ++n)
9531 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9532 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9533 DCI.CombineTo(VLD, VLDDupResults);
9534
9535 return true;
9536 }
9537
9538 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9539 /// ARMISD::VDUPLANE.
PerformVDUPLANECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)9540 static SDValue PerformVDUPLANECombine(SDNode *N,
9541 TargetLowering::DAGCombinerInfo &DCI) {
9542 SDValue Op = N->getOperand(0);
9543
9544 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9545 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9546 if (CombineVLDDUP(N, DCI))
9547 return SDValue(N, 0);
9548
9549 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9550 // redundant. Ignore bit_converts for now; element sizes are checked below.
9551 while (Op.getOpcode() == ISD::BITCAST)
9552 Op = Op.getOperand(0);
9553 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9554 return SDValue();
9555
9556 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9557 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9558 // The canonical VMOV for a zero vector uses a 32-bit element size.
9559 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9560 unsigned EltBits;
9561 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9562 EltSize = 8;
9563 EVT VT = N->getValueType(0);
9564 if (EltSize > VT.getVectorElementType().getSizeInBits())
9565 return SDValue();
9566
9567 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9568 }
9569
9570 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9571 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
isConstVecPow2(SDValue ConstVec,bool isSigned,uint64_t & C)9572 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9573 {
9574 integerPart cN;
9575 integerPart c0 = 0;
9576 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9577 I != E; I++) {
9578 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9579 if (!C)
9580 return false;
9581
9582 bool isExact;
9583 APFloat APF = C->getValueAPF();
9584 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9585 != APFloat::opOK || !isExact)
9586 return false;
9587
9588 c0 = (I == 0) ? cN : c0;
9589 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9590 return false;
9591 }
9592 C = c0;
9593 return true;
9594 }
9595
9596 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9597 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9598 /// when the VMUL has a constant operand that is a power of 2.
9599 ///
9600 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9601 /// vmul.f32 d16, d17, d16
9602 /// vcvt.s32.f32 d16, d16
9603 /// becomes:
9604 /// vcvt.s32.f32 d16, d16, #3
PerformVCVTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)9605 static SDValue PerformVCVTCombine(SDNode *N,
9606 TargetLowering::DAGCombinerInfo &DCI,
9607 const ARMSubtarget *Subtarget) {
9608 SelectionDAG &DAG = DCI.DAG;
9609 SDValue Op = N->getOperand(0);
9610
9611 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9612 Op.getOpcode() != ISD::FMUL)
9613 return SDValue();
9614
9615 uint64_t C;
9616 SDValue N0 = Op->getOperand(0);
9617 SDValue ConstVec = Op->getOperand(1);
9618 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9619
9620 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9621 !isConstVecPow2(ConstVec, isSigned, C))
9622 return SDValue();
9623
9624 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9625 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9626 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9627 // These instructions only exist converting from f32 to i32. We can handle
9628 // smaller integers by generating an extra truncate, but larger ones would
9629 // be lossy.
9630 return SDValue();
9631 }
9632
9633 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9634 Intrinsic::arm_neon_vcvtfp2fxu;
9635 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9636 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9637 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9638 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9639 DAG.getConstant(Log2_64(C), MVT::i32));
9640
9641 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9642 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9643
9644 return FixConv;
9645 }
9646
9647 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9648 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9649 /// when the VDIV has a constant operand that is a power of 2.
9650 ///
9651 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9652 /// vcvt.f32.s32 d16, d16
9653 /// vdiv.f32 d16, d17, d16
9654 /// becomes:
9655 /// vcvt.f32.s32 d16, d16, #3
PerformVDIVCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)9656 static SDValue PerformVDIVCombine(SDNode *N,
9657 TargetLowering::DAGCombinerInfo &DCI,
9658 const ARMSubtarget *Subtarget) {
9659 SelectionDAG &DAG = DCI.DAG;
9660 SDValue Op = N->getOperand(0);
9661 unsigned OpOpcode = Op.getNode()->getOpcode();
9662
9663 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9664 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9665 return SDValue();
9666
9667 uint64_t C;
9668 SDValue ConstVec = N->getOperand(1);
9669 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9670
9671 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9672 !isConstVecPow2(ConstVec, isSigned, C))
9673 return SDValue();
9674
9675 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9676 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9677 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9678 // These instructions only exist converting from i32 to f32. We can handle
9679 // smaller integers by generating an extra extend, but larger ones would
9680 // be lossy.
9681 return SDValue();
9682 }
9683
9684 SDValue ConvInput = Op.getOperand(0);
9685 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9686 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9687 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9688 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9689 ConvInput);
9690
9691 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9692 Intrinsic::arm_neon_vcvtfxu2fp;
9693 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9694 Op.getValueType(),
9695 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9696 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9697 }
9698
9699 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9700 /// operand of a vector shift operation, where all the elements of the
9701 /// build_vector must have the same constant integer value.
getVShiftImm(SDValue Op,unsigned ElementBits,int64_t & Cnt)9702 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9703 // Ignore bit_converts.
9704 while (Op.getOpcode() == ISD::BITCAST)
9705 Op = Op.getOperand(0);
9706 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9707 APInt SplatBits, SplatUndef;
9708 unsigned SplatBitSize;
9709 bool HasAnyUndefs;
9710 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9711 HasAnyUndefs, ElementBits) ||
9712 SplatBitSize > ElementBits)
9713 return false;
9714 Cnt = SplatBits.getSExtValue();
9715 return true;
9716 }
9717
9718 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9719 /// operand of a vector shift left operation. That value must be in the range:
9720 /// 0 <= Value < ElementBits for a left shift; or
9721 /// 0 <= Value <= ElementBits for a long left shift.
isVShiftLImm(SDValue Op,EVT VT,bool isLong,int64_t & Cnt)9722 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9723 assert(VT.isVector() && "vector shift count is not a vector type");
9724 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9725 if (! getVShiftImm(Op, ElementBits, Cnt))
9726 return false;
9727 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9728 }
9729
9730 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9731 /// operand of a vector shift right operation. For a shift opcode, the value
9732 /// is positive, but for an intrinsic the value count must be negative. The
9733 /// absolute value must be in the range:
9734 /// 1 <= |Value| <= ElementBits for a right shift; or
9735 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
isVShiftRImm(SDValue Op,EVT VT,bool isNarrow,bool isIntrinsic,int64_t & Cnt)9736 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9737 int64_t &Cnt) {
9738 assert(VT.isVector() && "vector shift count is not a vector type");
9739 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9740 if (! getVShiftImm(Op, ElementBits, Cnt))
9741 return false;
9742 if (isIntrinsic)
9743 Cnt = -Cnt;
9744 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9745 }
9746
9747 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
PerformIntrinsicCombine(SDNode * N,SelectionDAG & DAG)9748 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9749 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9750 switch (IntNo) {
9751 default:
9752 // Don't do anything for most intrinsics.
9753 break;
9754
9755 // Vector shifts: check for immediate versions and lower them.
9756 // Note: This is done during DAG combining instead of DAG legalizing because
9757 // the build_vectors for 64-bit vector element shift counts are generally
9758 // not legal, and it is hard to see their values after they get legalized to
9759 // loads from a constant pool.
9760 case Intrinsic::arm_neon_vshifts:
9761 case Intrinsic::arm_neon_vshiftu:
9762 case Intrinsic::arm_neon_vshiftls:
9763 case Intrinsic::arm_neon_vshiftlu:
9764 case Intrinsic::arm_neon_vshiftn:
9765 case Intrinsic::arm_neon_vrshifts:
9766 case Intrinsic::arm_neon_vrshiftu:
9767 case Intrinsic::arm_neon_vrshiftn:
9768 case Intrinsic::arm_neon_vqshifts:
9769 case Intrinsic::arm_neon_vqshiftu:
9770 case Intrinsic::arm_neon_vqshiftsu:
9771 case Intrinsic::arm_neon_vqshiftns:
9772 case Intrinsic::arm_neon_vqshiftnu:
9773 case Intrinsic::arm_neon_vqshiftnsu:
9774 case Intrinsic::arm_neon_vqrshiftns:
9775 case Intrinsic::arm_neon_vqrshiftnu:
9776 case Intrinsic::arm_neon_vqrshiftnsu: {
9777 EVT VT = N->getOperand(1).getValueType();
9778 int64_t Cnt;
9779 unsigned VShiftOpc = 0;
9780
9781 switch (IntNo) {
9782 case Intrinsic::arm_neon_vshifts:
9783 case Intrinsic::arm_neon_vshiftu:
9784 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9785 VShiftOpc = ARMISD::VSHL;
9786 break;
9787 }
9788 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9789 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9790 ARMISD::VSHRs : ARMISD::VSHRu);
9791 break;
9792 }
9793 return SDValue();
9794
9795 case Intrinsic::arm_neon_vshiftls:
9796 case Intrinsic::arm_neon_vshiftlu:
9797 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9798 break;
9799 llvm_unreachable("invalid shift count for vshll intrinsic");
9800
9801 case Intrinsic::arm_neon_vrshifts:
9802 case Intrinsic::arm_neon_vrshiftu:
9803 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9804 break;
9805 return SDValue();
9806
9807 case Intrinsic::arm_neon_vqshifts:
9808 case Intrinsic::arm_neon_vqshiftu:
9809 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9810 break;
9811 return SDValue();
9812
9813 case Intrinsic::arm_neon_vqshiftsu:
9814 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9815 break;
9816 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9817
9818 case Intrinsic::arm_neon_vshiftn:
9819 case Intrinsic::arm_neon_vrshiftn:
9820 case Intrinsic::arm_neon_vqshiftns:
9821 case Intrinsic::arm_neon_vqshiftnu:
9822 case Intrinsic::arm_neon_vqshiftnsu:
9823 case Intrinsic::arm_neon_vqrshiftns:
9824 case Intrinsic::arm_neon_vqrshiftnu:
9825 case Intrinsic::arm_neon_vqrshiftnsu:
9826 // Narrowing shifts require an immediate right shift.
9827 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9828 break;
9829 llvm_unreachable("invalid shift count for narrowing vector shift "
9830 "intrinsic");
9831
9832 default:
9833 llvm_unreachable("unhandled vector shift");
9834 }
9835
9836 switch (IntNo) {
9837 case Intrinsic::arm_neon_vshifts:
9838 case Intrinsic::arm_neon_vshiftu:
9839 // Opcode already set above.
9840 break;
9841 case Intrinsic::arm_neon_vshiftls:
9842 case Intrinsic::arm_neon_vshiftlu:
9843 if (Cnt == VT.getVectorElementType().getSizeInBits())
9844 VShiftOpc = ARMISD::VSHLLi;
9845 else
9846 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9847 ARMISD::VSHLLs : ARMISD::VSHLLu);
9848 break;
9849 case Intrinsic::arm_neon_vshiftn:
9850 VShiftOpc = ARMISD::VSHRN; break;
9851 case Intrinsic::arm_neon_vrshifts:
9852 VShiftOpc = ARMISD::VRSHRs; break;
9853 case Intrinsic::arm_neon_vrshiftu:
9854 VShiftOpc = ARMISD::VRSHRu; break;
9855 case Intrinsic::arm_neon_vrshiftn:
9856 VShiftOpc = ARMISD::VRSHRN; break;
9857 case Intrinsic::arm_neon_vqshifts:
9858 VShiftOpc = ARMISD::VQSHLs; break;
9859 case Intrinsic::arm_neon_vqshiftu:
9860 VShiftOpc = ARMISD::VQSHLu; break;
9861 case Intrinsic::arm_neon_vqshiftsu:
9862 VShiftOpc = ARMISD::VQSHLsu; break;
9863 case Intrinsic::arm_neon_vqshiftns:
9864 VShiftOpc = ARMISD::VQSHRNs; break;
9865 case Intrinsic::arm_neon_vqshiftnu:
9866 VShiftOpc = ARMISD::VQSHRNu; break;
9867 case Intrinsic::arm_neon_vqshiftnsu:
9868 VShiftOpc = ARMISD::VQSHRNsu; break;
9869 case Intrinsic::arm_neon_vqrshiftns:
9870 VShiftOpc = ARMISD::VQRSHRNs; break;
9871 case Intrinsic::arm_neon_vqrshiftnu:
9872 VShiftOpc = ARMISD::VQRSHRNu; break;
9873 case Intrinsic::arm_neon_vqrshiftnsu:
9874 VShiftOpc = ARMISD::VQRSHRNsu; break;
9875 }
9876
9877 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9878 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9879 }
9880
9881 case Intrinsic::arm_neon_vshiftins: {
9882 EVT VT = N->getOperand(1).getValueType();
9883 int64_t Cnt;
9884 unsigned VShiftOpc = 0;
9885
9886 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9887 VShiftOpc = ARMISD::VSLI;
9888 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9889 VShiftOpc = ARMISD::VSRI;
9890 else {
9891 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9892 }
9893
9894 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9895 N->getOperand(1), N->getOperand(2),
9896 DAG.getConstant(Cnt, MVT::i32));
9897 }
9898
9899 case Intrinsic::arm_neon_vqrshifts:
9900 case Intrinsic::arm_neon_vqrshiftu:
9901 // No immediate versions of these to check for.
9902 break;
9903 }
9904
9905 return SDValue();
9906 }
9907
9908 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9909 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9910 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9911 /// vector element shift counts are generally not legal, and it is hard to see
9912 /// their values after they get legalized to loads from a constant pool.
PerformShiftCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)9913 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9914 const ARMSubtarget *ST) {
9915 EVT VT = N->getValueType(0);
9916 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9917 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9918 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9919 SDValue N1 = N->getOperand(1);
9920 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9921 SDValue N0 = N->getOperand(0);
9922 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9923 DAG.MaskedValueIsZero(N0.getOperand(0),
9924 APInt::getHighBitsSet(32, 16)))
9925 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9926 }
9927 }
9928
9929 // Nothing to be done for scalar shifts.
9930 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9931 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9932 return SDValue();
9933
9934 assert(ST->hasNEON() && "unexpected vector shift");
9935 int64_t Cnt;
9936
9937 switch (N->getOpcode()) {
9938 default: llvm_unreachable("unexpected shift opcode");
9939
9940 case ISD::SHL:
9941 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9942 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9943 DAG.getConstant(Cnt, MVT::i32));
9944 break;
9945
9946 case ISD::SRA:
9947 case ISD::SRL:
9948 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9949 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9950 ARMISD::VSHRs : ARMISD::VSHRu);
9951 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9952 DAG.getConstant(Cnt, MVT::i32));
9953 }
9954 }
9955 return SDValue();
9956 }
9957
9958 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9959 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
PerformExtendCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)9960 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9961 const ARMSubtarget *ST) {
9962 SDValue N0 = N->getOperand(0);
9963
9964 // Check for sign- and zero-extensions of vector extract operations of 8-
9965 // and 16-bit vector elements. NEON supports these directly. They are
9966 // handled during DAG combining because type legalization will promote them
9967 // to 32-bit types and it is messy to recognize the operations after that.
9968 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9969 SDValue Vec = N0.getOperand(0);
9970 SDValue Lane = N0.getOperand(1);
9971 EVT VT = N->getValueType(0);
9972 EVT EltVT = N0.getValueType();
9973 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9974
9975 if (VT == MVT::i32 &&
9976 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9977 TLI.isTypeLegal(Vec.getValueType()) &&
9978 isa<ConstantSDNode>(Lane)) {
9979
9980 unsigned Opc = 0;
9981 switch (N->getOpcode()) {
9982 default: llvm_unreachable("unexpected opcode");
9983 case ISD::SIGN_EXTEND:
9984 Opc = ARMISD::VGETLANEs;
9985 break;
9986 case ISD::ZERO_EXTEND:
9987 case ISD::ANY_EXTEND:
9988 Opc = ARMISD::VGETLANEu;
9989 break;
9990 }
9991 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9992 }
9993 }
9994
9995 return SDValue();
9996 }
9997
9998 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9999 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
PerformSELECT_CCCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)10000 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10001 const ARMSubtarget *ST) {
10002 // If the target supports NEON, try to use vmax/vmin instructions for f32
10003 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
10004 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
10005 // a NaN; only do the transformation when it matches that behavior.
10006
10007 // For now only do this when using NEON for FP operations; if using VFP, it
10008 // is not obvious that the benefit outweighs the cost of switching to the
10009 // NEON pipeline.
10010 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10011 N->getValueType(0) != MVT::f32)
10012 return SDValue();
10013
10014 SDValue CondLHS = N->getOperand(0);
10015 SDValue CondRHS = N->getOperand(1);
10016 SDValue LHS = N->getOperand(2);
10017 SDValue RHS = N->getOperand(3);
10018 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10019
10020 unsigned Opcode = 0;
10021 bool IsReversed;
10022 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10023 IsReversed = false; // x CC y ? x : y
10024 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10025 IsReversed = true ; // x CC y ? y : x
10026 } else {
10027 return SDValue();
10028 }
10029
10030 bool IsUnordered;
10031 switch (CC) {
10032 default: break;
10033 case ISD::SETOLT:
10034 case ISD::SETOLE:
10035 case ISD::SETLT:
10036 case ISD::SETLE:
10037 case ISD::SETULT:
10038 case ISD::SETULE:
10039 // If LHS is NaN, an ordered comparison will be false and the result will
10040 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
10041 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10042 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10043 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10044 break;
10045 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10046 // will return -0, so vmin can only be used for unsafe math or if one of
10047 // the operands is known to be nonzero.
10048 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10049 !DAG.getTarget().Options.UnsafeFPMath &&
10050 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10051 break;
10052 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10053 break;
10054
10055 case ISD::SETOGT:
10056 case ISD::SETOGE:
10057 case ISD::SETGT:
10058 case ISD::SETGE:
10059 case ISD::SETUGT:
10060 case ISD::SETUGE:
10061 // If LHS is NaN, an ordered comparison will be false and the result will
10062 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
10063 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10064 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10065 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10066 break;
10067 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10068 // will return +0, so vmax can only be used for unsafe math or if one of
10069 // the operands is known to be nonzero.
10070 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10071 !DAG.getTarget().Options.UnsafeFPMath &&
10072 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10073 break;
10074 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10075 break;
10076 }
10077
10078 if (!Opcode)
10079 return SDValue();
10080 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10081 }
10082
10083 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10084 SDValue
PerformCMOVCombine(SDNode * N,SelectionDAG & DAG) const10085 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10086 SDValue Cmp = N->getOperand(4);
10087 if (Cmp.getOpcode() != ARMISD::CMPZ)
10088 // Only looking at EQ and NE cases.
10089 return SDValue();
10090
10091 EVT VT = N->getValueType(0);
10092 SDLoc dl(N);
10093 SDValue LHS = Cmp.getOperand(0);
10094 SDValue RHS = Cmp.getOperand(1);
10095 SDValue FalseVal = N->getOperand(0);
10096 SDValue TrueVal = N->getOperand(1);
10097 SDValue ARMcc = N->getOperand(2);
10098 ARMCC::CondCodes CC =
10099 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10100
10101 // Simplify
10102 // mov r1, r0
10103 // cmp r1, x
10104 // mov r0, y
10105 // moveq r0, x
10106 // to
10107 // cmp r0, x
10108 // movne r0, y
10109 //
10110 // mov r1, r0
10111 // cmp r1, x
10112 // mov r0, x
10113 // movne r0, y
10114 // to
10115 // cmp r0, x
10116 // movne r0, y
10117 /// FIXME: Turn this into a target neutral optimization?
10118 SDValue Res;
10119 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10120 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10121 N->getOperand(3), Cmp);
10122 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10123 SDValue ARMcc;
10124 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10125 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10126 N->getOperand(3), NewCmp);
10127 }
10128
10129 if (Res.getNode()) {
10130 APInt KnownZero, KnownOne;
10131 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10132 // Capture demanded bits information that would be otherwise lost.
10133 if (KnownZero == 0xfffffffe)
10134 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10135 DAG.getValueType(MVT::i1));
10136 else if (KnownZero == 0xffffff00)
10137 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10138 DAG.getValueType(MVT::i8));
10139 else if (KnownZero == 0xffff0000)
10140 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10141 DAG.getValueType(MVT::i16));
10142 }
10143
10144 return Res;
10145 }
10146
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const10147 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10148 DAGCombinerInfo &DCI) const {
10149 switch (N->getOpcode()) {
10150 default: break;
10151 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10152 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10153 case ISD::SUB: return PerformSUBCombine(N, DCI);
10154 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10155 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10156 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10157 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10158 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10159 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10160 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10161 case ISD::STORE: return PerformSTORECombine(N, DCI);
10162 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10163 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10164 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10165 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10166 case ISD::FP_TO_SINT:
10167 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10168 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10169 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10170 case ISD::SHL:
10171 case ISD::SRA:
10172 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10173 case ISD::SIGN_EXTEND:
10174 case ISD::ZERO_EXTEND:
10175 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10176 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10177 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10178 case ARMISD::VLD2DUP:
10179 case ARMISD::VLD3DUP:
10180 case ARMISD::VLD4DUP:
10181 return CombineBaseUpdate(N, DCI);
10182 case ARMISD::BUILD_VECTOR:
10183 return PerformARMBUILD_VECTORCombine(N, DCI);
10184 case ISD::INTRINSIC_VOID:
10185 case ISD::INTRINSIC_W_CHAIN:
10186 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10187 case Intrinsic::arm_neon_vld1:
10188 case Intrinsic::arm_neon_vld2:
10189 case Intrinsic::arm_neon_vld3:
10190 case Intrinsic::arm_neon_vld4:
10191 case Intrinsic::arm_neon_vld2lane:
10192 case Intrinsic::arm_neon_vld3lane:
10193 case Intrinsic::arm_neon_vld4lane:
10194 case Intrinsic::arm_neon_vst1:
10195 case Intrinsic::arm_neon_vst2:
10196 case Intrinsic::arm_neon_vst3:
10197 case Intrinsic::arm_neon_vst4:
10198 case Intrinsic::arm_neon_vst2lane:
10199 case Intrinsic::arm_neon_vst3lane:
10200 case Intrinsic::arm_neon_vst4lane:
10201 return CombineBaseUpdate(N, DCI);
10202 default: break;
10203 }
10204 break;
10205 }
10206 return SDValue();
10207 }
10208
isDesirableToTransformToIntegerOp(unsigned Opc,EVT VT) const10209 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10210 EVT VT) const {
10211 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10212 }
10213
allowsUnalignedMemoryAccesses(EVT VT,bool * Fast) const10214 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10215 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10216 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10217
10218 switch (VT.getSimpleVT().SimpleTy) {
10219 default:
10220 return false;
10221 case MVT::i8:
10222 case MVT::i16:
10223 case MVT::i32: {
10224 // Unaligned access can use (for example) LRDB, LRDH, LDR
10225 if (AllowsUnaligned) {
10226 if (Fast)
10227 *Fast = Subtarget->hasV7Ops();
10228 return true;
10229 }
10230 return false;
10231 }
10232 case MVT::f64:
10233 case MVT::v2f64: {
10234 // For any little-endian targets with neon, we can support unaligned ld/st
10235 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10236 // A big-endian target may also explictly support unaligned accesses
10237 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10238 if (Fast)
10239 *Fast = true;
10240 return true;
10241 }
10242 return false;
10243 }
10244 }
10245 }
10246
memOpAlign(unsigned DstAlign,unsigned SrcAlign,unsigned AlignCheck)10247 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10248 unsigned AlignCheck) {
10249 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10250 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10251 }
10252
getOptimalMemOpType(uint64_t Size,unsigned DstAlign,unsigned SrcAlign,bool IsMemset,bool ZeroMemset,bool MemcpyStrSrc,MachineFunction & MF) const10253 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10254 unsigned DstAlign, unsigned SrcAlign,
10255 bool IsMemset, bool ZeroMemset,
10256 bool MemcpyStrSrc,
10257 MachineFunction &MF) const {
10258 const Function *F = MF.getFunction();
10259
10260 // See if we can use NEON instructions for this...
10261 if ((!IsMemset || ZeroMemset) &&
10262 Subtarget->hasNEON() &&
10263 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10264 Attribute::NoImplicitFloat)) {
10265 bool Fast;
10266 if (Size >= 16 &&
10267 (memOpAlign(SrcAlign, DstAlign, 16) ||
10268 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10269 return MVT::v2f64;
10270 } else if (Size >= 8 &&
10271 (memOpAlign(SrcAlign, DstAlign, 8) ||
10272 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10273 return MVT::f64;
10274 }
10275 }
10276
10277 // Lowering to i32/i16 if the size permits.
10278 if (Size >= 4)
10279 return MVT::i32;
10280 else if (Size >= 2)
10281 return MVT::i16;
10282
10283 // Let the target-independent logic figure it out.
10284 return MVT::Other;
10285 }
10286
isZExtFree(SDValue Val,EVT VT2) const10287 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10288 if (Val.getOpcode() != ISD::LOAD)
10289 return false;
10290
10291 EVT VT1 = Val.getValueType();
10292 if (!VT1.isSimple() || !VT1.isInteger() ||
10293 !VT2.isSimple() || !VT2.isInteger())
10294 return false;
10295
10296 switch (VT1.getSimpleVT().SimpleTy) {
10297 default: break;
10298 case MVT::i1:
10299 case MVT::i8:
10300 case MVT::i16:
10301 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10302 return true;
10303 }
10304
10305 return false;
10306 }
10307
allowTruncateForTailCall(Type * Ty1,Type * Ty2) const10308 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10309 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10310 return false;
10311
10312 if (!isTypeLegal(EVT::getEVT(Ty1)))
10313 return false;
10314
10315 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10316
10317 // Assuming the caller doesn't have a zeroext or signext return parameter,
10318 // truncation all the way down to i1 is valid.
10319 return true;
10320 }
10321
10322
isLegalT1AddressImmediate(int64_t V,EVT VT)10323 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10324 if (V < 0)
10325 return false;
10326
10327 unsigned Scale = 1;
10328 switch (VT.getSimpleVT().SimpleTy) {
10329 default: return false;
10330 case MVT::i1:
10331 case MVT::i8:
10332 // Scale == 1;
10333 break;
10334 case MVT::i16:
10335 // Scale == 2;
10336 Scale = 2;
10337 break;
10338 case MVT::i32:
10339 // Scale == 4;
10340 Scale = 4;
10341 break;
10342 }
10343
10344 if ((V & (Scale - 1)) != 0)
10345 return false;
10346 V /= Scale;
10347 return V == (V & ((1LL << 5) - 1));
10348 }
10349
isLegalT2AddressImmediate(int64_t V,EVT VT,const ARMSubtarget * Subtarget)10350 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10351 const ARMSubtarget *Subtarget) {
10352 bool isNeg = false;
10353 if (V < 0) {
10354 isNeg = true;
10355 V = - V;
10356 }
10357
10358 switch (VT.getSimpleVT().SimpleTy) {
10359 default: return false;
10360 case MVT::i1:
10361 case MVT::i8:
10362 case MVT::i16:
10363 case MVT::i32:
10364 // + imm12 or - imm8
10365 if (isNeg)
10366 return V == (V & ((1LL << 8) - 1));
10367 return V == (V & ((1LL << 12) - 1));
10368 case MVT::f32:
10369 case MVT::f64:
10370 // Same as ARM mode. FIXME: NEON?
10371 if (!Subtarget->hasVFP2())
10372 return false;
10373 if ((V & 3) != 0)
10374 return false;
10375 V >>= 2;
10376 return V == (V & ((1LL << 8) - 1));
10377 }
10378 }
10379
10380 /// isLegalAddressImmediate - Return true if the integer value can be used
10381 /// as the offset of the target addressing mode for load / store of the
10382 /// given type.
isLegalAddressImmediate(int64_t V,EVT VT,const ARMSubtarget * Subtarget)10383 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10384 const ARMSubtarget *Subtarget) {
10385 if (V == 0)
10386 return true;
10387
10388 if (!VT.isSimple())
10389 return false;
10390
10391 if (Subtarget->isThumb1Only())
10392 return isLegalT1AddressImmediate(V, VT);
10393 else if (Subtarget->isThumb2())
10394 return isLegalT2AddressImmediate(V, VT, Subtarget);
10395
10396 // ARM mode.
10397 if (V < 0)
10398 V = - V;
10399 switch (VT.getSimpleVT().SimpleTy) {
10400 default: return false;
10401 case MVT::i1:
10402 case MVT::i8:
10403 case MVT::i32:
10404 // +- imm12
10405 return V == (V & ((1LL << 12) - 1));
10406 case MVT::i16:
10407 // +- imm8
10408 return V == (V & ((1LL << 8) - 1));
10409 case MVT::f32:
10410 case MVT::f64:
10411 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10412 return false;
10413 if ((V & 3) != 0)
10414 return false;
10415 V >>= 2;
10416 return V == (V & ((1LL << 8) - 1));
10417 }
10418 }
10419
isLegalT2ScaledAddressingMode(const AddrMode & AM,EVT VT) const10420 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10421 EVT VT) const {
10422 int Scale = AM.Scale;
10423 if (Scale < 0)
10424 return false;
10425
10426 switch (VT.getSimpleVT().SimpleTy) {
10427 default: return false;
10428 case MVT::i1:
10429 case MVT::i8:
10430 case MVT::i16:
10431 case MVT::i32:
10432 if (Scale == 1)
10433 return true;
10434 // r + r << imm
10435 Scale = Scale & ~1;
10436 return Scale == 2 || Scale == 4 || Scale == 8;
10437 case MVT::i64:
10438 // r + r
10439 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10440 return true;
10441 return false;
10442 case MVT::isVoid:
10443 // Note, we allow "void" uses (basically, uses that aren't loads or
10444 // stores), because arm allows folding a scale into many arithmetic
10445 // operations. This should be made more precise and revisited later.
10446
10447 // Allow r << imm, but the imm has to be a multiple of two.
10448 if (Scale & 1) return false;
10449 return isPowerOf2_32(Scale);
10450 }
10451 }
10452
10453 /// isLegalAddressingMode - Return true if the addressing mode represented
10454 /// by AM is legal for this target, for a load/store of the specified type.
isLegalAddressingMode(const AddrMode & AM,Type * Ty) const10455 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10456 Type *Ty) const {
10457 EVT VT = getValueType(Ty, true);
10458 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10459 return false;
10460
10461 // Can never fold addr of global into load/store.
10462 if (AM.BaseGV)
10463 return false;
10464
10465 switch (AM.Scale) {
10466 case 0: // no scale reg, must be "r+i" or "r", or "i".
10467 break;
10468 case 1:
10469 if (Subtarget->isThumb1Only())
10470 return false;
10471 // FALL THROUGH.
10472 default:
10473 // ARM doesn't support any R+R*scale+imm addr modes.
10474 if (AM.BaseOffs)
10475 return false;
10476
10477 if (!VT.isSimple())
10478 return false;
10479
10480 if (Subtarget->isThumb2())
10481 return isLegalT2ScaledAddressingMode(AM, VT);
10482
10483 int Scale = AM.Scale;
10484 switch (VT.getSimpleVT().SimpleTy) {
10485 default: return false;
10486 case MVT::i1:
10487 case MVT::i8:
10488 case MVT::i32:
10489 if (Scale < 0) Scale = -Scale;
10490 if (Scale == 1)
10491 return true;
10492 // r + r << imm
10493 return isPowerOf2_32(Scale & ~1);
10494 case MVT::i16:
10495 case MVT::i64:
10496 // r + r
10497 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10498 return true;
10499 return false;
10500
10501 case MVT::isVoid:
10502 // Note, we allow "void" uses (basically, uses that aren't loads or
10503 // stores), because arm allows folding a scale into many arithmetic
10504 // operations. This should be made more precise and revisited later.
10505
10506 // Allow r << imm, but the imm has to be a multiple of two.
10507 if (Scale & 1) return false;
10508 return isPowerOf2_32(Scale);
10509 }
10510 }
10511 return true;
10512 }
10513
10514 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10515 /// icmp immediate, that is the target has icmp instructions which can compare
10516 /// a register against the immediate without having to materialize the
10517 /// immediate into a register.
isLegalICmpImmediate(int64_t Imm) const10518 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10519 // Thumb2 and ARM modes can use cmn for negative immediates.
10520 if (!Subtarget->isThumb())
10521 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10522 if (Subtarget->isThumb2())
10523 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10524 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10525 return Imm >= 0 && Imm <= 255;
10526 }
10527
10528 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10529 /// *or sub* immediate, that is the target has add or sub instructions which can
10530 /// add a register with the immediate without having to materialize the
10531 /// immediate into a register.
isLegalAddImmediate(int64_t Imm) const10532 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10533 // Same encoding for add/sub, just flip the sign.
10534 int64_t AbsImm = llvm::abs64(Imm);
10535 if (!Subtarget->isThumb())
10536 return ARM_AM::getSOImmVal(AbsImm) != -1;
10537 if (Subtarget->isThumb2())
10538 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10539 // Thumb1 only has 8-bit unsigned immediate.
10540 return AbsImm >= 0 && AbsImm <= 255;
10541 }
10542
getARMIndexedAddressParts(SDNode * Ptr,EVT VT,bool isSEXTLoad,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)10543 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10544 bool isSEXTLoad, SDValue &Base,
10545 SDValue &Offset, bool &isInc,
10546 SelectionDAG &DAG) {
10547 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10548 return false;
10549
10550 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10551 // AddressingMode 3
10552 Base = Ptr->getOperand(0);
10553 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10554 int RHSC = (int)RHS->getZExtValue();
10555 if (RHSC < 0 && RHSC > -256) {
10556 assert(Ptr->getOpcode() == ISD::ADD);
10557 isInc = false;
10558 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10559 return true;
10560 }
10561 }
10562 isInc = (Ptr->getOpcode() == ISD::ADD);
10563 Offset = Ptr->getOperand(1);
10564 return true;
10565 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10566 // AddressingMode 2
10567 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10568 int RHSC = (int)RHS->getZExtValue();
10569 if (RHSC < 0 && RHSC > -0x1000) {
10570 assert(Ptr->getOpcode() == ISD::ADD);
10571 isInc = false;
10572 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10573 Base = Ptr->getOperand(0);
10574 return true;
10575 }
10576 }
10577
10578 if (Ptr->getOpcode() == ISD::ADD) {
10579 isInc = true;
10580 ARM_AM::ShiftOpc ShOpcVal=
10581 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10582 if (ShOpcVal != ARM_AM::no_shift) {
10583 Base = Ptr->getOperand(1);
10584 Offset = Ptr->getOperand(0);
10585 } else {
10586 Base = Ptr->getOperand(0);
10587 Offset = Ptr->getOperand(1);
10588 }
10589 return true;
10590 }
10591
10592 isInc = (Ptr->getOpcode() == ISD::ADD);
10593 Base = Ptr->getOperand(0);
10594 Offset = Ptr->getOperand(1);
10595 return true;
10596 }
10597
10598 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10599 return false;
10600 }
10601
getT2IndexedAddressParts(SDNode * Ptr,EVT VT,bool isSEXTLoad,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)10602 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10603 bool isSEXTLoad, SDValue &Base,
10604 SDValue &Offset, bool &isInc,
10605 SelectionDAG &DAG) {
10606 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10607 return false;
10608
10609 Base = Ptr->getOperand(0);
10610 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10611 int RHSC = (int)RHS->getZExtValue();
10612 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10613 assert(Ptr->getOpcode() == ISD::ADD);
10614 isInc = false;
10615 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10616 return true;
10617 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10618 isInc = Ptr->getOpcode() == ISD::ADD;
10619 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10620 return true;
10621 }
10622 }
10623
10624 return false;
10625 }
10626
10627 /// getPreIndexedAddressParts - returns true by value, base pointer and
10628 /// offset pointer and addressing mode by reference if the node's address
10629 /// can be legally represented as pre-indexed load / store address.
10630 bool
getPreIndexedAddressParts(SDNode * N,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const10631 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10632 SDValue &Offset,
10633 ISD::MemIndexedMode &AM,
10634 SelectionDAG &DAG) const {
10635 if (Subtarget->isThumb1Only())
10636 return false;
10637
10638 EVT VT;
10639 SDValue Ptr;
10640 bool isSEXTLoad = false;
10641 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10642 Ptr = LD->getBasePtr();
10643 VT = LD->getMemoryVT();
10644 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10645 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10646 Ptr = ST->getBasePtr();
10647 VT = ST->getMemoryVT();
10648 } else
10649 return false;
10650
10651 bool isInc;
10652 bool isLegal = false;
10653 if (Subtarget->isThumb2())
10654 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10655 Offset, isInc, DAG);
10656 else
10657 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10658 Offset, isInc, DAG);
10659 if (!isLegal)
10660 return false;
10661
10662 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10663 return true;
10664 }
10665
10666 /// getPostIndexedAddressParts - returns true by value, base pointer and
10667 /// offset pointer and addressing mode by reference if this node can be
10668 /// combined with a load / store to form a post-indexed load / store.
getPostIndexedAddressParts(SDNode * N,SDNode * Op,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const10669 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10670 SDValue &Base,
10671 SDValue &Offset,
10672 ISD::MemIndexedMode &AM,
10673 SelectionDAG &DAG) const {
10674 if (Subtarget->isThumb1Only())
10675 return false;
10676
10677 EVT VT;
10678 SDValue Ptr;
10679 bool isSEXTLoad = false;
10680 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10681 VT = LD->getMemoryVT();
10682 Ptr = LD->getBasePtr();
10683 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10684 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10685 VT = ST->getMemoryVT();
10686 Ptr = ST->getBasePtr();
10687 } else
10688 return false;
10689
10690 bool isInc;
10691 bool isLegal = false;
10692 if (Subtarget->isThumb2())
10693 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10694 isInc, DAG);
10695 else
10696 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10697 isInc, DAG);
10698 if (!isLegal)
10699 return false;
10700
10701 if (Ptr != Base) {
10702 // Swap base ptr and offset to catch more post-index load / store when
10703 // it's legal. In Thumb2 mode, offset must be an immediate.
10704 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10705 !Subtarget->isThumb2())
10706 std::swap(Base, Offset);
10707
10708 // Post-indexed load / store update the base pointer.
10709 if (Ptr != Base)
10710 return false;
10711 }
10712
10713 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10714 return true;
10715 }
10716
computeMaskedBitsForTargetNode(const SDValue Op,APInt & KnownZero,APInt & KnownOne,const SelectionDAG & DAG,unsigned Depth) const10717 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10718 APInt &KnownZero,
10719 APInt &KnownOne,
10720 const SelectionDAG &DAG,
10721 unsigned Depth) const {
10722 unsigned BitWidth = KnownOne.getBitWidth();
10723 KnownZero = KnownOne = APInt(BitWidth, 0);
10724 switch (Op.getOpcode()) {
10725 default: break;
10726 case ARMISD::ADDC:
10727 case ARMISD::ADDE:
10728 case ARMISD::SUBC:
10729 case ARMISD::SUBE:
10730 // These nodes' second result is a boolean
10731 if (Op.getResNo() == 0)
10732 break;
10733 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10734 break;
10735 case ARMISD::CMOV: {
10736 // Bits are known zero/one if known on the LHS and RHS.
10737 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10738 if (KnownZero == 0 && KnownOne == 0) return;
10739
10740 APInt KnownZeroRHS, KnownOneRHS;
10741 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10742 KnownZero &= KnownZeroRHS;
10743 KnownOne &= KnownOneRHS;
10744 return;
10745 }
10746 }
10747 }
10748
10749 //===----------------------------------------------------------------------===//
10750 // ARM Inline Assembly Support
10751 //===----------------------------------------------------------------------===//
10752
ExpandInlineAsm(CallInst * CI) const10753 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10754 // Looking for "rev" which is V6+.
10755 if (!Subtarget->hasV6Ops())
10756 return false;
10757
10758 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10759 std::string AsmStr = IA->getAsmString();
10760 SmallVector<StringRef, 4> AsmPieces;
10761 SplitString(AsmStr, AsmPieces, ";\n");
10762
10763 switch (AsmPieces.size()) {
10764 default: return false;
10765 case 1:
10766 AsmStr = AsmPieces[0];
10767 AsmPieces.clear();
10768 SplitString(AsmStr, AsmPieces, " \t,");
10769
10770 // rev $0, $1
10771 if (AsmPieces.size() == 3 &&
10772 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10773 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10774 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10775 if (Ty && Ty->getBitWidth() == 32)
10776 return IntrinsicLowering::LowerToByteSwap(CI);
10777 }
10778 break;
10779 }
10780
10781 return false;
10782 }
10783
10784 /// getConstraintType - Given a constraint letter, return the type of
10785 /// constraint it is for this target.
10786 ARMTargetLowering::ConstraintType
getConstraintType(const std::string & Constraint) const10787 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10788 if (Constraint.size() == 1) {
10789 switch (Constraint[0]) {
10790 default: break;
10791 case 'l': return C_RegisterClass;
10792 case 'w': return C_RegisterClass;
10793 case 'h': return C_RegisterClass;
10794 case 'x': return C_RegisterClass;
10795 case 't': return C_RegisterClass;
10796 case 'j': return C_Other; // Constant for movw.
10797 // An address with a single base register. Due to the way we
10798 // currently handle addresses it is the same as an 'r' memory constraint.
10799 case 'Q': return C_Memory;
10800 }
10801 } else if (Constraint.size() == 2) {
10802 switch (Constraint[0]) {
10803 default: break;
10804 // All 'U+' constraints are addresses.
10805 case 'U': return C_Memory;
10806 }
10807 }
10808 return TargetLowering::getConstraintType(Constraint);
10809 }
10810
10811 /// Examine constraint type and operand type and determine a weight value.
10812 /// This object must already have been set up with the operand type
10813 /// and the current alternative constraint selected.
10814 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const10815 ARMTargetLowering::getSingleConstraintMatchWeight(
10816 AsmOperandInfo &info, const char *constraint) const {
10817 ConstraintWeight weight = CW_Invalid;
10818 Value *CallOperandVal = info.CallOperandVal;
10819 // If we don't have a value, we can't do a match,
10820 // but allow it at the lowest weight.
10821 if (CallOperandVal == NULL)
10822 return CW_Default;
10823 Type *type = CallOperandVal->getType();
10824 // Look at the constraint type.
10825 switch (*constraint) {
10826 default:
10827 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10828 break;
10829 case 'l':
10830 if (type->isIntegerTy()) {
10831 if (Subtarget->isThumb())
10832 weight = CW_SpecificReg;
10833 else
10834 weight = CW_Register;
10835 }
10836 break;
10837 case 'w':
10838 if (type->isFloatingPointTy())
10839 weight = CW_Register;
10840 break;
10841 }
10842 return weight;
10843 }
10844
10845 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10846 RCPair
getRegForInlineAsmConstraint(const std::string & Constraint,MVT VT) const10847 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10848 MVT VT) const {
10849 if (Constraint.size() == 1) {
10850 // GCC ARM Constraint Letters
10851 switch (Constraint[0]) {
10852 case 'l': // Low regs or general regs.
10853 if (Subtarget->isThumb())
10854 return RCPair(0U, &ARM::tGPRRegClass);
10855 return RCPair(0U, &ARM::GPRRegClass);
10856 case 'h': // High regs or no regs.
10857 if (Subtarget->isThumb())
10858 return RCPair(0U, &ARM::hGPRRegClass);
10859 break;
10860 case 'r':
10861 return RCPair(0U, &ARM::GPRRegClass);
10862 case 'w':
10863 if (VT == MVT::Other)
10864 break;
10865 if (VT == MVT::f32)
10866 return RCPair(0U, &ARM::SPRRegClass);
10867 if (VT.getSizeInBits() == 64)
10868 return RCPair(0U, &ARM::DPRRegClass);
10869 if (VT.getSizeInBits() == 128)
10870 return RCPair(0U, &ARM::QPRRegClass);
10871 break;
10872 case 'x':
10873 if (VT == MVT::Other)
10874 break;
10875 if (VT == MVT::f32)
10876 return RCPair(0U, &ARM::SPR_8RegClass);
10877 if (VT.getSizeInBits() == 64)
10878 return RCPair(0U, &ARM::DPR_8RegClass);
10879 if (VT.getSizeInBits() == 128)
10880 return RCPair(0U, &ARM::QPR_8RegClass);
10881 break;
10882 case 't':
10883 if (VT == MVT::f32)
10884 return RCPair(0U, &ARM::SPRRegClass);
10885 break;
10886 }
10887 }
10888 if (StringRef("{cc}").equals_lower(Constraint))
10889 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10890
10891 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10892 }
10893
10894 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10895 /// vector. If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const10896 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10897 std::string &Constraint,
10898 std::vector<SDValue>&Ops,
10899 SelectionDAG &DAG) const {
10900 SDValue Result(0, 0);
10901
10902 // Currently only support length 1 constraints.
10903 if (Constraint.length() != 1) return;
10904
10905 char ConstraintLetter = Constraint[0];
10906 switch (ConstraintLetter) {
10907 default: break;
10908 case 'j':
10909 case 'I': case 'J': case 'K': case 'L':
10910 case 'M': case 'N': case 'O':
10911 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10912 if (!C)
10913 return;
10914
10915 int64_t CVal64 = C->getSExtValue();
10916 int CVal = (int) CVal64;
10917 // None of these constraints allow values larger than 32 bits. Check
10918 // that the value fits in an int.
10919 if (CVal != CVal64)
10920 return;
10921
10922 switch (ConstraintLetter) {
10923 case 'j':
10924 // Constant suitable for movw, must be between 0 and
10925 // 65535.
10926 if (Subtarget->hasV6T2Ops())
10927 if (CVal >= 0 && CVal <= 65535)
10928 break;
10929 return;
10930 case 'I':
10931 if (Subtarget->isThumb1Only()) {
10932 // This must be a constant between 0 and 255, for ADD
10933 // immediates.
10934 if (CVal >= 0 && CVal <= 255)
10935 break;
10936 } else if (Subtarget->isThumb2()) {
10937 // A constant that can be used as an immediate value in a
10938 // data-processing instruction.
10939 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10940 break;
10941 } else {
10942 // A constant that can be used as an immediate value in a
10943 // data-processing instruction.
10944 if (ARM_AM::getSOImmVal(CVal) != -1)
10945 break;
10946 }
10947 return;
10948
10949 case 'J':
10950 if (Subtarget->isThumb()) { // FIXME thumb2
10951 // This must be a constant between -255 and -1, for negated ADD
10952 // immediates. This can be used in GCC with an "n" modifier that
10953 // prints the negated value, for use with SUB instructions. It is
10954 // not useful otherwise but is implemented for compatibility.
10955 if (CVal >= -255 && CVal <= -1)
10956 break;
10957 } else {
10958 // This must be a constant between -4095 and 4095. It is not clear
10959 // what this constraint is intended for. Implemented for
10960 // compatibility with GCC.
10961 if (CVal >= -4095 && CVal <= 4095)
10962 break;
10963 }
10964 return;
10965
10966 case 'K':
10967 if (Subtarget->isThumb1Only()) {
10968 // A 32-bit value where only one byte has a nonzero value. Exclude
10969 // zero to match GCC. This constraint is used by GCC internally for
10970 // constants that can be loaded with a move/shift combination.
10971 // It is not useful otherwise but is implemented for compatibility.
10972 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10973 break;
10974 } else if (Subtarget->isThumb2()) {
10975 // A constant whose bitwise inverse can be used as an immediate
10976 // value in a data-processing instruction. This can be used in GCC
10977 // with a "B" modifier that prints the inverted value, for use with
10978 // BIC and MVN instructions. It is not useful otherwise but is
10979 // implemented for compatibility.
10980 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10981 break;
10982 } else {
10983 // A constant whose bitwise inverse can be used as an immediate
10984 // value in a data-processing instruction. This can be used in GCC
10985 // with a "B" modifier that prints the inverted value, for use with
10986 // BIC and MVN instructions. It is not useful otherwise but is
10987 // implemented for compatibility.
10988 if (ARM_AM::getSOImmVal(~CVal) != -1)
10989 break;
10990 }
10991 return;
10992
10993 case 'L':
10994 if (Subtarget->isThumb1Only()) {
10995 // This must be a constant between -7 and 7,
10996 // for 3-operand ADD/SUB immediate instructions.
10997 if (CVal >= -7 && CVal < 7)
10998 break;
10999 } else if (Subtarget->isThumb2()) {
11000 // A constant whose negation can be used as an immediate value in a
11001 // data-processing instruction. This can be used in GCC with an "n"
11002 // modifier that prints the negated value, for use with SUB
11003 // instructions. It is not useful otherwise but is implemented for
11004 // compatibility.
11005 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11006 break;
11007 } else {
11008 // A constant whose negation can be used as an immediate value in a
11009 // data-processing instruction. This can be used in GCC with an "n"
11010 // modifier that prints the negated value, for use with SUB
11011 // instructions. It is not useful otherwise but is implemented for
11012 // compatibility.
11013 if (ARM_AM::getSOImmVal(-CVal) != -1)
11014 break;
11015 }
11016 return;
11017
11018 case 'M':
11019 if (Subtarget->isThumb()) { // FIXME thumb2
11020 // This must be a multiple of 4 between 0 and 1020, for
11021 // ADD sp + immediate.
11022 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11023 break;
11024 } else {
11025 // A power of two or a constant between 0 and 32. This is used in
11026 // GCC for the shift amount on shifted register operands, but it is
11027 // useful in general for any shift amounts.
11028 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11029 break;
11030 }
11031 return;
11032
11033 case 'N':
11034 if (Subtarget->isThumb()) { // FIXME thumb2
11035 // This must be a constant between 0 and 31, for shift amounts.
11036 if (CVal >= 0 && CVal <= 31)
11037 break;
11038 }
11039 return;
11040
11041 case 'O':
11042 if (Subtarget->isThumb()) { // FIXME thumb2
11043 // This must be a multiple of 4 between -508 and 508, for
11044 // ADD/SUB sp = sp + immediate.
11045 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11046 break;
11047 }
11048 return;
11049 }
11050 Result = DAG.getTargetConstant(CVal, Op.getValueType());
11051 break;
11052 }
11053
11054 if (Result.getNode()) {
11055 Ops.push_back(Result);
11056 return;
11057 }
11058 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11059 }
11060
LowerDivRem(SDValue Op,SelectionDAG & DAG) const11061 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11062 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11063 unsigned Opcode = Op->getOpcode();
11064 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11065 "Invalid opcode for Div/Rem lowering");
11066 bool isSigned = (Opcode == ISD::SDIVREM);
11067 EVT VT = Op->getValueType(0);
11068 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11069
11070 RTLIB::Libcall LC;
11071 switch (VT.getSimpleVT().SimpleTy) {
11072 default: llvm_unreachable("Unexpected request for libcall!");
11073 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11074 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11075 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11076 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11077 }
11078
11079 SDValue InChain = DAG.getEntryNode();
11080
11081 TargetLowering::ArgListTy Args;
11082 TargetLowering::ArgListEntry Entry;
11083 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11084 EVT ArgVT = Op->getOperand(i).getValueType();
11085 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11086 Entry.Node = Op->getOperand(i);
11087 Entry.Ty = ArgTy;
11088 Entry.isSExt = isSigned;
11089 Entry.isZExt = !isSigned;
11090 Args.push_back(Entry);
11091 }
11092
11093 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11094 getPointerTy());
11095
11096 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11097
11098 SDLoc dl(Op);
11099 TargetLowering::
11100 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11101 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11102 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11103 Callee, Args, DAG, dl);
11104 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11105
11106 return CallInfo.first;
11107 }
11108
11109 bool
isOffsetFoldingLegal(const GlobalAddressSDNode * GA) const11110 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11111 // The ARM target isn't yet aware of offsets.
11112 return false;
11113 }
11114
isBitFieldInvertedMask(unsigned v)11115 bool ARM::isBitFieldInvertedMask(unsigned v) {
11116 if (v == 0xffffffff)
11117 return false;
11118
11119 // there can be 1's on either or both "outsides", all the "inside"
11120 // bits must be 0's
11121 unsigned TO = CountTrailingOnes_32(v);
11122 unsigned LO = CountLeadingOnes_32(v);
11123 v = (v >> TO) << TO;
11124 v = (v << LO) >> LO;
11125 return v == 0;
11126 }
11127
11128 /// isFPImmLegal - Returns true if the target can instruction select the
11129 /// specified FP immediate natively. If false, the legalizer will
11130 /// materialize the FP immediate as a load from a constant pool.
isFPImmLegal(const APFloat & Imm,EVT VT) const11131 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11132 if (!Subtarget->hasVFP3())
11133 return false;
11134 if (VT == MVT::f32)
11135 return ARM_AM::getFP32Imm(Imm) != -1;
11136 if (VT == MVT::f64)
11137 return ARM_AM::getFP64Imm(Imm) != -1;
11138 return false;
11139 }
11140
11141 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11142 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11143 /// specified in the intrinsic calls.
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,unsigned Intrinsic) const11144 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11145 const CallInst &I,
11146 unsigned Intrinsic) const {
11147 switch (Intrinsic) {
11148 case Intrinsic::arm_neon_vld1:
11149 case Intrinsic::arm_neon_vld2:
11150 case Intrinsic::arm_neon_vld3:
11151 case Intrinsic::arm_neon_vld4:
11152 case Intrinsic::arm_neon_vld2lane:
11153 case Intrinsic::arm_neon_vld3lane:
11154 case Intrinsic::arm_neon_vld4lane: {
11155 Info.opc = ISD::INTRINSIC_W_CHAIN;
11156 // Conservatively set memVT to the entire set of vectors loaded.
11157 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11158 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11159 Info.ptrVal = I.getArgOperand(0);
11160 Info.offset = 0;
11161 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11162 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11163 Info.vol = false; // volatile loads with NEON intrinsics not supported
11164 Info.readMem = true;
11165 Info.writeMem = false;
11166 return true;
11167 }
11168 case Intrinsic::arm_neon_vst1:
11169 case Intrinsic::arm_neon_vst2:
11170 case Intrinsic::arm_neon_vst3:
11171 case Intrinsic::arm_neon_vst4:
11172 case Intrinsic::arm_neon_vst2lane:
11173 case Intrinsic::arm_neon_vst3lane:
11174 case Intrinsic::arm_neon_vst4lane: {
11175 Info.opc = ISD::INTRINSIC_VOID;
11176 // Conservatively set memVT to the entire set of vectors stored.
11177 unsigned NumElts = 0;
11178 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11179 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11180 if (!ArgTy->isVectorTy())
11181 break;
11182 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11183 }
11184 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11185 Info.ptrVal = I.getArgOperand(0);
11186 Info.offset = 0;
11187 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11188 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11189 Info.vol = false; // volatile stores with NEON intrinsics not supported
11190 Info.readMem = false;
11191 Info.writeMem = true;
11192 return true;
11193 }
11194 case Intrinsic::arm_ldrex: {
11195 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11196 Info.opc = ISD::INTRINSIC_W_CHAIN;
11197 Info.memVT = MVT::getVT(PtrTy->getElementType());
11198 Info.ptrVal = I.getArgOperand(0);
11199 Info.offset = 0;
11200 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11201 Info.vol = true;
11202 Info.readMem = true;
11203 Info.writeMem = false;
11204 return true;
11205 }
11206 case Intrinsic::arm_strex: {
11207 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11208 Info.opc = ISD::INTRINSIC_W_CHAIN;
11209 Info.memVT = MVT::getVT(PtrTy->getElementType());
11210 Info.ptrVal = I.getArgOperand(1);
11211 Info.offset = 0;
11212 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11213 Info.vol = true;
11214 Info.readMem = false;
11215 Info.writeMem = true;
11216 return true;
11217 }
11218 case Intrinsic::arm_strexd: {
11219 Info.opc = ISD::INTRINSIC_W_CHAIN;
11220 Info.memVT = MVT::i64;
11221 Info.ptrVal = I.getArgOperand(2);
11222 Info.offset = 0;
11223 Info.align = 8;
11224 Info.vol = true;
11225 Info.readMem = false;
11226 Info.writeMem = true;
11227 return true;
11228 }
11229 case Intrinsic::arm_ldrexd: {
11230 Info.opc = ISD::INTRINSIC_W_CHAIN;
11231 Info.memVT = MVT::i64;
11232 Info.ptrVal = I.getArgOperand(0);
11233 Info.offset = 0;
11234 Info.align = 8;
11235 Info.vol = true;
11236 Info.readMem = true;
11237 Info.writeMem = false;
11238 return true;
11239 }
11240 default:
11241 break;
11242 }
11243
11244 return false;
11245 }
11246