1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "Utils/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/RuntimeLibcalls.h"
56 #include "llvm/CodeGen/SelectionDAG.h"
57 #include "llvm/CodeGen/SelectionDAGNodes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/IntrinsicsARM.h"
82 #include "llvm/IR/Module.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/User.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/MC/MCInstrDesc.h"
88 #include "llvm/MC/MCInstrItineraries.h"
89 #include "llvm/MC/MCRegisterInfo.h"
90 #include "llvm/MC/MCSchedule.h"
91 #include "llvm/Support/AtomicOrdering.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CodeGen.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/ErrorHandling.h"
99 #include "llvm/Support/KnownBits.h"
100 #include "llvm/Support/MachineValueType.h"
101 #include "llvm/Support/MathExtras.h"
102 #include "llvm/Support/raw_ostream.h"
103 #include "llvm/Target/TargetMachine.h"
104 #include "llvm/Target/TargetOptions.h"
105 #include <algorithm>
106 #include <cassert>
107 #include <cstdint>
108 #include <cstdlib>
109 #include <iterator>
110 #include <limits>
111 #include <string>
112 #include <tuple>
113 #include <utility>
114 #include <vector>
115
116 using namespace llvm;
117 using namespace llvm::PatternMatch;
118
119 #define DEBUG_TYPE "arm-isel"
120
121 STATISTIC(NumTailCalls, "Number of tail calls");
122 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
123 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
124 STATISTIC(NumConstpoolPromoted,
125 "Number of constants with their storage promoted into constant pools");
126
127 static cl::opt<bool>
128 ARMInterworking("arm-interworking", cl::Hidden,
129 cl::desc("Enable / disable ARM interworking (for debugging only)"),
130 cl::init(true));
131
132 static cl::opt<bool> EnableConstpoolPromotion(
133 "arm-promote-constant", cl::Hidden,
134 cl::desc("Enable / disable promotion of unnamed_addr constants into "
135 "constant pools"),
136 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
137 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
138 "arm-promote-constant-max-size", cl::Hidden,
139 cl::desc("Maximum size of constant to promote into a constant pool"),
140 cl::init(64));
141 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
142 "arm-promote-constant-max-total", cl::Hidden,
143 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
144 cl::init(128));
145
146 cl::opt<unsigned>
147 MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
148 cl::desc("Maximum interleave factor for MVE VLDn to generate."),
149 cl::init(2));
150
151 // The APCS parameter registers.
152 static const MCPhysReg GPRArgRegs[] = {
153 ARM::R0, ARM::R1, ARM::R2, ARM::R3
154 };
155
addTypeForNEON(MVT VT,MVT PromotedLdStVT,MVT PromotedBitwiseVT)156 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
157 MVT PromotedBitwiseVT) {
158 if (VT != PromotedLdStVT) {
159 setOperationAction(ISD::LOAD, VT, Promote);
160 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
161
162 setOperationAction(ISD::STORE, VT, Promote);
163 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
164 }
165
166 MVT ElemTy = VT.getVectorElementType();
167 if (ElemTy != MVT::f64)
168 setOperationAction(ISD::SETCC, VT, Custom);
169 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
170 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
171 if (ElemTy == MVT::i32) {
172 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
173 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
174 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
175 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
176 } else {
177 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
178 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
179 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
180 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
181 }
182 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
183 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
184 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
185 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
186 setOperationAction(ISD::SELECT, VT, Expand);
187 setOperationAction(ISD::SELECT_CC, VT, Expand);
188 setOperationAction(ISD::VSELECT, VT, Expand);
189 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
190 if (VT.isInteger()) {
191 setOperationAction(ISD::SHL, VT, Custom);
192 setOperationAction(ISD::SRA, VT, Custom);
193 setOperationAction(ISD::SRL, VT, Custom);
194 }
195
196 // Promote all bit-wise operations.
197 if (VT.isInteger() && VT != PromotedBitwiseVT) {
198 setOperationAction(ISD::AND, VT, Promote);
199 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
200 setOperationAction(ISD::OR, VT, Promote);
201 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
202 setOperationAction(ISD::XOR, VT, Promote);
203 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
204 }
205
206 // Neon does not support vector divide/remainder operations.
207 setOperationAction(ISD::SDIV, VT, Expand);
208 setOperationAction(ISD::UDIV, VT, Expand);
209 setOperationAction(ISD::FDIV, VT, Expand);
210 setOperationAction(ISD::SREM, VT, Expand);
211 setOperationAction(ISD::UREM, VT, Expand);
212 setOperationAction(ISD::FREM, VT, Expand);
213 setOperationAction(ISD::SDIVREM, VT, Expand);
214 setOperationAction(ISD::UDIVREM, VT, Expand);
215
216 if (!VT.isFloatingPoint() &&
217 VT != MVT::v2i64 && VT != MVT::v1i64)
218 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
219 setOperationAction(Opcode, VT, Legal);
220 if (!VT.isFloatingPoint())
221 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
222 setOperationAction(Opcode, VT, Legal);
223 }
224
addDRTypeForNEON(MVT VT)225 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
226 addRegisterClass(VT, &ARM::DPRRegClass);
227 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
228 }
229
addQRTypeForNEON(MVT VT)230 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
231 addRegisterClass(VT, &ARM::DPairRegClass);
232 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
233 }
234
setAllExpand(MVT VT)235 void ARMTargetLowering::setAllExpand(MVT VT) {
236 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
237 setOperationAction(Opc, VT, Expand);
238
239 // We support these really simple operations even on types where all
240 // the actual arithmetic has to be broken down into simpler
241 // operations or turned into library calls.
242 setOperationAction(ISD::BITCAST, VT, Legal);
243 setOperationAction(ISD::LOAD, VT, Legal);
244 setOperationAction(ISD::STORE, VT, Legal);
245 setOperationAction(ISD::UNDEF, VT, Legal);
246 }
247
addAllExtLoads(const MVT From,const MVT To,LegalizeAction Action)248 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
249 LegalizeAction Action) {
250 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
251 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
252 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
253 }
254
addMVEVectorTypes(bool HasMVEFP)255 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
256 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
257
258 for (auto VT : IntTypes) {
259 addRegisterClass(VT, &ARM::MQPRRegClass);
260 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
261 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
262 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
263 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
264 setOperationAction(ISD::SHL, VT, Custom);
265 setOperationAction(ISD::SRA, VT, Custom);
266 setOperationAction(ISD::SRL, VT, Custom);
267 setOperationAction(ISD::SMIN, VT, Legal);
268 setOperationAction(ISD::SMAX, VT, Legal);
269 setOperationAction(ISD::UMIN, VT, Legal);
270 setOperationAction(ISD::UMAX, VT, Legal);
271 setOperationAction(ISD::ABS, VT, Legal);
272 setOperationAction(ISD::SETCC, VT, Custom);
273 setOperationAction(ISD::MLOAD, VT, Custom);
274 setOperationAction(ISD::MSTORE, VT, Legal);
275 setOperationAction(ISD::CTLZ, VT, Legal);
276 setOperationAction(ISD::CTTZ, VT, Custom);
277 setOperationAction(ISD::BITREVERSE, VT, Legal);
278 setOperationAction(ISD::BSWAP, VT, Legal);
279 setOperationAction(ISD::SADDSAT, VT, Legal);
280 setOperationAction(ISD::UADDSAT, VT, Legal);
281 setOperationAction(ISD::SSUBSAT, VT, Legal);
282 setOperationAction(ISD::USUBSAT, VT, Legal);
283
284 // No native support for these.
285 setOperationAction(ISD::UDIV, VT, Expand);
286 setOperationAction(ISD::SDIV, VT, Expand);
287 setOperationAction(ISD::UREM, VT, Expand);
288 setOperationAction(ISD::SREM, VT, Expand);
289 setOperationAction(ISD::UDIVREM, VT, Expand);
290 setOperationAction(ISD::SDIVREM, VT, Expand);
291 setOperationAction(ISD::CTPOP, VT, Expand);
292 setOperationAction(ISD::SELECT, VT, Expand);
293 setOperationAction(ISD::SELECT_CC, VT, Expand);
294
295 // Vector reductions
296 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
297 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
298 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
299 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
300 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
301 setOperationAction(ISD::VECREDUCE_MUL, VT, Custom);
302 setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
303 setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
304 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
305
306 if (!HasMVEFP) {
307 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
308 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
309 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
310 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
311 }
312
313 // Pre and Post inc are supported on loads and stores
314 for (unsigned im = (unsigned)ISD::PRE_INC;
315 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
316 setIndexedLoadAction(im, VT, Legal);
317 setIndexedStoreAction(im, VT, Legal);
318 setIndexedMaskedLoadAction(im, VT, Legal);
319 setIndexedMaskedStoreAction(im, VT, Legal);
320 }
321 }
322
323 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
324 for (auto VT : FloatTypes) {
325 addRegisterClass(VT, &ARM::MQPRRegClass);
326 if (!HasMVEFP)
327 setAllExpand(VT);
328
329 // These are legal or custom whether we have MVE.fp or not
330 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
331 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
332 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
334 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
335 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
336 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
337 setOperationAction(ISD::SETCC, VT, Custom);
338 setOperationAction(ISD::MLOAD, VT, Custom);
339 setOperationAction(ISD::MSTORE, VT, Legal);
340 setOperationAction(ISD::SELECT, VT, Expand);
341 setOperationAction(ISD::SELECT_CC, VT, Expand);
342
343 // Pre and Post inc are supported on loads and stores
344 for (unsigned im = (unsigned)ISD::PRE_INC;
345 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
346 setIndexedLoadAction(im, VT, Legal);
347 setIndexedStoreAction(im, VT, Legal);
348 setIndexedMaskedLoadAction(im, VT, Legal);
349 setIndexedMaskedStoreAction(im, VT, Legal);
350 }
351
352 if (HasMVEFP) {
353 setOperationAction(ISD::FMINNUM, VT, Legal);
354 setOperationAction(ISD::FMAXNUM, VT, Legal);
355 setOperationAction(ISD::FROUND, VT, Legal);
356 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
357 setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom);
358 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
359 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
360
361 // No native support for these.
362 setOperationAction(ISD::FDIV, VT, Expand);
363 setOperationAction(ISD::FREM, VT, Expand);
364 setOperationAction(ISD::FSQRT, VT, Expand);
365 setOperationAction(ISD::FSIN, VT, Expand);
366 setOperationAction(ISD::FCOS, VT, Expand);
367 setOperationAction(ISD::FPOW, VT, Expand);
368 setOperationAction(ISD::FLOG, VT, Expand);
369 setOperationAction(ISD::FLOG2, VT, Expand);
370 setOperationAction(ISD::FLOG10, VT, Expand);
371 setOperationAction(ISD::FEXP, VT, Expand);
372 setOperationAction(ISD::FEXP2, VT, Expand);
373 setOperationAction(ISD::FNEARBYINT, VT, Expand);
374 }
375 }
376
377 // Custom Expand smaller than legal vector reductions to prevent false zero
378 // items being added.
379 setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom);
380 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom);
381 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom);
382 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom);
383 setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom);
384 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom);
385 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom);
386 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom);
387
388 // We 'support' these types up to bitcast/load/store level, regardless of
389 // MVE integer-only / float support. Only doing FP data processing on the FP
390 // vector types is inhibited at integer-only level.
391 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
392 for (auto VT : LongTypes) {
393 addRegisterClass(VT, &ARM::MQPRRegClass);
394 setAllExpand(VT);
395 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
397 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
398 }
399 // We can do bitwise operations on v2i64 vectors
400 setOperationAction(ISD::AND, MVT::v2i64, Legal);
401 setOperationAction(ISD::OR, MVT::v2i64, Legal);
402 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
403
404 // It is legal to extload from v4i8 to v4i16 or v4i32.
405 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
406 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
407 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
408
409 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
410 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal);
411 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
412 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
413 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Legal);
414 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
415
416 // Some truncating stores are legal too.
417 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
418 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
419 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
420
421 // Pre and Post inc on these are legal, given the correct extends
422 for (unsigned im = (unsigned)ISD::PRE_INC;
423 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
424 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
425 setIndexedLoadAction(im, VT, Legal);
426 setIndexedStoreAction(im, VT, Legal);
427 setIndexedMaskedLoadAction(im, VT, Legal);
428 setIndexedMaskedStoreAction(im, VT, Legal);
429 }
430 }
431
432 // Predicate types
433 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
434 for (auto VT : pTypes) {
435 addRegisterClass(VT, &ARM::VCCRRegClass);
436 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
437 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
438 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
439 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
440 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
441 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
442 setOperationAction(ISD::SETCC, VT, Custom);
443 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
444 setOperationAction(ISD::LOAD, VT, Custom);
445 setOperationAction(ISD::STORE, VT, Custom);
446 }
447 }
448
ARMTargetLowering(const TargetMachine & TM,const ARMSubtarget & STI)449 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
450 const ARMSubtarget &STI)
451 : TargetLowering(TM), Subtarget(&STI) {
452 RegInfo = Subtarget->getRegisterInfo();
453 Itins = Subtarget->getInstrItineraryData();
454
455 setBooleanContents(ZeroOrOneBooleanContent);
456 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
457
458 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
459 !Subtarget->isTargetWatchOS()) {
460 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
461 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
462 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
463 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
464 : CallingConv::ARM_AAPCS);
465 }
466
467 if (Subtarget->isTargetMachO()) {
468 // Uses VFP for Thumb libfuncs if available.
469 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
470 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
471 static const struct {
472 const RTLIB::Libcall Op;
473 const char * const Name;
474 const ISD::CondCode Cond;
475 } LibraryCalls[] = {
476 // Single-precision floating-point arithmetic.
477 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
478 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
479 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
480 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
481
482 // Double-precision floating-point arithmetic.
483 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
484 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
485 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
486 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
487
488 // Single-precision comparisons.
489 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
490 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
491 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
492 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
493 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
494 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
495 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
496
497 // Double-precision comparisons.
498 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
499 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
500 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
501 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
502 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
503 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
504 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
505
506 // Floating-point to integer conversions.
507 // i64 conversions are done via library routines even when generating VFP
508 // instructions, so use the same ones.
509 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
510 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
511 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
512 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
513
514 // Conversions between floating types.
515 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
516 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
517
518 // Integer to floating-point conversions.
519 // i64 conversions are done via library routines even when generating VFP
520 // instructions, so use the same ones.
521 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
522 // e.g., __floatunsidf vs. __floatunssidfvfp.
523 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
524 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
525 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
526 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
527 };
528
529 for (const auto &LC : LibraryCalls) {
530 setLibcallName(LC.Op, LC.Name);
531 if (LC.Cond != ISD::SETCC_INVALID)
532 setCmpLibcallCC(LC.Op, LC.Cond);
533 }
534 }
535 }
536
537 // These libcalls are not available in 32-bit.
538 setLibcallName(RTLIB::SHL_I128, nullptr);
539 setLibcallName(RTLIB::SRL_I128, nullptr);
540 setLibcallName(RTLIB::SRA_I128, nullptr);
541
542 // RTLIB
543 if (Subtarget->isAAPCS_ABI() &&
544 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
545 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
546 static const struct {
547 const RTLIB::Libcall Op;
548 const char * const Name;
549 const CallingConv::ID CC;
550 const ISD::CondCode Cond;
551 } LibraryCalls[] = {
552 // Double-precision floating-point arithmetic helper functions
553 // RTABI chapter 4.1.2, Table 2
554 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
555 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
556 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
557 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
558
559 // Double-precision floating-point comparison helper functions
560 // RTABI chapter 4.1.2, Table 3
561 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
562 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
563 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
564 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
565 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
566 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
567 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
568
569 // Single-precision floating-point arithmetic helper functions
570 // RTABI chapter 4.1.2, Table 4
571 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
572 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
573 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
574 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
575
576 // Single-precision floating-point comparison helper functions
577 // RTABI chapter 4.1.2, Table 5
578 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
579 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
580 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
581 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
582 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
583 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
584 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
585
586 // Floating-point to integer conversions.
587 // RTABI chapter 4.1.2, Table 6
588 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
589 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
590 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
593 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
594 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
595 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
596
597 // Conversions between floating types.
598 // RTABI chapter 4.1.2, Table 7
599 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
600 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
601 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
602
603 // Integer to floating-point conversions.
604 // RTABI chapter 4.1.2, Table 8
605 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
606 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
607 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
608 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
609 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
610 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
611 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
612 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
613
614 // Long long helper functions
615 // RTABI chapter 4.2, Table 9
616 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
617 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
618 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
619 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
620
621 // Integer division functions
622 // RTABI chapter 4.3.1
623 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
624 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
625 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
626 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
627 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
628 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
629 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
630 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
631 };
632
633 for (const auto &LC : LibraryCalls) {
634 setLibcallName(LC.Op, LC.Name);
635 setLibcallCallingConv(LC.Op, LC.CC);
636 if (LC.Cond != ISD::SETCC_INVALID)
637 setCmpLibcallCC(LC.Op, LC.Cond);
638 }
639
640 // EABI dependent RTLIB
641 if (TM.Options.EABIVersion == EABI::EABI4 ||
642 TM.Options.EABIVersion == EABI::EABI5) {
643 static const struct {
644 const RTLIB::Libcall Op;
645 const char *const Name;
646 const CallingConv::ID CC;
647 const ISD::CondCode Cond;
648 } MemOpsLibraryCalls[] = {
649 // Memory operations
650 // RTABI chapter 4.3.4
651 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
652 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
653 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
654 };
655
656 for (const auto &LC : MemOpsLibraryCalls) {
657 setLibcallName(LC.Op, LC.Name);
658 setLibcallCallingConv(LC.Op, LC.CC);
659 if (LC.Cond != ISD::SETCC_INVALID)
660 setCmpLibcallCC(LC.Op, LC.Cond);
661 }
662 }
663 }
664
665 if (Subtarget->isTargetWindows()) {
666 static const struct {
667 const RTLIB::Libcall Op;
668 const char * const Name;
669 const CallingConv::ID CC;
670 } LibraryCalls[] = {
671 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
672 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
673 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
674 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
675 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
676 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
677 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
678 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
679 };
680
681 for (const auto &LC : LibraryCalls) {
682 setLibcallName(LC.Op, LC.Name);
683 setLibcallCallingConv(LC.Op, LC.CC);
684 }
685 }
686
687 // Use divmod compiler-rt calls for iOS 5.0 and later.
688 if (Subtarget->isTargetMachO() &&
689 !(Subtarget->isTargetIOS() &&
690 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
691 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
692 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
693 }
694
695 // The half <-> float conversion functions are always soft-float on
696 // non-watchos platforms, but are needed for some targets which use a
697 // hard-float calling convention by default.
698 if (!Subtarget->isTargetWatchABI()) {
699 if (Subtarget->isAAPCS_ABI()) {
700 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
701 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
702 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
703 } else {
704 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
705 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
706 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
707 }
708 }
709
710 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
711 // a __gnu_ prefix (which is the default).
712 if (Subtarget->isTargetAEABI()) {
713 static const struct {
714 const RTLIB::Libcall Op;
715 const char * const Name;
716 const CallingConv::ID CC;
717 } LibraryCalls[] = {
718 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
719 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
720 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
721 };
722
723 for (const auto &LC : LibraryCalls) {
724 setLibcallName(LC.Op, LC.Name);
725 setLibcallCallingConv(LC.Op, LC.CC);
726 }
727 }
728
729 if (Subtarget->isThumb1Only())
730 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
731 else
732 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
733
734 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
735 Subtarget->hasFPRegs()) {
736 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
737 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
738 if (!Subtarget->hasVFP2Base())
739 setAllExpand(MVT::f32);
740 if (!Subtarget->hasFP64())
741 setAllExpand(MVT::f64);
742 }
743
744 if (Subtarget->hasFullFP16()) {
745 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
746 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
747 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
748
749 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
750 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
751 }
752
753 if (Subtarget->hasBF16()) {
754 addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
755 setAllExpand(MVT::bf16);
756 if (!Subtarget->hasFullFP16())
757 setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
758 }
759
760 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
761 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
762 setTruncStoreAction(VT, InnerVT, Expand);
763 addAllExtLoads(VT, InnerVT, Expand);
764 }
765
766 setOperationAction(ISD::MULHS, VT, Expand);
767 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
768 setOperationAction(ISD::MULHU, VT, Expand);
769 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
770
771 setOperationAction(ISD::BSWAP, VT, Expand);
772 }
773
774 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
775 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
776
777 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
778 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
779
780 if (Subtarget->hasMVEIntegerOps())
781 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
782
783 // Combine low-overhead loop intrinsics so that we can lower i1 types.
784 if (Subtarget->hasLOB()) {
785 setTargetDAGCombine(ISD::BRCOND);
786 setTargetDAGCombine(ISD::BR_CC);
787 }
788
789 if (Subtarget->hasNEON()) {
790 addDRTypeForNEON(MVT::v2f32);
791 addDRTypeForNEON(MVT::v8i8);
792 addDRTypeForNEON(MVT::v4i16);
793 addDRTypeForNEON(MVT::v2i32);
794 addDRTypeForNEON(MVT::v1i64);
795
796 addQRTypeForNEON(MVT::v4f32);
797 addQRTypeForNEON(MVT::v2f64);
798 addQRTypeForNEON(MVT::v16i8);
799 addQRTypeForNEON(MVT::v8i16);
800 addQRTypeForNEON(MVT::v4i32);
801 addQRTypeForNEON(MVT::v2i64);
802
803 if (Subtarget->hasFullFP16()) {
804 addQRTypeForNEON(MVT::v8f16);
805 addDRTypeForNEON(MVT::v4f16);
806 }
807
808 if (Subtarget->hasBF16()) {
809 addQRTypeForNEON(MVT::v8bf16);
810 addDRTypeForNEON(MVT::v4bf16);
811 }
812 }
813
814 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
815 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
816 // none of Neon, MVE or VFP supports any arithmetic operations on it.
817 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
818 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
819 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
820 // FIXME: Code duplication: FDIV and FREM are expanded always, see
821 // ARMTargetLowering::addTypeForNEON method for details.
822 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
823 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
824 // FIXME: Create unittest.
825 // In another words, find a way when "copysign" appears in DAG with vector
826 // operands.
827 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
828 // FIXME: Code duplication: SETCC has custom operation action, see
829 // ARMTargetLowering::addTypeForNEON method for details.
830 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
831 // FIXME: Create unittest for FNEG and for FABS.
832 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
833 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
834 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
835 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
836 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
837 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
838 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
839 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
840 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
841 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
842 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
843 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
844 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
845 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
846 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
847 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
848 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
849 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
850 }
851
852 if (Subtarget->hasNEON()) {
853 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
854 // supported for v4f32.
855 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
856 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
857 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
858 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
859 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
860 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
861 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
862 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
863 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
864 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
865 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
866 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
867 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
868 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
869
870 // Mark v2f32 intrinsics.
871 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
872 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
873 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
874 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
875 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
876 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
877 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
878 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
879 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
880 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
881 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
882 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
883 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
884 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
885
886 // Neon does not support some operations on v1i64 and v2i64 types.
887 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
888 // Custom handling for some quad-vector types to detect VMULL.
889 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
890 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
891 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
892 // Custom handling for some vector types to avoid expensive expansions
893 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
894 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
895 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
896 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
897 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
898 // a destination type that is wider than the source, and nor does
899 // it have a FP_TO_[SU]INT instruction with a narrower destination than
900 // source.
901 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
902 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
903 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
904 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
905 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
906 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
908 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
909
910 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
911 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
912
913 // NEON does not have single instruction CTPOP for vectors with element
914 // types wider than 8-bits. However, custom lowering can leverage the
915 // v8i8/v16i8 vcnt instruction.
916 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
917 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
918 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
919 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
920 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
921 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
922
923 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
924 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
925
926 // NEON does not have single instruction CTTZ for vectors.
927 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
928 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
929 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
930 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
931
932 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
933 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
934 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
935 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
936
937 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
938 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
939 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
940 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
941
942 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
943 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
944 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
945 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
946
947 // NEON only has FMA instructions as of VFP4.
948 if (!Subtarget->hasVFP4Base()) {
949 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
950 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
951 }
952
953 setTargetDAGCombine(ISD::SHL);
954 setTargetDAGCombine(ISD::SRL);
955 setTargetDAGCombine(ISD::SRA);
956 setTargetDAGCombine(ISD::FP_TO_SINT);
957 setTargetDAGCombine(ISD::FP_TO_UINT);
958 setTargetDAGCombine(ISD::FDIV);
959 setTargetDAGCombine(ISD::LOAD);
960
961 // It is legal to extload from v4i8 to v4i16 or v4i32.
962 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
963 MVT::v2i32}) {
964 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
965 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
966 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
967 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
968 }
969 }
970 }
971
972 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
973 setTargetDAGCombine(ISD::BUILD_VECTOR);
974 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
975 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
976 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
977 setTargetDAGCombine(ISD::STORE);
978 setTargetDAGCombine(ISD::SIGN_EXTEND);
979 setTargetDAGCombine(ISD::ZERO_EXTEND);
980 setTargetDAGCombine(ISD::ANY_EXTEND);
981 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
982 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
983 setTargetDAGCombine(ISD::INTRINSIC_VOID);
984 setTargetDAGCombine(ISD::VECREDUCE_ADD);
985 setTargetDAGCombine(ISD::ADD);
986 setTargetDAGCombine(ISD::BITCAST);
987 }
988 if (Subtarget->hasMVEIntegerOps()) {
989 setTargetDAGCombine(ISD::SMIN);
990 setTargetDAGCombine(ISD::UMIN);
991 setTargetDAGCombine(ISD::SMAX);
992 setTargetDAGCombine(ISD::UMAX);
993 setTargetDAGCombine(ISD::FP_EXTEND);
994 setTargetDAGCombine(ISD::SELECT);
995 setTargetDAGCombine(ISD::SELECT_CC);
996 }
997
998 if (!Subtarget->hasFP64()) {
999 // When targeting a floating-point unit with only single-precision
1000 // operations, f64 is legal for the few double-precision instructions which
1001 // are present However, no double-precision operations other than moves,
1002 // loads and stores are provided by the hardware.
1003 setOperationAction(ISD::FADD, MVT::f64, Expand);
1004 setOperationAction(ISD::FSUB, MVT::f64, Expand);
1005 setOperationAction(ISD::FMUL, MVT::f64, Expand);
1006 setOperationAction(ISD::FMA, MVT::f64, Expand);
1007 setOperationAction(ISD::FDIV, MVT::f64, Expand);
1008 setOperationAction(ISD::FREM, MVT::f64, Expand);
1009 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1010 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
1011 setOperationAction(ISD::FNEG, MVT::f64, Expand);
1012 setOperationAction(ISD::FABS, MVT::f64, Expand);
1013 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
1014 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1015 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1016 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1017 setOperationAction(ISD::FLOG, MVT::f64, Expand);
1018 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
1019 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
1020 setOperationAction(ISD::FEXP, MVT::f64, Expand);
1021 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
1022 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
1023 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
1024 setOperationAction(ISD::FRINT, MVT::f64, Expand);
1025 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
1026 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
1027 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1029 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1030 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1031 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
1032 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
1033 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
1034 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
1035 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
1036 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
1037 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
1038 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
1039 }
1040
1041 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1042 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
1043 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1044 if (Subtarget->hasFullFP16()) {
1045 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
1046 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1047 }
1048 }
1049
1050 if (!Subtarget->hasFP16()) {
1051 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
1052 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1053 }
1054
1055 computeRegisterProperties(Subtarget->getRegisterInfo());
1056
1057 // ARM does not have floating-point extending loads.
1058 for (MVT VT : MVT::fp_valuetypes()) {
1059 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1060 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1061 }
1062
1063 // ... or truncating stores
1064 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1065 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1066 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1067
1068 // ARM does not have i1 sign extending load.
1069 for (MVT VT : MVT::integer_valuetypes())
1070 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1071
1072 // ARM supports all 4 flavors of integer indexed load / store.
1073 if (!Subtarget->isThumb1Only()) {
1074 for (unsigned im = (unsigned)ISD::PRE_INC;
1075 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1076 setIndexedLoadAction(im, MVT::i1, Legal);
1077 setIndexedLoadAction(im, MVT::i8, Legal);
1078 setIndexedLoadAction(im, MVT::i16, Legal);
1079 setIndexedLoadAction(im, MVT::i32, Legal);
1080 setIndexedStoreAction(im, MVT::i1, Legal);
1081 setIndexedStoreAction(im, MVT::i8, Legal);
1082 setIndexedStoreAction(im, MVT::i16, Legal);
1083 setIndexedStoreAction(im, MVT::i32, Legal);
1084 }
1085 } else {
1086 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1087 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1088 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1089 }
1090
1091 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1092 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1093 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1094 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1095
1096 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1097 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1098 if (Subtarget->hasDSP()) {
1099 setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1100 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1101 setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1102 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1103 }
1104 if (Subtarget->hasBaseDSP()) {
1105 setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1106 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1107 }
1108
1109 // i64 operation support.
1110 setOperationAction(ISD::MUL, MVT::i64, Expand);
1111 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1112 if (Subtarget->isThumb1Only()) {
1113 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1114 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1115 }
1116 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1117 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1118 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1119
1120 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1121 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1122 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1123 setOperationAction(ISD::SRL, MVT::i64, Custom);
1124 setOperationAction(ISD::SRA, MVT::i64, Custom);
1125 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1127 setOperationAction(ISD::LOAD, MVT::i64, Custom);
1128 setOperationAction(ISD::STORE, MVT::i64, Custom);
1129
1130 // MVE lowers 64 bit shifts to lsll and lsrl
1131 // assuming that ISD::SRL and SRA of i64 are already marked custom
1132 if (Subtarget->hasMVEIntegerOps())
1133 setOperationAction(ISD::SHL, MVT::i64, Custom);
1134
1135 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1136 if (Subtarget->isThumb1Only()) {
1137 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1138 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1139 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1140 }
1141
1142 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1143 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1144
1145 // ARM does not have ROTL.
1146 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1147 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1148 setOperationAction(ISD::ROTL, VT, Expand);
1149 setOperationAction(ISD::ROTR, VT, Expand);
1150 }
1151 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1152 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1153 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1154 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1155 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1156 }
1157
1158 // @llvm.readcyclecounter requires the Performance Monitors extension.
1159 // Default to the 0 expansion on unsupported platforms.
1160 // FIXME: Technically there are older ARM CPUs that have
1161 // implementation-specific ways of obtaining this information.
1162 if (Subtarget->hasPerfMon())
1163 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1164
1165 // Only ARMv6 has BSWAP.
1166 if (!Subtarget->hasV6Ops())
1167 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1168
1169 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1170 : Subtarget->hasDivideInARMMode();
1171 if (!hasDivide) {
1172 // These are expanded into libcalls if the cpu doesn't have HW divider.
1173 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1174 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1175 }
1176
1177 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1178 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1179 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1180
1181 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1182 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1183 }
1184
1185 setOperationAction(ISD::SREM, MVT::i32, Expand);
1186 setOperationAction(ISD::UREM, MVT::i32, Expand);
1187
1188 // Register based DivRem for AEABI (RTABI 4.2)
1189 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1190 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1191 Subtarget->isTargetWindows()) {
1192 setOperationAction(ISD::SREM, MVT::i64, Custom);
1193 setOperationAction(ISD::UREM, MVT::i64, Custom);
1194 HasStandaloneRem = false;
1195
1196 if (Subtarget->isTargetWindows()) {
1197 const struct {
1198 const RTLIB::Libcall Op;
1199 const char * const Name;
1200 const CallingConv::ID CC;
1201 } LibraryCalls[] = {
1202 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1203 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1204 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1205 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1206
1207 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1208 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1209 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1210 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1211 };
1212
1213 for (const auto &LC : LibraryCalls) {
1214 setLibcallName(LC.Op, LC.Name);
1215 setLibcallCallingConv(LC.Op, LC.CC);
1216 }
1217 } else {
1218 const struct {
1219 const RTLIB::Libcall Op;
1220 const char * const Name;
1221 const CallingConv::ID CC;
1222 } LibraryCalls[] = {
1223 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1224 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1225 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1226 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1227
1228 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1229 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1230 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1231 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1232 };
1233
1234 for (const auto &LC : LibraryCalls) {
1235 setLibcallName(LC.Op, LC.Name);
1236 setLibcallCallingConv(LC.Op, LC.CC);
1237 }
1238 }
1239
1240 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1241 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1242 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1243 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1244 } else {
1245 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1246 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1247 }
1248
1249 if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1250 // MSVCRT doesn't have powi; fall back to pow
1251 setLibcallName(RTLIB::POWI_F32, nullptr);
1252 setLibcallName(RTLIB::POWI_F64, nullptr);
1253 }
1254
1255 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1256 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1257 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1258 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1259
1260 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1261 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1262
1263 // Use the default implementation.
1264 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1265 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1266 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1267 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1268 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1269 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1270
1271 if (Subtarget->isTargetWindows())
1272 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1273 else
1274 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1275
1276 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1277 // the default expansion.
1278 InsertFencesForAtomic = false;
1279 if (Subtarget->hasAnyDataBarrier() &&
1280 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1281 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1282 // to ldrex/strex loops already.
1283 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1284 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1285 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1286
1287 // On v8, we have particularly efficient implementations of atomic fences
1288 // if they can be combined with nearby atomic loads and stores.
1289 if (!Subtarget->hasAcquireRelease() ||
1290 getTargetMachine().getOptLevel() == 0) {
1291 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1292 InsertFencesForAtomic = true;
1293 }
1294 } else {
1295 // If there's anything we can use as a barrier, go through custom lowering
1296 // for ATOMIC_FENCE.
1297 // If target has DMB in thumb, Fences can be inserted.
1298 if (Subtarget->hasDataBarrier())
1299 InsertFencesForAtomic = true;
1300
1301 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1302 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1303
1304 // Set them all for expansion, which will force libcalls.
1305 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1306 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1307 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1308 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1309 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1310 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1311 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1312 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1313 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1314 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1315 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1316 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1317 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1318 // Unordered/Monotonic case.
1319 if (!InsertFencesForAtomic) {
1320 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1321 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1322 }
1323 }
1324
1325 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1326
1327 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1328 if (!Subtarget->hasV6Ops()) {
1329 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1330 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1331 }
1332 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1333
1334 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1335 !Subtarget->isThumb1Only()) {
1336 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1337 // iff target supports vfp2.
1338 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1339 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1340 }
1341
1342 // We want to custom lower some of our intrinsics.
1343 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1344 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1345 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1346 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1347 if (Subtarget->useSjLjEH())
1348 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1349
1350 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1351 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1352 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1353 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1354 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1355 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1356 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1357 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1358 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1359 if (Subtarget->hasFullFP16()) {
1360 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1361 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1362 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1363 }
1364
1365 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1366
1367 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1368 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1369 if (Subtarget->hasFullFP16())
1370 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1371 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1372 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1373 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1374
1375 // We don't support sin/cos/fmod/copysign/pow
1376 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1377 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1378 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1379 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1380 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1381 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1382 setOperationAction(ISD::FREM, MVT::f64, Expand);
1383 setOperationAction(ISD::FREM, MVT::f32, Expand);
1384 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1385 !Subtarget->isThumb1Only()) {
1386 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1387 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1388 }
1389 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1390 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1391
1392 if (!Subtarget->hasVFP4Base()) {
1393 setOperationAction(ISD::FMA, MVT::f64, Expand);
1394 setOperationAction(ISD::FMA, MVT::f32, Expand);
1395 }
1396
1397 // Various VFP goodness
1398 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1399 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1400 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1401 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1402 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1403 }
1404
1405 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1406 if (!Subtarget->hasFP16()) {
1407 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1408 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1409 }
1410
1411 // Strict floating-point comparisons need custom lowering.
1412 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
1413 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1414 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
1415 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1416 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
1417 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1418 }
1419
1420 // Use __sincos_stret if available.
1421 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1422 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1423 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1424 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1425 }
1426
1427 // FP-ARMv8 implements a lot of rounding-like FP operations.
1428 if (Subtarget->hasFPARMv8Base()) {
1429 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1430 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1431 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1432 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1433 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1434 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1435 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1436 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1437 if (Subtarget->hasNEON()) {
1438 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1439 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1440 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1441 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1442 }
1443
1444 if (Subtarget->hasFP64()) {
1445 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1446 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1447 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1448 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1449 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1450 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1451 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1452 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1453 }
1454 }
1455
1456 // FP16 often need to be promoted to call lib functions
1457 if (Subtarget->hasFullFP16()) {
1458 setOperationAction(ISD::FREM, MVT::f16, Promote);
1459 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1460 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1461 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1462 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1463 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1464 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1465 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1466 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1467 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1468 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1469 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1470
1471 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1472 }
1473
1474 if (Subtarget->hasNEON()) {
1475 // vmin and vmax aren't available in a scalar form, so we can use
1476 // a NEON instruction with an undef lane instead. This has a performance
1477 // penalty on some cores, so we don't do this unless we have been
1478 // asked to by the core tuning model.
1479 if (Subtarget->useNEONForSinglePrecisionFP()) {
1480 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1481 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1482 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1483 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1484 }
1485 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1486 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1487 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1488 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1489
1490 if (Subtarget->hasFullFP16()) {
1491 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1492 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1493 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1494 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1495
1496 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1497 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1498 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1499 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1500 }
1501 }
1502
1503 // We have target-specific dag combine patterns for the following nodes:
1504 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1505 setTargetDAGCombine(ISD::ADD);
1506 setTargetDAGCombine(ISD::SUB);
1507 setTargetDAGCombine(ISD::MUL);
1508 setTargetDAGCombine(ISD::AND);
1509 setTargetDAGCombine(ISD::OR);
1510 setTargetDAGCombine(ISD::XOR);
1511
1512 if (Subtarget->hasMVEIntegerOps())
1513 setTargetDAGCombine(ISD::VSELECT);
1514
1515 if (Subtarget->hasV6Ops())
1516 setTargetDAGCombine(ISD::SRL);
1517 if (Subtarget->isThumb1Only())
1518 setTargetDAGCombine(ISD::SHL);
1519
1520 setStackPointerRegisterToSaveRestore(ARM::SP);
1521
1522 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1523 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1524 setSchedulingPreference(Sched::RegPressure);
1525 else
1526 setSchedulingPreference(Sched::Hybrid);
1527
1528 //// temporary - rewrite interface to use type
1529 MaxStoresPerMemset = 8;
1530 MaxStoresPerMemsetOptSize = 4;
1531 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1532 MaxStoresPerMemcpyOptSize = 2;
1533 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1534 MaxStoresPerMemmoveOptSize = 2;
1535
1536 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1537 // are at least 4 bytes aligned.
1538 setMinStackArgumentAlignment(Align(4));
1539
1540 // Prefer likely predicted branches to selects on out-of-order cores.
1541 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1542
1543 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1544
1545 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1546
1547 if (Subtarget->isThumb() || Subtarget->isThumb2())
1548 setTargetDAGCombine(ISD::ABS);
1549 }
1550
useSoftFloat() const1551 bool ARMTargetLowering::useSoftFloat() const {
1552 return Subtarget->useSoftFloat();
1553 }
1554
1555 // FIXME: It might make sense to define the representative register class as the
1556 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1557 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1558 // SPR's representative would be DPR_VFP2. This should work well if register
1559 // pressure tracking were modified such that a register use would increment the
1560 // pressure of the register class's representative and all of it's super
1561 // classes' representatives transitively. We have not implemented this because
1562 // of the difficulty prior to coalescing of modeling operand register classes
1563 // due to the common occurrence of cross class copies and subregister insertions
1564 // and extractions.
1565 std::pair<const TargetRegisterClass *, uint8_t>
findRepresentativeClass(const TargetRegisterInfo * TRI,MVT VT) const1566 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1567 MVT VT) const {
1568 const TargetRegisterClass *RRC = nullptr;
1569 uint8_t Cost = 1;
1570 switch (VT.SimpleTy) {
1571 default:
1572 return TargetLowering::findRepresentativeClass(TRI, VT);
1573 // Use DPR as representative register class for all floating point
1574 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1575 // the cost is 1 for both f32 and f64.
1576 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1577 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1578 RRC = &ARM::DPRRegClass;
1579 // When NEON is used for SP, only half of the register file is available
1580 // because operations that define both SP and DP results will be constrained
1581 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1582 // coalescing by double-counting the SP regs. See the FIXME above.
1583 if (Subtarget->useNEONForSinglePrecisionFP())
1584 Cost = 2;
1585 break;
1586 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1587 case MVT::v4f32: case MVT::v2f64:
1588 RRC = &ARM::DPRRegClass;
1589 Cost = 2;
1590 break;
1591 case MVT::v4i64:
1592 RRC = &ARM::DPRRegClass;
1593 Cost = 4;
1594 break;
1595 case MVT::v8i64:
1596 RRC = &ARM::DPRRegClass;
1597 Cost = 8;
1598 break;
1599 }
1600 return std::make_pair(RRC, Cost);
1601 }
1602
getTargetNodeName(unsigned Opcode) const1603 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1604 switch ((ARMISD::NodeType)Opcode) {
1605 case ARMISD::FIRST_NUMBER: break;
1606 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1607 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1608 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1609 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1610 case ARMISD::CALL: return "ARMISD::CALL";
1611 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1612 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1613 case ARMISD::tSECALL: return "ARMISD::tSECALL";
1614 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1615 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1616 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1617 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1618 case ARMISD::SERET_FLAG: return "ARMISD::SERET_FLAG";
1619 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1620 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1621 case ARMISD::CMP: return "ARMISD::CMP";
1622 case ARMISD::CMN: return "ARMISD::CMN";
1623 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1624 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1625 case ARMISD::CMPFPE: return "ARMISD::CMPFPE";
1626 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1627 case ARMISD::CMPFPEw0: return "ARMISD::CMPFPEw0";
1628 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1629 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1630
1631 case ARMISD::CMOV: return "ARMISD::CMOV";
1632 case ARMISD::SUBS: return "ARMISD::SUBS";
1633
1634 case ARMISD::SSAT: return "ARMISD::SSAT";
1635 case ARMISD::USAT: return "ARMISD::USAT";
1636
1637 case ARMISD::ASRL: return "ARMISD::ASRL";
1638 case ARMISD::LSRL: return "ARMISD::LSRL";
1639 case ARMISD::LSLL: return "ARMISD::LSLL";
1640
1641 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1642 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1643 case ARMISD::RRX: return "ARMISD::RRX";
1644
1645 case ARMISD::ADDC: return "ARMISD::ADDC";
1646 case ARMISD::ADDE: return "ARMISD::ADDE";
1647 case ARMISD::SUBC: return "ARMISD::SUBC";
1648 case ARMISD::SUBE: return "ARMISD::SUBE";
1649 case ARMISD::LSLS: return "ARMISD::LSLS";
1650
1651 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1652 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1653 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1654 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1655 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1656
1657 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1658 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1659 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1660
1661 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1662
1663 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1664
1665 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1666
1667 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1668
1669 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1670
1671 case ARMISD::LDRD: return "ARMISD::LDRD";
1672 case ARMISD::STRD: return "ARMISD::STRD";
1673
1674 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1675 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1676
1677 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1678 case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST";
1679 case ARMISD::VCMP: return "ARMISD::VCMP";
1680 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1681 case ARMISD::VTST: return "ARMISD::VTST";
1682
1683 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1684 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1685 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1686 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1687 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1688 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1689 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1690 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1691 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1692 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1693 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1694 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1695 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1696 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1697 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1698 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1699 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1700 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1701 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1702 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1703 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1704 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1705 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1706 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1707 case ARMISD::VDUP: return "ARMISD::VDUP";
1708 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1709 case ARMISD::VEXT: return "ARMISD::VEXT";
1710 case ARMISD::VREV64: return "ARMISD::VREV64";
1711 case ARMISD::VREV32: return "ARMISD::VREV32";
1712 case ARMISD::VREV16: return "ARMISD::VREV16";
1713 case ARMISD::VZIP: return "ARMISD::VZIP";
1714 case ARMISD::VUZP: return "ARMISD::VUZP";
1715 case ARMISD::VTRN: return "ARMISD::VTRN";
1716 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1717 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1718 case ARMISD::VMOVN: return "ARMISD::VMOVN";
1719 case ARMISD::VQMOVNs: return "ARMISD::VQMOVNs";
1720 case ARMISD::VQMOVNu: return "ARMISD::VQMOVNu";
1721 case ARMISD::VCVTN: return "ARMISD::VCVTN";
1722 case ARMISD::VCVTL: return "ARMISD::VCVTL";
1723 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1724 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1725 case ARMISD::VQDMULH: return "ARMISD::VQDMULH";
1726 case ARMISD::VADDVs: return "ARMISD::VADDVs";
1727 case ARMISD::VADDVu: return "ARMISD::VADDVu";
1728 case ARMISD::VADDVps: return "ARMISD::VADDVps";
1729 case ARMISD::VADDVpu: return "ARMISD::VADDVpu";
1730 case ARMISD::VADDLVs: return "ARMISD::VADDLVs";
1731 case ARMISD::VADDLVu: return "ARMISD::VADDLVu";
1732 case ARMISD::VADDLVAs: return "ARMISD::VADDLVAs";
1733 case ARMISD::VADDLVAu: return "ARMISD::VADDLVAu";
1734 case ARMISD::VADDLVps: return "ARMISD::VADDLVps";
1735 case ARMISD::VADDLVpu: return "ARMISD::VADDLVpu";
1736 case ARMISD::VADDLVAps: return "ARMISD::VADDLVAps";
1737 case ARMISD::VADDLVApu: return "ARMISD::VADDLVApu";
1738 case ARMISD::VMLAVs: return "ARMISD::VMLAVs";
1739 case ARMISD::VMLAVu: return "ARMISD::VMLAVu";
1740 case ARMISD::VMLAVps: return "ARMISD::VMLAVps";
1741 case ARMISD::VMLAVpu: return "ARMISD::VMLAVpu";
1742 case ARMISD::VMLALVs: return "ARMISD::VMLALVs";
1743 case ARMISD::VMLALVu: return "ARMISD::VMLALVu";
1744 case ARMISD::VMLALVps: return "ARMISD::VMLALVps";
1745 case ARMISD::VMLALVpu: return "ARMISD::VMLALVpu";
1746 case ARMISD::VMLALVAs: return "ARMISD::VMLALVAs";
1747 case ARMISD::VMLALVAu: return "ARMISD::VMLALVAu";
1748 case ARMISD::VMLALVAps: return "ARMISD::VMLALVAps";
1749 case ARMISD::VMLALVApu: return "ARMISD::VMLALVApu";
1750 case ARMISD::VMINVu: return "ARMISD::VMINVu";
1751 case ARMISD::VMINVs: return "ARMISD::VMINVs";
1752 case ARMISD::VMAXVu: return "ARMISD::VMAXVu";
1753 case ARMISD::VMAXVs: return "ARMISD::VMAXVs";
1754 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1755 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1756 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1757 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1758 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1759 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1760 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1761 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1762 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1763 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1764 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1765 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1766 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1767 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1768 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1769 case ARMISD::QADD16b: return "ARMISD::QADD16b";
1770 case ARMISD::QSUB16b: return "ARMISD::QSUB16b";
1771 case ARMISD::QADD8b: return "ARMISD::QADD8b";
1772 case ARMISD::QSUB8b: return "ARMISD::QSUB8b";
1773 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1774 case ARMISD::BFI: return "ARMISD::BFI";
1775 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1776 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1777 case ARMISD::VBSP: return "ARMISD::VBSP";
1778 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1779 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1780 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1781 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1782 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1783 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1784 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1785 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1786 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1787 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1788 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1789 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1790 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1791 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1792 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1793 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1794 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1795 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1796 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1797 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1798 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1799 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1800 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1801 case ARMISD::WLS: return "ARMISD::WLS";
1802 case ARMISD::LE: return "ARMISD::LE";
1803 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1804 case ARMISD::CSINV: return "ARMISD::CSINV";
1805 case ARMISD::CSNEG: return "ARMISD::CSNEG";
1806 case ARMISD::CSINC: return "ARMISD::CSINC";
1807 }
1808 return nullptr;
1809 }
1810
getSetCCResultType(const DataLayout & DL,LLVMContext &,EVT VT) const1811 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1812 EVT VT) const {
1813 if (!VT.isVector())
1814 return getPointerTy(DL);
1815
1816 // MVE has a predicate register.
1817 if (Subtarget->hasMVEIntegerOps() &&
1818 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1819 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1820 return VT.changeVectorElementTypeToInteger();
1821 }
1822
1823 /// getRegClassFor - Return the register class that should be used for the
1824 /// specified value type.
1825 const TargetRegisterClass *
getRegClassFor(MVT VT,bool isDivergent) const1826 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1827 (void)isDivergent;
1828 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1829 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1830 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1831 // MVE Q registers.
1832 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1833 if (VT == MVT::v4i64)
1834 return &ARM::QQPRRegClass;
1835 if (VT == MVT::v8i64)
1836 return &ARM::QQQQPRRegClass;
1837 }
1838 return TargetLowering::getRegClassFor(VT);
1839 }
1840
1841 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1842 // source/dest is aligned and the copy size is large enough. We therefore want
1843 // to align such objects passed to memory intrinsics.
shouldAlignPointerArgs(CallInst * CI,unsigned & MinSize,unsigned & PrefAlign) const1844 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1845 unsigned &PrefAlign) const {
1846 if (!isa<MemIntrinsic>(CI))
1847 return false;
1848 MinSize = 8;
1849 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1850 // cycle faster than 4-byte aligned LDM.
1851 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1852 return true;
1853 }
1854
1855 // Create a fast isel object.
1856 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const1857 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1858 const TargetLibraryInfo *libInfo) const {
1859 return ARM::createFastISel(funcInfo, libInfo);
1860 }
1861
getSchedulingPreference(SDNode * N) const1862 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1863 unsigned NumVals = N->getNumValues();
1864 if (!NumVals)
1865 return Sched::RegPressure;
1866
1867 for (unsigned i = 0; i != NumVals; ++i) {
1868 EVT VT = N->getValueType(i);
1869 if (VT == MVT::Glue || VT == MVT::Other)
1870 continue;
1871 if (VT.isFloatingPoint() || VT.isVector())
1872 return Sched::ILP;
1873 }
1874
1875 if (!N->isMachineOpcode())
1876 return Sched::RegPressure;
1877
1878 // Load are scheduled for latency even if there instruction itinerary
1879 // is not available.
1880 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1881 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1882
1883 if (MCID.getNumDefs() == 0)
1884 return Sched::RegPressure;
1885 if (!Itins->isEmpty() &&
1886 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1887 return Sched::ILP;
1888
1889 return Sched::RegPressure;
1890 }
1891
1892 //===----------------------------------------------------------------------===//
1893 // Lowering Code
1894 //===----------------------------------------------------------------------===//
1895
isSRL16(const SDValue & Op)1896 static bool isSRL16(const SDValue &Op) {
1897 if (Op.getOpcode() != ISD::SRL)
1898 return false;
1899 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1900 return Const->getZExtValue() == 16;
1901 return false;
1902 }
1903
isSRA16(const SDValue & Op)1904 static bool isSRA16(const SDValue &Op) {
1905 if (Op.getOpcode() != ISD::SRA)
1906 return false;
1907 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1908 return Const->getZExtValue() == 16;
1909 return false;
1910 }
1911
isSHL16(const SDValue & Op)1912 static bool isSHL16(const SDValue &Op) {
1913 if (Op.getOpcode() != ISD::SHL)
1914 return false;
1915 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1916 return Const->getZExtValue() == 16;
1917 return false;
1918 }
1919
1920 // Check for a signed 16-bit value. We special case SRA because it makes it
1921 // more simple when also looking for SRAs that aren't sign extending a
1922 // smaller value. Without the check, we'd need to take extra care with
1923 // checking order for some operations.
isS16(const SDValue & Op,SelectionDAG & DAG)1924 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1925 if (isSRA16(Op))
1926 return isSHL16(Op.getOperand(0));
1927 return DAG.ComputeNumSignBits(Op) == 17;
1928 }
1929
1930 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
IntCCToARMCC(ISD::CondCode CC)1931 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1932 switch (CC) {
1933 default: llvm_unreachable("Unknown condition code!");
1934 case ISD::SETNE: return ARMCC::NE;
1935 case ISD::SETEQ: return ARMCC::EQ;
1936 case ISD::SETGT: return ARMCC::GT;
1937 case ISD::SETGE: return ARMCC::GE;
1938 case ISD::SETLT: return ARMCC::LT;
1939 case ISD::SETLE: return ARMCC::LE;
1940 case ISD::SETUGT: return ARMCC::HI;
1941 case ISD::SETUGE: return ARMCC::HS;
1942 case ISD::SETULT: return ARMCC::LO;
1943 case ISD::SETULE: return ARMCC::LS;
1944 }
1945 }
1946
1947 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
FPCCToARMCC(ISD::CondCode CC,ARMCC::CondCodes & CondCode,ARMCC::CondCodes & CondCode2)1948 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1949 ARMCC::CondCodes &CondCode2) {
1950 CondCode2 = ARMCC::AL;
1951 switch (CC) {
1952 default: llvm_unreachable("Unknown FP condition!");
1953 case ISD::SETEQ:
1954 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1955 case ISD::SETGT:
1956 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1957 case ISD::SETGE:
1958 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1959 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1960 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1961 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1962 case ISD::SETO: CondCode = ARMCC::VC; break;
1963 case ISD::SETUO: CondCode = ARMCC::VS; break;
1964 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1965 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1966 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1967 case ISD::SETLT:
1968 case ISD::SETULT: CondCode = ARMCC::LT; break;
1969 case ISD::SETLE:
1970 case ISD::SETULE: CondCode = ARMCC::LE; break;
1971 case ISD::SETNE:
1972 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1973 }
1974 }
1975
1976 //===----------------------------------------------------------------------===//
1977 // Calling Convention Implementation
1978 //===----------------------------------------------------------------------===//
1979
1980 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1981 /// account presence of floating point hardware and calling convention
1982 /// limitations, such as support for variadic functions.
1983 CallingConv::ID
getEffectiveCallingConv(CallingConv::ID CC,bool isVarArg) const1984 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1985 bool isVarArg) const {
1986 switch (CC) {
1987 default:
1988 report_fatal_error("Unsupported calling convention");
1989 case CallingConv::ARM_AAPCS:
1990 case CallingConv::ARM_APCS:
1991 case CallingConv::GHC:
1992 case CallingConv::CFGuard_Check:
1993 return CC;
1994 case CallingConv::PreserveMost:
1995 return CallingConv::PreserveMost;
1996 case CallingConv::ARM_AAPCS_VFP:
1997 case CallingConv::Swift:
1998 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1999 case CallingConv::C:
2000 if (!Subtarget->isAAPCS_ABI())
2001 return CallingConv::ARM_APCS;
2002 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
2003 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
2004 !isVarArg)
2005 return CallingConv::ARM_AAPCS_VFP;
2006 else
2007 return CallingConv::ARM_AAPCS;
2008 case CallingConv::Fast:
2009 case CallingConv::CXX_FAST_TLS:
2010 if (!Subtarget->isAAPCS_ABI()) {
2011 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
2012 return CallingConv::Fast;
2013 return CallingConv::ARM_APCS;
2014 } else if (Subtarget->hasVFP2Base() &&
2015 !Subtarget->isThumb1Only() && !isVarArg)
2016 return CallingConv::ARM_AAPCS_VFP;
2017 else
2018 return CallingConv::ARM_AAPCS;
2019 }
2020 }
2021
CCAssignFnForCall(CallingConv::ID CC,bool isVarArg) const2022 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2023 bool isVarArg) const {
2024 return CCAssignFnForNode(CC, false, isVarArg);
2025 }
2026
CCAssignFnForReturn(CallingConv::ID CC,bool isVarArg) const2027 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
2028 bool isVarArg) const {
2029 return CCAssignFnForNode(CC, true, isVarArg);
2030 }
2031
2032 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
2033 /// CallingConvention.
CCAssignFnForNode(CallingConv::ID CC,bool Return,bool isVarArg) const2034 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
2035 bool Return,
2036 bool isVarArg) const {
2037 switch (getEffectiveCallingConv(CC, isVarArg)) {
2038 default:
2039 report_fatal_error("Unsupported calling convention");
2040 case CallingConv::ARM_APCS:
2041 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
2042 case CallingConv::ARM_AAPCS:
2043 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2044 case CallingConv::ARM_AAPCS_VFP:
2045 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
2046 case CallingConv::Fast:
2047 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
2048 case CallingConv::GHC:
2049 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
2050 case CallingConv::PreserveMost:
2051 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2052 case CallingConv::CFGuard_Check:
2053 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
2054 }
2055 }
2056
MoveToHPR(const SDLoc & dl,SelectionDAG & DAG,MVT LocVT,MVT ValVT,SDValue Val) const2057 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
2058 MVT LocVT, MVT ValVT, SDValue Val) const {
2059 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
2060 Val);
2061 if (Subtarget->hasFullFP16()) {
2062 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
2063 } else {
2064 Val = DAG.getNode(ISD::TRUNCATE, dl,
2065 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2066 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
2067 }
2068 return Val;
2069 }
2070
MoveFromHPR(const SDLoc & dl,SelectionDAG & DAG,MVT LocVT,MVT ValVT,SDValue Val) const2071 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
2072 MVT LocVT, MVT ValVT,
2073 SDValue Val) const {
2074 if (Subtarget->hasFullFP16()) {
2075 Val = DAG.getNode(ARMISD::VMOVrh, dl,
2076 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2077 } else {
2078 Val = DAG.getNode(ISD::BITCAST, dl,
2079 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2080 Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
2081 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2082 }
2083 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
2084 }
2085
2086 /// LowerCallResult - Lower the result values of a call into the
2087 /// appropriate copies out of appropriate physical registers.
LowerCallResult(SDValue Chain,SDValue InFlag,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,bool isThisReturn,SDValue ThisVal) const2088 SDValue ARMTargetLowering::LowerCallResult(
2089 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2090 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2091 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2092 SDValue ThisVal) const {
2093 // Assign locations to each value returned by this call.
2094 SmallVector<CCValAssign, 16> RVLocs;
2095 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2096 *DAG.getContext());
2097 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2098
2099 // Copy all of the result registers out of their specified physreg.
2100 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2101 CCValAssign VA = RVLocs[i];
2102
2103 // Pass 'this' value directly from the argument to return value, to avoid
2104 // reg unit interference
2105 if (i == 0 && isThisReturn) {
2106 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
2107 "unexpected return calling convention register assignment");
2108 InVals.push_back(ThisVal);
2109 continue;
2110 }
2111
2112 SDValue Val;
2113 if (VA.needsCustom() &&
2114 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
2115 // Handle f64 or half of a v2f64.
2116 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2117 InFlag);
2118 Chain = Lo.getValue(1);
2119 InFlag = Lo.getValue(2);
2120 VA = RVLocs[++i]; // skip ahead to next loc
2121 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2122 InFlag);
2123 Chain = Hi.getValue(1);
2124 InFlag = Hi.getValue(2);
2125 if (!Subtarget->isLittle())
2126 std::swap (Lo, Hi);
2127 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2128
2129 if (VA.getLocVT() == MVT::v2f64) {
2130 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2131 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2132 DAG.getConstant(0, dl, MVT::i32));
2133
2134 VA = RVLocs[++i]; // skip ahead to next loc
2135 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2136 Chain = Lo.getValue(1);
2137 InFlag = Lo.getValue(2);
2138 VA = RVLocs[++i]; // skip ahead to next loc
2139 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2140 Chain = Hi.getValue(1);
2141 InFlag = Hi.getValue(2);
2142 if (!Subtarget->isLittle())
2143 std::swap (Lo, Hi);
2144 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2145 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2146 DAG.getConstant(1, dl, MVT::i32));
2147 }
2148 } else {
2149 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2150 InFlag);
2151 Chain = Val.getValue(1);
2152 InFlag = Val.getValue(2);
2153 }
2154
2155 switch (VA.getLocInfo()) {
2156 default: llvm_unreachable("Unknown loc info!");
2157 case CCValAssign::Full: break;
2158 case CCValAssign::BCvt:
2159 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2160 break;
2161 }
2162
2163 // f16 arguments have their size extended to 4 bytes and passed as if they
2164 // had been copied to the LSBs of a 32-bit register.
2165 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2166 if (VA.needsCustom() &&
2167 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
2168 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
2169
2170 InVals.push_back(Val);
2171 }
2172
2173 return Chain;
2174 }
2175
2176 /// LowerMemOpCallTo - Store the argument to the stack.
LowerMemOpCallTo(SDValue Chain,SDValue StackPtr,SDValue Arg,const SDLoc & dl,SelectionDAG & DAG,const CCValAssign & VA,ISD::ArgFlagsTy Flags) const2177 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2178 SDValue Arg, const SDLoc &dl,
2179 SelectionDAG &DAG,
2180 const CCValAssign &VA,
2181 ISD::ArgFlagsTy Flags) const {
2182 unsigned LocMemOffset = VA.getLocMemOffset();
2183 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2184 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2185 StackPtr, PtrOff);
2186 return DAG.getStore(
2187 Chain, dl, Arg, PtrOff,
2188 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2189 }
2190
PassF64ArgInRegs(const SDLoc & dl,SelectionDAG & DAG,SDValue Chain,SDValue & Arg,RegsToPassVector & RegsToPass,CCValAssign & VA,CCValAssign & NextVA,SDValue & StackPtr,SmallVectorImpl<SDValue> & MemOpChains,ISD::ArgFlagsTy Flags) const2191 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2192 SDValue Chain, SDValue &Arg,
2193 RegsToPassVector &RegsToPass,
2194 CCValAssign &VA, CCValAssign &NextVA,
2195 SDValue &StackPtr,
2196 SmallVectorImpl<SDValue> &MemOpChains,
2197 ISD::ArgFlagsTy Flags) const {
2198 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2199 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2200 unsigned id = Subtarget->isLittle() ? 0 : 1;
2201 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2202
2203 if (NextVA.isRegLoc())
2204 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2205 else {
2206 assert(NextVA.isMemLoc());
2207 if (!StackPtr.getNode())
2208 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2209 getPointerTy(DAG.getDataLayout()));
2210
2211 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2212 dl, DAG, NextVA,
2213 Flags));
2214 }
2215 }
2216
2217 /// LowerCall - Lowering a call into a callseq_start <-
2218 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2219 /// nodes.
2220 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const2221 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2222 SmallVectorImpl<SDValue> &InVals) const {
2223 SelectionDAG &DAG = CLI.DAG;
2224 SDLoc &dl = CLI.DL;
2225 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2226 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2227 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2228 SDValue Chain = CLI.Chain;
2229 SDValue Callee = CLI.Callee;
2230 bool &isTailCall = CLI.IsTailCall;
2231 CallingConv::ID CallConv = CLI.CallConv;
2232 bool doesNotRet = CLI.DoesNotReturn;
2233 bool isVarArg = CLI.IsVarArg;
2234
2235 MachineFunction &MF = DAG.getMachineFunction();
2236 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2237 MachineFunction::CallSiteInfo CSInfo;
2238 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2239 bool isThisReturn = false;
2240 bool isCmseNSCall = false;
2241 bool PreferIndirect = false;
2242
2243 // Determine whether this is a non-secure function call.
2244 if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call"))
2245 isCmseNSCall = true;
2246
2247 // Disable tail calls if they're not supported.
2248 if (!Subtarget->supportsTailCall())
2249 isTailCall = false;
2250
2251 // For both the non-secure calls and the returns from a CMSE entry function,
2252 // the function needs to do some extra work afte r the call, or before the
2253 // return, respectively, thus it cannot end with atail call
2254 if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2255 isTailCall = false;
2256
2257 if (isa<GlobalAddressSDNode>(Callee)) {
2258 // If we're optimizing for minimum size and the function is called three or
2259 // more times in this block, we can improve codesize by calling indirectly
2260 // as BLXr has a 16-bit encoding.
2261 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2262 if (CLI.CB) {
2263 auto *BB = CLI.CB->getParent();
2264 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2265 count_if(GV->users(), [&BB](const User *U) {
2266 return isa<Instruction>(U) &&
2267 cast<Instruction>(U)->getParent() == BB;
2268 }) > 2;
2269 }
2270 }
2271 if (isTailCall) {
2272 // Check if it's really possible to do a tail call.
2273 isTailCall = IsEligibleForTailCallOptimization(
2274 Callee, CallConv, isVarArg, isStructRet,
2275 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2276 PreferIndirect);
2277 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2278 report_fatal_error("failed to perform tail call elimination on a call "
2279 "site marked musttail");
2280 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2281 // detected sibcalls.
2282 if (isTailCall)
2283 ++NumTailCalls;
2284 }
2285
2286 // Analyze operands of the call, assigning locations to each operand.
2287 SmallVector<CCValAssign, 16> ArgLocs;
2288 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2289 *DAG.getContext());
2290 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2291
2292 // Get a count of how many bytes are to be pushed on the stack.
2293 unsigned NumBytes = CCInfo.getNextStackOffset();
2294
2295 if (isTailCall) {
2296 // For tail calls, memory operands are available in our caller's stack.
2297 NumBytes = 0;
2298 } else {
2299 // Adjust the stack pointer for the new arguments...
2300 // These operations are automatically eliminated by the prolog/epilog pass
2301 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2302 }
2303
2304 SDValue StackPtr =
2305 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2306
2307 RegsToPassVector RegsToPass;
2308 SmallVector<SDValue, 8> MemOpChains;
2309
2310 // Walk the register/memloc assignments, inserting copies/loads. In the case
2311 // of tail call optimization, arguments are handled later.
2312 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2313 i != e;
2314 ++i, ++realArgIdx) {
2315 CCValAssign &VA = ArgLocs[i];
2316 SDValue Arg = OutVals[realArgIdx];
2317 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2318 bool isByVal = Flags.isByVal();
2319
2320 // Promote the value if needed.
2321 switch (VA.getLocInfo()) {
2322 default: llvm_unreachable("Unknown loc info!");
2323 case CCValAssign::Full: break;
2324 case CCValAssign::SExt:
2325 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2326 break;
2327 case CCValAssign::ZExt:
2328 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2329 break;
2330 case CCValAssign::AExt:
2331 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2332 break;
2333 case CCValAssign::BCvt:
2334 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2335 break;
2336 }
2337
2338 // f16 arguments have their size extended to 4 bytes and passed as if they
2339 // had been copied to the LSBs of a 32-bit register.
2340 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2341 if (VA.needsCustom() &&
2342 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2343 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2344 } else {
2345 // f16 arguments could have been extended prior to argument lowering.
2346 // Mask them arguments if this is a CMSE nonsecure call.
2347 auto ArgVT = Outs[realArgIdx].ArgVT;
2348 if (isCmseNSCall && (ArgVT == MVT::f16)) {
2349 auto LocBits = VA.getLocVT().getSizeInBits();
2350 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2351 SDValue Mask =
2352 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2353 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2354 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2355 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2356 }
2357 }
2358
2359 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2360 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2361 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2362 DAG.getConstant(0, dl, MVT::i32));
2363 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2364 DAG.getConstant(1, dl, MVT::i32));
2365
2366 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2367 StackPtr, MemOpChains, Flags);
2368
2369 VA = ArgLocs[++i]; // skip ahead to next loc
2370 if (VA.isRegLoc()) {
2371 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2372 StackPtr, MemOpChains, Flags);
2373 } else {
2374 assert(VA.isMemLoc());
2375
2376 MemOpChains.push_back(
2377 LowerMemOpCallTo(Chain, StackPtr, Op1, dl, DAG, VA, Flags));
2378 }
2379 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2380 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2381 StackPtr, MemOpChains, Flags);
2382 } else if (VA.isRegLoc()) {
2383 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2384 Outs[0].VT == MVT::i32) {
2385 assert(VA.getLocVT() == MVT::i32 &&
2386 "unexpected calling convention register assignment");
2387 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2388 "unexpected use of 'returned'");
2389 isThisReturn = true;
2390 }
2391 const TargetOptions &Options = DAG.getTarget().Options;
2392 if (Options.EmitCallSiteInfo)
2393 CSInfo.emplace_back(VA.getLocReg(), i);
2394 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2395 } else if (isByVal) {
2396 assert(VA.isMemLoc());
2397 unsigned offset = 0;
2398
2399 // True if this byval aggregate will be split between registers
2400 // and memory.
2401 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2402 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2403
2404 if (CurByValIdx < ByValArgsCount) {
2405
2406 unsigned RegBegin, RegEnd;
2407 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2408
2409 EVT PtrVT =
2410 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2411 unsigned int i, j;
2412 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2413 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2414 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2415 SDValue Load =
2416 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2417 DAG.InferPtrAlign(AddArg));
2418 MemOpChains.push_back(Load.getValue(1));
2419 RegsToPass.push_back(std::make_pair(j, Load));
2420 }
2421
2422 // If parameter size outsides register area, "offset" value
2423 // helps us to calculate stack slot for remained part properly.
2424 offset = RegEnd - RegBegin;
2425
2426 CCInfo.nextInRegsParam();
2427 }
2428
2429 if (Flags.getByValSize() > 4*offset) {
2430 auto PtrVT = getPointerTy(DAG.getDataLayout());
2431 unsigned LocMemOffset = VA.getLocMemOffset();
2432 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2433 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2434 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2435 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2436 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2437 MVT::i32);
2438 SDValue AlignNode =
2439 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2440
2441 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2442 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2443 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2444 Ops));
2445 }
2446 } else if (!isTailCall) {
2447 assert(VA.isMemLoc());
2448
2449 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2450 dl, DAG, VA, Flags));
2451 }
2452 }
2453
2454 if (!MemOpChains.empty())
2455 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2456
2457 // Build a sequence of copy-to-reg nodes chained together with token chain
2458 // and flag operands which copy the outgoing args into the appropriate regs.
2459 SDValue InFlag;
2460 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2461 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2462 RegsToPass[i].second, InFlag);
2463 InFlag = Chain.getValue(1);
2464 }
2465
2466 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2467 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2468 // node so that legalize doesn't hack it.
2469 bool isDirect = false;
2470
2471 const TargetMachine &TM = getTargetMachine();
2472 const Module *Mod = MF.getFunction().getParent();
2473 const GlobalValue *GV = nullptr;
2474 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2475 GV = G->getGlobal();
2476 bool isStub =
2477 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2478
2479 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2480 bool isLocalARMFunc = false;
2481 auto PtrVt = getPointerTy(DAG.getDataLayout());
2482
2483 if (Subtarget->genLongCalls()) {
2484 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2485 "long-calls codegen is not position independent!");
2486 // Handle a global address or an external symbol. If it's not one of
2487 // those, the target's already in a register, so we don't need to do
2488 // anything extra.
2489 if (isa<GlobalAddressSDNode>(Callee)) {
2490 // Create a constant pool entry for the callee address
2491 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2492 ARMConstantPoolValue *CPV =
2493 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2494
2495 // Get the address of the callee into a register
2496 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2497 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2498 Callee = DAG.getLoad(
2499 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2500 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2501 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2502 const char *Sym = S->getSymbol();
2503
2504 // Create a constant pool entry for the callee address
2505 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2506 ARMConstantPoolValue *CPV =
2507 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2508 ARMPCLabelIndex, 0);
2509 // Get the address of the callee into a register
2510 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2511 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2512 Callee = DAG.getLoad(
2513 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2514 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2515 }
2516 } else if (isa<GlobalAddressSDNode>(Callee)) {
2517 if (!PreferIndirect) {
2518 isDirect = true;
2519 bool isDef = GV->isStrongDefinitionForLinker();
2520
2521 // ARM call to a local ARM function is predicable.
2522 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2523 // tBX takes a register source operand.
2524 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2525 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2526 Callee = DAG.getNode(
2527 ARMISD::WrapperPIC, dl, PtrVt,
2528 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2529 Callee = DAG.getLoad(
2530 PtrVt, dl, DAG.getEntryNode(), Callee,
2531 MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(),
2532 MachineMemOperand::MODereferenceable |
2533 MachineMemOperand::MOInvariant);
2534 } else if (Subtarget->isTargetCOFF()) {
2535 assert(Subtarget->isTargetWindows() &&
2536 "Windows is the only supported COFF target");
2537 unsigned TargetFlags = ARMII::MO_NO_FLAG;
2538 if (GV->hasDLLImportStorageClass())
2539 TargetFlags = ARMII::MO_DLLIMPORT;
2540 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2541 TargetFlags = ARMII::MO_COFFSTUB;
2542 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2543 TargetFlags);
2544 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2545 Callee =
2546 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2547 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2548 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2549 } else {
2550 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2551 }
2552 }
2553 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2554 isDirect = true;
2555 // tBX takes a register source operand.
2556 const char *Sym = S->getSymbol();
2557 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2558 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2559 ARMConstantPoolValue *CPV =
2560 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2561 ARMPCLabelIndex, 4);
2562 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2563 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2564 Callee = DAG.getLoad(
2565 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2566 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2567 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2568 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2569 } else {
2570 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2571 }
2572 }
2573
2574 if (isCmseNSCall) {
2575 assert(!isARMFunc && !isDirect &&
2576 "Cannot handle call to ARM function or direct call");
2577 if (NumBytes > 0) {
2578 DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(),
2579 "call to non-secure function would "
2580 "require passing arguments on stack",
2581 dl.getDebugLoc());
2582 DAG.getContext()->diagnose(Diag);
2583 }
2584 if (isStructRet) {
2585 DiagnosticInfoUnsupported Diag(
2586 DAG.getMachineFunction().getFunction(),
2587 "call to non-secure function would return value through pointer",
2588 dl.getDebugLoc());
2589 DAG.getContext()->diagnose(Diag);
2590 }
2591 }
2592
2593 // FIXME: handle tail calls differently.
2594 unsigned CallOpc;
2595 if (Subtarget->isThumb()) {
2596 if (isCmseNSCall)
2597 CallOpc = ARMISD::tSECALL;
2598 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2599 CallOpc = ARMISD::CALL_NOLINK;
2600 else
2601 CallOpc = ARMISD::CALL;
2602 } else {
2603 if (!isDirect && !Subtarget->hasV5TOps())
2604 CallOpc = ARMISD::CALL_NOLINK;
2605 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2606 // Emit regular call when code size is the priority
2607 !Subtarget->hasMinSize())
2608 // "mov lr, pc; b _foo" to avoid confusing the RSP
2609 CallOpc = ARMISD::CALL_NOLINK;
2610 else
2611 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2612 }
2613
2614 std::vector<SDValue> Ops;
2615 Ops.push_back(Chain);
2616 Ops.push_back(Callee);
2617
2618 // Add argument registers to the end of the list so that they are known live
2619 // into the call.
2620 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2621 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2622 RegsToPass[i].second.getValueType()));
2623
2624 // Add a register mask operand representing the call-preserved registers.
2625 if (!isTailCall) {
2626 const uint32_t *Mask;
2627 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2628 if (isThisReturn) {
2629 // For 'this' returns, use the R0-preserving mask if applicable
2630 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2631 if (!Mask) {
2632 // Set isThisReturn to false if the calling convention is not one that
2633 // allows 'returned' to be modeled in this way, so LowerCallResult does
2634 // not try to pass 'this' straight through
2635 isThisReturn = false;
2636 Mask = ARI->getCallPreservedMask(MF, CallConv);
2637 }
2638 } else
2639 Mask = ARI->getCallPreservedMask(MF, CallConv);
2640
2641 assert(Mask && "Missing call preserved mask for calling convention");
2642 Ops.push_back(DAG.getRegisterMask(Mask));
2643 }
2644
2645 if (InFlag.getNode())
2646 Ops.push_back(InFlag);
2647
2648 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2649 if (isTailCall) {
2650 MF.getFrameInfo().setHasTailCall();
2651 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2652 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2653 return Ret;
2654 }
2655
2656 // Returns a chain and a flag for retval copy to use.
2657 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2658 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2659 InFlag = Chain.getValue(1);
2660 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2661
2662 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2663 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2664 if (!Ins.empty())
2665 InFlag = Chain.getValue(1);
2666
2667 // Handle result values, copying them out of physregs into vregs that we
2668 // return.
2669 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2670 InVals, isThisReturn,
2671 isThisReturn ? OutVals[0] : SDValue());
2672 }
2673
2674 /// HandleByVal - Every parameter *after* a byval parameter is passed
2675 /// on the stack. Remember the next parameter register to allocate,
2676 /// and then confiscate the rest of the parameter registers to insure
2677 /// this.
HandleByVal(CCState * State,unsigned & Size,Align Alignment) const2678 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2679 Align Alignment) const {
2680 // Byval (as with any stack) slots are always at least 4 byte aligned.
2681 Alignment = std::max(Alignment, Align(4));
2682
2683 unsigned Reg = State->AllocateReg(GPRArgRegs);
2684 if (!Reg)
2685 return;
2686
2687 unsigned AlignInRegs = Alignment.value() / 4;
2688 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2689 for (unsigned i = 0; i < Waste; ++i)
2690 Reg = State->AllocateReg(GPRArgRegs);
2691
2692 if (!Reg)
2693 return;
2694
2695 unsigned Excess = 4 * (ARM::R4 - Reg);
2696
2697 // Special case when NSAA != SP and parameter size greater than size of
2698 // all remained GPR regs. In that case we can't split parameter, we must
2699 // send it to stack. We also must set NCRN to R4, so waste all
2700 // remained registers.
2701 const unsigned NSAAOffset = State->getNextStackOffset();
2702 if (NSAAOffset != 0 && Size > Excess) {
2703 while (State->AllocateReg(GPRArgRegs))
2704 ;
2705 return;
2706 }
2707
2708 // First register for byval parameter is the first register that wasn't
2709 // allocated before this method call, so it would be "reg".
2710 // If parameter is small enough to be saved in range [reg, r4), then
2711 // the end (first after last) register would be reg + param-size-in-regs,
2712 // else parameter would be splitted between registers and stack,
2713 // end register would be r4 in this case.
2714 unsigned ByValRegBegin = Reg;
2715 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2716 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2717 // Note, first register is allocated in the beginning of function already,
2718 // allocate remained amount of registers we need.
2719 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2720 State->AllocateReg(GPRArgRegs);
2721 // A byval parameter that is split between registers and memory needs its
2722 // size truncated here.
2723 // In the case where the entire structure fits in registers, we set the
2724 // size in memory to zero.
2725 Size = std::max<int>(Size - Excess, 0);
2726 }
2727
2728 /// MatchingStackOffset - Return true if the given stack call argument is
2729 /// already available in the same position (relatively) of the caller's
2730 /// incoming argument stack.
2731 static
MatchingStackOffset(SDValue Arg,unsigned Offset,ISD::ArgFlagsTy Flags,MachineFrameInfo & MFI,const MachineRegisterInfo * MRI,const TargetInstrInfo * TII)2732 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2733 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2734 const TargetInstrInfo *TII) {
2735 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2736 int FI = std::numeric_limits<int>::max();
2737 if (Arg.getOpcode() == ISD::CopyFromReg) {
2738 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2739 if (!Register::isVirtualRegister(VR))
2740 return false;
2741 MachineInstr *Def = MRI->getVRegDef(VR);
2742 if (!Def)
2743 return false;
2744 if (!Flags.isByVal()) {
2745 if (!TII->isLoadFromStackSlot(*Def, FI))
2746 return false;
2747 } else {
2748 return false;
2749 }
2750 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2751 if (Flags.isByVal())
2752 // ByVal argument is passed in as a pointer but it's now being
2753 // dereferenced. e.g.
2754 // define @foo(%struct.X* %A) {
2755 // tail call @bar(%struct.X* byval %A)
2756 // }
2757 return false;
2758 SDValue Ptr = Ld->getBasePtr();
2759 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2760 if (!FINode)
2761 return false;
2762 FI = FINode->getIndex();
2763 } else
2764 return false;
2765
2766 assert(FI != std::numeric_limits<int>::max());
2767 if (!MFI.isFixedObjectIndex(FI))
2768 return false;
2769 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2770 }
2771
2772 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2773 /// for tail call optimization. Targets which want to do tail call
2774 /// optimization should implement this function.
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,const bool isIndirect) const2775 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2776 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2777 bool isCalleeStructRet, bool isCallerStructRet,
2778 const SmallVectorImpl<ISD::OutputArg> &Outs,
2779 const SmallVectorImpl<SDValue> &OutVals,
2780 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2781 const bool isIndirect) const {
2782 MachineFunction &MF = DAG.getMachineFunction();
2783 const Function &CallerF = MF.getFunction();
2784 CallingConv::ID CallerCC = CallerF.getCallingConv();
2785
2786 assert(Subtarget->supportsTailCall());
2787
2788 // Indirect tail calls cannot be optimized for Thumb1 if the args
2789 // to the call take up r0-r3. The reason is that there are no legal registers
2790 // left to hold the pointer to the function to be called.
2791 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2792 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2793 return false;
2794
2795 // Look for obvious safe cases to perform tail call optimization that do not
2796 // require ABI changes. This is what gcc calls sibcall.
2797
2798 // Exception-handling functions need a special set of instructions to indicate
2799 // a return to the hardware. Tail-calling another function would probably
2800 // break this.
2801 if (CallerF.hasFnAttribute("interrupt"))
2802 return false;
2803
2804 // Also avoid sibcall optimization if either caller or callee uses struct
2805 // return semantics.
2806 if (isCalleeStructRet || isCallerStructRet)
2807 return false;
2808
2809 // Externally-defined functions with weak linkage should not be
2810 // tail-called on ARM when the OS does not support dynamic
2811 // pre-emption of symbols, as the AAELF spec requires normal calls
2812 // to undefined weak functions to be replaced with a NOP or jump to the
2813 // next instruction. The behaviour of branch instructions in this
2814 // situation (as used for tail calls) is implementation-defined, so we
2815 // cannot rely on the linker replacing the tail call with a return.
2816 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2817 const GlobalValue *GV = G->getGlobal();
2818 const Triple &TT = getTargetMachine().getTargetTriple();
2819 if (GV->hasExternalWeakLinkage() &&
2820 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2821 return false;
2822 }
2823
2824 // Check that the call results are passed in the same way.
2825 LLVMContext &C = *DAG.getContext();
2826 if (!CCState::resultsCompatible(
2827 getEffectiveCallingConv(CalleeCC, isVarArg),
2828 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2829 CCAssignFnForReturn(CalleeCC, isVarArg),
2830 CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
2831 return false;
2832 // The callee has to preserve all registers the caller needs to preserve.
2833 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2834 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2835 if (CalleeCC != CallerCC) {
2836 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2837 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2838 return false;
2839 }
2840
2841 // If Caller's vararg or byval argument has been split between registers and
2842 // stack, do not perform tail call, since part of the argument is in caller's
2843 // local frame.
2844 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2845 if (AFI_Caller->getArgRegsSaveSize())
2846 return false;
2847
2848 // If the callee takes no arguments then go on to check the results of the
2849 // call.
2850 if (!Outs.empty()) {
2851 // Check if stack adjustment is needed. For now, do not do this if any
2852 // argument is passed on the stack.
2853 SmallVector<CCValAssign, 16> ArgLocs;
2854 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2855 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2856 if (CCInfo.getNextStackOffset()) {
2857 // Check if the arguments are already laid out in the right way as
2858 // the caller's fixed stack objects.
2859 MachineFrameInfo &MFI = MF.getFrameInfo();
2860 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2861 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2862 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2863 i != e;
2864 ++i, ++realArgIdx) {
2865 CCValAssign &VA = ArgLocs[i];
2866 EVT RegVT = VA.getLocVT();
2867 SDValue Arg = OutVals[realArgIdx];
2868 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2869 if (VA.getLocInfo() == CCValAssign::Indirect)
2870 return false;
2871 if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) {
2872 // f64 and vector types are split into multiple registers or
2873 // register/stack-slot combinations. The types will not match
2874 // the registers; give up on memory f64 refs until we figure
2875 // out what to do about this.
2876 if (!VA.isRegLoc())
2877 return false;
2878 if (!ArgLocs[++i].isRegLoc())
2879 return false;
2880 if (RegVT == MVT::v2f64) {
2881 if (!ArgLocs[++i].isRegLoc())
2882 return false;
2883 if (!ArgLocs[++i].isRegLoc())
2884 return false;
2885 }
2886 } else if (!VA.isRegLoc()) {
2887 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2888 MFI, MRI, TII))
2889 return false;
2890 }
2891 }
2892 }
2893
2894 const MachineRegisterInfo &MRI = MF.getRegInfo();
2895 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2896 return false;
2897 }
2898
2899 return true;
2900 }
2901
2902 bool
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const2903 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2904 MachineFunction &MF, bool isVarArg,
2905 const SmallVectorImpl<ISD::OutputArg> &Outs,
2906 LLVMContext &Context) const {
2907 SmallVector<CCValAssign, 16> RVLocs;
2908 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2909 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2910 }
2911
LowerInterruptReturn(SmallVectorImpl<SDValue> & RetOps,const SDLoc & DL,SelectionDAG & DAG)2912 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2913 const SDLoc &DL, SelectionDAG &DAG) {
2914 const MachineFunction &MF = DAG.getMachineFunction();
2915 const Function &F = MF.getFunction();
2916
2917 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2918
2919 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2920 // version of the "preferred return address". These offsets affect the return
2921 // instruction if this is a return from PL1 without hypervisor extensions.
2922 // IRQ/FIQ: +4 "subs pc, lr, #4"
2923 // SWI: 0 "subs pc, lr, #0"
2924 // ABORT: +4 "subs pc, lr, #4"
2925 // UNDEF: +4/+2 "subs pc, lr, #0"
2926 // UNDEF varies depending on where the exception came from ARM or Thumb
2927 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2928
2929 int64_t LROffset;
2930 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2931 IntKind == "ABORT")
2932 LROffset = 4;
2933 else if (IntKind == "SWI" || IntKind == "UNDEF")
2934 LROffset = 0;
2935 else
2936 report_fatal_error("Unsupported interrupt attribute. If present, value "
2937 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2938
2939 RetOps.insert(RetOps.begin() + 1,
2940 DAG.getConstant(LROffset, DL, MVT::i32, false));
2941
2942 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2943 }
2944
2945 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & dl,SelectionDAG & DAG) const2946 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2947 bool isVarArg,
2948 const SmallVectorImpl<ISD::OutputArg> &Outs,
2949 const SmallVectorImpl<SDValue> &OutVals,
2950 const SDLoc &dl, SelectionDAG &DAG) const {
2951 // CCValAssign - represent the assignment of the return value to a location.
2952 SmallVector<CCValAssign, 16> RVLocs;
2953
2954 // CCState - Info about the registers and stack slots.
2955 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2956 *DAG.getContext());
2957
2958 // Analyze outgoing return values.
2959 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2960
2961 SDValue Flag;
2962 SmallVector<SDValue, 4> RetOps;
2963 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2964 bool isLittleEndian = Subtarget->isLittle();
2965
2966 MachineFunction &MF = DAG.getMachineFunction();
2967 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2968 AFI->setReturnRegsCount(RVLocs.size());
2969
2970 // Report error if cmse entry function returns structure through first ptr arg.
2971 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
2972 // Note: using an empty SDLoc(), as the first line of the function is a
2973 // better place to report than the last line.
2974 DiagnosticInfoUnsupported Diag(
2975 DAG.getMachineFunction().getFunction(),
2976 "secure entry function would return value through pointer",
2977 SDLoc().getDebugLoc());
2978 DAG.getContext()->diagnose(Diag);
2979 }
2980
2981 // Copy the result values into the output registers.
2982 for (unsigned i = 0, realRVLocIdx = 0;
2983 i != RVLocs.size();
2984 ++i, ++realRVLocIdx) {
2985 CCValAssign &VA = RVLocs[i];
2986 assert(VA.isRegLoc() && "Can only return in registers!");
2987
2988 SDValue Arg = OutVals[realRVLocIdx];
2989 bool ReturnF16 = false;
2990
2991 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2992 // Half-precision return values can be returned like this:
2993 //
2994 // t11 f16 = fadd ...
2995 // t12: i16 = bitcast t11
2996 // t13: i32 = zero_extend t12
2997 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2998 //
2999 // to avoid code generation for bitcasts, we simply set Arg to the node
3000 // that produces the f16 value, t11 in this case.
3001 //
3002 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3003 SDValue ZE = Arg.getOperand(0);
3004 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3005 SDValue BC = ZE.getOperand(0);
3006 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3007 Arg = BC.getOperand(0);
3008 ReturnF16 = true;
3009 }
3010 }
3011 }
3012 }
3013
3014 switch (VA.getLocInfo()) {
3015 default: llvm_unreachable("Unknown loc info!");
3016 case CCValAssign::Full: break;
3017 case CCValAssign::BCvt:
3018 if (!ReturnF16)
3019 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3020 break;
3021 }
3022
3023 // Mask f16 arguments if this is a CMSE nonsecure entry.
3024 auto RetVT = Outs[realRVLocIdx].ArgVT;
3025 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3026 if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3027 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3028 } else {
3029 auto LocBits = VA.getLocVT().getSizeInBits();
3030 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3031 SDValue Mask =
3032 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3033 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3034 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3035 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3036 }
3037 }
3038
3039 if (VA.needsCustom() &&
3040 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3041 if (VA.getLocVT() == MVT::v2f64) {
3042 // Extract the first half and return it in two registers.
3043 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3044 DAG.getConstant(0, dl, MVT::i32));
3045 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3046 DAG.getVTList(MVT::i32, MVT::i32), Half);
3047
3048 Chain =
3049 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3050 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag);
3051 Flag = Chain.getValue(1);
3052 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3053 VA = RVLocs[++i]; // skip ahead to next loc
3054 Chain =
3055 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3056 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag);
3057 Flag = Chain.getValue(1);
3058 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3059 VA = RVLocs[++i]; // skip ahead to next loc
3060
3061 // Extract the 2nd half and fall through to handle it as an f64 value.
3062 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3063 DAG.getConstant(1, dl, MVT::i32));
3064 }
3065 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
3066 // available.
3067 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3068 DAG.getVTList(MVT::i32, MVT::i32), Arg);
3069 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3070 fmrrd.getValue(isLittleEndian ? 0 : 1), Flag);
3071 Flag = Chain.getValue(1);
3072 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3073 VA = RVLocs[++i]; // skip ahead to next loc
3074 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3075 fmrrd.getValue(isLittleEndian ? 1 : 0), Flag);
3076 } else
3077 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
3078
3079 // Guarantee that all emitted copies are
3080 // stuck together, avoiding something bad.
3081 Flag = Chain.getValue(1);
3082 RetOps.push_back(DAG.getRegister(
3083 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3084 }
3085 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3086 const MCPhysReg *I =
3087 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3088 if (I) {
3089 for (; *I; ++I) {
3090 if (ARM::GPRRegClass.contains(*I))
3091 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3092 else if (ARM::DPRRegClass.contains(*I))
3093 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3094 else
3095 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3096 }
3097 }
3098
3099 // Update chain and glue.
3100 RetOps[0] = Chain;
3101 if (Flag.getNode())
3102 RetOps.push_back(Flag);
3103
3104 // CPUs which aren't M-class use a special sequence to return from
3105 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3106 // though we use "subs pc, lr, #N").
3107 //
3108 // M-class CPUs actually use a normal return sequence with a special
3109 // (hardware-provided) value in LR, so the normal code path works.
3110 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3111 !Subtarget->isMClass()) {
3112 if (Subtarget->isThumb1Only())
3113 report_fatal_error("interrupt attribute is not supported in Thumb1");
3114 return LowerInterruptReturn(RetOps, dl, DAG);
3115 }
3116
3117 ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG :
3118 ARMISD::RET_FLAG;
3119 return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3120 }
3121
isUsedByReturnOnly(SDNode * N,SDValue & Chain) const3122 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3123 if (N->getNumValues() != 1)
3124 return false;
3125 if (!N->hasNUsesOfValue(1, 0))
3126 return false;
3127
3128 SDValue TCChain = Chain;
3129 SDNode *Copy = *N->use_begin();
3130 if (Copy->getOpcode() == ISD::CopyToReg) {
3131 // If the copy has a glue operand, we conservatively assume it isn't safe to
3132 // perform a tail call.
3133 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3134 return false;
3135 TCChain = Copy->getOperand(0);
3136 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3137 SDNode *VMov = Copy;
3138 // f64 returned in a pair of GPRs.
3139 SmallPtrSet<SDNode*, 2> Copies;
3140 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3141 UI != UE; ++UI) {
3142 if (UI->getOpcode() != ISD::CopyToReg)
3143 return false;
3144 Copies.insert(*UI);
3145 }
3146 if (Copies.size() > 2)
3147 return false;
3148
3149 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3150 UI != UE; ++UI) {
3151 SDValue UseChain = UI->getOperand(0);
3152 if (Copies.count(UseChain.getNode()))
3153 // Second CopyToReg
3154 Copy = *UI;
3155 else {
3156 // We are at the top of this chain.
3157 // If the copy has a glue operand, we conservatively assume it
3158 // isn't safe to perform a tail call.
3159 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
3160 return false;
3161 // First CopyToReg
3162 TCChain = UseChain;
3163 }
3164 }
3165 } else if (Copy->getOpcode() == ISD::BITCAST) {
3166 // f32 returned in a single GPR.
3167 if (!Copy->hasOneUse())
3168 return false;
3169 Copy = *Copy->use_begin();
3170 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3171 return false;
3172 // If the copy has a glue operand, we conservatively assume it isn't safe to
3173 // perform a tail call.
3174 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3175 return false;
3176 TCChain = Copy->getOperand(0);
3177 } else {
3178 return false;
3179 }
3180
3181 bool HasRet = false;
3182 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
3183 UI != UE; ++UI) {
3184 if (UI->getOpcode() != ARMISD::RET_FLAG &&
3185 UI->getOpcode() != ARMISD::INTRET_FLAG)
3186 return false;
3187 HasRet = true;
3188 }
3189
3190 if (!HasRet)
3191 return false;
3192
3193 Chain = TCChain;
3194 return true;
3195 }
3196
mayBeEmittedAsTailCall(const CallInst * CI) const3197 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3198 if (!Subtarget->supportsTailCall())
3199 return false;
3200
3201 if (!CI->isTailCall())
3202 return false;
3203
3204 return true;
3205 }
3206
3207 // Trying to write a 64 bit value so need to split into two 32 bit values first,
3208 // and pass the lower and high parts through.
LowerWRITE_REGISTER(SDValue Op,SelectionDAG & DAG)3209 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3210 SDLoc DL(Op);
3211 SDValue WriteValue = Op->getOperand(2);
3212
3213 // This function is only supposed to be called for i64 type argument.
3214 assert(WriteValue.getValueType() == MVT::i64
3215 && "LowerWRITE_REGISTER called for non-i64 type argument.");
3216
3217 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3218 DAG.getConstant(0, DL, MVT::i32));
3219 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3220 DAG.getConstant(1, DL, MVT::i32));
3221 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3222 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3223 }
3224
3225 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3226 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3227 // one of the above mentioned nodes. It has to be wrapped because otherwise
3228 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3229 // be used to form addressing mode. These wrapped nodes will be selected
3230 // into MOVi.
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const3231 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3232 SelectionDAG &DAG) const {
3233 EVT PtrVT = Op.getValueType();
3234 // FIXME there is no actual debug info here
3235 SDLoc dl(Op);
3236 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3237 SDValue Res;
3238
3239 // When generating execute-only code Constant Pools must be promoted to the
3240 // global data section. It's a bit ugly that we can't share them across basic
3241 // blocks, but this way we guarantee that execute-only behaves correct with
3242 // position-independent addressing modes.
3243 if (Subtarget->genExecuteOnly()) {
3244 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3245 auto T = const_cast<Type*>(CP->getType());
3246 auto C = const_cast<Constant*>(CP->getConstVal());
3247 auto M = const_cast<Module*>(DAG.getMachineFunction().
3248 getFunction().getParent());
3249 auto GV = new GlobalVariable(
3250 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3251 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3252 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3253 Twine(AFI->createPICLabelUId())
3254 );
3255 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3256 dl, PtrVT);
3257 return LowerGlobalAddress(GA, DAG);
3258 }
3259
3260 if (CP->isMachineConstantPoolEntry())
3261 Res =
3262 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3263 else
3264 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign());
3265 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3266 }
3267
getJumpTableEncoding() const3268 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3269 return MachineJumpTableInfo::EK_Inline;
3270 }
3271
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const3272 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3273 SelectionDAG &DAG) const {
3274 MachineFunction &MF = DAG.getMachineFunction();
3275 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3276 unsigned ARMPCLabelIndex = 0;
3277 SDLoc DL(Op);
3278 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3279 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3280 SDValue CPAddr;
3281 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3282 if (!IsPositionIndependent) {
3283 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3284 } else {
3285 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3286 ARMPCLabelIndex = AFI->createPICLabelUId();
3287 ARMConstantPoolValue *CPV =
3288 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3289 ARMCP::CPBlockAddress, PCAdj);
3290 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3291 }
3292 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3293 SDValue Result = DAG.getLoad(
3294 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3295 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3296 if (!IsPositionIndependent)
3297 return Result;
3298 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3299 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3300 }
3301
3302 /// Convert a TLS address reference into the correct sequence of loads
3303 /// and calls to compute the variable's address for Darwin, and return an
3304 /// SDValue containing the final node.
3305
3306 /// Darwin only has one TLS scheme which must be capable of dealing with the
3307 /// fully general situation, in the worst case. This means:
3308 /// + "extern __thread" declaration.
3309 /// + Defined in a possibly unknown dynamic library.
3310 ///
3311 /// The general system is that each __thread variable has a [3 x i32] descriptor
3312 /// which contains information used by the runtime to calculate the address. The
3313 /// only part of this the compiler needs to know about is the first word, which
3314 /// contains a function pointer that must be called with the address of the
3315 /// entire descriptor in "r0".
3316 ///
3317 /// Since this descriptor may be in a different unit, in general access must
3318 /// proceed along the usual ARM rules. A common sequence to produce is:
3319 ///
3320 /// movw rT1, :lower16:_var$non_lazy_ptr
3321 /// movt rT1, :upper16:_var$non_lazy_ptr
3322 /// ldr r0, [rT1]
3323 /// ldr rT2, [r0]
3324 /// blx rT2
3325 /// [...address now in r0...]
3326 SDValue
LowerGlobalTLSAddressDarwin(SDValue Op,SelectionDAG & DAG) const3327 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3328 SelectionDAG &DAG) const {
3329 assert(Subtarget->isTargetDarwin() &&
3330 "This function expects a Darwin target");
3331 SDLoc DL(Op);
3332
3333 // First step is to get the address of the actua global symbol. This is where
3334 // the TLS descriptor lives.
3335 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3336
3337 // The first entry in the descriptor is a function pointer that we must call
3338 // to obtain the address of the variable.
3339 SDValue Chain = DAG.getEntryNode();
3340 SDValue FuncTLVGet = DAG.getLoad(
3341 MVT::i32, DL, Chain, DescAddr,
3342 MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4),
3343 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3344 MachineMemOperand::MOInvariant);
3345 Chain = FuncTLVGet.getValue(1);
3346
3347 MachineFunction &F = DAG.getMachineFunction();
3348 MachineFrameInfo &MFI = F.getFrameInfo();
3349 MFI.setAdjustsStack(true);
3350
3351 // TLS calls preserve all registers except those that absolutely must be
3352 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3353 // silly).
3354 auto TRI =
3355 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3356 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3357 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3358
3359 // Finally, we can make the call. This is just a degenerate version of a
3360 // normal AArch64 call node: r0 takes the address of the descriptor, and
3361 // returns the address of the variable in this thread.
3362 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3363 Chain =
3364 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3365 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3366 DAG.getRegisterMask(Mask), Chain.getValue(1));
3367 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3368 }
3369
3370 SDValue
LowerGlobalTLSAddressWindows(SDValue Op,SelectionDAG & DAG) const3371 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3372 SelectionDAG &DAG) const {
3373 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3374
3375 SDValue Chain = DAG.getEntryNode();
3376 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3377 SDLoc DL(Op);
3378
3379 // Load the current TEB (thread environment block)
3380 SDValue Ops[] = {Chain,
3381 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3382 DAG.getTargetConstant(15, DL, MVT::i32),
3383 DAG.getTargetConstant(0, DL, MVT::i32),
3384 DAG.getTargetConstant(13, DL, MVT::i32),
3385 DAG.getTargetConstant(0, DL, MVT::i32),
3386 DAG.getTargetConstant(2, DL, MVT::i32)};
3387 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3388 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3389
3390 SDValue TEB = CurrentTEB.getValue(0);
3391 Chain = CurrentTEB.getValue(1);
3392
3393 // Load the ThreadLocalStoragePointer from the TEB
3394 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3395 SDValue TLSArray =
3396 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3397 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3398
3399 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3400 // offset into the TLSArray.
3401
3402 // Load the TLS index from the C runtime
3403 SDValue TLSIndex =
3404 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3405 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3406 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3407
3408 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3409 DAG.getConstant(2, DL, MVT::i32));
3410 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3411 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3412 MachinePointerInfo());
3413
3414 // Get the offset of the start of the .tls section (section base)
3415 const auto *GA = cast<GlobalAddressSDNode>(Op);
3416 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3417 SDValue Offset = DAG.getLoad(
3418 PtrVT, DL, Chain,
3419 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3420 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3421 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3422
3423 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3424 }
3425
3426 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3427 SDValue
LowerToTLSGeneralDynamicModel(GlobalAddressSDNode * GA,SelectionDAG & DAG) const3428 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3429 SelectionDAG &DAG) const {
3430 SDLoc dl(GA);
3431 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3432 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3433 MachineFunction &MF = DAG.getMachineFunction();
3434 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3435 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3436 ARMConstantPoolValue *CPV =
3437 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3438 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3439 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3440 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3441 Argument = DAG.getLoad(
3442 PtrVT, dl, DAG.getEntryNode(), Argument,
3443 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3444 SDValue Chain = Argument.getValue(1);
3445
3446 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3447 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3448
3449 // call __tls_get_addr.
3450 ArgListTy Args;
3451 ArgListEntry Entry;
3452 Entry.Node = Argument;
3453 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3454 Args.push_back(Entry);
3455
3456 // FIXME: is there useful debug info available here?
3457 TargetLowering::CallLoweringInfo CLI(DAG);
3458 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3459 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3460 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3461
3462 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3463 return CallResult.first;
3464 }
3465
3466 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3467 // "local exec" model.
3468 SDValue
LowerToTLSExecModels(GlobalAddressSDNode * GA,SelectionDAG & DAG,TLSModel::Model model) const3469 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3470 SelectionDAG &DAG,
3471 TLSModel::Model model) const {
3472 const GlobalValue *GV = GA->getGlobal();
3473 SDLoc dl(GA);
3474 SDValue Offset;
3475 SDValue Chain = DAG.getEntryNode();
3476 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3477 // Get the Thread Pointer
3478 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3479
3480 if (model == TLSModel::InitialExec) {
3481 MachineFunction &MF = DAG.getMachineFunction();
3482 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3483 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3484 // Initial exec model.
3485 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3486 ARMConstantPoolValue *CPV =
3487 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3488 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3489 true);
3490 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3491 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3492 Offset = DAG.getLoad(
3493 PtrVT, dl, Chain, Offset,
3494 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3495 Chain = Offset.getValue(1);
3496
3497 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3498 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3499
3500 Offset = DAG.getLoad(
3501 PtrVT, dl, Chain, Offset,
3502 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3503 } else {
3504 // local exec model
3505 assert(model == TLSModel::LocalExec);
3506 ARMConstantPoolValue *CPV =
3507 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3508 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3509 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3510 Offset = DAG.getLoad(
3511 PtrVT, dl, Chain, Offset,
3512 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3513 }
3514
3515 // The address of the thread local variable is the add of the thread
3516 // pointer with the offset of the variable.
3517 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3518 }
3519
3520 SDValue
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const3521 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3522 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3523 if (DAG.getTarget().useEmulatedTLS())
3524 return LowerToTLSEmulatedModel(GA, DAG);
3525
3526 if (Subtarget->isTargetDarwin())
3527 return LowerGlobalTLSAddressDarwin(Op, DAG);
3528
3529 if (Subtarget->isTargetWindows())
3530 return LowerGlobalTLSAddressWindows(Op, DAG);
3531
3532 // TODO: implement the "local dynamic" model
3533 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3534 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3535
3536 switch (model) {
3537 case TLSModel::GeneralDynamic:
3538 case TLSModel::LocalDynamic:
3539 return LowerToTLSGeneralDynamicModel(GA, DAG);
3540 case TLSModel::InitialExec:
3541 case TLSModel::LocalExec:
3542 return LowerToTLSExecModels(GA, DAG, model);
3543 }
3544 llvm_unreachable("bogus TLS model");
3545 }
3546
3547 /// Return true if all users of V are within function F, looking through
3548 /// ConstantExprs.
allUsersAreInFunction(const Value * V,const Function * F)3549 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3550 SmallVector<const User*,4> Worklist;
3551 for (auto *U : V->users())
3552 Worklist.push_back(U);
3553 while (!Worklist.empty()) {
3554 auto *U = Worklist.pop_back_val();
3555 if (isa<ConstantExpr>(U)) {
3556 for (auto *UU : U->users())
3557 Worklist.push_back(UU);
3558 continue;
3559 }
3560
3561 auto *I = dyn_cast<Instruction>(U);
3562 if (!I || I->getParent()->getParent() != F)
3563 return false;
3564 }
3565 return true;
3566 }
3567
promoteToConstantPool(const ARMTargetLowering * TLI,const GlobalValue * GV,SelectionDAG & DAG,EVT PtrVT,const SDLoc & dl)3568 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3569 const GlobalValue *GV, SelectionDAG &DAG,
3570 EVT PtrVT, const SDLoc &dl) {
3571 // If we're creating a pool entry for a constant global with unnamed address,
3572 // and the global is small enough, we can emit it inline into the constant pool
3573 // to save ourselves an indirection.
3574 //
3575 // This is a win if the constant is only used in one function (so it doesn't
3576 // need to be duplicated) or duplicating the constant wouldn't increase code
3577 // size (implying the constant is no larger than 4 bytes).
3578 const Function &F = DAG.getMachineFunction().getFunction();
3579
3580 // We rely on this decision to inline being idemopotent and unrelated to the
3581 // use-site. We know that if we inline a variable at one use site, we'll
3582 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3583 // doesn't know about this optimization, so bail out if it's enabled else
3584 // we could decide to inline here (and thus never emit the GV) but require
3585 // the GV from fast-isel generated code.
3586 if (!EnableConstpoolPromotion ||
3587 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3588 return SDValue();
3589
3590 auto *GVar = dyn_cast<GlobalVariable>(GV);
3591 if (!GVar || !GVar->hasInitializer() ||
3592 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3593 !GVar->hasLocalLinkage())
3594 return SDValue();
3595
3596 // If we inline a value that contains relocations, we move the relocations
3597 // from .data to .text. This is not allowed in position-independent code.
3598 auto *Init = GVar->getInitializer();
3599 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3600 Init->needsRelocation())
3601 return SDValue();
3602
3603 // The constant islands pass can only really deal with alignment requests
3604 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3605 // any type wanting greater alignment requirements than 4 bytes. We also
3606 // can only promote constants that are multiples of 4 bytes in size or
3607 // are paddable to a multiple of 4. Currently we only try and pad constants
3608 // that are strings for simplicity.
3609 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3610 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3611 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3612 unsigned RequiredPadding = 4 - (Size % 4);
3613 bool PaddingPossible =
3614 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3615 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3616 Size == 0)
3617 return SDValue();
3618
3619 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3620 MachineFunction &MF = DAG.getMachineFunction();
3621 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3622
3623 // We can't bloat the constant pool too much, else the ConstantIslands pass
3624 // may fail to converge. If we haven't promoted this global yet (it may have
3625 // multiple uses), and promoting it would increase the constant pool size (Sz
3626 // > 4), ensure we have space to do so up to MaxTotal.
3627 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3628 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3629 ConstpoolPromotionMaxTotal)
3630 return SDValue();
3631
3632 // This is only valid if all users are in a single function; we can't clone
3633 // the constant in general. The LLVM IR unnamed_addr allows merging
3634 // constants, but not cloning them.
3635 //
3636 // We could potentially allow cloning if we could prove all uses of the
3637 // constant in the current function don't care about the address, like
3638 // printf format strings. But that isn't implemented for now.
3639 if (!allUsersAreInFunction(GVar, &F))
3640 return SDValue();
3641
3642 // We're going to inline this global. Pad it out if needed.
3643 if (RequiredPadding != 4) {
3644 StringRef S = CDAInit->getAsString();
3645
3646 SmallVector<uint8_t,16> V(S.size());
3647 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3648 while (RequiredPadding--)
3649 V.push_back(0);
3650 Init = ConstantDataArray::get(*DAG.getContext(), V);
3651 }
3652
3653 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3654 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3655 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3656 AFI->markGlobalAsPromotedToConstantPool(GVar);
3657 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3658 PaddedSize - 4);
3659 }
3660 ++NumConstpoolPromoted;
3661 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3662 }
3663
isReadOnly(const GlobalValue * GV) const3664 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3665 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3666 if (!(GV = GA->getBaseObject()))
3667 return false;
3668 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3669 return V->isConstant();
3670 return isa<Function>(GV);
3671 }
3672
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const3673 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3674 SelectionDAG &DAG) const {
3675 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3676 default: llvm_unreachable("unknown object format");
3677 case Triple::COFF:
3678 return LowerGlobalAddressWindows(Op, DAG);
3679 case Triple::ELF:
3680 return LowerGlobalAddressELF(Op, DAG);
3681 case Triple::MachO:
3682 return LowerGlobalAddressDarwin(Op, DAG);
3683 }
3684 }
3685
LowerGlobalAddressELF(SDValue Op,SelectionDAG & DAG) const3686 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3687 SelectionDAG &DAG) const {
3688 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3689 SDLoc dl(Op);
3690 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3691 const TargetMachine &TM = getTargetMachine();
3692 bool IsRO = isReadOnly(GV);
3693
3694 // promoteToConstantPool only if not generating XO text section
3695 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3696 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3697 return V;
3698
3699 if (isPositionIndependent()) {
3700 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3701 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3702 UseGOT_PREL ? ARMII::MO_GOT : 0);
3703 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3704 if (UseGOT_PREL)
3705 Result =
3706 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3707 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3708 return Result;
3709 } else if (Subtarget->isROPI() && IsRO) {
3710 // PC-relative.
3711 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3712 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3713 return Result;
3714 } else if (Subtarget->isRWPI() && !IsRO) {
3715 // SB-relative.
3716 SDValue RelAddr;
3717 if (Subtarget->useMovt()) {
3718 ++NumMovwMovt;
3719 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3720 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3721 } else { // use literal pool for address constant
3722 ARMConstantPoolValue *CPV =
3723 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3724 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3725 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3726 RelAddr = DAG.getLoad(
3727 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3728 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3729 }
3730 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3731 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3732 return Result;
3733 }
3734
3735 // If we have T2 ops, we can materialize the address directly via movt/movw
3736 // pair. This is always cheaper.
3737 if (Subtarget->useMovt()) {
3738 ++NumMovwMovt;
3739 // FIXME: Once remat is capable of dealing with instructions with register
3740 // operands, expand this into two nodes.
3741 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3742 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3743 } else {
3744 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3745 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3746 return DAG.getLoad(
3747 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3748 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3749 }
3750 }
3751
LowerGlobalAddressDarwin(SDValue Op,SelectionDAG & DAG) const3752 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3753 SelectionDAG &DAG) const {
3754 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3755 "ROPI/RWPI not currently supported for Darwin");
3756 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3757 SDLoc dl(Op);
3758 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3759
3760 if (Subtarget->useMovt())
3761 ++NumMovwMovt;
3762
3763 // FIXME: Once remat is capable of dealing with instructions with register
3764 // operands, expand this into multiple nodes
3765 unsigned Wrapper =
3766 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3767
3768 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3769 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3770
3771 if (Subtarget->isGVIndirectSymbol(GV))
3772 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3773 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3774 return Result;
3775 }
3776
LowerGlobalAddressWindows(SDValue Op,SelectionDAG & DAG) const3777 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3778 SelectionDAG &DAG) const {
3779 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3780 assert(Subtarget->useMovt() &&
3781 "Windows on ARM expects to use movw/movt");
3782 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3783 "ROPI/RWPI not currently supported for Windows");
3784
3785 const TargetMachine &TM = getTargetMachine();
3786 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3787 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3788 if (GV->hasDLLImportStorageClass())
3789 TargetFlags = ARMII::MO_DLLIMPORT;
3790 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3791 TargetFlags = ARMII::MO_COFFSTUB;
3792 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3793 SDValue Result;
3794 SDLoc DL(Op);
3795
3796 ++NumMovwMovt;
3797
3798 // FIXME: Once remat is capable of dealing with instructions with register
3799 // operands, expand this into two nodes.
3800 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3801 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3802 TargetFlags));
3803 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3804 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3805 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3806 return Result;
3807 }
3808
3809 SDValue
LowerEH_SJLJ_SETJMP(SDValue Op,SelectionDAG & DAG) const3810 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3811 SDLoc dl(Op);
3812 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3813 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3814 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3815 Op.getOperand(1), Val);
3816 }
3817
3818 SDValue
LowerEH_SJLJ_LONGJMP(SDValue Op,SelectionDAG & DAG) const3819 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3820 SDLoc dl(Op);
3821 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3822 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3823 }
3824
LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,SelectionDAG & DAG) const3825 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3826 SelectionDAG &DAG) const {
3827 SDLoc dl(Op);
3828 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3829 Op.getOperand(0));
3830 }
3831
LowerINTRINSIC_VOID(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget) const3832 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3833 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3834 unsigned IntNo =
3835 cast<ConstantSDNode>(
3836 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3837 ->getZExtValue();
3838 switch (IntNo) {
3839 default:
3840 return SDValue(); // Don't custom lower most intrinsics.
3841 case Intrinsic::arm_gnu_eabi_mcount: {
3842 MachineFunction &MF = DAG.getMachineFunction();
3843 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3844 SDLoc dl(Op);
3845 SDValue Chain = Op.getOperand(0);
3846 // call "\01__gnu_mcount_nc"
3847 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3848 const uint32_t *Mask =
3849 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3850 assert(Mask && "Missing call preserved mask for calling convention");
3851 // Mark LR an implicit live-in.
3852 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3853 SDValue ReturnAddress =
3854 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3855 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3856 SDValue Callee =
3857 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3858 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3859 if (Subtarget->isThumb())
3860 return SDValue(
3861 DAG.getMachineNode(
3862 ARM::tBL_PUSHLR, dl, ResultTys,
3863 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3864 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3865 0);
3866 return SDValue(
3867 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3868 {ReturnAddress, Callee, RegisterMask, Chain}),
3869 0);
3870 }
3871 }
3872 }
3873
3874 SDValue
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget) const3875 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3876 const ARMSubtarget *Subtarget) const {
3877 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3878 SDLoc dl(Op);
3879 switch (IntNo) {
3880 default: return SDValue(); // Don't custom lower most intrinsics.
3881 case Intrinsic::thread_pointer: {
3882 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3883 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3884 }
3885 case Intrinsic::arm_cls: {
3886 const SDValue &Operand = Op.getOperand(1);
3887 const EVT VTy = Op.getValueType();
3888 SDValue SRA =
3889 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
3890 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
3891 SDValue SHL =
3892 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
3893 SDValue OR =
3894 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
3895 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
3896 return Result;
3897 }
3898 case Intrinsic::arm_cls64: {
3899 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
3900 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
3901 const SDValue &Operand = Op.getOperand(1);
3902 const EVT VTy = Op.getValueType();
3903
3904 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3905 DAG.getConstant(1, dl, VTy));
3906 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3907 DAG.getConstant(0, dl, VTy));
3908 SDValue Constant0 = DAG.getConstant(0, dl, VTy);
3909 SDValue Constant1 = DAG.getConstant(1, dl, VTy);
3910 SDValue Constant31 = DAG.getConstant(31, dl, VTy);
3911 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
3912 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
3913 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
3914 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
3915 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
3916 SDValue CheckLo =
3917 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
3918 SDValue HiIsZero =
3919 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
3920 SDValue AdjustedLo =
3921 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
3922 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
3923 SDValue Result =
3924 DAG.getSelect(dl, VTy, CheckLo,
3925 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
3926 return Result;
3927 }
3928 case Intrinsic::eh_sjlj_lsda: {
3929 MachineFunction &MF = DAG.getMachineFunction();
3930 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3931 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3932 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3933 SDValue CPAddr;
3934 bool IsPositionIndependent = isPositionIndependent();
3935 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3936 ARMConstantPoolValue *CPV =
3937 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3938 ARMCP::CPLSDA, PCAdj);
3939 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3940 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3941 SDValue Result = DAG.getLoad(
3942 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3943 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3944
3945 if (IsPositionIndependent) {
3946 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3947 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3948 }
3949 return Result;
3950 }
3951 case Intrinsic::arm_neon_vabs:
3952 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3953 Op.getOperand(1));
3954 case Intrinsic::arm_neon_vmulls:
3955 case Intrinsic::arm_neon_vmullu: {
3956 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3957 ? ARMISD::VMULLs : ARMISD::VMULLu;
3958 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3959 Op.getOperand(1), Op.getOperand(2));
3960 }
3961 case Intrinsic::arm_neon_vminnm:
3962 case Intrinsic::arm_neon_vmaxnm: {
3963 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3964 ? ISD::FMINNUM : ISD::FMAXNUM;
3965 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3966 Op.getOperand(1), Op.getOperand(2));
3967 }
3968 case Intrinsic::arm_neon_vminu:
3969 case Intrinsic::arm_neon_vmaxu: {
3970 if (Op.getValueType().isFloatingPoint())
3971 return SDValue();
3972 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3973 ? ISD::UMIN : ISD::UMAX;
3974 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3975 Op.getOperand(1), Op.getOperand(2));
3976 }
3977 case Intrinsic::arm_neon_vmins:
3978 case Intrinsic::arm_neon_vmaxs: {
3979 // v{min,max}s is overloaded between signed integers and floats.
3980 if (!Op.getValueType().isFloatingPoint()) {
3981 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3982 ? ISD::SMIN : ISD::SMAX;
3983 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3984 Op.getOperand(1), Op.getOperand(2));
3985 }
3986 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3987 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3988 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3989 Op.getOperand(1), Op.getOperand(2));
3990 }
3991 case Intrinsic::arm_neon_vtbl1:
3992 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3993 Op.getOperand(1), Op.getOperand(2));
3994 case Intrinsic::arm_neon_vtbl2:
3995 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3996 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3997 case Intrinsic::arm_mve_pred_i2v:
3998 case Intrinsic::arm_mve_pred_v2i:
3999 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4000 Op.getOperand(1));
4001 case Intrinsic::arm_mve_vreinterpretq:
4002 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4003 Op.getOperand(1));
4004 case Intrinsic::arm_mve_lsll:
4005 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4006 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4007 case Intrinsic::arm_mve_asrl:
4008 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4009 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4010 }
4011 }
4012
LowerATOMIC_FENCE(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)4013 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
4014 const ARMSubtarget *Subtarget) {
4015 SDLoc dl(Op);
4016 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
4017 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
4018 if (SSID == SyncScope::SingleThread)
4019 return Op;
4020
4021 if (!Subtarget->hasDataBarrier()) {
4022 // Some ARMv6 cpus can support data barriers with an mcr instruction.
4023 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4024 // here.
4025 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
4026 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
4027 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4028 DAG.getConstant(0, dl, MVT::i32));
4029 }
4030
4031 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
4032 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
4033 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
4034 if (Subtarget->isMClass()) {
4035 // Only a full system barrier exists in the M-class architectures.
4036 Domain = ARM_MB::SY;
4037 } else if (Subtarget->preferISHSTBarriers() &&
4038 Ord == AtomicOrdering::Release) {
4039 // Swift happens to implement ISHST barriers in a way that's compatible with
4040 // Release semantics but weaker than ISH so we'd be fools not to use
4041 // it. Beware: other processors probably don't!
4042 Domain = ARM_MB::ISHST;
4043 }
4044
4045 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4046 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4047 DAG.getConstant(Domain, dl, MVT::i32));
4048 }
4049
LowerPREFETCH(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)4050 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4051 const ARMSubtarget *Subtarget) {
4052 // ARM pre v5TE and Thumb1 does not have preload instructions.
4053 if (!(Subtarget->isThumb2() ||
4054 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4055 // Just preserve the chain.
4056 return Op.getOperand(0);
4057
4058 SDLoc dl(Op);
4059 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
4060 if (!isRead &&
4061 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4062 // ARMv7 with MP extension has PLDW.
4063 return Op.getOperand(0);
4064
4065 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4066 if (Subtarget->isThumb()) {
4067 // Invert the bits.
4068 isRead = ~isRead & 1;
4069 isData = ~isData & 1;
4070 }
4071
4072 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4073 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4074 DAG.getConstant(isData, dl, MVT::i32));
4075 }
4076
LowerVASTART(SDValue Op,SelectionDAG & DAG)4077 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4078 MachineFunction &MF = DAG.getMachineFunction();
4079 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4080
4081 // vastart just stores the address of the VarArgsFrameIndex slot into the
4082 // memory location argument.
4083 SDLoc dl(Op);
4084 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4085 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4086 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4087 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4088 MachinePointerInfo(SV));
4089 }
4090
GetF64FormalArgument(CCValAssign & VA,CCValAssign & NextVA,SDValue & Root,SelectionDAG & DAG,const SDLoc & dl) const4091 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4092 CCValAssign &NextVA,
4093 SDValue &Root,
4094 SelectionDAG &DAG,
4095 const SDLoc &dl) const {
4096 MachineFunction &MF = DAG.getMachineFunction();
4097 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4098
4099 const TargetRegisterClass *RC;
4100 if (AFI->isThumb1OnlyFunction())
4101 RC = &ARM::tGPRRegClass;
4102 else
4103 RC = &ARM::GPRRegClass;
4104
4105 // Transform the arguments stored in physical registers into virtual ones.
4106 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4107 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4108
4109 SDValue ArgValue2;
4110 if (NextVA.isMemLoc()) {
4111 MachineFrameInfo &MFI = MF.getFrameInfo();
4112 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4113
4114 // Create load node to retrieve arguments from the stack.
4115 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4116 ArgValue2 = DAG.getLoad(
4117 MVT::i32, dl, Root, FIN,
4118 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4119 } else {
4120 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4121 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4122 }
4123 if (!Subtarget->isLittle())
4124 std::swap (ArgValue, ArgValue2);
4125 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4126 }
4127
4128 // The remaining GPRs hold either the beginning of variable-argument
4129 // data, or the beginning of an aggregate passed by value (usually
4130 // byval). Either way, we allocate stack slots adjacent to the data
4131 // provided by our caller, and store the unallocated registers there.
4132 // If this is a variadic function, the va_list pointer will begin with
4133 // these values; otherwise, this reassembles a (byval) structure that
4134 // was split between registers and memory.
4135 // Return: The frame index registers were stored into.
StoreByValRegs(CCState & CCInfo,SelectionDAG & DAG,const SDLoc & dl,SDValue & Chain,const Value * OrigArg,unsigned InRegsParamRecordIdx,int ArgOffset,unsigned ArgSize) const4136 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4137 const SDLoc &dl, SDValue &Chain,
4138 const Value *OrigArg,
4139 unsigned InRegsParamRecordIdx,
4140 int ArgOffset, unsigned ArgSize) const {
4141 // Currently, two use-cases possible:
4142 // Case #1. Non-var-args function, and we meet first byval parameter.
4143 // Setup first unallocated register as first byval register;
4144 // eat all remained registers
4145 // (these two actions are performed by HandleByVal method).
4146 // Then, here, we initialize stack frame with
4147 // "store-reg" instructions.
4148 // Case #2. Var-args function, that doesn't contain byval parameters.
4149 // The same: eat all remained unallocated registers,
4150 // initialize stack frame.
4151
4152 MachineFunction &MF = DAG.getMachineFunction();
4153 MachineFrameInfo &MFI = MF.getFrameInfo();
4154 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4155 unsigned RBegin, REnd;
4156 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4157 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4158 } else {
4159 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4160 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4161 REnd = ARM::R4;
4162 }
4163
4164 if (REnd != RBegin)
4165 ArgOffset = -4 * (ARM::R4 - RBegin);
4166
4167 auto PtrVT = getPointerTy(DAG.getDataLayout());
4168 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4169 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4170
4171 SmallVector<SDValue, 4> MemOps;
4172 const TargetRegisterClass *RC =
4173 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4174
4175 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4176 unsigned VReg = MF.addLiveIn(Reg, RC);
4177 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4178 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4179 MachinePointerInfo(OrigArg, 4 * i));
4180 MemOps.push_back(Store);
4181 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4182 }
4183
4184 if (!MemOps.empty())
4185 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4186 return FrameIndex;
4187 }
4188
4189 // Setup stack frame, the va_list pointer will start from.
VarArgStyleRegisters(CCState & CCInfo,SelectionDAG & DAG,const SDLoc & dl,SDValue & Chain,unsigned ArgOffset,unsigned TotalArgRegsSaveSize,bool ForceMutable) const4190 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4191 const SDLoc &dl, SDValue &Chain,
4192 unsigned ArgOffset,
4193 unsigned TotalArgRegsSaveSize,
4194 bool ForceMutable) const {
4195 MachineFunction &MF = DAG.getMachineFunction();
4196 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4197
4198 // Try to store any remaining integer argument regs
4199 // to their spots on the stack so that they may be loaded by dereferencing
4200 // the result of va_next.
4201 // If there is no regs to be stored, just point address after last
4202 // argument passed via stack.
4203 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4204 CCInfo.getInRegsParamsCount(),
4205 CCInfo.getNextStackOffset(),
4206 std::max(4U, TotalArgRegsSaveSize));
4207 AFI->setVarArgsFrameIndex(FrameIndex);
4208 }
4209
splitValueIntoRegisterParts(SelectionDAG & DAG,const SDLoc & DL,SDValue Val,SDValue * Parts,unsigned NumParts,MVT PartVT,Optional<CallingConv::ID> CC) const4210 bool ARMTargetLowering::splitValueIntoRegisterParts(
4211 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4212 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
4213 bool IsABIRegCopy = CC.hasValue();
4214 EVT ValueVT = Val.getValueType();
4215 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4216 PartVT == MVT::f32) {
4217 unsigned ValueBits = ValueVT.getSizeInBits();
4218 unsigned PartBits = PartVT.getSizeInBits();
4219 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4220 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4221 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4222 Parts[0] = Val;
4223 return true;
4224 }
4225 return false;
4226 }
4227
joinRegisterPartsIntoValue(SelectionDAG & DAG,const SDLoc & DL,const SDValue * Parts,unsigned NumParts,MVT PartVT,EVT ValueVT,Optional<CallingConv::ID> CC) const4228 SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4229 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4230 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
4231 bool IsABIRegCopy = CC.hasValue();
4232 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4233 PartVT == MVT::f32) {
4234 unsigned ValueBits = ValueVT.getSizeInBits();
4235 unsigned PartBits = PartVT.getSizeInBits();
4236 SDValue Val = Parts[0];
4237
4238 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4239 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4240 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4241 return Val;
4242 }
4243 return SDValue();
4244 }
4245
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const4246 SDValue ARMTargetLowering::LowerFormalArguments(
4247 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4248 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4249 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4250 MachineFunction &MF = DAG.getMachineFunction();
4251 MachineFrameInfo &MFI = MF.getFrameInfo();
4252
4253 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4254
4255 // Assign locations to all of the incoming arguments.
4256 SmallVector<CCValAssign, 16> ArgLocs;
4257 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4258 *DAG.getContext());
4259 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4260
4261 SmallVector<SDValue, 16> ArgValues;
4262 SDValue ArgValue;
4263 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4264 unsigned CurArgIdx = 0;
4265
4266 // Initially ArgRegsSaveSize is zero.
4267 // Then we increase this value each time we meet byval parameter.
4268 // We also increase this value in case of varargs function.
4269 AFI->setArgRegsSaveSize(0);
4270
4271 // Calculate the amount of stack space that we need to allocate to store
4272 // byval and variadic arguments that are passed in registers.
4273 // We need to know this before we allocate the first byval or variadic
4274 // argument, as they will be allocated a stack slot below the CFA (Canonical
4275 // Frame Address, the stack pointer at entry to the function).
4276 unsigned ArgRegBegin = ARM::R4;
4277 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4278 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4279 break;
4280
4281 CCValAssign &VA = ArgLocs[i];
4282 unsigned Index = VA.getValNo();
4283 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4284 if (!Flags.isByVal())
4285 continue;
4286
4287 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4288 unsigned RBegin, REnd;
4289 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4290 ArgRegBegin = std::min(ArgRegBegin, RBegin);
4291
4292 CCInfo.nextInRegsParam();
4293 }
4294 CCInfo.rewindByValRegsInfo();
4295
4296 int lastInsIndex = -1;
4297 if (isVarArg && MFI.hasVAStart()) {
4298 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4299 if (RegIdx != array_lengthof(GPRArgRegs))
4300 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4301 }
4302
4303 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4304 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4305 auto PtrVT = getPointerTy(DAG.getDataLayout());
4306
4307 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4308 CCValAssign &VA = ArgLocs[i];
4309 if (Ins[VA.getValNo()].isOrigArg()) {
4310 std::advance(CurOrigArg,
4311 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4312 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4313 }
4314 // Arguments stored in registers.
4315 if (VA.isRegLoc()) {
4316 EVT RegVT = VA.getLocVT();
4317
4318 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4319 // f64 and vector types are split up into multiple registers or
4320 // combinations of registers and stack slots.
4321 SDValue ArgValue1 =
4322 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4323 VA = ArgLocs[++i]; // skip ahead to next loc
4324 SDValue ArgValue2;
4325 if (VA.isMemLoc()) {
4326 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4327 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4328 ArgValue2 = DAG.getLoad(
4329 MVT::f64, dl, Chain, FIN,
4330 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4331 } else {
4332 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4333 }
4334 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4335 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4336 ArgValue1, DAG.getIntPtrConstant(0, dl));
4337 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4338 ArgValue2, DAG.getIntPtrConstant(1, dl));
4339 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4340 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4341 } else {
4342 const TargetRegisterClass *RC;
4343
4344 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4345 RC = &ARM::HPRRegClass;
4346 else if (RegVT == MVT::f32)
4347 RC = &ARM::SPRRegClass;
4348 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4349 RegVT == MVT::v4bf16)
4350 RC = &ARM::DPRRegClass;
4351 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4352 RegVT == MVT::v8bf16)
4353 RC = &ARM::QPRRegClass;
4354 else if (RegVT == MVT::i32)
4355 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4356 : &ARM::GPRRegClass;
4357 else
4358 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4359
4360 // Transform the arguments in physical registers into virtual ones.
4361 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4362 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4363
4364 // If this value is passed in r0 and has the returned attribute (e.g.
4365 // C++ 'structors), record this fact for later use.
4366 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4367 AFI->setPreservesR0();
4368 }
4369 }
4370
4371 // If this is an 8 or 16-bit value, it is really passed promoted
4372 // to 32 bits. Insert an assert[sz]ext to capture this, then
4373 // truncate to the right size.
4374 switch (VA.getLocInfo()) {
4375 default: llvm_unreachable("Unknown loc info!");
4376 case CCValAssign::Full: break;
4377 case CCValAssign::BCvt:
4378 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4379 break;
4380 case CCValAssign::SExt:
4381 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4382 DAG.getValueType(VA.getValVT()));
4383 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4384 break;
4385 case CCValAssign::ZExt:
4386 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4387 DAG.getValueType(VA.getValVT()));
4388 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4389 break;
4390 }
4391
4392 // f16 arguments have their size extended to 4 bytes and passed as if they
4393 // had been copied to the LSBs of a 32-bit register.
4394 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4395 if (VA.needsCustom() &&
4396 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4397 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4398
4399 InVals.push_back(ArgValue);
4400 } else { // VA.isRegLoc()
4401 // sanity check
4402 assert(VA.isMemLoc());
4403 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4404
4405 int index = VA.getValNo();
4406
4407 // Some Ins[] entries become multiple ArgLoc[] entries.
4408 // Process them only once.
4409 if (index != lastInsIndex)
4410 {
4411 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4412 // FIXME: For now, all byval parameter objects are marked mutable.
4413 // This can be changed with more analysis.
4414 // In case of tail call optimization mark all arguments mutable.
4415 // Since they could be overwritten by lowering of arguments in case of
4416 // a tail call.
4417 if (Flags.isByVal()) {
4418 assert(Ins[index].isOrigArg() &&
4419 "Byval arguments cannot be implicit");
4420 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4421
4422 int FrameIndex = StoreByValRegs(
4423 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4424 VA.getLocMemOffset(), Flags.getByValSize());
4425 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4426 CCInfo.nextInRegsParam();
4427 } else {
4428 unsigned FIOffset = VA.getLocMemOffset();
4429 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4430 FIOffset, true);
4431
4432 // Create load nodes to retrieve arguments from the stack.
4433 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4434 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4435 MachinePointerInfo::getFixedStack(
4436 DAG.getMachineFunction(), FI)));
4437 }
4438 lastInsIndex = index;
4439 }
4440 }
4441 }
4442
4443 // varargs
4444 if (isVarArg && MFI.hasVAStart()) {
4445 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(),
4446 TotalArgRegsSaveSize);
4447 if (AFI->isCmseNSEntryFunction()) {
4448 DiagnosticInfoUnsupported Diag(
4449 DAG.getMachineFunction().getFunction(),
4450 "secure entry function must not be variadic", dl.getDebugLoc());
4451 DAG.getContext()->diagnose(Diag);
4452 }
4453 }
4454
4455 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4456
4457 if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) {
4458 DiagnosticInfoUnsupported Diag(
4459 DAG.getMachineFunction().getFunction(),
4460 "secure entry function requires arguments on stack", dl.getDebugLoc());
4461 DAG.getContext()->diagnose(Diag);
4462 }
4463
4464 return Chain;
4465 }
4466
4467 /// isFloatingPointZero - Return true if this is +0.0.
isFloatingPointZero(SDValue Op)4468 static bool isFloatingPointZero(SDValue Op) {
4469 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4470 return CFP->getValueAPF().isPosZero();
4471 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4472 // Maybe this has already been legalized into the constant pool?
4473 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4474 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4475 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4476 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4477 return CFP->getValueAPF().isPosZero();
4478 }
4479 } else if (Op->getOpcode() == ISD::BITCAST &&
4480 Op->getValueType(0) == MVT::f64) {
4481 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4482 // created by LowerConstantFP().
4483 SDValue BitcastOp = Op->getOperand(0);
4484 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4485 isNullConstant(BitcastOp->getOperand(0)))
4486 return true;
4487 }
4488 return false;
4489 }
4490
4491 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4492 /// the given operands.
getARMCmp(SDValue LHS,SDValue RHS,ISD::CondCode CC,SDValue & ARMcc,SelectionDAG & DAG,const SDLoc & dl) const4493 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4494 SDValue &ARMcc, SelectionDAG &DAG,
4495 const SDLoc &dl) const {
4496 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4497 unsigned C = RHSC->getZExtValue();
4498 if (!isLegalICmpImmediate((int32_t)C)) {
4499 // Constant does not fit, try adjusting it by one.
4500 switch (CC) {
4501 default: break;
4502 case ISD::SETLT:
4503 case ISD::SETGE:
4504 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4505 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4506 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4507 }
4508 break;
4509 case ISD::SETULT:
4510 case ISD::SETUGE:
4511 if (C != 0 && isLegalICmpImmediate(C-1)) {
4512 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4513 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4514 }
4515 break;
4516 case ISD::SETLE:
4517 case ISD::SETGT:
4518 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4519 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4520 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4521 }
4522 break;
4523 case ISD::SETULE:
4524 case ISD::SETUGT:
4525 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4526 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4527 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4528 }
4529 break;
4530 }
4531 }
4532 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4533 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4534 // In ARM and Thumb-2, the compare instructions can shift their second
4535 // operand.
4536 CC = ISD::getSetCCSwappedOperands(CC);
4537 std::swap(LHS, RHS);
4538 }
4539
4540 // Thumb1 has very limited immediate modes, so turning an "and" into a
4541 // shift can save multiple instructions.
4542 //
4543 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4544 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4545 // own. If it's the operand to an unsigned comparison with an immediate,
4546 // we can eliminate one of the shifts: we transform
4547 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4548 //
4549 // We avoid transforming cases which aren't profitable due to encoding
4550 // details:
4551 //
4552 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4553 // would not; in that case, we're essentially trading one immediate load for
4554 // another.
4555 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4556 // 3. C2 is zero; we have other code for this special case.
4557 //
4558 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4559 // instruction, since the AND is always one instruction anyway, but we could
4560 // use narrow instructions in some cases.
4561 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4562 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4563 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4564 !isSignedIntSetCC(CC)) {
4565 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4566 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4567 uint64_t RHSV = RHSC->getZExtValue();
4568 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4569 unsigned ShiftBits = countLeadingZeros(Mask);
4570 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4571 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4572 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4573 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4574 }
4575 }
4576 }
4577
4578 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4579 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4580 // way a cmp would.
4581 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4582 // some tweaks to the heuristics for the previous and->shift transform.
4583 // FIXME: Optimize cases where the LHS isn't a shift.
4584 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4585 isa<ConstantSDNode>(RHS) &&
4586 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4587 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4588 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4589 unsigned ShiftAmt =
4590 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4591 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4592 DAG.getVTList(MVT::i32, MVT::i32),
4593 LHS.getOperand(0),
4594 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4595 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4596 Shift.getValue(1), SDValue());
4597 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4598 return Chain.getValue(1);
4599 }
4600
4601 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4602
4603 // If the RHS is a constant zero then the V (overflow) flag will never be
4604 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4605 // simpler for other passes (like the peephole optimiser) to deal with.
4606 if (isNullConstant(RHS)) {
4607 switch (CondCode) {
4608 default: break;
4609 case ARMCC::GE:
4610 CondCode = ARMCC::PL;
4611 break;
4612 case ARMCC::LT:
4613 CondCode = ARMCC::MI;
4614 break;
4615 }
4616 }
4617
4618 ARMISD::NodeType CompareType;
4619 switch (CondCode) {
4620 default:
4621 CompareType = ARMISD::CMP;
4622 break;
4623 case ARMCC::EQ:
4624 case ARMCC::NE:
4625 // Uses only Z Flag
4626 CompareType = ARMISD::CMPZ;
4627 break;
4628 }
4629 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4630 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4631 }
4632
4633 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
getVFPCmp(SDValue LHS,SDValue RHS,SelectionDAG & DAG,const SDLoc & dl,bool Signaling) const4634 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4635 SelectionDAG &DAG, const SDLoc &dl,
4636 bool Signaling) const {
4637 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4638 SDValue Cmp;
4639 if (!isFloatingPointZero(RHS))
4640 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4641 dl, MVT::Glue, LHS, RHS);
4642 else
4643 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4644 dl, MVT::Glue, LHS);
4645 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4646 }
4647
4648 /// duplicateCmp - Glue values can have only one use, so this function
4649 /// duplicates a comparison node.
4650 SDValue
duplicateCmp(SDValue Cmp,SelectionDAG & DAG) const4651 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4652 unsigned Opc = Cmp.getOpcode();
4653 SDLoc DL(Cmp);
4654 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4655 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4656
4657 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4658 Cmp = Cmp.getOperand(0);
4659 Opc = Cmp.getOpcode();
4660 if (Opc == ARMISD::CMPFP)
4661 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4662 else {
4663 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4664 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4665 }
4666 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4667 }
4668
4669 // This function returns three things: the arithmetic computation itself
4670 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4671 // comparison and the condition code define the case in which the arithmetic
4672 // computation *does not* overflow.
4673 std::pair<SDValue, SDValue>
getARMXALUOOp(SDValue Op,SelectionDAG & DAG,SDValue & ARMcc) const4674 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4675 SDValue &ARMcc) const {
4676 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4677
4678 SDValue Value, OverflowCmp;
4679 SDValue LHS = Op.getOperand(0);
4680 SDValue RHS = Op.getOperand(1);
4681 SDLoc dl(Op);
4682
4683 // FIXME: We are currently always generating CMPs because we don't support
4684 // generating CMN through the backend. This is not as good as the natural
4685 // CMP case because it causes a register dependency and cannot be folded
4686 // later.
4687
4688 switch (Op.getOpcode()) {
4689 default:
4690 llvm_unreachable("Unknown overflow instruction!");
4691 case ISD::SADDO:
4692 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4693 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4694 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4695 break;
4696 case ISD::UADDO:
4697 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4698 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4699 // We do not use it in the USUBO case as Value may not be used.
4700 Value = DAG.getNode(ARMISD::ADDC, dl,
4701 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4702 .getValue(0);
4703 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4704 break;
4705 case ISD::SSUBO:
4706 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4707 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4708 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4709 break;
4710 case ISD::USUBO:
4711 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4712 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4713 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4714 break;
4715 case ISD::UMULO:
4716 // We generate a UMUL_LOHI and then check if the high word is 0.
4717 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4718 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4719 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4720 LHS, RHS);
4721 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4722 DAG.getConstant(0, dl, MVT::i32));
4723 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4724 break;
4725 case ISD::SMULO:
4726 // We generate a SMUL_LOHI and then check if all the bits of the high word
4727 // are the same as the sign bit of the low word.
4728 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4729 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4730 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4731 LHS, RHS);
4732 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4733 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4734 Value.getValue(0),
4735 DAG.getConstant(31, dl, MVT::i32)));
4736 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4737 break;
4738 } // switch (...)
4739
4740 return std::make_pair(Value, OverflowCmp);
4741 }
4742
4743 SDValue
LowerSignedALUO(SDValue Op,SelectionDAG & DAG) const4744 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4745 // Let legalize expand this if it isn't a legal type yet.
4746 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4747 return SDValue();
4748
4749 SDValue Value, OverflowCmp;
4750 SDValue ARMcc;
4751 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4752 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4753 SDLoc dl(Op);
4754 // We use 0 and 1 as false and true values.
4755 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4756 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4757 EVT VT = Op.getValueType();
4758
4759 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4760 ARMcc, CCR, OverflowCmp);
4761
4762 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4763 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4764 }
4765
ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,SelectionDAG & DAG)4766 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4767 SelectionDAG &DAG) {
4768 SDLoc DL(BoolCarry);
4769 EVT CarryVT = BoolCarry.getValueType();
4770
4771 // This converts the boolean value carry into the carry flag by doing
4772 // ARMISD::SUBC Carry, 1
4773 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4774 DAG.getVTList(CarryVT, MVT::i32),
4775 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4776 return Carry.getValue(1);
4777 }
4778
ConvertCarryFlagToBooleanCarry(SDValue Flags,EVT VT,SelectionDAG & DAG)4779 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4780 SelectionDAG &DAG) {
4781 SDLoc DL(Flags);
4782
4783 // Now convert the carry flag into a boolean carry. We do this
4784 // using ARMISD:ADDE 0, 0, Carry
4785 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4786 DAG.getConstant(0, DL, MVT::i32),
4787 DAG.getConstant(0, DL, MVT::i32), Flags);
4788 }
4789
LowerUnsignedALUO(SDValue Op,SelectionDAG & DAG) const4790 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4791 SelectionDAG &DAG) const {
4792 // Let legalize expand this if it isn't a legal type yet.
4793 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4794 return SDValue();
4795
4796 SDValue LHS = Op.getOperand(0);
4797 SDValue RHS = Op.getOperand(1);
4798 SDLoc dl(Op);
4799
4800 EVT VT = Op.getValueType();
4801 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4802 SDValue Value;
4803 SDValue Overflow;
4804 switch (Op.getOpcode()) {
4805 default:
4806 llvm_unreachable("Unknown overflow instruction!");
4807 case ISD::UADDO:
4808 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4809 // Convert the carry flag into a boolean value.
4810 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4811 break;
4812 case ISD::USUBO: {
4813 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4814 // Convert the carry flag into a boolean value.
4815 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4816 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4817 // value. So compute 1 - C.
4818 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4819 DAG.getConstant(1, dl, MVT::i32), Overflow);
4820 break;
4821 }
4822 }
4823
4824 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4825 }
4826
LowerSADDSUBSAT(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)4827 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4828 const ARMSubtarget *Subtarget) {
4829 EVT VT = Op.getValueType();
4830 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
4831 return SDValue();
4832 if (!VT.isSimple())
4833 return SDValue();
4834
4835 unsigned NewOpcode;
4836 bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4837 switch (VT.getSimpleVT().SimpleTy) {
4838 default:
4839 return SDValue();
4840 case MVT::i8:
4841 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4842 break;
4843 case MVT::i16:
4844 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4845 break;
4846 }
4847
4848 SDLoc dl(Op);
4849 SDValue Add =
4850 DAG.getNode(NewOpcode, dl, MVT::i32,
4851 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4852 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4853 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4854 }
4855
LowerSELECT(SDValue Op,SelectionDAG & DAG) const4856 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4857 SDValue Cond = Op.getOperand(0);
4858 SDValue SelectTrue = Op.getOperand(1);
4859 SDValue SelectFalse = Op.getOperand(2);
4860 SDLoc dl(Op);
4861 unsigned Opc = Cond.getOpcode();
4862
4863 if (Cond.getResNo() == 1 &&
4864 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4865 Opc == ISD::USUBO)) {
4866 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4867 return SDValue();
4868
4869 SDValue Value, OverflowCmp;
4870 SDValue ARMcc;
4871 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4872 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4873 EVT VT = Op.getValueType();
4874
4875 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4876 OverflowCmp, DAG);
4877 }
4878
4879 // Convert:
4880 //
4881 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4882 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4883 //
4884 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4885 const ConstantSDNode *CMOVTrue =
4886 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4887 const ConstantSDNode *CMOVFalse =
4888 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4889
4890 if (CMOVTrue && CMOVFalse) {
4891 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4892 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4893
4894 SDValue True;
4895 SDValue False;
4896 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4897 True = SelectTrue;
4898 False = SelectFalse;
4899 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4900 True = SelectFalse;
4901 False = SelectTrue;
4902 }
4903
4904 if (True.getNode() && False.getNode()) {
4905 EVT VT = Op.getValueType();
4906 SDValue ARMcc = Cond.getOperand(2);
4907 SDValue CCR = Cond.getOperand(3);
4908 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4909 assert(True.getValueType() == VT);
4910 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4911 }
4912 }
4913 }
4914
4915 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4916 // undefined bits before doing a full-word comparison with zero.
4917 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4918 DAG.getConstant(1, dl, Cond.getValueType()));
4919
4920 return DAG.getSelectCC(dl, Cond,
4921 DAG.getConstant(0, dl, Cond.getValueType()),
4922 SelectTrue, SelectFalse, ISD::SETNE);
4923 }
4924
checkVSELConstraints(ISD::CondCode CC,ARMCC::CondCodes & CondCode,bool & swpCmpOps,bool & swpVselOps)4925 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4926 bool &swpCmpOps, bool &swpVselOps) {
4927 // Start by selecting the GE condition code for opcodes that return true for
4928 // 'equality'
4929 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4930 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4931 CondCode = ARMCC::GE;
4932
4933 // and GT for opcodes that return false for 'equality'.
4934 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4935 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4936 CondCode = ARMCC::GT;
4937
4938 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4939 // to swap the compare operands.
4940 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4941 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4942 swpCmpOps = true;
4943
4944 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4945 // If we have an unordered opcode, we need to swap the operands to the VSEL
4946 // instruction (effectively negating the condition).
4947 //
4948 // This also has the effect of swapping which one of 'less' or 'greater'
4949 // returns true, so we also swap the compare operands. It also switches
4950 // whether we return true for 'equality', so we compensate by picking the
4951 // opposite condition code to our original choice.
4952 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4953 CC == ISD::SETUGT) {
4954 swpCmpOps = !swpCmpOps;
4955 swpVselOps = !swpVselOps;
4956 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4957 }
4958
4959 // 'ordered' is 'anything but unordered', so use the VS condition code and
4960 // swap the VSEL operands.
4961 if (CC == ISD::SETO) {
4962 CondCode = ARMCC::VS;
4963 swpVselOps = true;
4964 }
4965
4966 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4967 // code and swap the VSEL operands. Also do this if we don't care about the
4968 // unordered case.
4969 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4970 CondCode = ARMCC::EQ;
4971 swpVselOps = true;
4972 }
4973 }
4974
getCMOV(const SDLoc & dl,EVT VT,SDValue FalseVal,SDValue TrueVal,SDValue ARMcc,SDValue CCR,SDValue Cmp,SelectionDAG & DAG) const4975 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4976 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4977 SDValue Cmp, SelectionDAG &DAG) const {
4978 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4979 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4980 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4981 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4982 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4983
4984 SDValue TrueLow = TrueVal.getValue(0);
4985 SDValue TrueHigh = TrueVal.getValue(1);
4986 SDValue FalseLow = FalseVal.getValue(0);
4987 SDValue FalseHigh = FalseVal.getValue(1);
4988
4989 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4990 ARMcc, CCR, Cmp);
4991 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4992 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4993
4994 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4995 } else {
4996 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4997 Cmp);
4998 }
4999 }
5000
isGTorGE(ISD::CondCode CC)5001 static bool isGTorGE(ISD::CondCode CC) {
5002 return CC == ISD::SETGT || CC == ISD::SETGE;
5003 }
5004
isLTorLE(ISD::CondCode CC)5005 static bool isLTorLE(ISD::CondCode CC) {
5006 return CC == ISD::SETLT || CC == ISD::SETLE;
5007 }
5008
5009 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5010 // All of these conditions (and their <= and >= counterparts) will do:
5011 // x < k ? k : x
5012 // x > k ? x : k
5013 // k < x ? x : k
5014 // k > x ? k : x
isLowerSaturate(const SDValue LHS,const SDValue RHS,const SDValue TrueVal,const SDValue FalseVal,const ISD::CondCode CC,const SDValue K)5015 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5016 const SDValue TrueVal, const SDValue FalseVal,
5017 const ISD::CondCode CC, const SDValue K) {
5018 return (isGTorGE(CC) &&
5019 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5020 (isLTorLE(CC) &&
5021 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5022 }
5023
5024 // Check if two chained conditionals could be converted into SSAT or USAT.
5025 //
5026 // SSAT can replace a set of two conditional selectors that bound a number to an
5027 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5028 //
5029 // x < -k ? -k : (x > k ? k : x)
5030 // x < -k ? -k : (x < k ? x : k)
5031 // x > -k ? (x > k ? k : x) : -k
5032 // x < k ? (x < -k ? -k : x) : k
5033 // etc.
5034 //
5035 // LLVM canonicalizes these to either a min(max()) or a max(min())
5036 // pattern. This function tries to match one of these and will return true
5037 // if successful.
5038 //
5039 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
5040 // a power of 2.
5041 //
5042 // It returns true if the conversion can be done, false otherwise.
5043 // Additionally, the variable is returned in parameter V, the constant in K and
5044 // usat is set to true if the conditional represents an unsigned saturation
isSaturatingConditional(const SDValue & Op,SDValue & V,uint64_t & K,bool & Usat)5045 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
5046 uint64_t &K, bool &Usat) {
5047 SDValue V1 = Op.getOperand(0);
5048 SDValue K1 = Op.getOperand(1);
5049 SDValue TrueVal1 = Op.getOperand(2);
5050 SDValue FalseVal1 = Op.getOperand(3);
5051 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5052
5053 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5054 if (Op2.getOpcode() != ISD::SELECT_CC)
5055 return false;
5056
5057 SDValue V2 = Op2.getOperand(0);
5058 SDValue K2 = Op2.getOperand(1);
5059 SDValue TrueVal2 = Op2.getOperand(2);
5060 SDValue FalseVal2 = Op2.getOperand(3);
5061 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5062
5063 SDValue V1Tmp = V1;
5064 SDValue V2Tmp = V2;
5065
5066 if (V1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5067 V2.getOpcode() == ISD::SIGN_EXTEND_INREG) {
5068 V1Tmp = V1.getOperand(0);
5069 V2Tmp = V2.getOperand(0);
5070 }
5071
5072 // Check that the registers and the constants match a max(min()) or min(max())
5073 // pattern
5074 if (V1Tmp == TrueVal1 && V2Tmp == TrueVal2 && K1 == FalseVal1 &&
5075 K2 == FalseVal2 &&
5076 ((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2)))) {
5077
5078 // Check that the constant in the lower-bound check is
5079 // the opposite of the constant in the upper-bound check
5080 // in 1's complement.
5081 if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2))
5082 return false;
5083
5084 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5085 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5086 int64_t PosVal = std::max(Val1, Val2);
5087 int64_t NegVal = std::min(Val1, Val2);
5088
5089 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5090 !isPowerOf2_64(PosVal + 1))
5091 return false;
5092
5093 // Handle the difference between USAT (unsigned) and SSAT (signed)
5094 // saturation
5095 if (Val1 == ~Val2)
5096 Usat = false;
5097 else if (NegVal == 0)
5098 Usat = true;
5099 else
5100 return false;
5101
5102 V = V2Tmp;
5103 // At this point, PosVal is guaranteed to be positive
5104 K = (uint64_t) PosVal;
5105
5106 return true;
5107 }
5108 return false;
5109 }
5110
5111 // Check if a condition of the type x < k ? k : x can be converted into a
5112 // bit operation instead of conditional moves.
5113 // Currently this is allowed given:
5114 // - The conditions and values match up
5115 // - k is 0 or -1 (all ones)
5116 // This function will not check the last condition, thats up to the caller
5117 // It returns true if the transformation can be made, and in such case
5118 // returns x in V, and k in SatK.
isLowerSaturatingConditional(const SDValue & Op,SDValue & V,SDValue & SatK)5119 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5120 SDValue &SatK)
5121 {
5122 SDValue LHS = Op.getOperand(0);
5123 SDValue RHS = Op.getOperand(1);
5124 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5125 SDValue TrueVal = Op.getOperand(2);
5126 SDValue FalseVal = Op.getOperand(3);
5127
5128 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
5129 ? &RHS
5130 : nullptr;
5131
5132 // No constant operation in comparison, early out
5133 if (!K)
5134 return false;
5135
5136 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5137 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5138 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5139
5140 // If the constant on left and right side, or variable on left and right,
5141 // does not match, early out
5142 if (*K != KTmp || V != VTmp)
5143 return false;
5144
5145 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5146 SatK = *K;
5147 return true;
5148 }
5149
5150 return false;
5151 }
5152
isUnsupportedFloatingType(EVT VT) const5153 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5154 if (VT == MVT::f32)
5155 return !Subtarget->hasVFP2Base();
5156 if (VT == MVT::f64)
5157 return !Subtarget->hasFP64();
5158 if (VT == MVT::f16)
5159 return !Subtarget->hasFullFP16();
5160 return false;
5161 }
5162
LowerSELECT_CC(SDValue Op,SelectionDAG & DAG) const5163 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5164 EVT VT = Op.getValueType();
5165 SDLoc dl(Op);
5166
5167 // Try to convert two saturating conditional selects into a single SSAT
5168 SDValue SatValue;
5169 uint64_t SatConstant;
5170 bool SatUSat;
5171 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
5172 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
5173 if (SatUSat)
5174 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
5175 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5176 else
5177 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
5178 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5179 }
5180
5181 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5182 // into more efficient bit operations, which is possible when k is 0 or -1
5183 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5184 // single instructions. On Thumb the shift and the bit operation will be two
5185 // instructions.
5186 // Only allow this transformation on full-width (32-bit) operations
5187 SDValue LowerSatConstant;
5188 if (VT == MVT::i32 &&
5189 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5190 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5191 DAG.getConstant(31, dl, VT));
5192 if (isNullConstant(LowerSatConstant)) {
5193 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5194 DAG.getAllOnesConstant(dl, VT));
5195 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5196 } else if (isAllOnesConstant(LowerSatConstant))
5197 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5198 }
5199
5200 SDValue LHS = Op.getOperand(0);
5201 SDValue RHS = Op.getOperand(1);
5202 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5203 SDValue TrueVal = Op.getOperand(2);
5204 SDValue FalseVal = Op.getOperand(3);
5205 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5206 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5207
5208 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5209 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5210 unsigned TVal = CTVal->getZExtValue();
5211 unsigned FVal = CFVal->getZExtValue();
5212 unsigned Opcode = 0;
5213
5214 if (TVal == ~FVal) {
5215 Opcode = ARMISD::CSINV;
5216 } else if (TVal == ~FVal + 1) {
5217 Opcode = ARMISD::CSNEG;
5218 } else if (TVal + 1 == FVal) {
5219 Opcode = ARMISD::CSINC;
5220 } else if (TVal == FVal + 1) {
5221 Opcode = ARMISD::CSINC;
5222 std::swap(TrueVal, FalseVal);
5223 std::swap(TVal, FVal);
5224 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5225 }
5226
5227 if (Opcode) {
5228 // If one of the constants is cheaper than another, materialise the
5229 // cheaper one and let the csel generate the other.
5230 if (Opcode != ARMISD::CSINC &&
5231 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5232 std::swap(TrueVal, FalseVal);
5233 std::swap(TVal, FVal);
5234 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5235 }
5236
5237 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5238 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5239 // -(-a) == a, but (a+1)+1 != a).
5240 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5241 std::swap(TrueVal, FalseVal);
5242 std::swap(TVal, FVal);
5243 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5244 }
5245 if (TVal == 0)
5246 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
5247
5248 // Drops F's value because we can get it by inverting/negating TVal.
5249 FalseVal = TrueVal;
5250
5251 SDValue ARMcc;
5252 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5253 EVT VT = TrueVal.getValueType();
5254 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5255 }
5256 }
5257
5258 if (isUnsupportedFloatingType(LHS.getValueType())) {
5259 DAG.getTargetLoweringInfo().softenSetCCOperands(
5260 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5261
5262 // If softenSetCCOperands only returned one value, we should compare it to
5263 // zero.
5264 if (!RHS.getNode()) {
5265 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5266 CC = ISD::SETNE;
5267 }
5268 }
5269
5270 if (LHS.getValueType() == MVT::i32) {
5271 // Try to generate VSEL on ARMv8.
5272 // The VSEL instruction can't use all the usual ARM condition
5273 // codes: it only has two bits to select the condition code, so it's
5274 // constrained to use only GE, GT, VS and EQ.
5275 //
5276 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5277 // swap the operands of the previous compare instruction (effectively
5278 // inverting the compare condition, swapping 'less' and 'greater') and
5279 // sometimes need to swap the operands to the VSEL (which inverts the
5280 // condition in the sense of firing whenever the previous condition didn't)
5281 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5282 TrueVal.getValueType() == MVT::f32 ||
5283 TrueVal.getValueType() == MVT::f64)) {
5284 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5285 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5286 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5287 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5288 std::swap(TrueVal, FalseVal);
5289 }
5290 }
5291
5292 SDValue ARMcc;
5293 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5294 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5295 // Choose GE over PL, which vsel does now support
5296 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5297 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5298 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5299 }
5300
5301 ARMCC::CondCodes CondCode, CondCode2;
5302 FPCCToARMCC(CC, CondCode, CondCode2);
5303
5304 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5305 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5306 // must use VSEL (limited condition codes), due to not having conditional f16
5307 // moves.
5308 if (Subtarget->hasFPARMv8Base() &&
5309 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5310 (TrueVal.getValueType() == MVT::f16 ||
5311 TrueVal.getValueType() == MVT::f32 ||
5312 TrueVal.getValueType() == MVT::f64)) {
5313 bool swpCmpOps = false;
5314 bool swpVselOps = false;
5315 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5316
5317 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5318 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5319 if (swpCmpOps)
5320 std::swap(LHS, RHS);
5321 if (swpVselOps)
5322 std::swap(TrueVal, FalseVal);
5323 }
5324 }
5325
5326 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5327 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5328 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5329 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5330 if (CondCode2 != ARMCC::AL) {
5331 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5332 // FIXME: Needs another CMP because flag can have but one use.
5333 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5334 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5335 }
5336 return Result;
5337 }
5338
5339 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5340 /// to morph to an integer compare sequence.
canChangeToInt(SDValue Op,bool & SeenZero,const ARMSubtarget * Subtarget)5341 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5342 const ARMSubtarget *Subtarget) {
5343 SDNode *N = Op.getNode();
5344 if (!N->hasOneUse())
5345 // Otherwise it requires moving the value from fp to integer registers.
5346 return false;
5347 if (!N->getNumValues())
5348 return false;
5349 EVT VT = Op.getValueType();
5350 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5351 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5352 // vmrs are very slow, e.g. cortex-a8.
5353 return false;
5354
5355 if (isFloatingPointZero(Op)) {
5356 SeenZero = true;
5357 return true;
5358 }
5359 return ISD::isNormalLoad(N);
5360 }
5361
bitcastf32Toi32(SDValue Op,SelectionDAG & DAG)5362 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5363 if (isFloatingPointZero(Op))
5364 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5365
5366 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5367 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5368 Ld->getPointerInfo(), Ld->getAlignment(),
5369 Ld->getMemOperand()->getFlags());
5370
5371 llvm_unreachable("Unknown VFP cmp argument!");
5372 }
5373
expandf64Toi32(SDValue Op,SelectionDAG & DAG,SDValue & RetVal1,SDValue & RetVal2)5374 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5375 SDValue &RetVal1, SDValue &RetVal2) {
5376 SDLoc dl(Op);
5377
5378 if (isFloatingPointZero(Op)) {
5379 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5380 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5381 return;
5382 }
5383
5384 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5385 SDValue Ptr = Ld->getBasePtr();
5386 RetVal1 =
5387 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5388 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5389
5390 EVT PtrType = Ptr.getValueType();
5391 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5392 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5393 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5394 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5395 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5396 Ld->getMemOperand()->getFlags());
5397 return;
5398 }
5399
5400 llvm_unreachable("Unknown VFP cmp argument!");
5401 }
5402
5403 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5404 /// f32 and even f64 comparisons to integer ones.
5405 SDValue
OptimizeVFPBrcond(SDValue Op,SelectionDAG & DAG) const5406 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5407 SDValue Chain = Op.getOperand(0);
5408 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5409 SDValue LHS = Op.getOperand(2);
5410 SDValue RHS = Op.getOperand(3);
5411 SDValue Dest = Op.getOperand(4);
5412 SDLoc dl(Op);
5413
5414 bool LHSSeenZero = false;
5415 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5416 bool RHSSeenZero = false;
5417 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5418 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5419 // If unsafe fp math optimization is enabled and there are no other uses of
5420 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5421 // to an integer comparison.
5422 if (CC == ISD::SETOEQ)
5423 CC = ISD::SETEQ;
5424 else if (CC == ISD::SETUNE)
5425 CC = ISD::SETNE;
5426
5427 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5428 SDValue ARMcc;
5429 if (LHS.getValueType() == MVT::f32) {
5430 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5431 bitcastf32Toi32(LHS, DAG), Mask);
5432 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5433 bitcastf32Toi32(RHS, DAG), Mask);
5434 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5435 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5436 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5437 Chain, Dest, ARMcc, CCR, Cmp);
5438 }
5439
5440 SDValue LHS1, LHS2;
5441 SDValue RHS1, RHS2;
5442 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5443 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5444 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5445 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5446 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5447 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5448 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5449 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5450 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5451 }
5452
5453 return SDValue();
5454 }
5455
LowerBRCOND(SDValue Op,SelectionDAG & DAG) const5456 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5457 SDValue Chain = Op.getOperand(0);
5458 SDValue Cond = Op.getOperand(1);
5459 SDValue Dest = Op.getOperand(2);
5460 SDLoc dl(Op);
5461
5462 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5463 // instruction.
5464 unsigned Opc = Cond.getOpcode();
5465 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5466 !Subtarget->isThumb1Only();
5467 if (Cond.getResNo() == 1 &&
5468 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5469 Opc == ISD::USUBO || OptimizeMul)) {
5470 // Only lower legal XALUO ops.
5471 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5472 return SDValue();
5473
5474 // The actual operation with overflow check.
5475 SDValue Value, OverflowCmp;
5476 SDValue ARMcc;
5477 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5478
5479 // Reverse the condition code.
5480 ARMCC::CondCodes CondCode =
5481 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5482 CondCode = ARMCC::getOppositeCondition(CondCode);
5483 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5484 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5485
5486 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5487 OverflowCmp);
5488 }
5489
5490 return SDValue();
5491 }
5492
LowerBR_CC(SDValue Op,SelectionDAG & DAG) const5493 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5494 SDValue Chain = Op.getOperand(0);
5495 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5496 SDValue LHS = Op.getOperand(2);
5497 SDValue RHS = Op.getOperand(3);
5498 SDValue Dest = Op.getOperand(4);
5499 SDLoc dl(Op);
5500
5501 if (isUnsupportedFloatingType(LHS.getValueType())) {
5502 DAG.getTargetLoweringInfo().softenSetCCOperands(
5503 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5504
5505 // If softenSetCCOperands only returned one value, we should compare it to
5506 // zero.
5507 if (!RHS.getNode()) {
5508 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5509 CC = ISD::SETNE;
5510 }
5511 }
5512
5513 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5514 // instruction.
5515 unsigned Opc = LHS.getOpcode();
5516 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5517 !Subtarget->isThumb1Only();
5518 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5519 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5520 Opc == ISD::USUBO || OptimizeMul) &&
5521 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5522 // Only lower legal XALUO ops.
5523 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5524 return SDValue();
5525
5526 // The actual operation with overflow check.
5527 SDValue Value, OverflowCmp;
5528 SDValue ARMcc;
5529 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5530
5531 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5532 // Reverse the condition code.
5533 ARMCC::CondCodes CondCode =
5534 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5535 CondCode = ARMCC::getOppositeCondition(CondCode);
5536 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5537 }
5538 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5539
5540 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5541 OverflowCmp);
5542 }
5543
5544 if (LHS.getValueType() == MVT::i32) {
5545 SDValue ARMcc;
5546 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5547 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5548 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5549 Chain, Dest, ARMcc, CCR, Cmp);
5550 }
5551
5552 if (getTargetMachine().Options.UnsafeFPMath &&
5553 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5554 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5555 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5556 return Result;
5557 }
5558
5559 ARMCC::CondCodes CondCode, CondCode2;
5560 FPCCToARMCC(CC, CondCode, CondCode2);
5561
5562 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5563 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5564 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5565 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5566 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5567 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5568 if (CondCode2 != ARMCC::AL) {
5569 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5570 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5571 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5572 }
5573 return Res;
5574 }
5575
LowerBR_JT(SDValue Op,SelectionDAG & DAG) const5576 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5577 SDValue Chain = Op.getOperand(0);
5578 SDValue Table = Op.getOperand(1);
5579 SDValue Index = Op.getOperand(2);
5580 SDLoc dl(Op);
5581
5582 EVT PTy = getPointerTy(DAG.getDataLayout());
5583 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5584 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5585 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5586 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5587 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5588 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5589 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5590 // which does another jump to the destination. This also makes it easier
5591 // to translate it to TBB / TBH later (Thumb2 only).
5592 // FIXME: This might not work if the function is extremely large.
5593 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5594 Addr, Op.getOperand(2), JTI);
5595 }
5596 if (isPositionIndependent() || Subtarget->isROPI()) {
5597 Addr =
5598 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5599 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5600 Chain = Addr.getValue(1);
5601 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5602 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5603 } else {
5604 Addr =
5605 DAG.getLoad(PTy, dl, Chain, Addr,
5606 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5607 Chain = Addr.getValue(1);
5608 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5609 }
5610 }
5611
LowerVectorFP_TO_INT(SDValue Op,SelectionDAG & DAG)5612 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5613 EVT VT = Op.getValueType();
5614 SDLoc dl(Op);
5615
5616 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5617 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5618 return Op;
5619 return DAG.UnrollVectorOp(Op.getNode());
5620 }
5621
5622 const bool HasFullFP16 =
5623 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5624
5625 EVT NewTy;
5626 const EVT OpTy = Op.getOperand(0).getValueType();
5627 if (OpTy == MVT::v4f32)
5628 NewTy = MVT::v4i32;
5629 else if (OpTy == MVT::v4f16 && HasFullFP16)
5630 NewTy = MVT::v4i16;
5631 else if (OpTy == MVT::v8f16 && HasFullFP16)
5632 NewTy = MVT::v8i16;
5633 else
5634 llvm_unreachable("Invalid type for custom lowering!");
5635
5636 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5637 return DAG.UnrollVectorOp(Op.getNode());
5638
5639 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5640 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5641 }
5642
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const5643 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5644 EVT VT = Op.getValueType();
5645 if (VT.isVector())
5646 return LowerVectorFP_TO_INT(Op, DAG);
5647
5648 bool IsStrict = Op->isStrictFPOpcode();
5649 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5650
5651 if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5652 RTLIB::Libcall LC;
5653 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5654 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5655 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5656 Op.getValueType());
5657 else
5658 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5659 Op.getValueType());
5660 SDLoc Loc(Op);
5661 MakeLibCallOptions CallOptions;
5662 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5663 SDValue Result;
5664 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5665 CallOptions, Loc, Chain);
5666 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5667 }
5668
5669 // FIXME: Remove this when we have strict fp instruction selection patterns
5670 if (IsStrict) {
5671 SDLoc Loc(Op);
5672 SDValue Result =
5673 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5674 : ISD::FP_TO_UINT,
5675 Loc, Op.getValueType(), SrcVal);
5676 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5677 }
5678
5679 return Op;
5680 }
5681
LowerVectorINT_TO_FP(SDValue Op,SelectionDAG & DAG)5682 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5683 EVT VT = Op.getValueType();
5684 SDLoc dl(Op);
5685
5686 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5687 if (VT.getVectorElementType() == MVT::f32)
5688 return Op;
5689 return DAG.UnrollVectorOp(Op.getNode());
5690 }
5691
5692 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5693 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5694 "Invalid type for custom lowering!");
5695
5696 const bool HasFullFP16 =
5697 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5698
5699 EVT DestVecType;
5700 if (VT == MVT::v4f32)
5701 DestVecType = MVT::v4i32;
5702 else if (VT == MVT::v4f16 && HasFullFP16)
5703 DestVecType = MVT::v4i16;
5704 else if (VT == MVT::v8f16 && HasFullFP16)
5705 DestVecType = MVT::v8i16;
5706 else
5707 return DAG.UnrollVectorOp(Op.getNode());
5708
5709 unsigned CastOpc;
5710 unsigned Opc;
5711 switch (Op.getOpcode()) {
5712 default: llvm_unreachable("Invalid opcode!");
5713 case ISD::SINT_TO_FP:
5714 CastOpc = ISD::SIGN_EXTEND;
5715 Opc = ISD::SINT_TO_FP;
5716 break;
5717 case ISD::UINT_TO_FP:
5718 CastOpc = ISD::ZERO_EXTEND;
5719 Opc = ISD::UINT_TO_FP;
5720 break;
5721 }
5722
5723 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5724 return DAG.getNode(Opc, dl, VT, Op);
5725 }
5726
LowerINT_TO_FP(SDValue Op,SelectionDAG & DAG) const5727 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5728 EVT VT = Op.getValueType();
5729 if (VT.isVector())
5730 return LowerVectorINT_TO_FP(Op, DAG);
5731 if (isUnsupportedFloatingType(VT)) {
5732 RTLIB::Libcall LC;
5733 if (Op.getOpcode() == ISD::SINT_TO_FP)
5734 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5735 Op.getValueType());
5736 else
5737 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5738 Op.getValueType());
5739 MakeLibCallOptions CallOptions;
5740 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5741 CallOptions, SDLoc(Op)).first;
5742 }
5743
5744 return Op;
5745 }
5746
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG) const5747 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5748 // Implement fcopysign with a fabs and a conditional fneg.
5749 SDValue Tmp0 = Op.getOperand(0);
5750 SDValue Tmp1 = Op.getOperand(1);
5751 SDLoc dl(Op);
5752 EVT VT = Op.getValueType();
5753 EVT SrcVT = Tmp1.getValueType();
5754 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5755 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5756 bool UseNEON = !InGPR && Subtarget->hasNEON();
5757
5758 if (UseNEON) {
5759 // Use VBSL to copy the sign bit.
5760 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5761 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5762 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5763 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5764 if (VT == MVT::f64)
5765 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5766 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5767 DAG.getConstant(32, dl, MVT::i32));
5768 else /*if (VT == MVT::f32)*/
5769 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5770 if (SrcVT == MVT::f32) {
5771 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5772 if (VT == MVT::f64)
5773 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5774 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5775 DAG.getConstant(32, dl, MVT::i32));
5776 } else if (VT == MVT::f32)
5777 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5778 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5779 DAG.getConstant(32, dl, MVT::i32));
5780 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5781 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5782
5783 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5784 dl, MVT::i32);
5785 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5786 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5787 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5788
5789 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5790 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5791 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5792 if (VT == MVT::f32) {
5793 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5794 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5795 DAG.getConstant(0, dl, MVT::i32));
5796 } else {
5797 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5798 }
5799
5800 return Res;
5801 }
5802
5803 // Bitcast operand 1 to i32.
5804 if (SrcVT == MVT::f64)
5805 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5806 Tmp1).getValue(1);
5807 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5808
5809 // Or in the signbit with integer operations.
5810 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5811 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5812 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5813 if (VT == MVT::f32) {
5814 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5815 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5816 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5817 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5818 }
5819
5820 // f64: Or the high part with signbit and then combine two parts.
5821 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5822 Tmp0);
5823 SDValue Lo = Tmp0.getValue(0);
5824 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5825 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5826 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5827 }
5828
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const5829 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5830 MachineFunction &MF = DAG.getMachineFunction();
5831 MachineFrameInfo &MFI = MF.getFrameInfo();
5832 MFI.setReturnAddressIsTaken(true);
5833
5834 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5835 return SDValue();
5836
5837 EVT VT = Op.getValueType();
5838 SDLoc dl(Op);
5839 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5840 if (Depth) {
5841 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5842 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5843 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5844 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5845 MachinePointerInfo());
5846 }
5847
5848 // Return LR, which contains the return address. Mark it an implicit live-in.
5849 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5850 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5851 }
5852
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const5853 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5854 const ARMBaseRegisterInfo &ARI =
5855 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5856 MachineFunction &MF = DAG.getMachineFunction();
5857 MachineFrameInfo &MFI = MF.getFrameInfo();
5858 MFI.setFrameAddressIsTaken(true);
5859
5860 EVT VT = Op.getValueType();
5861 SDLoc dl(Op); // FIXME probably not meaningful
5862 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5863 Register FrameReg = ARI.getFrameRegister(MF);
5864 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5865 while (Depth--)
5866 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5867 MachinePointerInfo());
5868 return FrameAddr;
5869 }
5870
5871 // FIXME? Maybe this could be a TableGen attribute on some registers and
5872 // this table could be generated automatically from RegInfo.
getRegisterByName(const char * RegName,LLT VT,const MachineFunction & MF) const5873 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5874 const MachineFunction &MF) const {
5875 Register Reg = StringSwitch<unsigned>(RegName)
5876 .Case("sp", ARM::SP)
5877 .Default(0);
5878 if (Reg)
5879 return Reg;
5880 report_fatal_error(Twine("Invalid register name \""
5881 + StringRef(RegName) + "\"."));
5882 }
5883
5884 // Result is 64 bit value so split into two 32 bit values and return as a
5885 // pair of values.
ExpandREAD_REGISTER(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG)5886 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5887 SelectionDAG &DAG) {
5888 SDLoc DL(N);
5889
5890 // This function is only supposed to be called for i64 type destination.
5891 assert(N->getValueType(0) == MVT::i64
5892 && "ExpandREAD_REGISTER called for non-i64 type result.");
5893
5894 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5895 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5896 N->getOperand(0),
5897 N->getOperand(1));
5898
5899 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5900 Read.getValue(1)));
5901 Results.push_back(Read.getOperand(0));
5902 }
5903
5904 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5905 /// When \p DstVT, the destination type of \p BC, is on the vector
5906 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5907 /// it might be possible to combine them, such that everything stays on the
5908 /// vector register bank.
5909 /// \p return The node that would replace \p BT, if the combine
5910 /// is possible.
CombineVMOVDRRCandidateWithVecOp(const SDNode * BC,SelectionDAG & DAG)5911 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5912 SelectionDAG &DAG) {
5913 SDValue Op = BC->getOperand(0);
5914 EVT DstVT = BC->getValueType(0);
5915
5916 // The only vector instruction that can produce a scalar (remember,
5917 // since the bitcast was about to be turned into VMOVDRR, the source
5918 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5919 // Moreover, we can do this combine only if there is one use.
5920 // Finally, if the destination type is not a vector, there is not
5921 // much point on forcing everything on the vector bank.
5922 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5923 !Op.hasOneUse())
5924 return SDValue();
5925
5926 // If the index is not constant, we will introduce an additional
5927 // multiply that will stick.
5928 // Give up in that case.
5929 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5930 if (!Index)
5931 return SDValue();
5932 unsigned DstNumElt = DstVT.getVectorNumElements();
5933
5934 // Compute the new index.
5935 const APInt &APIntIndex = Index->getAPIntValue();
5936 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5937 NewIndex *= APIntIndex;
5938 // Check if the new constant index fits into i32.
5939 if (NewIndex.getBitWidth() > 32)
5940 return SDValue();
5941
5942 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5943 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5944 SDLoc dl(Op);
5945 SDValue ExtractSrc = Op.getOperand(0);
5946 EVT VecVT = EVT::getVectorVT(
5947 *DAG.getContext(), DstVT.getScalarType(),
5948 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5949 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5950 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5951 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5952 }
5953
5954 /// ExpandBITCAST - If the target supports VFP, this function is called to
5955 /// expand a bit convert where either the source or destination type is i64 to
5956 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5957 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5958 /// vectors), since the legalizer won't know what to do with that.
ExpandBITCAST(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget) const5959 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5960 const ARMSubtarget *Subtarget) const {
5961 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5962 SDLoc dl(N);
5963 SDValue Op = N->getOperand(0);
5964
5965 // This function is only supposed to be called for i16 and i64 types, either
5966 // as the source or destination of the bit convert.
5967 EVT SrcVT = Op.getValueType();
5968 EVT DstVT = N->getValueType(0);
5969
5970 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
5971 (DstVT == MVT::f16 || DstVT == MVT::bf16))
5972 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
5973 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
5974
5975 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
5976 (SrcVT == MVT::f16 || SrcVT == MVT::bf16))
5977 return DAG.getNode(
5978 ISD::TRUNCATE, SDLoc(N), DstVT,
5979 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
5980
5981 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5982 return SDValue();
5983
5984 // Turn i64->f64 into VMOVDRR.
5985 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5986 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5987 // if we can combine the bitcast with its source.
5988 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5989 return Val;
5990
5991 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5992 DAG.getConstant(0, dl, MVT::i32));
5993 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5994 DAG.getConstant(1, dl, MVT::i32));
5995 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5996 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5997 }
5998
5999 // Turn f64->i64 into VMOVRRD.
6000 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
6001 SDValue Cvt;
6002 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6003 SrcVT.getVectorNumElements() > 1)
6004 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6005 DAG.getVTList(MVT::i32, MVT::i32),
6006 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6007 else
6008 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6009 DAG.getVTList(MVT::i32, MVT::i32), Op);
6010 // Merge the pieces into a single i64 value.
6011 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6012 }
6013
6014 return SDValue();
6015 }
6016
6017 /// getZeroVector - Returns a vector of specified type with all zero elements.
6018 /// Zero vectors are used to represent vector negation and in those cases
6019 /// will be implemented with the NEON VNEG instruction. However, VNEG does
6020 /// not support i64 elements, so sometimes the zero vectors will need to be
6021 /// explicitly constructed. Regardless, use a canonical VMOV to create the
6022 /// zero vector.
getZeroVector(EVT VT,SelectionDAG & DAG,const SDLoc & dl)6023 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6024 assert(VT.isVector() && "Expected a vector type");
6025 // The canonical modified immediate encoding of a zero vector is....0!
6026 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6027 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6028 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6029 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6030 }
6031
6032 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6033 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
LowerShiftRightParts(SDValue Op,SelectionDAG & DAG) const6034 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6035 SelectionDAG &DAG) const {
6036 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6037 EVT VT = Op.getValueType();
6038 unsigned VTBits = VT.getSizeInBits();
6039 SDLoc dl(Op);
6040 SDValue ShOpLo = Op.getOperand(0);
6041 SDValue ShOpHi = Op.getOperand(1);
6042 SDValue ShAmt = Op.getOperand(2);
6043 SDValue ARMcc;
6044 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6045 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6046
6047 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6048
6049 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6050 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6051 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6052 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6053 DAG.getConstant(VTBits, dl, MVT::i32));
6054 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6055 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6056 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6057 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6058 ISD::SETGE, ARMcc, DAG, dl);
6059 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
6060 ARMcc, CCR, CmpLo);
6061
6062 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6063 SDValue HiBigShift = Opc == ISD::SRA
6064 ? DAG.getNode(Opc, dl, VT, ShOpHi,
6065 DAG.getConstant(VTBits - 1, dl, VT))
6066 : DAG.getConstant(0, dl, VT);
6067 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6068 ISD::SETGE, ARMcc, DAG, dl);
6069 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6070 ARMcc, CCR, CmpHi);
6071
6072 SDValue Ops[2] = { Lo, Hi };
6073 return DAG.getMergeValues(Ops, dl);
6074 }
6075
6076 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6077 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
LowerShiftLeftParts(SDValue Op,SelectionDAG & DAG) const6078 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6079 SelectionDAG &DAG) const {
6080 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6081 EVT VT = Op.getValueType();
6082 unsigned VTBits = VT.getSizeInBits();
6083 SDLoc dl(Op);
6084 SDValue ShOpLo = Op.getOperand(0);
6085 SDValue ShOpHi = Op.getOperand(1);
6086 SDValue ShAmt = Op.getOperand(2);
6087 SDValue ARMcc;
6088 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6089
6090 assert(Op.getOpcode() == ISD::SHL_PARTS);
6091 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6092 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6093 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6094 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6095 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6096
6097 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6098 DAG.getConstant(VTBits, dl, MVT::i32));
6099 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6100 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6101 ISD::SETGE, ARMcc, DAG, dl);
6102 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6103 ARMcc, CCR, CmpHi);
6104
6105 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6106 ISD::SETGE, ARMcc, DAG, dl);
6107 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6108 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6109 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
6110
6111 SDValue Ops[2] = { Lo, Hi };
6112 return DAG.getMergeValues(Ops, dl);
6113 }
6114
LowerFLT_ROUNDS_(SDValue Op,SelectionDAG & DAG) const6115 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6116 SelectionDAG &DAG) const {
6117 // The rounding mode is in bits 23:22 of the FPSCR.
6118 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6119 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6120 // so that the shift + and get folded into a bitfield extract.
6121 SDLoc dl(Op);
6122 SDValue Chain = Op.getOperand(0);
6123 SDValue Ops[] = {Chain,
6124 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6125
6126 SDValue FPSCR =
6127 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6128 Chain = FPSCR.getValue(1);
6129 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6130 DAG.getConstant(1U << 22, dl, MVT::i32));
6131 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6132 DAG.getConstant(22, dl, MVT::i32));
6133 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6134 DAG.getConstant(3, dl, MVT::i32));
6135 return DAG.getMergeValues({And, Chain}, dl);
6136 }
6137
LowerCTTZ(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)6138 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6139 const ARMSubtarget *ST) {
6140 SDLoc dl(N);
6141 EVT VT = N->getValueType(0);
6142 if (VT.isVector() && ST->hasNEON()) {
6143
6144 // Compute the least significant set bit: LSB = X & -X
6145 SDValue X = N->getOperand(0);
6146 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6147 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6148
6149 EVT ElemTy = VT.getVectorElementType();
6150
6151 if (ElemTy == MVT::i8) {
6152 // Compute with: cttz(x) = ctpop(lsb - 1)
6153 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6154 DAG.getTargetConstant(1, dl, ElemTy));
6155 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6156 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6157 }
6158
6159 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6160 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6161 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6162 unsigned NumBits = ElemTy.getSizeInBits();
6163 SDValue WidthMinus1 =
6164 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6165 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6166 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6167 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6168 }
6169
6170 // Compute with: cttz(x) = ctpop(lsb - 1)
6171
6172 // Compute LSB - 1.
6173 SDValue Bits;
6174 if (ElemTy == MVT::i64) {
6175 // Load constant 0xffff'ffff'ffff'ffff to register.
6176 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6177 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6178 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6179 } else {
6180 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6181 DAG.getTargetConstant(1, dl, ElemTy));
6182 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6183 }
6184 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6185 }
6186
6187 if (!ST->hasV6T2Ops())
6188 return SDValue();
6189
6190 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6191 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6192 }
6193
LowerCTPOP(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)6194 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6195 const ARMSubtarget *ST) {
6196 EVT VT = N->getValueType(0);
6197 SDLoc DL(N);
6198
6199 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6200 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6201 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6202 "Unexpected type for custom ctpop lowering");
6203
6204 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6205 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6206 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6207 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6208
6209 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6210 unsigned EltSize = 8;
6211 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6212 while (EltSize != VT.getScalarSizeInBits()) {
6213 SmallVector<SDValue, 8> Ops;
6214 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6215 TLI.getPointerTy(DAG.getDataLayout())));
6216 Ops.push_back(Res);
6217
6218 EltSize *= 2;
6219 NumElts /= 2;
6220 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6221 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6222 }
6223
6224 return Res;
6225 }
6226
6227 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6228 /// operand of a vector shift operation, where all the elements of the
6229 /// build_vector must have the same constant integer value.
getVShiftImm(SDValue Op,unsigned ElementBits,int64_t & Cnt)6230 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6231 // Ignore bit_converts.
6232 while (Op.getOpcode() == ISD::BITCAST)
6233 Op = Op.getOperand(0);
6234 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6235 APInt SplatBits, SplatUndef;
6236 unsigned SplatBitSize;
6237 bool HasAnyUndefs;
6238 if (!BVN ||
6239 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6240 ElementBits) ||
6241 SplatBitSize > ElementBits)
6242 return false;
6243 Cnt = SplatBits.getSExtValue();
6244 return true;
6245 }
6246
6247 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6248 /// operand of a vector shift left operation. That value must be in the range:
6249 /// 0 <= Value < ElementBits for a left shift; or
6250 /// 0 <= Value <= ElementBits for a long left shift.
isVShiftLImm(SDValue Op,EVT VT,bool isLong,int64_t & Cnt)6251 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6252 assert(VT.isVector() && "vector shift count is not a vector type");
6253 int64_t ElementBits = VT.getScalarSizeInBits();
6254 if (!getVShiftImm(Op, ElementBits, Cnt))
6255 return false;
6256 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6257 }
6258
6259 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6260 /// operand of a vector shift right operation. For a shift opcode, the value
6261 /// is positive, but for an intrinsic the value count must be negative. The
6262 /// absolute value must be in the range:
6263 /// 1 <= |Value| <= ElementBits for a right shift; or
6264 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
isVShiftRImm(SDValue Op,EVT VT,bool isNarrow,bool isIntrinsic,int64_t & Cnt)6265 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6266 int64_t &Cnt) {
6267 assert(VT.isVector() && "vector shift count is not a vector type");
6268 int64_t ElementBits = VT.getScalarSizeInBits();
6269 if (!getVShiftImm(Op, ElementBits, Cnt))
6270 return false;
6271 if (!isIntrinsic)
6272 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6273 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6274 Cnt = -Cnt;
6275 return true;
6276 }
6277 return false;
6278 }
6279
LowerShift(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)6280 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6281 const ARMSubtarget *ST) {
6282 EVT VT = N->getValueType(0);
6283 SDLoc dl(N);
6284 int64_t Cnt;
6285
6286 if (!VT.isVector())
6287 return SDValue();
6288
6289 // We essentially have two forms here. Shift by an immediate and shift by a
6290 // vector register (there are also shift by a gpr, but that is just handled
6291 // with a tablegen pattern). We cannot easily match shift by an immediate in
6292 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6293 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6294 // signed or unsigned, and a negative shift indicates a shift right).
6295 if (N->getOpcode() == ISD::SHL) {
6296 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6297 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6298 DAG.getConstant(Cnt, dl, MVT::i32));
6299 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6300 N->getOperand(1));
6301 }
6302
6303 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6304 "unexpected vector shift opcode");
6305
6306 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6307 unsigned VShiftOpc =
6308 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6309 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6310 DAG.getConstant(Cnt, dl, MVT::i32));
6311 }
6312
6313 // Other right shifts we don't have operations for (we use a shift left by a
6314 // negative number).
6315 EVT ShiftVT = N->getOperand(1).getValueType();
6316 SDValue NegatedCount = DAG.getNode(
6317 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6318 unsigned VShiftOpc =
6319 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6320 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6321 }
6322
Expand64BitShift(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)6323 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6324 const ARMSubtarget *ST) {
6325 EVT VT = N->getValueType(0);
6326 SDLoc dl(N);
6327
6328 // We can get here for a node like i32 = ISD::SHL i32, i64
6329 if (VT != MVT::i64)
6330 return SDValue();
6331
6332 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6333 N->getOpcode() == ISD::SHL) &&
6334 "Unknown shift to lower!");
6335
6336 unsigned ShOpc = N->getOpcode();
6337 if (ST->hasMVEIntegerOps()) {
6338 SDValue ShAmt = N->getOperand(1);
6339 unsigned ShPartsOpc = ARMISD::LSLL;
6340 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6341
6342 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6343 // then do the default optimisation
6344 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6345 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6346 return SDValue();
6347
6348 // Extract the lower 32 bits of the shift amount if it's not an i32
6349 if (ShAmt->getValueType(0) != MVT::i32)
6350 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6351
6352 if (ShOpc == ISD::SRL) {
6353 if (!Con)
6354 // There is no t2LSRLr instruction so negate and perform an lsll if the
6355 // shift amount is in a register, emulating a right shift.
6356 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6357 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6358 else
6359 // Else generate an lsrl on the immediate shift amount
6360 ShPartsOpc = ARMISD::LSRL;
6361 } else if (ShOpc == ISD::SRA)
6362 ShPartsOpc = ARMISD::ASRL;
6363
6364 // Lower 32 bits of the destination/source
6365 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6366 DAG.getConstant(0, dl, MVT::i32));
6367 // Upper 32 bits of the destination/source
6368 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6369 DAG.getConstant(1, dl, MVT::i32));
6370
6371 // Generate the shift operation as computed above
6372 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6373 ShAmt);
6374 // The upper 32 bits come from the second return value of lsll
6375 Hi = SDValue(Lo.getNode(), 1);
6376 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6377 }
6378
6379 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6380 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6381 return SDValue();
6382
6383 // If we are in thumb mode, we don't have RRX.
6384 if (ST->isThumb1Only())
6385 return SDValue();
6386
6387 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6388 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6389 DAG.getConstant(0, dl, MVT::i32));
6390 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6391 DAG.getConstant(1, dl, MVT::i32));
6392
6393 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6394 // captures the result into a carry flag.
6395 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6396 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6397
6398 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6399 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6400
6401 // Merge the pieces into a single i64 value.
6402 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6403 }
6404
LowerVSETCC(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)6405 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6406 const ARMSubtarget *ST) {
6407 bool Invert = false;
6408 bool Swap = false;
6409 unsigned Opc = ARMCC::AL;
6410
6411 SDValue Op0 = Op.getOperand(0);
6412 SDValue Op1 = Op.getOperand(1);
6413 SDValue CC = Op.getOperand(2);
6414 EVT VT = Op.getValueType();
6415 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6416 SDLoc dl(Op);
6417
6418 EVT CmpVT;
6419 if (ST->hasNEON())
6420 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6421 else {
6422 assert(ST->hasMVEIntegerOps() &&
6423 "No hardware support for integer vector comparison!");
6424
6425 if (Op.getValueType().getVectorElementType() != MVT::i1)
6426 return SDValue();
6427
6428 // Make sure we expand floating point setcc to scalar if we do not have
6429 // mve.fp, so that we can handle them from there.
6430 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6431 return SDValue();
6432
6433 CmpVT = VT;
6434 }
6435
6436 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6437 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6438 // Special-case integer 64-bit equality comparisons. They aren't legal,
6439 // but they can be lowered with a few vector instructions.
6440 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6441 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6442 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6443 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6444 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6445 DAG.getCondCode(ISD::SETEQ));
6446 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6447 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6448 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6449 if (SetCCOpcode == ISD::SETNE)
6450 Merged = DAG.getNOT(dl, Merged, CmpVT);
6451 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6452 return Merged;
6453 }
6454
6455 if (CmpVT.getVectorElementType() == MVT::i64)
6456 // 64-bit comparisons are not legal in general.
6457 return SDValue();
6458
6459 if (Op1.getValueType().isFloatingPoint()) {
6460 switch (SetCCOpcode) {
6461 default: llvm_unreachable("Illegal FP comparison");
6462 case ISD::SETUNE:
6463 case ISD::SETNE:
6464 if (ST->hasMVEFloatOps()) {
6465 Opc = ARMCC::NE; break;
6466 } else {
6467 Invert = true; LLVM_FALLTHROUGH;
6468 }
6469 case ISD::SETOEQ:
6470 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6471 case ISD::SETOLT:
6472 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6473 case ISD::SETOGT:
6474 case ISD::SETGT: Opc = ARMCC::GT; break;
6475 case ISD::SETOLE:
6476 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6477 case ISD::SETOGE:
6478 case ISD::SETGE: Opc = ARMCC::GE; break;
6479 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6480 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6481 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6482 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6483 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6484 case ISD::SETONE: {
6485 // Expand this to (OLT | OGT).
6486 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6487 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6488 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6489 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6490 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6491 if (Invert)
6492 Result = DAG.getNOT(dl, Result, VT);
6493 return Result;
6494 }
6495 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6496 case ISD::SETO: {
6497 // Expand this to (OLT | OGE).
6498 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6499 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6500 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6501 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6502 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6503 if (Invert)
6504 Result = DAG.getNOT(dl, Result, VT);
6505 return Result;
6506 }
6507 }
6508 } else {
6509 // Integer comparisons.
6510 switch (SetCCOpcode) {
6511 default: llvm_unreachable("Illegal integer comparison");
6512 case ISD::SETNE:
6513 if (ST->hasMVEIntegerOps()) {
6514 Opc = ARMCC::NE; break;
6515 } else {
6516 Invert = true; LLVM_FALLTHROUGH;
6517 }
6518 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6519 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6520 case ISD::SETGT: Opc = ARMCC::GT; break;
6521 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6522 case ISD::SETGE: Opc = ARMCC::GE; break;
6523 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6524 case ISD::SETUGT: Opc = ARMCC::HI; break;
6525 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6526 case ISD::SETUGE: Opc = ARMCC::HS; break;
6527 }
6528
6529 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6530 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6531 SDValue AndOp;
6532 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6533 AndOp = Op0;
6534 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6535 AndOp = Op1;
6536
6537 // Ignore bitconvert.
6538 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6539 AndOp = AndOp.getOperand(0);
6540
6541 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6542 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6543 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6544 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6545 if (!Invert)
6546 Result = DAG.getNOT(dl, Result, VT);
6547 return Result;
6548 }
6549 }
6550 }
6551
6552 if (Swap)
6553 std::swap(Op0, Op1);
6554
6555 // If one of the operands is a constant vector zero, attempt to fold the
6556 // comparison to a specialized compare-against-zero form.
6557 SDValue SingleOp;
6558 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6559 SingleOp = Op0;
6560 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6561 if (Opc == ARMCC::GE)
6562 Opc = ARMCC::LE;
6563 else if (Opc == ARMCC::GT)
6564 Opc = ARMCC::LT;
6565 SingleOp = Op1;
6566 }
6567
6568 SDValue Result;
6569 if (SingleOp.getNode()) {
6570 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6571 DAG.getConstant(Opc, dl, MVT::i32));
6572 } else {
6573 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6574 DAG.getConstant(Opc, dl, MVT::i32));
6575 }
6576
6577 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6578
6579 if (Invert)
6580 Result = DAG.getNOT(dl, Result, VT);
6581
6582 return Result;
6583 }
6584
LowerSETCCCARRY(SDValue Op,SelectionDAG & DAG)6585 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6586 SDValue LHS = Op.getOperand(0);
6587 SDValue RHS = Op.getOperand(1);
6588 SDValue Carry = Op.getOperand(2);
6589 SDValue Cond = Op.getOperand(3);
6590 SDLoc DL(Op);
6591
6592 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6593
6594 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6595 // have to invert the carry first.
6596 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6597 DAG.getConstant(1, DL, MVT::i32), Carry);
6598 // This converts the boolean value carry into the carry flag.
6599 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6600
6601 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6602 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6603
6604 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6605 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6606 SDValue ARMcc = DAG.getConstant(
6607 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6608 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6609 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6610 Cmp.getValue(1), SDValue());
6611 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6612 CCR, Chain.getValue(1));
6613 }
6614
6615 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6616 /// valid vector constant for a NEON or MVE instruction with a "modified
6617 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
isVMOVModifiedImm(uint64_t SplatBits,uint64_t SplatUndef,unsigned SplatBitSize,SelectionDAG & DAG,const SDLoc & dl,EVT & VT,EVT VectorVT,VMOVModImmType type)6618 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6619 unsigned SplatBitSize, SelectionDAG &DAG,
6620 const SDLoc &dl, EVT &VT, EVT VectorVT,
6621 VMOVModImmType type) {
6622 unsigned OpCmode, Imm;
6623 bool is128Bits = VectorVT.is128BitVector();
6624
6625 // SplatBitSize is set to the smallest size that splats the vector, so a
6626 // zero vector will always have SplatBitSize == 8. However, NEON modified
6627 // immediate instructions others than VMOV do not support the 8-bit encoding
6628 // of a zero vector, and the default encoding of zero is supposed to be the
6629 // 32-bit version.
6630 if (SplatBits == 0)
6631 SplatBitSize = 32;
6632
6633 switch (SplatBitSize) {
6634 case 8:
6635 if (type != VMOVModImm)
6636 return SDValue();
6637 // Any 1-byte value is OK. Op=0, Cmode=1110.
6638 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6639 OpCmode = 0xe;
6640 Imm = SplatBits;
6641 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6642 break;
6643
6644 case 16:
6645 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6646 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6647 if ((SplatBits & ~0xff) == 0) {
6648 // Value = 0x00nn: Op=x, Cmode=100x.
6649 OpCmode = 0x8;
6650 Imm = SplatBits;
6651 break;
6652 }
6653 if ((SplatBits & ~0xff00) == 0) {
6654 // Value = 0xnn00: Op=x, Cmode=101x.
6655 OpCmode = 0xa;
6656 Imm = SplatBits >> 8;
6657 break;
6658 }
6659 return SDValue();
6660
6661 case 32:
6662 // NEON's 32-bit VMOV supports splat values where:
6663 // * only one byte is nonzero, or
6664 // * the least significant byte is 0xff and the second byte is nonzero, or
6665 // * the least significant 2 bytes are 0xff and the third is nonzero.
6666 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6667 if ((SplatBits & ~0xff) == 0) {
6668 // Value = 0x000000nn: Op=x, Cmode=000x.
6669 OpCmode = 0;
6670 Imm = SplatBits;
6671 break;
6672 }
6673 if ((SplatBits & ~0xff00) == 0) {
6674 // Value = 0x0000nn00: Op=x, Cmode=001x.
6675 OpCmode = 0x2;
6676 Imm = SplatBits >> 8;
6677 break;
6678 }
6679 if ((SplatBits & ~0xff0000) == 0) {
6680 // Value = 0x00nn0000: Op=x, Cmode=010x.
6681 OpCmode = 0x4;
6682 Imm = SplatBits >> 16;
6683 break;
6684 }
6685 if ((SplatBits & ~0xff000000) == 0) {
6686 // Value = 0xnn000000: Op=x, Cmode=011x.
6687 OpCmode = 0x6;
6688 Imm = SplatBits >> 24;
6689 break;
6690 }
6691
6692 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6693 if (type == OtherModImm) return SDValue();
6694
6695 if ((SplatBits & ~0xffff) == 0 &&
6696 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6697 // Value = 0x0000nnff: Op=x, Cmode=1100.
6698 OpCmode = 0xc;
6699 Imm = SplatBits >> 8;
6700 break;
6701 }
6702
6703 // cmode == 0b1101 is not supported for MVE VMVN
6704 if (type == MVEVMVNModImm)
6705 return SDValue();
6706
6707 if ((SplatBits & ~0xffffff) == 0 &&
6708 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6709 // Value = 0x00nnffff: Op=x, Cmode=1101.
6710 OpCmode = 0xd;
6711 Imm = SplatBits >> 16;
6712 break;
6713 }
6714
6715 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6716 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6717 // VMOV.I32. A (very) minor optimization would be to replicate the value
6718 // and fall through here to test for a valid 64-bit splat. But, then the
6719 // caller would also need to check and handle the change in size.
6720 return SDValue();
6721
6722 case 64: {
6723 if (type != VMOVModImm)
6724 return SDValue();
6725 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6726 uint64_t BitMask = 0xff;
6727 uint64_t Val = 0;
6728 unsigned ImmMask = 1;
6729 Imm = 0;
6730 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6731 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6732 Val |= BitMask;
6733 Imm |= ImmMask;
6734 } else if ((SplatBits & BitMask) != 0) {
6735 return SDValue();
6736 }
6737 BitMask <<= 8;
6738 ImmMask <<= 1;
6739 }
6740
6741 if (DAG.getDataLayout().isBigEndian()) {
6742 // Reverse the order of elements within the vector.
6743 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
6744 unsigned Mask = (1 << BytesPerElem) - 1;
6745 unsigned NumElems = 8 / BytesPerElem;
6746 unsigned NewImm = 0;
6747 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
6748 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
6749 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
6750 }
6751 Imm = NewImm;
6752 }
6753
6754 // Op=1, Cmode=1110.
6755 OpCmode = 0x1e;
6756 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6757 break;
6758 }
6759
6760 default:
6761 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6762 }
6763
6764 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6765 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6766 }
6767
LowerConstantFP(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST) const6768 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6769 const ARMSubtarget *ST) const {
6770 EVT VT = Op.getValueType();
6771 bool IsDouble = (VT == MVT::f64);
6772 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6773 const APFloat &FPVal = CFP->getValueAPF();
6774
6775 // Prevent floating-point constants from using literal loads
6776 // when execute-only is enabled.
6777 if (ST->genExecuteOnly()) {
6778 // If we can represent the constant as an immediate, don't lower it
6779 if (isFPImmLegal(FPVal, VT))
6780 return Op;
6781 // Otherwise, construct as integer, and move to float register
6782 APInt INTVal = FPVal.bitcastToAPInt();
6783 SDLoc DL(CFP);
6784 switch (VT.getSimpleVT().SimpleTy) {
6785 default:
6786 llvm_unreachable("Unknown floating point type!");
6787 break;
6788 case MVT::f64: {
6789 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6790 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6791 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6792 }
6793 case MVT::f32:
6794 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6795 DAG.getConstant(INTVal, DL, MVT::i32));
6796 }
6797 }
6798
6799 if (!ST->hasVFP3Base())
6800 return SDValue();
6801
6802 // Use the default (constant pool) lowering for double constants when we have
6803 // an SP-only FPU
6804 if (IsDouble && !Subtarget->hasFP64())
6805 return SDValue();
6806
6807 // Try splatting with a VMOV.f32...
6808 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6809
6810 if (ImmVal != -1) {
6811 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6812 // We have code in place to select a valid ConstantFP already, no need to
6813 // do any mangling.
6814 return Op;
6815 }
6816
6817 // It's a float and we are trying to use NEON operations where
6818 // possible. Lower it to a splat followed by an extract.
6819 SDLoc DL(Op);
6820 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6821 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6822 NewVal);
6823 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6824 DAG.getConstant(0, DL, MVT::i32));
6825 }
6826
6827 // The rest of our options are NEON only, make sure that's allowed before
6828 // proceeding..
6829 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6830 return SDValue();
6831
6832 EVT VMovVT;
6833 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6834
6835 // It wouldn't really be worth bothering for doubles except for one very
6836 // important value, which does happen to match: 0.0. So make sure we don't do
6837 // anything stupid.
6838 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6839 return SDValue();
6840
6841 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6842 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6843 VMovVT, VT, VMOVModImm);
6844 if (NewVal != SDValue()) {
6845 SDLoc DL(Op);
6846 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6847 NewVal);
6848 if (IsDouble)
6849 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6850
6851 // It's a float: cast and extract a vector element.
6852 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6853 VecConstant);
6854 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6855 DAG.getConstant(0, DL, MVT::i32));
6856 }
6857
6858 // Finally, try a VMVN.i32
6859 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6860 VT, VMVNModImm);
6861 if (NewVal != SDValue()) {
6862 SDLoc DL(Op);
6863 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6864
6865 if (IsDouble)
6866 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6867
6868 // It's a float: cast and extract a vector element.
6869 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6870 VecConstant);
6871 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6872 DAG.getConstant(0, DL, MVT::i32));
6873 }
6874
6875 return SDValue();
6876 }
6877
6878 // check if an VEXT instruction can handle the shuffle mask when the
6879 // vector sources of the shuffle are the same.
isSingletonVEXTMask(ArrayRef<int> M,EVT VT,unsigned & Imm)6880 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6881 unsigned NumElts = VT.getVectorNumElements();
6882
6883 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6884 if (M[0] < 0)
6885 return false;
6886
6887 Imm = M[0];
6888
6889 // If this is a VEXT shuffle, the immediate value is the index of the first
6890 // element. The other shuffle indices must be the successive elements after
6891 // the first one.
6892 unsigned ExpectedElt = Imm;
6893 for (unsigned i = 1; i < NumElts; ++i) {
6894 // Increment the expected index. If it wraps around, just follow it
6895 // back to index zero and keep going.
6896 ++ExpectedElt;
6897 if (ExpectedElt == NumElts)
6898 ExpectedElt = 0;
6899
6900 if (M[i] < 0) continue; // ignore UNDEF indices
6901 if (ExpectedElt != static_cast<unsigned>(M[i]))
6902 return false;
6903 }
6904
6905 return true;
6906 }
6907
isVEXTMask(ArrayRef<int> M,EVT VT,bool & ReverseVEXT,unsigned & Imm)6908 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6909 bool &ReverseVEXT, unsigned &Imm) {
6910 unsigned NumElts = VT.getVectorNumElements();
6911 ReverseVEXT = false;
6912
6913 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6914 if (M[0] < 0)
6915 return false;
6916
6917 Imm = M[0];
6918
6919 // If this is a VEXT shuffle, the immediate value is the index of the first
6920 // element. The other shuffle indices must be the successive elements after
6921 // the first one.
6922 unsigned ExpectedElt = Imm;
6923 for (unsigned i = 1; i < NumElts; ++i) {
6924 // Increment the expected index. If it wraps around, it may still be
6925 // a VEXT but the source vectors must be swapped.
6926 ExpectedElt += 1;
6927 if (ExpectedElt == NumElts * 2) {
6928 ExpectedElt = 0;
6929 ReverseVEXT = true;
6930 }
6931
6932 if (M[i] < 0) continue; // ignore UNDEF indices
6933 if (ExpectedElt != static_cast<unsigned>(M[i]))
6934 return false;
6935 }
6936
6937 // Adjust the index value if the source operands will be swapped.
6938 if (ReverseVEXT)
6939 Imm -= NumElts;
6940
6941 return true;
6942 }
6943
6944 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6945 /// instruction with the specified blocksize. (The order of the elements
6946 /// within each block of the vector is reversed.)
isVREVMask(ArrayRef<int> M,EVT VT,unsigned BlockSize)6947 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6948 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6949 "Only possible block sizes for VREV are: 16, 32, 64");
6950
6951 unsigned EltSz = VT.getScalarSizeInBits();
6952 if (EltSz == 64)
6953 return false;
6954
6955 unsigned NumElts = VT.getVectorNumElements();
6956 unsigned BlockElts = M[0] + 1;
6957 // If the first shuffle index is UNDEF, be optimistic.
6958 if (M[0] < 0)
6959 BlockElts = BlockSize / EltSz;
6960
6961 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6962 return false;
6963
6964 for (unsigned i = 0; i < NumElts; ++i) {
6965 if (M[i] < 0) continue; // ignore UNDEF indices
6966 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6967 return false;
6968 }
6969
6970 return true;
6971 }
6972
isVTBLMask(ArrayRef<int> M,EVT VT)6973 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6974 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6975 // range, then 0 is placed into the resulting vector. So pretty much any mask
6976 // of 8 elements can work here.
6977 return VT == MVT::v8i8 && M.size() == 8;
6978 }
6979
SelectPairHalf(unsigned Elements,ArrayRef<int> Mask,unsigned Index)6980 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6981 unsigned Index) {
6982 if (Mask.size() == Elements * 2)
6983 return Index / Elements;
6984 return Mask[Index] == 0 ? 0 : 1;
6985 }
6986
6987 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6988 // checking that pairs of elements in the shuffle mask represent the same index
6989 // in each vector, incrementing the expected index by 2 at each step.
6990 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6991 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6992 // v2={e,f,g,h}
6993 // WhichResult gives the offset for each element in the mask based on which
6994 // of the two results it belongs to.
6995 //
6996 // The transpose can be represented either as:
6997 // result1 = shufflevector v1, v2, result1_shuffle_mask
6998 // result2 = shufflevector v1, v2, result2_shuffle_mask
6999 // where v1/v2 and the shuffle masks have the same number of elements
7000 // (here WhichResult (see below) indicates which result is being checked)
7001 //
7002 // or as:
7003 // results = shufflevector v1, v2, shuffle_mask
7004 // where both results are returned in one vector and the shuffle mask has twice
7005 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7006 // want to check the low half and high half of the shuffle mask as if it were
7007 // the other case
isVTRNMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7008 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7009 unsigned EltSz = VT.getScalarSizeInBits();
7010 if (EltSz == 64)
7011 return false;
7012
7013 unsigned NumElts = VT.getVectorNumElements();
7014 if (M.size() != NumElts && M.size() != NumElts*2)
7015 return false;
7016
7017 // If the mask is twice as long as the input vector then we need to check the
7018 // upper and lower parts of the mask with a matching value for WhichResult
7019 // FIXME: A mask with only even values will be rejected in case the first
7020 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7021 // M[0] is used to determine WhichResult
7022 for (unsigned i = 0; i < M.size(); i += NumElts) {
7023 WhichResult = SelectPairHalf(NumElts, M, i);
7024 for (unsigned j = 0; j < NumElts; j += 2) {
7025 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7026 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7027 return false;
7028 }
7029 }
7030
7031 if (M.size() == NumElts*2)
7032 WhichResult = 0;
7033
7034 return true;
7035 }
7036
7037 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7038 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7039 /// 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)7040 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7041 unsigned EltSz = VT.getScalarSizeInBits();
7042 if (EltSz == 64)
7043 return false;
7044
7045 unsigned NumElts = VT.getVectorNumElements();
7046 if (M.size() != NumElts && M.size() != NumElts*2)
7047 return false;
7048
7049 for (unsigned i = 0; i < M.size(); i += NumElts) {
7050 WhichResult = SelectPairHalf(NumElts, M, i);
7051 for (unsigned j = 0; j < NumElts; j += 2) {
7052 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7053 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7054 return false;
7055 }
7056 }
7057
7058 if (M.size() == NumElts*2)
7059 WhichResult = 0;
7060
7061 return true;
7062 }
7063
7064 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7065 // that the mask elements are either all even and in steps of size 2 or all odd
7066 // and in steps of size 2.
7067 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7068 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7069 // v2={e,f,g,h}
7070 // Requires similar checks to that of isVTRNMask with
7071 // respect the how results are returned.
isVUZPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7072 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7073 unsigned EltSz = VT.getScalarSizeInBits();
7074 if (EltSz == 64)
7075 return false;
7076
7077 unsigned NumElts = VT.getVectorNumElements();
7078 if (M.size() != NumElts && M.size() != NumElts*2)
7079 return false;
7080
7081 for (unsigned i = 0; i < M.size(); i += NumElts) {
7082 WhichResult = SelectPairHalf(NumElts, M, i);
7083 for (unsigned j = 0; j < NumElts; ++j) {
7084 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7085 return false;
7086 }
7087 }
7088
7089 if (M.size() == NumElts*2)
7090 WhichResult = 0;
7091
7092 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7093 if (VT.is64BitVector() && EltSz == 32)
7094 return false;
7095
7096 return true;
7097 }
7098
7099 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7100 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7101 /// 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)7102 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7103 unsigned EltSz = VT.getScalarSizeInBits();
7104 if (EltSz == 64)
7105 return false;
7106
7107 unsigned NumElts = VT.getVectorNumElements();
7108 if (M.size() != NumElts && M.size() != NumElts*2)
7109 return false;
7110
7111 unsigned Half = NumElts / 2;
7112 for (unsigned i = 0; i < M.size(); i += NumElts) {
7113 WhichResult = SelectPairHalf(NumElts, M, i);
7114 for (unsigned j = 0; j < NumElts; j += Half) {
7115 unsigned Idx = WhichResult;
7116 for (unsigned k = 0; k < Half; ++k) {
7117 int MIdx = M[i + j + k];
7118 if (MIdx >= 0 && (unsigned) MIdx != Idx)
7119 return false;
7120 Idx += 2;
7121 }
7122 }
7123 }
7124
7125 if (M.size() == NumElts*2)
7126 WhichResult = 0;
7127
7128 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7129 if (VT.is64BitVector() && EltSz == 32)
7130 return false;
7131
7132 return true;
7133 }
7134
7135 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7136 // that pairs of elements of the shufflemask represent the same index in each
7137 // vector incrementing sequentially through the vectors.
7138 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7139 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7140 // v2={e,f,g,h}
7141 // Requires similar checks to that of isVTRNMask with respect the how results
7142 // are returned.
isVZIPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7143 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7144 unsigned EltSz = VT.getScalarSizeInBits();
7145 if (EltSz == 64)
7146 return false;
7147
7148 unsigned NumElts = VT.getVectorNumElements();
7149 if (M.size() != NumElts && M.size() != NumElts*2)
7150 return false;
7151
7152 for (unsigned i = 0; i < M.size(); i += NumElts) {
7153 WhichResult = SelectPairHalf(NumElts, M, i);
7154 unsigned Idx = WhichResult * NumElts / 2;
7155 for (unsigned j = 0; j < NumElts; j += 2) {
7156 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7157 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7158 return false;
7159 Idx += 1;
7160 }
7161 }
7162
7163 if (M.size() == NumElts*2)
7164 WhichResult = 0;
7165
7166 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7167 if (VT.is64BitVector() && EltSz == 32)
7168 return false;
7169
7170 return true;
7171 }
7172
7173 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7174 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7175 /// 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)7176 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7177 unsigned EltSz = VT.getScalarSizeInBits();
7178 if (EltSz == 64)
7179 return false;
7180
7181 unsigned NumElts = VT.getVectorNumElements();
7182 if (M.size() != NumElts && M.size() != NumElts*2)
7183 return false;
7184
7185 for (unsigned i = 0; i < M.size(); i += NumElts) {
7186 WhichResult = SelectPairHalf(NumElts, M, i);
7187 unsigned Idx = WhichResult * NumElts / 2;
7188 for (unsigned j = 0; j < NumElts; j += 2) {
7189 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7190 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7191 return false;
7192 Idx += 1;
7193 }
7194 }
7195
7196 if (M.size() == NumElts*2)
7197 WhichResult = 0;
7198
7199 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7200 if (VT.is64BitVector() && EltSz == 32)
7201 return false;
7202
7203 return true;
7204 }
7205
7206 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7207 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask,EVT VT,unsigned & WhichResult,bool & isV_UNDEF)7208 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7209 unsigned &WhichResult,
7210 bool &isV_UNDEF) {
7211 isV_UNDEF = false;
7212 if (isVTRNMask(ShuffleMask, VT, WhichResult))
7213 return ARMISD::VTRN;
7214 if (isVUZPMask(ShuffleMask, VT, WhichResult))
7215 return ARMISD::VUZP;
7216 if (isVZIPMask(ShuffleMask, VT, WhichResult))
7217 return ARMISD::VZIP;
7218
7219 isV_UNDEF = true;
7220 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7221 return ARMISD::VTRN;
7222 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7223 return ARMISD::VUZP;
7224 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7225 return ARMISD::VZIP;
7226
7227 return 0;
7228 }
7229
7230 /// \return true if this is a reverse operation on an vector.
isReverseMask(ArrayRef<int> M,EVT VT)7231 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7232 unsigned NumElts = VT.getVectorNumElements();
7233 // Make sure the mask has the right size.
7234 if (NumElts != M.size())
7235 return false;
7236
7237 // Look for <15, ..., 3, -1, 1, 0>.
7238 for (unsigned i = 0; i != NumElts; ++i)
7239 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7240 return false;
7241
7242 return true;
7243 }
7244
isVMOVNMask(ArrayRef<int> M,EVT VT,bool Top)7245 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
7246 unsigned NumElts = VT.getVectorNumElements();
7247 // Make sure the mask has the right size.
7248 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7249 return false;
7250
7251 // If Top
7252 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7253 // This inserts Input2 into Input1
7254 // else if not Top
7255 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7256 // This inserts Input1 into Input2
7257 unsigned Offset = Top ? 0 : 1;
7258 for (unsigned i = 0; i < NumElts; i+=2) {
7259 if (M[i] >= 0 && M[i] != (int)i)
7260 return false;
7261 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
7262 return false;
7263 }
7264
7265 return true;
7266 }
7267
7268 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7269 // from a pair of inputs. For example:
7270 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7271 // FP_ROUND(EXTRACT_ELT(Y, 0),
7272 // FP_ROUND(EXTRACT_ELT(X, 1),
7273 // FP_ROUND(EXTRACT_ELT(Y, 1), ...)
LowerBuildVectorOfFPTrunc(SDValue BV,SelectionDAG & DAG,const ARMSubtarget * ST)7274 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7275 const ARMSubtarget *ST) {
7276 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7277 if (!ST->hasMVEFloatOps())
7278 return SDValue();
7279
7280 SDLoc dl(BV);
7281 EVT VT = BV.getValueType();
7282 if (VT != MVT::v8f16)
7283 return SDValue();
7284
7285 // We are looking for a buildvector of fptrunc elements, where all the
7286 // elements are interleavingly extracted from two sources. Check the first two
7287 // items are valid enough and extract some info from them (they are checked
7288 // properly in the loop below).
7289 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7290 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7291 BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0)
7292 return SDValue();
7293 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7294 BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7295 BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0)
7296 return SDValue();
7297 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7298 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7299 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7300 return SDValue();
7301
7302 // Check all the values in the BuildVector line up with our expectations.
7303 for (unsigned i = 1; i < 4; i++) {
7304 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7305 return Trunc.getOpcode() == ISD::FP_ROUND &&
7306 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7307 Trunc.getOperand(0).getOperand(0) == Op &&
7308 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7309 };
7310 if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7311 return SDValue();
7312 if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7313 return SDValue();
7314 }
7315
7316 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7317 DAG.getConstant(0, dl, MVT::i32));
7318 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7319 DAG.getConstant(1, dl, MVT::i32));
7320 }
7321
7322 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7323 // from a single input on alternating lanes. For example:
7324 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7325 // FP_ROUND(EXTRACT_ELT(X, 2),
7326 // FP_ROUND(EXTRACT_ELT(X, 4), ...)
LowerBuildVectorOfFPExt(SDValue BV,SelectionDAG & DAG,const ARMSubtarget * ST)7327 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7328 const ARMSubtarget *ST) {
7329 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7330 if (!ST->hasMVEFloatOps())
7331 return SDValue();
7332
7333 SDLoc dl(BV);
7334 EVT VT = BV.getValueType();
7335 if (VT != MVT::v4f32)
7336 return SDValue();
7337
7338 // We are looking for a buildvector of fptext elements, where all the
7339 // elements are alternating lanes from a single source. For example <0,2,4,6>
7340 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7341 // info from them (they are checked properly in the loop below).
7342 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7343 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7344 return SDValue();
7345 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7346 int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1);
7347 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7348 return SDValue();
7349
7350 // Check all the values in the BuildVector line up with our expectations.
7351 for (unsigned i = 1; i < 4; i++) {
7352 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7353 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7354 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7355 Trunc.getOperand(0).getOperand(0) == Op &&
7356 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7357 };
7358 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7359 return SDValue();
7360 }
7361
7362 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7363 DAG.getConstant(Offset, dl, MVT::i32));
7364 }
7365
7366 // If N is an integer constant that can be moved into a register in one
7367 // instruction, return an SDValue of such a constant (will become a MOV
7368 // instruction). Otherwise return null.
IsSingleInstrConstant(SDValue N,SelectionDAG & DAG,const ARMSubtarget * ST,const SDLoc & dl)7369 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7370 const ARMSubtarget *ST, const SDLoc &dl) {
7371 uint64_t Val;
7372 if (!isa<ConstantSDNode>(N))
7373 return SDValue();
7374 Val = cast<ConstantSDNode>(N)->getZExtValue();
7375
7376 if (ST->isThumb1Only()) {
7377 if (Val <= 255 || ~Val <= 255)
7378 return DAG.getConstant(Val, dl, MVT::i32);
7379 } else {
7380 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7381 return DAG.getConstant(Val, dl, MVT::i32);
7382 }
7383 return SDValue();
7384 }
7385
LowerBUILD_VECTOR_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)7386 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7387 const ARMSubtarget *ST) {
7388 SDLoc dl(Op);
7389 EVT VT = Op.getValueType();
7390
7391 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7392
7393 unsigned NumElts = VT.getVectorNumElements();
7394 unsigned BoolMask;
7395 unsigned BitsPerBool;
7396 if (NumElts == 4) {
7397 BitsPerBool = 4;
7398 BoolMask = 0xf;
7399 } else if (NumElts == 8) {
7400 BitsPerBool = 2;
7401 BoolMask = 0x3;
7402 } else if (NumElts == 16) {
7403 BitsPerBool = 1;
7404 BoolMask = 0x1;
7405 } else
7406 return SDValue();
7407
7408 // If this is a single value copied into all lanes (a splat), we can just sign
7409 // extend that single value
7410 SDValue FirstOp = Op.getOperand(0);
7411 if (!isa<ConstantSDNode>(FirstOp) &&
7412 std::all_of(std::next(Op->op_begin()), Op->op_end(),
7413 [&FirstOp](SDUse &U) {
7414 return U.get().isUndef() || U.get() == FirstOp;
7415 })) {
7416 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7417 DAG.getValueType(MVT::i1));
7418 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7419 }
7420
7421 // First create base with bits set where known
7422 unsigned Bits32 = 0;
7423 for (unsigned i = 0; i < NumElts; ++i) {
7424 SDValue V = Op.getOperand(i);
7425 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7426 continue;
7427 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7428 if (BitSet)
7429 Bits32 |= BoolMask << (i * BitsPerBool);
7430 }
7431
7432 // Add in unknown nodes
7433 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7434 DAG.getConstant(Bits32, dl, MVT::i32));
7435 for (unsigned i = 0; i < NumElts; ++i) {
7436 SDValue V = Op.getOperand(i);
7437 if (isa<ConstantSDNode>(V) || V.isUndef())
7438 continue;
7439 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7440 DAG.getConstant(i, dl, MVT::i32));
7441 }
7442
7443 return Base;
7444 }
7445
7446 // If this is a case we can't handle, return null and let the default
7447 // expansion code take care of it.
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST) const7448 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7449 const ARMSubtarget *ST) const {
7450 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7451 SDLoc dl(Op);
7452 EVT VT = Op.getValueType();
7453
7454 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7455 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7456
7457 APInt SplatBits, SplatUndef;
7458 unsigned SplatBitSize;
7459 bool HasAnyUndefs;
7460 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7461 if (SplatUndef.isAllOnesValue())
7462 return DAG.getUNDEF(VT);
7463
7464 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7465 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7466 // Check if an immediate VMOV works.
7467 EVT VmovVT;
7468 SDValue Val =
7469 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7470 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7471
7472 if (Val.getNode()) {
7473 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7474 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7475 }
7476
7477 // Try an immediate VMVN.
7478 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7479 Val = isVMOVModifiedImm(
7480 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7481 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7482 if (Val.getNode()) {
7483 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7484 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7485 }
7486
7487 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7488 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7489 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7490 if (ImmVal != -1) {
7491 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7492 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7493 }
7494 }
7495 }
7496 }
7497
7498 // Scan through the operands to see if only one value is used.
7499 //
7500 // As an optimisation, even if more than one value is used it may be more
7501 // profitable to splat with one value then change some lanes.
7502 //
7503 // Heuristically we decide to do this if the vector has a "dominant" value,
7504 // defined as splatted to more than half of the lanes.
7505 unsigned NumElts = VT.getVectorNumElements();
7506 bool isOnlyLowElement = true;
7507 bool usesOnlyOneValue = true;
7508 bool hasDominantValue = false;
7509 bool isConstant = true;
7510
7511 // Map of the number of times a particular SDValue appears in the
7512 // element list.
7513 DenseMap<SDValue, unsigned> ValueCounts;
7514 SDValue Value;
7515 for (unsigned i = 0; i < NumElts; ++i) {
7516 SDValue V = Op.getOperand(i);
7517 if (V.isUndef())
7518 continue;
7519 if (i > 0)
7520 isOnlyLowElement = false;
7521 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7522 isConstant = false;
7523
7524 ValueCounts.insert(std::make_pair(V, 0));
7525 unsigned &Count = ValueCounts[V];
7526
7527 // Is this value dominant? (takes up more than half of the lanes)
7528 if (++Count > (NumElts / 2)) {
7529 hasDominantValue = true;
7530 Value = V;
7531 }
7532 }
7533 if (ValueCounts.size() != 1)
7534 usesOnlyOneValue = false;
7535 if (!Value.getNode() && !ValueCounts.empty())
7536 Value = ValueCounts.begin()->first;
7537
7538 if (ValueCounts.empty())
7539 return DAG.getUNDEF(VT);
7540
7541 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7542 // Keep going if we are hitting this case.
7543 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7544 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7545
7546 unsigned EltSize = VT.getScalarSizeInBits();
7547
7548 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7549 // i32 and try again.
7550 if (hasDominantValue && EltSize <= 32) {
7551 if (!isConstant) {
7552 SDValue N;
7553
7554 // If we are VDUPing a value that comes directly from a vector, that will
7555 // cause an unnecessary move to and from a GPR, where instead we could
7556 // just use VDUPLANE. We can only do this if the lane being extracted
7557 // is at a constant index, as the VDUP from lane instructions only have
7558 // constant-index forms.
7559 ConstantSDNode *constIndex;
7560 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7561 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7562 // We need to create a new undef vector to use for the VDUPLANE if the
7563 // size of the vector from which we get the value is different than the
7564 // size of the vector that we need to create. We will insert the element
7565 // such that the register coalescer will remove unnecessary copies.
7566 if (VT != Value->getOperand(0).getValueType()) {
7567 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7568 VT.getVectorNumElements();
7569 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7570 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7571 Value, DAG.getConstant(index, dl, MVT::i32)),
7572 DAG.getConstant(index, dl, MVT::i32));
7573 } else
7574 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7575 Value->getOperand(0), Value->getOperand(1));
7576 } else
7577 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7578
7579 if (!usesOnlyOneValue) {
7580 // The dominant value was splatted as 'N', but we now have to insert
7581 // all differing elements.
7582 for (unsigned I = 0; I < NumElts; ++I) {
7583 if (Op.getOperand(I) == Value)
7584 continue;
7585 SmallVector<SDValue, 3> Ops;
7586 Ops.push_back(N);
7587 Ops.push_back(Op.getOperand(I));
7588 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7589 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7590 }
7591 }
7592 return N;
7593 }
7594 if (VT.getVectorElementType().isFloatingPoint()) {
7595 SmallVector<SDValue, 8> Ops;
7596 MVT FVT = VT.getVectorElementType().getSimpleVT();
7597 assert(FVT == MVT::f32 || FVT == MVT::f16);
7598 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7599 for (unsigned i = 0; i < NumElts; ++i)
7600 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7601 Op.getOperand(i)));
7602 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7603 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7604 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7605 if (Val.getNode())
7606 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7607 }
7608 if (usesOnlyOneValue) {
7609 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7610 if (isConstant && Val.getNode())
7611 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7612 }
7613 }
7614
7615 // If all elements are constants and the case above didn't get hit, fall back
7616 // to the default expansion, which will generate a load from the constant
7617 // pool.
7618 if (isConstant)
7619 return SDValue();
7620
7621 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7622 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7623 // length <= 2.
7624 if (NumElts >= 4)
7625 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7626 return shuffle;
7627
7628 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7629 // VCVT's
7630 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7631 return VCVT;
7632 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7633 return VCVT;
7634
7635 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7636 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7637 // into two 64-bit vectors; we might discover a better way to lower it.
7638 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7639 EVT ExtVT = VT.getVectorElementType();
7640 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7641 SDValue Lower =
7642 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7643 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7644 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7645 SDValue Upper = DAG.getBuildVector(
7646 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7647 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7648 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7649 if (Lower && Upper)
7650 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7651 }
7652
7653 // Vectors with 32- or 64-bit elements can be built by directly assigning
7654 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7655 // will be legalized.
7656 if (EltSize >= 32) {
7657 // Do the expansion with floating-point types, since that is what the VFP
7658 // registers are defined to use, and since i64 is not legal.
7659 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7660 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7661 SmallVector<SDValue, 8> Ops;
7662 for (unsigned i = 0; i < NumElts; ++i)
7663 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7664 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7665 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7666 }
7667
7668 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7669 // know the default expansion would otherwise fall back on something even
7670 // worse. For a vector with one or two non-undef values, that's
7671 // scalar_to_vector for the elements followed by a shuffle (provided the
7672 // shuffle is valid for the target) and materialization element by element
7673 // on the stack followed by a load for everything else.
7674 if (!isConstant && !usesOnlyOneValue) {
7675 SDValue Vec = DAG.getUNDEF(VT);
7676 for (unsigned i = 0 ; i < NumElts; ++i) {
7677 SDValue V = Op.getOperand(i);
7678 if (V.isUndef())
7679 continue;
7680 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7681 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7682 }
7683 return Vec;
7684 }
7685
7686 return SDValue();
7687 }
7688
7689 // Gather data to see if the operation can be modelled as a
7690 // shuffle in combination with VEXTs.
ReconstructShuffle(SDValue Op,SelectionDAG & DAG) const7691 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7692 SelectionDAG &DAG) const {
7693 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7694 SDLoc dl(Op);
7695 EVT VT = Op.getValueType();
7696 unsigned NumElts = VT.getVectorNumElements();
7697
7698 struct ShuffleSourceInfo {
7699 SDValue Vec;
7700 unsigned MinElt = std::numeric_limits<unsigned>::max();
7701 unsigned MaxElt = 0;
7702
7703 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7704 // be compatible with the shuffle we intend to construct. As a result
7705 // ShuffleVec will be some sliding window into the original Vec.
7706 SDValue ShuffleVec;
7707
7708 // Code should guarantee that element i in Vec starts at element "WindowBase
7709 // + i * WindowScale in ShuffleVec".
7710 int WindowBase = 0;
7711 int WindowScale = 1;
7712
7713 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7714
7715 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7716 };
7717
7718 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7719 // node.
7720 SmallVector<ShuffleSourceInfo, 2> Sources;
7721 for (unsigned i = 0; i < NumElts; ++i) {
7722 SDValue V = Op.getOperand(i);
7723 if (V.isUndef())
7724 continue;
7725 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7726 // A shuffle can only come from building a vector from various
7727 // elements of other vectors.
7728 return SDValue();
7729 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7730 // Furthermore, shuffles require a constant mask, whereas extractelts
7731 // accept variable indices.
7732 return SDValue();
7733 }
7734
7735 // Add this element source to the list if it's not already there.
7736 SDValue SourceVec = V.getOperand(0);
7737 auto Source = llvm::find(Sources, SourceVec);
7738 if (Source == Sources.end())
7739 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7740
7741 // Update the minimum and maximum lane number seen.
7742 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7743 Source->MinElt = std::min(Source->MinElt, EltNo);
7744 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7745 }
7746
7747 // Currently only do something sane when at most two source vectors
7748 // are involved.
7749 if (Sources.size() > 2)
7750 return SDValue();
7751
7752 // Find out the smallest element size among result and two sources, and use
7753 // it as element size to build the shuffle_vector.
7754 EVT SmallestEltTy = VT.getVectorElementType();
7755 for (auto &Source : Sources) {
7756 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7757 if (SrcEltTy.bitsLT(SmallestEltTy))
7758 SmallestEltTy = SrcEltTy;
7759 }
7760 unsigned ResMultiplier =
7761 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7762 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7763 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7764
7765 // If the source vector is too wide or too narrow, we may nevertheless be able
7766 // to construct a compatible shuffle either by concatenating it with UNDEF or
7767 // extracting a suitable range of elements.
7768 for (auto &Src : Sources) {
7769 EVT SrcVT = Src.ShuffleVec.getValueType();
7770
7771 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7772 uint64_t VTSize = VT.getFixedSizeInBits();
7773 if (SrcVTSize == VTSize)
7774 continue;
7775
7776 // This stage of the search produces a source with the same element type as
7777 // the original, but with a total width matching the BUILD_VECTOR output.
7778 EVT EltVT = SrcVT.getVectorElementType();
7779 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
7780 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7781
7782 if (SrcVTSize < VTSize) {
7783 if (2 * SrcVTSize != VTSize)
7784 return SDValue();
7785 // We can pad out the smaller vector for free, so if it's part of a
7786 // shuffle...
7787 Src.ShuffleVec =
7788 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7789 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7790 continue;
7791 }
7792
7793 if (SrcVTSize != 2 * VTSize)
7794 return SDValue();
7795
7796 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7797 // Span too large for a VEXT to cope
7798 return SDValue();
7799 }
7800
7801 if (Src.MinElt >= NumSrcElts) {
7802 // The extraction can just take the second half
7803 Src.ShuffleVec =
7804 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7805 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7806 Src.WindowBase = -NumSrcElts;
7807 } else if (Src.MaxElt < NumSrcElts) {
7808 // The extraction can just take the first half
7809 Src.ShuffleVec =
7810 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7811 DAG.getConstant(0, dl, MVT::i32));
7812 } else {
7813 // An actual VEXT is needed
7814 SDValue VEXTSrc1 =
7815 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7816 DAG.getConstant(0, dl, MVT::i32));
7817 SDValue VEXTSrc2 =
7818 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7819 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7820
7821 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7822 VEXTSrc2,
7823 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7824 Src.WindowBase = -Src.MinElt;
7825 }
7826 }
7827
7828 // Another possible incompatibility occurs from the vector element types. We
7829 // can fix this by bitcasting the source vectors to the same type we intend
7830 // for the shuffle.
7831 for (auto &Src : Sources) {
7832 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7833 if (SrcEltTy == SmallestEltTy)
7834 continue;
7835 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7836 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
7837 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7838 Src.WindowBase *= Src.WindowScale;
7839 }
7840
7841 // Final sanity check before we try to actually produce a shuffle.
7842 LLVM_DEBUG(for (auto Src
7843 : Sources)
7844 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7845
7846 // The stars all align, our next step is to produce the mask for the shuffle.
7847 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7848 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7849 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7850 SDValue Entry = Op.getOperand(i);
7851 if (Entry.isUndef())
7852 continue;
7853
7854 auto Src = llvm::find(Sources, Entry.getOperand(0));
7855 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7856
7857 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7858 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7859 // segment.
7860 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7861 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
7862 VT.getScalarSizeInBits());
7863 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7864
7865 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7866 // starting at the appropriate offset.
7867 int *LaneMask = &Mask[i * ResMultiplier];
7868
7869 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7870 ExtractBase += NumElts * (Src - Sources.begin());
7871 for (int j = 0; j < LanesDefined; ++j)
7872 LaneMask[j] = ExtractBase + j;
7873 }
7874
7875
7876 // We can't handle more than two sources. This should have already
7877 // been checked before this point.
7878 assert(Sources.size() <= 2 && "Too many sources!");
7879
7880 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7881 for (unsigned i = 0; i < Sources.size(); ++i)
7882 ShuffleOps[i] = Sources[i].ShuffleVec;
7883
7884 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7885 ShuffleOps[1], Mask, DAG);
7886 if (!Shuffle)
7887 return SDValue();
7888 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
7889 }
7890
7891 enum ShuffleOpCodes {
7892 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7893 OP_VREV,
7894 OP_VDUP0,
7895 OP_VDUP1,
7896 OP_VDUP2,
7897 OP_VDUP3,
7898 OP_VEXT1,
7899 OP_VEXT2,
7900 OP_VEXT3,
7901 OP_VUZPL, // VUZP, left result
7902 OP_VUZPR, // VUZP, right result
7903 OP_VZIPL, // VZIP, left result
7904 OP_VZIPR, // VZIP, right result
7905 OP_VTRNL, // VTRN, left result
7906 OP_VTRNR // VTRN, right result
7907 };
7908
isLegalMVEShuffleOp(unsigned PFEntry)7909 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7910 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7911 switch (OpNum) {
7912 case OP_COPY:
7913 case OP_VREV:
7914 case OP_VDUP0:
7915 case OP_VDUP1:
7916 case OP_VDUP2:
7917 case OP_VDUP3:
7918 return true;
7919 }
7920 return false;
7921 }
7922
7923 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7924 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7925 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7926 /// are assumed to be legal.
isShuffleMaskLegal(ArrayRef<int> M,EVT VT) const7927 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7928 if (VT.getVectorNumElements() == 4 &&
7929 (VT.is128BitVector() || VT.is64BitVector())) {
7930 unsigned PFIndexes[4];
7931 for (unsigned i = 0; i != 4; ++i) {
7932 if (M[i] < 0)
7933 PFIndexes[i] = 8;
7934 else
7935 PFIndexes[i] = M[i];
7936 }
7937
7938 // Compute the index in the perfect shuffle table.
7939 unsigned PFTableIndex =
7940 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7941 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7942 unsigned Cost = (PFEntry >> 30);
7943
7944 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7945 return true;
7946 }
7947
7948 bool ReverseVEXT, isV_UNDEF;
7949 unsigned Imm, WhichResult;
7950
7951 unsigned EltSize = VT.getScalarSizeInBits();
7952 if (EltSize >= 32 ||
7953 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7954 ShuffleVectorInst::isIdentityMask(M) ||
7955 isVREVMask(M, VT, 64) ||
7956 isVREVMask(M, VT, 32) ||
7957 isVREVMask(M, VT, 16))
7958 return true;
7959 else if (Subtarget->hasNEON() &&
7960 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7961 isVTBLMask(M, VT) ||
7962 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7963 return true;
7964 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7965 isReverseMask(M, VT))
7966 return true;
7967 else if (Subtarget->hasMVEIntegerOps() &&
7968 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7969 return true;
7970 else
7971 return false;
7972 }
7973
7974 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7975 /// the specified operations to build the shuffle.
GeneratePerfectShuffle(unsigned PFEntry,SDValue LHS,SDValue RHS,SelectionDAG & DAG,const SDLoc & dl)7976 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7977 SDValue RHS, SelectionDAG &DAG,
7978 const SDLoc &dl) {
7979 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7980 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7981 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7982
7983 if (OpNum == OP_COPY) {
7984 if (LHSID == (1*9+2)*9+3) return LHS;
7985 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7986 return RHS;
7987 }
7988
7989 SDValue OpLHS, OpRHS;
7990 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7991 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7992 EVT VT = OpLHS.getValueType();
7993
7994 switch (OpNum) {
7995 default: llvm_unreachable("Unknown shuffle opcode!");
7996 case OP_VREV:
7997 // VREV divides the vector in half and swaps within the half.
7998 if (VT.getVectorElementType() == MVT::i32 ||
7999 VT.getVectorElementType() == MVT::f32)
8000 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8001 // vrev <4 x i16> -> VREV32
8002 if (VT.getVectorElementType() == MVT::i16)
8003 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8004 // vrev <4 x i8> -> VREV16
8005 assert(VT.getVectorElementType() == MVT::i8);
8006 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8007 case OP_VDUP0:
8008 case OP_VDUP1:
8009 case OP_VDUP2:
8010 case OP_VDUP3:
8011 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8012 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8013 case OP_VEXT1:
8014 case OP_VEXT2:
8015 case OP_VEXT3:
8016 return DAG.getNode(ARMISD::VEXT, dl, VT,
8017 OpLHS, OpRHS,
8018 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8019 case OP_VUZPL:
8020 case OP_VUZPR:
8021 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8022 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8023 case OP_VZIPL:
8024 case OP_VZIPR:
8025 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8026 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8027 case OP_VTRNL:
8028 case OP_VTRNR:
8029 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8030 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8031 }
8032 }
8033
LowerVECTOR_SHUFFLEv8i8(SDValue Op,ArrayRef<int> ShuffleMask,SelectionDAG & DAG)8034 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8035 ArrayRef<int> ShuffleMask,
8036 SelectionDAG &DAG) {
8037 // Check to see if we can use the VTBL instruction.
8038 SDValue V1 = Op.getOperand(0);
8039 SDValue V2 = Op.getOperand(1);
8040 SDLoc DL(Op);
8041
8042 SmallVector<SDValue, 8> VTBLMask;
8043 for (ArrayRef<int>::iterator
8044 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
8045 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
8046
8047 if (V2.getNode()->isUndef())
8048 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8049 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8050
8051 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8052 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8053 }
8054
LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,SelectionDAG & DAG)8055 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
8056 SelectionDAG &DAG) {
8057 SDLoc DL(Op);
8058 SDValue OpLHS = Op.getOperand(0);
8059 EVT VT = OpLHS.getValueType();
8060
8061 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
8062 "Expect an v8i16/v16i8 type");
8063 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
8064 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
8065 // extract the first 8 bytes into the top double word and the last 8 bytes
8066 // into the bottom double word. The v8i16 case is similar.
8067 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
8068 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
8069 DAG.getConstant(ExtractNum, DL, MVT::i32));
8070 }
8071
getVectorTyFromPredicateVector(EVT VT)8072 static EVT getVectorTyFromPredicateVector(EVT VT) {
8073 switch (VT.getSimpleVT().SimpleTy) {
8074 case MVT::v4i1:
8075 return MVT::v4i32;
8076 case MVT::v8i1:
8077 return MVT::v8i16;
8078 case MVT::v16i1:
8079 return MVT::v16i8;
8080 default:
8081 llvm_unreachable("Unexpected vector predicate type");
8082 }
8083 }
8084
PromoteMVEPredVector(SDLoc dl,SDValue Pred,EVT VT,SelectionDAG & DAG)8085 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8086 SelectionDAG &DAG) {
8087 // Converting from boolean predicates to integers involves creating a vector
8088 // of all ones or all zeroes and selecting the lanes based upon the real
8089 // predicate.
8090 SDValue AllOnes =
8091 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8092 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8093
8094 SDValue AllZeroes =
8095 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8096 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8097
8098 // Get full vector type from predicate type
8099 EVT NewVT = getVectorTyFromPredicateVector(VT);
8100
8101 SDValue RecastV1;
8102 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8103 // this to a v16i1. This cannot be done with an ordinary bitcast because the
8104 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8105 // since we know in hardware the sizes are really the same.
8106 if (VT != MVT::v16i1)
8107 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8108 else
8109 RecastV1 = Pred;
8110
8111 // Select either all ones or zeroes depending upon the real predicate bits.
8112 SDValue PredAsVector =
8113 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8114
8115 // Recast our new predicate-as-integer v16i8 vector into something
8116 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8117 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8118 }
8119
LowerVECTOR_SHUFFLE_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8120 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8121 const ARMSubtarget *ST) {
8122 EVT VT = Op.getValueType();
8123 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8124 ArrayRef<int> ShuffleMask = SVN->getMask();
8125
8126 assert(ST->hasMVEIntegerOps() &&
8127 "No support for vector shuffle of boolean predicates");
8128
8129 SDValue V1 = Op.getOperand(0);
8130 SDLoc dl(Op);
8131 if (isReverseMask(ShuffleMask, VT)) {
8132 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8133 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8134 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8135 DAG.getConstant(16, dl, MVT::i32));
8136 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8137 }
8138
8139 // Until we can come up with optimised cases for every single vector
8140 // shuffle in existence we have chosen the least painful strategy. This is
8141 // to essentially promote the boolean predicate to a 8-bit integer, where
8142 // each predicate represents a byte. Then we fall back on a normal integer
8143 // vector shuffle and convert the result back into a predicate vector. In
8144 // many cases the generated code might be even better than scalar code
8145 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8146 // fields in a register into 8 other arbitrary 2-bit fields!
8147 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
8148 EVT NewVT = PredAsVector.getValueType();
8149
8150 // Do the shuffle!
8151 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
8152 DAG.getUNDEF(NewVT), ShuffleMask);
8153
8154 // Now return the result of comparing the shuffled vector with zero,
8155 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8156 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8157 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8158 }
8159
LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,ArrayRef<int> ShuffleMask,SelectionDAG & DAG)8160 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8161 ArrayRef<int> ShuffleMask,
8162 SelectionDAG &DAG) {
8163 // Attempt to lower the vector shuffle using as many whole register movs as
8164 // possible. This is useful for types smaller than 32bits, which would
8165 // often otherwise become a series for grp movs.
8166 SDLoc dl(Op);
8167 EVT VT = Op.getValueType();
8168 if (VT.getScalarSizeInBits() >= 32)
8169 return SDValue();
8170
8171 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8172 "Unexpected vector type");
8173 int NumElts = VT.getVectorNumElements();
8174 int QuarterSize = NumElts / 4;
8175 // The four final parts of the vector, as i32's
8176 SDValue Parts[4];
8177
8178 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8179 // <u,u,u,u>), returning the vmov lane index
8180 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8181 // Detect which mov lane this would be from the first non-undef element.
8182 int MovIdx = -1;
8183 for (int i = 0; i < Length; i++) {
8184 if (ShuffleMask[Start + i] >= 0) {
8185 if (ShuffleMask[Start + i] % Length != i)
8186 return -1;
8187 MovIdx = ShuffleMask[Start + i] / Length;
8188 break;
8189 }
8190 }
8191 // If all items are undef, leave this for other combines
8192 if (MovIdx == -1)
8193 return -1;
8194 // Check the remaining values are the correct part of the same mov
8195 for (int i = 1; i < Length; i++) {
8196 if (ShuffleMask[Start + i] >= 0 &&
8197 (ShuffleMask[Start + i] / Length != MovIdx ||
8198 ShuffleMask[Start + i] % Length != i))
8199 return -1;
8200 }
8201 return MovIdx;
8202 };
8203
8204 for (int Part = 0; Part < 4; ++Part) {
8205 // Does this part look like a mov
8206 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8207 if (Elt != -1) {
8208 SDValue Input = Op->getOperand(0);
8209 if (Elt >= 4) {
8210 Input = Op->getOperand(1);
8211 Elt -= 4;
8212 }
8213 SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input);
8214 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast,
8215 DAG.getConstant(Elt, dl, MVT::i32));
8216 }
8217 }
8218
8219 // Nothing interesting found, just return
8220 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8221 return SDValue();
8222
8223 // The other parts need to be built with the old shuffle vector, cast to a
8224 // v4i32 and extract_vector_elts
8225 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8226 SmallVector<int, 16> NewShuffleMask;
8227 for (int Part = 0; Part < 4; ++Part)
8228 for (int i = 0; i < QuarterSize; i++)
8229 NewShuffleMask.push_back(
8230 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8231 SDValue NewShuffle = DAG.getVectorShuffle(
8232 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8233 SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle);
8234
8235 for (int Part = 0; Part < 4; ++Part)
8236 if (!Parts[Part])
8237 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8238 BitCast, DAG.getConstant(Part, dl, MVT::i32));
8239 }
8240 // Build a vector out of the various parts and bitcast it back to the original
8241 // type.
8242 SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts);
8243 return DAG.getBitcast(VT, NewVec);
8244 }
8245
LowerVECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8246 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8247 const ARMSubtarget *ST) {
8248 SDValue V1 = Op.getOperand(0);
8249 SDValue V2 = Op.getOperand(1);
8250 SDLoc dl(Op);
8251 EVT VT = Op.getValueType();
8252 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8253 unsigned EltSize = VT.getScalarSizeInBits();
8254
8255 if (ST->hasMVEIntegerOps() && EltSize == 1)
8256 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8257
8258 // Convert shuffles that are directly supported on NEON to target-specific
8259 // DAG nodes, instead of keeping them as shuffles and matching them again
8260 // during code selection. This is more efficient and avoids the possibility
8261 // of inconsistencies between legalization and selection.
8262 // FIXME: floating-point vectors should be canonicalized to integer vectors
8263 // of the same time so that they get CSEd properly.
8264 ArrayRef<int> ShuffleMask = SVN->getMask();
8265
8266 if (EltSize <= 32) {
8267 if (SVN->isSplat()) {
8268 int Lane = SVN->getSplatIndex();
8269 // If this is undef splat, generate it via "just" vdup, if possible.
8270 if (Lane == -1) Lane = 0;
8271
8272 // Test if V1 is a SCALAR_TO_VECTOR.
8273 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8274 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8275 }
8276 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8277 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8278 // reaches it).
8279 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8280 !isa<ConstantSDNode>(V1.getOperand(0))) {
8281 bool IsScalarToVector = true;
8282 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8283 if (!V1.getOperand(i).isUndef()) {
8284 IsScalarToVector = false;
8285 break;
8286 }
8287 if (IsScalarToVector)
8288 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8289 }
8290 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8291 DAG.getConstant(Lane, dl, MVT::i32));
8292 }
8293
8294 bool ReverseVEXT = false;
8295 unsigned Imm = 0;
8296 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8297 if (ReverseVEXT)
8298 std::swap(V1, V2);
8299 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8300 DAG.getConstant(Imm, dl, MVT::i32));
8301 }
8302
8303 if (isVREVMask(ShuffleMask, VT, 64))
8304 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8305 if (isVREVMask(ShuffleMask, VT, 32))
8306 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8307 if (isVREVMask(ShuffleMask, VT, 16))
8308 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8309
8310 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8311 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8312 DAG.getConstant(Imm, dl, MVT::i32));
8313 }
8314
8315 // Check for Neon shuffles that modify both input vectors in place.
8316 // If both results are used, i.e., if there are two shuffles with the same
8317 // source operands and with masks corresponding to both results of one of
8318 // these operations, DAG memoization will ensure that a single node is
8319 // used for both shuffles.
8320 unsigned WhichResult = 0;
8321 bool isV_UNDEF = false;
8322 if (ST->hasNEON()) {
8323 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8324 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8325 if (isV_UNDEF)
8326 V2 = V1;
8327 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8328 .getValue(WhichResult);
8329 }
8330 }
8331 if (ST->hasMVEIntegerOps()) {
8332 if (isVMOVNMask(ShuffleMask, VT, 0))
8333 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8334 DAG.getConstant(0, dl, MVT::i32));
8335 if (isVMOVNMask(ShuffleMask, VT, 1))
8336 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8337 DAG.getConstant(1, dl, MVT::i32));
8338 }
8339
8340 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8341 // shuffles that produce a result larger than their operands with:
8342 // shuffle(concat(v1, undef), concat(v2, undef))
8343 // ->
8344 // shuffle(concat(v1, v2), undef)
8345 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8346 //
8347 // This is useful in the general case, but there are special cases where
8348 // native shuffles produce larger results: the two-result ops.
8349 //
8350 // Look through the concat when lowering them:
8351 // shuffle(concat(v1, v2), undef)
8352 // ->
8353 // concat(VZIP(v1, v2):0, :1)
8354 //
8355 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8356 SDValue SubV1 = V1->getOperand(0);
8357 SDValue SubV2 = V1->getOperand(1);
8358 EVT SubVT = SubV1.getValueType();
8359
8360 // We expect these to have been canonicalized to -1.
8361 assert(llvm::all_of(ShuffleMask, [&](int i) {
8362 return i < (int)VT.getVectorNumElements();
8363 }) && "Unexpected shuffle index into UNDEF operand!");
8364
8365 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8366 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8367 if (isV_UNDEF)
8368 SubV2 = SubV1;
8369 assert((WhichResult == 0) &&
8370 "In-place shuffle of concat can only have one result!");
8371 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8372 SubV1, SubV2);
8373 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8374 Res.getValue(1));
8375 }
8376 }
8377 }
8378
8379 // If the shuffle is not directly supported and it has 4 elements, use
8380 // the PerfectShuffle-generated table to synthesize it from other shuffles.
8381 unsigned NumElts = VT.getVectorNumElements();
8382 if (NumElts == 4) {
8383 unsigned PFIndexes[4];
8384 for (unsigned i = 0; i != 4; ++i) {
8385 if (ShuffleMask[i] < 0)
8386 PFIndexes[i] = 8;
8387 else
8388 PFIndexes[i] = ShuffleMask[i];
8389 }
8390
8391 // Compute the index in the perfect shuffle table.
8392 unsigned PFTableIndex =
8393 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8394 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8395 unsigned Cost = (PFEntry >> 30);
8396
8397 if (Cost <= 4) {
8398 if (ST->hasNEON())
8399 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8400 else if (isLegalMVEShuffleOp(PFEntry)) {
8401 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8402 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8403 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8404 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8405 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8406 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8407 }
8408 }
8409 }
8410
8411 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8412 if (EltSize >= 32) {
8413 // Do the expansion with floating-point types, since that is what the VFP
8414 // registers are defined to use, and since i64 is not legal.
8415 EVT EltVT = EVT::getFloatingPointVT(EltSize);
8416 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8417 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8418 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8419 SmallVector<SDValue, 8> Ops;
8420 for (unsigned i = 0; i < NumElts; ++i) {
8421 if (ShuffleMask[i] < 0)
8422 Ops.push_back(DAG.getUNDEF(EltVT));
8423 else
8424 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8425 ShuffleMask[i] < (int)NumElts ? V1 : V2,
8426 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8427 dl, MVT::i32)));
8428 }
8429 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8430 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8431 }
8432
8433 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
8434 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
8435
8436 if (ST->hasNEON() && VT == MVT::v8i8)
8437 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8438 return NewOp;
8439
8440 if (ST->hasMVEIntegerOps())
8441 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8442 return NewOp;
8443
8444 return SDValue();
8445 }
8446
LowerINSERT_VECTOR_ELT_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8447 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8448 const ARMSubtarget *ST) {
8449 EVT VecVT = Op.getOperand(0).getValueType();
8450 SDLoc dl(Op);
8451
8452 assert(ST->hasMVEIntegerOps() &&
8453 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8454
8455 SDValue Conv =
8456 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8457 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8458 unsigned LaneWidth =
8459 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8460 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8461 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8462 Op.getOperand(1), DAG.getValueType(MVT::i1));
8463 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8464 DAG.getConstant(~Mask, dl, MVT::i32));
8465 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8466 }
8467
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const8468 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8469 SelectionDAG &DAG) const {
8470 // INSERT_VECTOR_ELT is legal only for immediate indexes.
8471 SDValue Lane = Op.getOperand(2);
8472 if (!isa<ConstantSDNode>(Lane))
8473 return SDValue();
8474
8475 SDValue Elt = Op.getOperand(1);
8476 EVT EltVT = Elt.getValueType();
8477
8478 if (Subtarget->hasMVEIntegerOps() &&
8479 Op.getValueType().getScalarSizeInBits() == 1)
8480 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8481
8482 if (getTypeAction(*DAG.getContext(), EltVT) ==
8483 TargetLowering::TypePromoteFloat) {
8484 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8485 // but the type system will try to do that if we don't intervene.
8486 // Reinterpret any such vector-element insertion as one with the
8487 // corresponding integer types.
8488
8489 SDLoc dl(Op);
8490
8491 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8492 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8493 TargetLowering::TypePromoteFloat);
8494
8495 SDValue VecIn = Op.getOperand(0);
8496 EVT VecVT = VecIn.getValueType();
8497 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8498 VecVT.getVectorNumElements());
8499
8500 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8501 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8502 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8503 IVecIn, IElt, Lane);
8504 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8505 }
8506
8507 return Op;
8508 }
8509
LowerEXTRACT_VECTOR_ELT_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8510 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8511 const ARMSubtarget *ST) {
8512 EVT VecVT = Op.getOperand(0).getValueType();
8513 SDLoc dl(Op);
8514
8515 assert(ST->hasMVEIntegerOps() &&
8516 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8517
8518 SDValue Conv =
8519 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8520 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8521 unsigned LaneWidth =
8522 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8523 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8524 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8525 return Shift;
8526 }
8527
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8528 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8529 const ARMSubtarget *ST) {
8530 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8531 SDValue Lane = Op.getOperand(1);
8532 if (!isa<ConstantSDNode>(Lane))
8533 return SDValue();
8534
8535 SDValue Vec = Op.getOperand(0);
8536 EVT VT = Vec.getValueType();
8537
8538 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8539 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8540
8541 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8542 SDLoc dl(Op);
8543 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8544 }
8545
8546 return Op;
8547 }
8548
LowerCONCAT_VECTORS_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8549 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8550 const ARMSubtarget *ST) {
8551 SDValue V1 = Op.getOperand(0);
8552 SDValue V2 = Op.getOperand(1);
8553 SDLoc dl(Op);
8554 EVT VT = Op.getValueType();
8555 EVT Op1VT = V1.getValueType();
8556 EVT Op2VT = V2.getValueType();
8557 unsigned NumElts = VT.getVectorNumElements();
8558
8559 assert(Op1VT == Op2VT && "Operand types don't match!");
8560 assert(VT.getScalarSizeInBits() == 1 &&
8561 "Unexpected custom CONCAT_VECTORS lowering");
8562 assert(ST->hasMVEIntegerOps() &&
8563 "CONCAT_VECTORS lowering only supported for MVE");
8564
8565 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8566 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8567
8568 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8569 // promoted to v8i16, etc.
8570
8571 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8572
8573 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8574 // to be the right size for the destination. For example, if Op1 is v4i1 then
8575 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8576 // which when promoted is v8i16. That means each i32 element from Op1 needs
8577 // truncating to i16 and inserting in the result.
8578 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8579 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8580 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8581 EVT NewVT = NewV.getValueType();
8582 EVT ConcatVT = ConVec.getValueType();
8583 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8584 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8585 DAG.getIntPtrConstant(i, dl));
8586 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8587 DAG.getConstant(j, dl, MVT::i32));
8588 }
8589 return ConVec;
8590 };
8591 unsigned j = 0;
8592 ConVec = ExractInto(NewV1, ConVec, j);
8593 ConVec = ExractInto(NewV2, ConVec, j);
8594
8595 // Now return the result of comparing the subvector with zero,
8596 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8597 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8598 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8599 }
8600
LowerCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8601 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8602 const ARMSubtarget *ST) {
8603 EVT VT = Op->getValueType(0);
8604 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8605 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8606
8607 // The only time a CONCAT_VECTORS operation can have legal types is when
8608 // two 64-bit vectors are concatenated to a 128-bit vector.
8609 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8610 "unexpected CONCAT_VECTORS");
8611 SDLoc dl(Op);
8612 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8613 SDValue Op0 = Op.getOperand(0);
8614 SDValue Op1 = Op.getOperand(1);
8615 if (!Op0.isUndef())
8616 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8617 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8618 DAG.getIntPtrConstant(0, dl));
8619 if (!Op1.isUndef())
8620 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8621 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8622 DAG.getIntPtrConstant(1, dl));
8623 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8624 }
8625
LowerEXTRACT_SUBVECTOR(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8626 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8627 const ARMSubtarget *ST) {
8628 SDValue V1 = Op.getOperand(0);
8629 SDValue V2 = Op.getOperand(1);
8630 SDLoc dl(Op);
8631 EVT VT = Op.getValueType();
8632 EVT Op1VT = V1.getValueType();
8633 unsigned NumElts = VT.getVectorNumElements();
8634 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8635
8636 assert(VT.getScalarSizeInBits() == 1 &&
8637 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8638 assert(ST->hasMVEIntegerOps() &&
8639 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8640
8641 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8642
8643 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8644 // promoted to v8i16, etc.
8645
8646 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8647
8648 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8649 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8650 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8651 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8652 DAG.getIntPtrConstant(i, dl));
8653 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8654 DAG.getConstant(j, dl, MVT::i32));
8655 }
8656
8657 // Now return the result of comparing the subvector with zero,
8658 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8659 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8660 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8661 }
8662
8663 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8664 /// element has been zero/sign-extended, depending on the isSigned parameter,
8665 /// from an integer type half its size.
isExtendedBUILD_VECTOR(SDNode * N,SelectionDAG & DAG,bool isSigned)8666 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8667 bool isSigned) {
8668 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8669 EVT VT = N->getValueType(0);
8670 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8671 SDNode *BVN = N->getOperand(0).getNode();
8672 if (BVN->getValueType(0) != MVT::v4i32 ||
8673 BVN->getOpcode() != ISD::BUILD_VECTOR)
8674 return false;
8675 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8676 unsigned HiElt = 1 - LoElt;
8677 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8678 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8679 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8680 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8681 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8682 return false;
8683 if (isSigned) {
8684 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8685 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8686 return true;
8687 } else {
8688 if (Hi0->isNullValue() && Hi1->isNullValue())
8689 return true;
8690 }
8691 return false;
8692 }
8693
8694 if (N->getOpcode() != ISD::BUILD_VECTOR)
8695 return false;
8696
8697 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8698 SDNode *Elt = N->getOperand(i).getNode();
8699 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8700 unsigned EltSize = VT.getScalarSizeInBits();
8701 unsigned HalfSize = EltSize / 2;
8702 if (isSigned) {
8703 if (!isIntN(HalfSize, C->getSExtValue()))
8704 return false;
8705 } else {
8706 if (!isUIntN(HalfSize, C->getZExtValue()))
8707 return false;
8708 }
8709 continue;
8710 }
8711 return false;
8712 }
8713
8714 return true;
8715 }
8716
8717 /// isSignExtended - Check if a node is a vector value that is sign-extended
8718 /// or a constant BUILD_VECTOR with sign-extended elements.
isSignExtended(SDNode * N,SelectionDAG & DAG)8719 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8720 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8721 return true;
8722 if (isExtendedBUILD_VECTOR(N, DAG, true))
8723 return true;
8724 return false;
8725 }
8726
8727 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8728 /// or a constant BUILD_VECTOR with zero-extended elements.
isZeroExtended(SDNode * N,SelectionDAG & DAG)8729 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8730 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8731 return true;
8732 if (isExtendedBUILD_VECTOR(N, DAG, false))
8733 return true;
8734 return false;
8735 }
8736
getExtensionTo64Bits(const EVT & OrigVT)8737 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8738 if (OrigVT.getSizeInBits() >= 64)
8739 return OrigVT;
8740
8741 assert(OrigVT.isSimple() && "Expecting a simple value type");
8742
8743 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8744 switch (OrigSimpleTy) {
8745 default: llvm_unreachable("Unexpected Vector Type");
8746 case MVT::v2i8:
8747 case MVT::v2i16:
8748 return MVT::v2i32;
8749 case MVT::v4i8:
8750 return MVT::v4i16;
8751 }
8752 }
8753
8754 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8755 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8756 /// 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)8757 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8758 const EVT &OrigTy,
8759 const EVT &ExtTy,
8760 unsigned ExtOpcode) {
8761 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8762 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8763 // 64-bits we need to insert a new extension so that it will be 64-bits.
8764 assert(ExtTy.is128BitVector() && "Unexpected extension size");
8765 if (OrigTy.getSizeInBits() >= 64)
8766 return N;
8767
8768 // Must extend size to at least 64 bits to be used as an operand for VMULL.
8769 EVT NewVT = getExtensionTo64Bits(OrigTy);
8770
8771 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8772 }
8773
8774 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8775 /// does not do any sign/zero extension. If the original vector is less
8776 /// than 64 bits, an appropriate extension will be added after the load to
8777 /// reach a total size of 64 bits. We have to add the extension separately
8778 /// because ARM does not have a sign/zero extending load for vectors.
SkipLoadExtensionForVMULL(LoadSDNode * LD,SelectionDAG & DAG)8779 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8780 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8781
8782 // The load already has the right type.
8783 if (ExtendedTy == LD->getMemoryVT())
8784 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8785 LD->getBasePtr(), LD->getPointerInfo(),
8786 LD->getAlignment(), LD->getMemOperand()->getFlags());
8787
8788 // We need to create a zextload/sextload. We cannot just create a load
8789 // followed by a zext/zext node because LowerMUL is also run during normal
8790 // operation legalization where we can't create illegal types.
8791 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8792 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8793 LD->getMemoryVT(), LD->getAlignment(),
8794 LD->getMemOperand()->getFlags());
8795 }
8796
8797 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8798 /// extending load, or BUILD_VECTOR with extended elements, return the
8799 /// unextended value. The unextended vector should be 64 bits so that it can
8800 /// be used as an operand to a VMULL instruction. If the original vector size
8801 /// before extension is less than 64 bits we add a an extension to resize
8802 /// the vector to 64 bits.
SkipExtensionForVMULL(SDNode * N,SelectionDAG & DAG)8803 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8804 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8805 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8806 N->getOperand(0)->getValueType(0),
8807 N->getValueType(0),
8808 N->getOpcode());
8809
8810 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8811 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8812 "Expected extending load");
8813
8814 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8815 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8816 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8817 SDValue extLoad =
8818 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8819 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8820
8821 return newLoad;
8822 }
8823
8824 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8825 // have been legalized as a BITCAST from v4i32.
8826 if (N->getOpcode() == ISD::BITCAST) {
8827 SDNode *BVN = N->getOperand(0).getNode();
8828 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8829 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8830 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8831 return DAG.getBuildVector(
8832 MVT::v2i32, SDLoc(N),
8833 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8834 }
8835 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8836 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8837 EVT VT = N->getValueType(0);
8838 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8839 unsigned NumElts = VT.getVectorNumElements();
8840 MVT TruncVT = MVT::getIntegerVT(EltSize);
8841 SmallVector<SDValue, 8> Ops;
8842 SDLoc dl(N);
8843 for (unsigned i = 0; i != NumElts; ++i) {
8844 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8845 const APInt &CInt = C->getAPIntValue();
8846 // Element types smaller than 32 bits are not legal, so use i32 elements.
8847 // The values are implicitly truncated so sext vs. zext doesn't matter.
8848 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8849 }
8850 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8851 }
8852
isAddSubSExt(SDNode * N,SelectionDAG & DAG)8853 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8854 unsigned Opcode = N->getOpcode();
8855 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8856 SDNode *N0 = N->getOperand(0).getNode();
8857 SDNode *N1 = N->getOperand(1).getNode();
8858 return N0->hasOneUse() && N1->hasOneUse() &&
8859 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8860 }
8861 return false;
8862 }
8863
isAddSubZExt(SDNode * N,SelectionDAG & DAG)8864 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8865 unsigned Opcode = N->getOpcode();
8866 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8867 SDNode *N0 = N->getOperand(0).getNode();
8868 SDNode *N1 = N->getOperand(1).getNode();
8869 return N0->hasOneUse() && N1->hasOneUse() &&
8870 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8871 }
8872 return false;
8873 }
8874
LowerMUL(SDValue Op,SelectionDAG & DAG)8875 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8876 // Multiplications are only custom-lowered for 128-bit vectors so that
8877 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8878 EVT VT = Op.getValueType();
8879 assert(VT.is128BitVector() && VT.isInteger() &&
8880 "unexpected type for custom-lowering ISD::MUL");
8881 SDNode *N0 = Op.getOperand(0).getNode();
8882 SDNode *N1 = Op.getOperand(1).getNode();
8883 unsigned NewOpc = 0;
8884 bool isMLA = false;
8885 bool isN0SExt = isSignExtended(N0, DAG);
8886 bool isN1SExt = isSignExtended(N1, DAG);
8887 if (isN0SExt && isN1SExt)
8888 NewOpc = ARMISD::VMULLs;
8889 else {
8890 bool isN0ZExt = isZeroExtended(N0, DAG);
8891 bool isN1ZExt = isZeroExtended(N1, DAG);
8892 if (isN0ZExt && isN1ZExt)
8893 NewOpc = ARMISD::VMULLu;
8894 else if (isN1SExt || isN1ZExt) {
8895 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8896 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8897 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8898 NewOpc = ARMISD::VMULLs;
8899 isMLA = true;
8900 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8901 NewOpc = ARMISD::VMULLu;
8902 isMLA = true;
8903 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8904 std::swap(N0, N1);
8905 NewOpc = ARMISD::VMULLu;
8906 isMLA = true;
8907 }
8908 }
8909
8910 if (!NewOpc) {
8911 if (VT == MVT::v2i64)
8912 // Fall through to expand this. It is not legal.
8913 return SDValue();
8914 else
8915 // Other vector multiplications are legal.
8916 return Op;
8917 }
8918 }
8919
8920 // Legalize to a VMULL instruction.
8921 SDLoc DL(Op);
8922 SDValue Op0;
8923 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8924 if (!isMLA) {
8925 Op0 = SkipExtensionForVMULL(N0, DAG);
8926 assert(Op0.getValueType().is64BitVector() &&
8927 Op1.getValueType().is64BitVector() &&
8928 "unexpected types for extended operands to VMULL");
8929 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8930 }
8931
8932 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8933 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8934 // vmull q0, d4, d6
8935 // vmlal q0, d5, d6
8936 // is faster than
8937 // vaddl q0, d4, d5
8938 // vmovl q1, d6
8939 // vmul q0, q0, q1
8940 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8941 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8942 EVT Op1VT = Op1.getValueType();
8943 return DAG.getNode(N0->getOpcode(), DL, VT,
8944 DAG.getNode(NewOpc, DL, VT,
8945 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8946 DAG.getNode(NewOpc, DL, VT,
8947 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8948 }
8949
LowerSDIV_v4i8(SDValue X,SDValue Y,const SDLoc & dl,SelectionDAG & DAG)8950 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8951 SelectionDAG &DAG) {
8952 // TODO: Should this propagate fast-math-flags?
8953
8954 // Convert to float
8955 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8956 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8957 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8958 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8959 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8960 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8961 // Get reciprocal estimate.
8962 // float4 recip = vrecpeq_f32(yf);
8963 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8964 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8965 Y);
8966 // Because char has a smaller range than uchar, we can actually get away
8967 // without any newton steps. This requires that we use a weird bias
8968 // of 0xb000, however (again, this has been exhaustively tested).
8969 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8970 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8971 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8972 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8973 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8974 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8975 // Convert back to short.
8976 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8977 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8978 return X;
8979 }
8980
LowerSDIV_v4i16(SDValue N0,SDValue N1,const SDLoc & dl,SelectionDAG & DAG)8981 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8982 SelectionDAG &DAG) {
8983 // TODO: Should this propagate fast-math-flags?
8984
8985 SDValue N2;
8986 // Convert to float.
8987 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8988 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8989 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8990 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8991 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8992 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8993
8994 // Use reciprocal estimate and one refinement step.
8995 // float4 recip = vrecpeq_f32(yf);
8996 // recip *= vrecpsq_f32(yf, recip);
8997 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8998 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8999 N1);
9000 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9001 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9002 N1, N2);
9003 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9004 // Because short has a smaller range than ushort, we can actually get away
9005 // with only a single newton step. This requires that we use a weird bias
9006 // of 89, however (again, this has been exhaustively tested).
9007 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9008 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9009 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9010 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9011 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9012 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9013 // Convert back to integer and return.
9014 // return vmovn_s32(vcvt_s32_f32(result));
9015 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9016 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9017 return N0;
9018 }
9019
LowerSDIV(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9020 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9021 const ARMSubtarget *ST) {
9022 EVT VT = Op.getValueType();
9023 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9024 "unexpected type for custom-lowering ISD::SDIV");
9025
9026 SDLoc dl(Op);
9027 SDValue N0 = Op.getOperand(0);
9028 SDValue N1 = Op.getOperand(1);
9029 SDValue N2, N3;
9030
9031 if (VT == MVT::v8i8) {
9032 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9033 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9034
9035 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9036 DAG.getIntPtrConstant(4, dl));
9037 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9038 DAG.getIntPtrConstant(4, dl));
9039 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9040 DAG.getIntPtrConstant(0, dl));
9041 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9042 DAG.getIntPtrConstant(0, dl));
9043
9044 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9045 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9046
9047 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9048 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9049
9050 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9051 return N0;
9052 }
9053 return LowerSDIV_v4i16(N0, N1, dl, DAG);
9054 }
9055
LowerUDIV(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9056 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9057 const ARMSubtarget *ST) {
9058 // TODO: Should this propagate fast-math-flags?
9059 EVT VT = Op.getValueType();
9060 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9061 "unexpected type for custom-lowering ISD::UDIV");
9062
9063 SDLoc dl(Op);
9064 SDValue N0 = Op.getOperand(0);
9065 SDValue N1 = Op.getOperand(1);
9066 SDValue N2, N3;
9067
9068 if (VT == MVT::v8i8) {
9069 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9070 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9071
9072 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9073 DAG.getIntPtrConstant(4, dl));
9074 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9075 DAG.getIntPtrConstant(4, dl));
9076 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9077 DAG.getIntPtrConstant(0, dl));
9078 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9079 DAG.getIntPtrConstant(0, dl));
9080
9081 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9082 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9083
9084 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9085 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9086
9087 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9088 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9089 MVT::i32),
9090 N0);
9091 return N0;
9092 }
9093
9094 // v4i16 sdiv ... Convert to float.
9095 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9096 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9097 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9098 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9099 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9100 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9101
9102 // Use reciprocal estimate and two refinement steps.
9103 // float4 recip = vrecpeq_f32(yf);
9104 // recip *= vrecpsq_f32(yf, recip);
9105 // recip *= vrecpsq_f32(yf, recip);
9106 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9107 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9108 BN1);
9109 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9110 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9111 BN1, N2);
9112 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9113 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9114 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9115 BN1, N2);
9116 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9117 // Simply multiplying by the reciprocal estimate can leave us a few ulps
9118 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9119 // and that it will never cause us to return an answer too large).
9120 // float4 result = as_float4(as_int4(xf*recip) + 2);
9121 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9122 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9123 N1 = DAG.getConstant(2, dl, MVT::v4i32);
9124 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9125 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9126 // Convert back to integer and return.
9127 // return vmovn_u32(vcvt_s32_f32(result));
9128 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9129 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9130 return N0;
9131 }
9132
LowerADDSUBCARRY(SDValue Op,SelectionDAG & DAG)9133 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
9134 SDNode *N = Op.getNode();
9135 EVT VT = N->getValueType(0);
9136 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9137
9138 SDValue Carry = Op.getOperand(2);
9139
9140 SDLoc DL(Op);
9141
9142 SDValue Result;
9143 if (Op.getOpcode() == ISD::ADDCARRY) {
9144 // This converts the boolean value carry into the carry flag.
9145 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9146
9147 // Do the addition proper using the carry flag we wanted.
9148 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
9149 Op.getOperand(1), Carry);
9150
9151 // Now convert the carry flag into a boolean value.
9152 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9153 } else {
9154 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
9155 // have to invert the carry first.
9156 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9157 DAG.getConstant(1, DL, MVT::i32), Carry);
9158 // This converts the boolean value carry into the carry flag.
9159 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9160
9161 // Do the subtraction proper using the carry flag we wanted.
9162 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
9163 Op.getOperand(1), Carry);
9164
9165 // Now convert the carry flag into a boolean value.
9166 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9167 // But the carry returned by ARMISD::SUBE is not a borrow as expected
9168 // by ISD::SUBCARRY, so compute 1 - C.
9169 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9170 DAG.getConstant(1, DL, MVT::i32), Carry);
9171 }
9172
9173 // Return both values.
9174 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
9175 }
9176
LowerFSINCOS(SDValue Op,SelectionDAG & DAG) const9177 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
9178 assert(Subtarget->isTargetDarwin());
9179
9180 // For iOS, we want to call an alternative entry point: __sincos_stret,
9181 // return values are passed via sret.
9182 SDLoc dl(Op);
9183 SDValue Arg = Op.getOperand(0);
9184 EVT ArgVT = Arg.getValueType();
9185 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9186 auto PtrVT = getPointerTy(DAG.getDataLayout());
9187
9188 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9189 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9190
9191 // Pair of floats / doubles used to pass the result.
9192 Type *RetTy = StructType::get(ArgTy, ArgTy);
9193 auto &DL = DAG.getDataLayout();
9194
9195 ArgListTy Args;
9196 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
9197 SDValue SRet;
9198 if (ShouldUseSRet) {
9199 // Create stack object for sret.
9200 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
9201 const Align StackAlign = DL.getPrefTypeAlign(RetTy);
9202 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
9203 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
9204
9205 ArgListEntry Entry;
9206 Entry.Node = SRet;
9207 Entry.Ty = RetTy->getPointerTo();
9208 Entry.IsSExt = false;
9209 Entry.IsZExt = false;
9210 Entry.IsSRet = true;
9211 Args.push_back(Entry);
9212 RetTy = Type::getVoidTy(*DAG.getContext());
9213 }
9214
9215 ArgListEntry Entry;
9216 Entry.Node = Arg;
9217 Entry.Ty = ArgTy;
9218 Entry.IsSExt = false;
9219 Entry.IsZExt = false;
9220 Args.push_back(Entry);
9221
9222 RTLIB::Libcall LC =
9223 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
9224 const char *LibcallName = getLibcallName(LC);
9225 CallingConv::ID CC = getLibcallCallingConv(LC);
9226 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
9227
9228 TargetLowering::CallLoweringInfo CLI(DAG);
9229 CLI.setDebugLoc(dl)
9230 .setChain(DAG.getEntryNode())
9231 .setCallee(CC, RetTy, Callee, std::move(Args))
9232 .setDiscardResult(ShouldUseSRet);
9233 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9234
9235 if (!ShouldUseSRet)
9236 return CallResult.first;
9237
9238 SDValue LoadSin =
9239 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
9240
9241 // Address of cos field.
9242 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
9243 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
9244 SDValue LoadCos =
9245 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
9246
9247 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
9248 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
9249 LoadSin.getValue(0), LoadCos.getValue(0));
9250 }
9251
LowerWindowsDIVLibCall(SDValue Op,SelectionDAG & DAG,bool Signed,SDValue & Chain) const9252 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9253 bool Signed,
9254 SDValue &Chain) const {
9255 EVT VT = Op.getValueType();
9256 assert((VT == MVT::i32 || VT == MVT::i64) &&
9257 "unexpected type for custom lowering DIV");
9258 SDLoc dl(Op);
9259
9260 const auto &DL = DAG.getDataLayout();
9261 const auto &TLI = DAG.getTargetLoweringInfo();
9262
9263 const char *Name = nullptr;
9264 if (Signed)
9265 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
9266 else
9267 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
9268
9269 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
9270
9271 ARMTargetLowering::ArgListTy Args;
9272
9273 for (auto AI : {1, 0}) {
9274 ArgListEntry Arg;
9275 Arg.Node = Op.getOperand(AI);
9276 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
9277 Args.push_back(Arg);
9278 }
9279
9280 CallLoweringInfo CLI(DAG);
9281 CLI.setDebugLoc(dl)
9282 .setChain(Chain)
9283 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
9284 ES, std::move(Args));
9285
9286 return LowerCallTo(CLI).first;
9287 }
9288
9289 // This is a code size optimisation: return the original SDIV node to
9290 // DAGCombiner when we don't want to expand SDIV into a sequence of
9291 // instructions, and an empty node otherwise which will cause the
9292 // SDIV to be expanded in DAGCombine.
9293 SDValue
BuildSDIVPow2(SDNode * N,const APInt & Divisor,SelectionDAG & DAG,SmallVectorImpl<SDNode * > & Created) const9294 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9295 SelectionDAG &DAG,
9296 SmallVectorImpl<SDNode *> &Created) const {
9297 // TODO: Support SREM
9298 if (N->getOpcode() != ISD::SDIV)
9299 return SDValue();
9300
9301 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
9302 const bool MinSize = ST.hasMinSize();
9303 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9304 : ST.hasDivideInARMMode();
9305
9306 // Don't touch vector types; rewriting this may lead to scalarizing
9307 // the int divs.
9308 if (N->getOperand(0).getValueType().isVector())
9309 return SDValue();
9310
9311 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9312 // hwdiv support for this to be really profitable.
9313 if (!(MinSize && HasDivide))
9314 return SDValue();
9315
9316 // ARM mode is a bit simpler than Thumb: we can handle large power
9317 // of 2 immediates with 1 mov instruction; no further checks required,
9318 // just return the sdiv node.
9319 if (!ST.isThumb())
9320 return SDValue(N, 0);
9321
9322 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9323 // and thus lose the code size benefits of a MOVS that requires only 2.
9324 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9325 // but as it's doing exactly this, it's not worth the trouble to get TTI.
9326 if (Divisor.sgt(128))
9327 return SDValue();
9328
9329 return SDValue(N, 0);
9330 }
9331
LowerDIV_Windows(SDValue Op,SelectionDAG & DAG,bool Signed) const9332 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9333 bool Signed) const {
9334 assert(Op.getValueType() == MVT::i32 &&
9335 "unexpected type for custom lowering DIV");
9336 SDLoc dl(Op);
9337
9338 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9339 DAG.getEntryNode(), Op.getOperand(1));
9340
9341 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9342 }
9343
WinDBZCheckDenominator(SelectionDAG & DAG,SDNode * N,SDValue InChain)9344 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9345 SDLoc DL(N);
9346 SDValue Op = N->getOperand(1);
9347 if (N->getValueType(0) == MVT::i32)
9348 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9349 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9350 DAG.getConstant(0, DL, MVT::i32));
9351 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9352 DAG.getConstant(1, DL, MVT::i32));
9353 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9354 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9355 }
9356
ExpandDIV_Windows(SDValue Op,SelectionDAG & DAG,bool Signed,SmallVectorImpl<SDValue> & Results) const9357 void ARMTargetLowering::ExpandDIV_Windows(
9358 SDValue Op, SelectionDAG &DAG, bool Signed,
9359 SmallVectorImpl<SDValue> &Results) const {
9360 const auto &DL = DAG.getDataLayout();
9361 const auto &TLI = DAG.getTargetLoweringInfo();
9362
9363 assert(Op.getValueType() == MVT::i64 &&
9364 "unexpected type for custom lowering DIV");
9365 SDLoc dl(Op);
9366
9367 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9368
9369 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9370
9371 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9372 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9373 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9374 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9375
9376 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9377 }
9378
LowerPredicateLoad(SDValue Op,SelectionDAG & DAG)9379 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9380 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9381 EVT MemVT = LD->getMemoryVT();
9382 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9383 "Expected a predicate type!");
9384 assert(MemVT == Op.getValueType());
9385 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9386 "Expected a non-extending load");
9387 assert(LD->isUnindexed() && "Expected a unindexed load");
9388
9389 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9390 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9391 // need to make sure that 8/4 bits are actually loaded into the correct
9392 // place, which means loading the value and then shuffling the values into
9393 // the bottom bits of the predicate.
9394 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9395 // for BE).
9396
9397 SDLoc dl(Op);
9398 SDValue Load = DAG.getExtLoad(
9399 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9400 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9401 LD->getMemOperand());
9402 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
9403 if (MemVT != MVT::v16i1)
9404 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9405 DAG.getConstant(0, dl, MVT::i32));
9406 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9407 }
9408
LowerLOAD(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const9409 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9410 SelectionDAG &DAG) const {
9411 LoadSDNode *LD = cast<LoadSDNode>(N);
9412 EVT MemVT = LD->getMemoryVT();
9413 assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9414
9415 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9416 !Subtarget->isThumb1Only() && LD->isVolatile()) {
9417 SDLoc dl(N);
9418 SDValue Result = DAG.getMemIntrinsicNode(
9419 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9420 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9421 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9422 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9423 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9424 Results.append({Pair, Result.getValue(2)});
9425 }
9426 }
9427
LowerPredicateStore(SDValue Op,SelectionDAG & DAG)9428 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9429 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9430 EVT MemVT = ST->getMemoryVT();
9431 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9432 "Expected a predicate type!");
9433 assert(MemVT == ST->getValue().getValueType());
9434 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9435 assert(ST->isUnindexed() && "Expected a unindexed store");
9436
9437 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9438 // unset and a scalar store.
9439 SDLoc dl(Op);
9440 SDValue Build = ST->getValue();
9441 if (MemVT != MVT::v16i1) {
9442 SmallVector<SDValue, 16> Ops;
9443 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
9444 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9445 DAG.getConstant(I, dl, MVT::i32)));
9446 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9447 Ops.push_back(DAG.getUNDEF(MVT::i32));
9448 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9449 }
9450 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9451 return DAG.getTruncStore(
9452 ST->getChain(), dl, GRP, ST->getBasePtr(),
9453 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9454 ST->getMemOperand());
9455 }
9456
LowerSTORE(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)9457 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
9458 const ARMSubtarget *Subtarget) {
9459 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9460 EVT MemVT = ST->getMemoryVT();
9461 assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9462
9463 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9464 !Subtarget->isThumb1Only() && ST->isVolatile()) {
9465 SDNode *N = Op.getNode();
9466 SDLoc dl(N);
9467
9468 SDValue Lo = DAG.getNode(
9469 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9470 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9471 MVT::i32));
9472 SDValue Hi = DAG.getNode(
9473 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9474 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9475 MVT::i32));
9476
9477 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9478 {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9479 MemVT, ST->getMemOperand());
9480 } else if (Subtarget->hasMVEIntegerOps() &&
9481 ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9482 MemVT == MVT::v16i1))) {
9483 return LowerPredicateStore(Op, DAG);
9484 }
9485
9486 return SDValue();
9487 }
9488
isZeroVector(SDValue N)9489 static bool isZeroVector(SDValue N) {
9490 return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9491 (N->getOpcode() == ARMISD::VMOVIMM &&
9492 isNullConstant(N->getOperand(0))));
9493 }
9494
LowerMLOAD(SDValue Op,SelectionDAG & DAG)9495 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9496 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9497 MVT VT = Op.getSimpleValueType();
9498 SDValue Mask = N->getMask();
9499 SDValue PassThru = N->getPassThru();
9500 SDLoc dl(Op);
9501
9502 if (isZeroVector(PassThru))
9503 return Op;
9504
9505 // MVE Masked loads use zero as the passthru value. Here we convert undef to
9506 // zero too, and other values are lowered to a select.
9507 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9508 DAG.getTargetConstant(0, dl, MVT::i32));
9509 SDValue NewLoad = DAG.getMaskedLoad(
9510 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9511 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9512 N->getExtensionType(), N->isExpandingLoad());
9513 SDValue Combo = NewLoad;
9514 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9515 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9516 isZeroVector(PassThru->getOperand(0));
9517 if (!PassThru.isUndef() && !PassThruIsCastZero)
9518 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9519 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9520 }
9521
LowerVecReduce(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9522 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
9523 const ARMSubtarget *ST) {
9524 if (!ST->hasMVEIntegerOps())
9525 return SDValue();
9526
9527 SDLoc dl(Op);
9528 unsigned BaseOpcode = 0;
9529 switch (Op->getOpcode()) {
9530 default: llvm_unreachable("Expected VECREDUCE opcode");
9531 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
9532 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
9533 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break;
9534 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break;
9535 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break;
9536 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break;
9537 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
9538 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
9539 }
9540
9541 SDValue Op0 = Op->getOperand(0);
9542 EVT VT = Op0.getValueType();
9543 EVT EltVT = VT.getVectorElementType();
9544 unsigned NumElts = VT.getVectorNumElements();
9545 unsigned NumActiveLanes = NumElts;
9546
9547 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
9548 NumActiveLanes == 2) &&
9549 "Only expected a power 2 vector size");
9550
9551 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
9552 // allows us to easily extract vector elements from the lanes.
9553 while (NumActiveLanes > 4) {
9554 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
9555 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
9556 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
9557 NumActiveLanes /= 2;
9558 }
9559
9560 SDValue Res;
9561 if (NumActiveLanes == 4) {
9562 // The remaining 4 elements are summed sequentially
9563 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9564 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
9565 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9566 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
9567 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9568 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
9569 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9570 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
9571 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
9572 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
9573 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
9574 } else {
9575 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9576 DAG.getConstant(0, dl, MVT::i32));
9577 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9578 DAG.getConstant(1, dl, MVT::i32));
9579 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
9580 }
9581
9582 // Result type may be wider than element type.
9583 if (EltVT != Op->getValueType(0))
9584 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
9585 return Res;
9586 }
9587
LowerVecReduceF(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9588 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
9589 const ARMSubtarget *ST) {
9590 if (!ST->hasMVEFloatOps())
9591 return SDValue();
9592 return LowerVecReduce(Op, DAG, ST);
9593 }
9594
LowerAtomicLoadStore(SDValue Op,SelectionDAG & DAG)9595 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
9596 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
9597 // Acquire/Release load/store is not legal for targets without a dmb or
9598 // equivalent available.
9599 return SDValue();
9600
9601 // Monotonic load/store is legal for all targets.
9602 return Op;
9603 }
9604
ReplaceREADCYCLECOUNTER(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG,const ARMSubtarget * Subtarget)9605 static void ReplaceREADCYCLECOUNTER(SDNode *N,
9606 SmallVectorImpl<SDValue> &Results,
9607 SelectionDAG &DAG,
9608 const ARMSubtarget *Subtarget) {
9609 SDLoc DL(N);
9610 // Under Power Management extensions, the cycle-count is:
9611 // mrc p15, #0, <Rt>, c9, c13, #0
9612 SDValue Ops[] = { N->getOperand(0), // Chain
9613 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
9614 DAG.getTargetConstant(15, DL, MVT::i32),
9615 DAG.getTargetConstant(0, DL, MVT::i32),
9616 DAG.getTargetConstant(9, DL, MVT::i32),
9617 DAG.getTargetConstant(13, DL, MVT::i32),
9618 DAG.getTargetConstant(0, DL, MVT::i32)
9619 };
9620
9621 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
9622 DAG.getVTList(MVT::i32, MVT::Other), Ops);
9623 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
9624 DAG.getConstant(0, DL, MVT::i32)));
9625 Results.push_back(Cycles32.getValue(1));
9626 }
9627
createGPRPairNode(SelectionDAG & DAG,SDValue V)9628 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
9629 SDLoc dl(V.getNode());
9630 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9631 SDValue VHi = DAG.getAnyExtOrTrunc(
9632 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9633 dl, MVT::i32);
9634 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9635 if (isBigEndian)
9636 std::swap (VLo, VHi);
9637 SDValue RegClass =
9638 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9639 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9640 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9641 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9642 return SDValue(
9643 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9644 }
9645
ReplaceCMP_SWAP_64Results(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG)9646 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9647 SmallVectorImpl<SDValue> & Results,
9648 SelectionDAG &DAG) {
9649 assert(N->getValueType(0) == MVT::i64 &&
9650 "AtomicCmpSwap on types less than 64 should be legal");
9651 SDValue Ops[] = {N->getOperand(1),
9652 createGPRPairNode(DAG, N->getOperand(2)),
9653 createGPRPairNode(DAG, N->getOperand(3)),
9654 N->getOperand(0)};
9655 SDNode *CmpSwap = DAG.getMachineNode(
9656 ARM::CMP_SWAP_64, SDLoc(N),
9657 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9658
9659 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9660 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9661
9662 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9663
9664 SDValue Lo =
9665 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9666 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9667 SDValue Hi =
9668 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9669 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9670 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
9671 Results.push_back(SDValue(CmpSwap, 2));
9672 }
9673
LowerFSETCC(SDValue Op,SelectionDAG & DAG) const9674 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
9675 SDLoc dl(Op);
9676 EVT VT = Op.getValueType();
9677 SDValue Chain = Op.getOperand(0);
9678 SDValue LHS = Op.getOperand(1);
9679 SDValue RHS = Op.getOperand(2);
9680 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
9681 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
9682
9683 // If we don't have instructions of this float type then soften to a libcall
9684 // and use SETCC instead.
9685 if (isUnsupportedFloatingType(LHS.getValueType())) {
9686 DAG.getTargetLoweringInfo().softenSetCCOperands(
9687 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
9688 if (!RHS.getNode()) {
9689 RHS = DAG.getConstant(0, dl, LHS.getValueType());
9690 CC = ISD::SETNE;
9691 }
9692 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
9693 DAG.getCondCode(CC));
9694 return DAG.getMergeValues({Result, Chain}, dl);
9695 }
9696
9697 ARMCC::CondCodes CondCode, CondCode2;
9698 FPCCToARMCC(CC, CondCode, CondCode2);
9699
9700 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
9701 // in CMPFP and CMPFPE, but instead it should be made explicit by these
9702 // instructions using a chain instead of glue. This would also fix the problem
9703 // here (and also in LowerSELECT_CC) where we generate two comparisons when
9704 // CondCode2 != AL.
9705 SDValue True = DAG.getConstant(1, dl, VT);
9706 SDValue False = DAG.getConstant(0, dl, VT);
9707 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
9708 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
9709 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9710 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
9711 if (CondCode2 != ARMCC::AL) {
9712 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
9713 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9714 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
9715 }
9716 return DAG.getMergeValues({Result, Chain}, dl);
9717 }
9718
LowerOperation(SDValue Op,SelectionDAG & DAG) const9719 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9720 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9721 switch (Op.getOpcode()) {
9722 default: llvm_unreachable("Don't know how to custom lower this!");
9723 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9724 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9725 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9726 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9727 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9728 case ISD::SELECT: return LowerSELECT(Op, DAG);
9729 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
9730 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9731 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
9732 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
9733 case ISD::VASTART: return LowerVASTART(Op, DAG);
9734 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9735 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
9736 case ISD::SINT_TO_FP:
9737 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
9738 case ISD::STRICT_FP_TO_SINT:
9739 case ISD::STRICT_FP_TO_UINT:
9740 case ISD::FP_TO_SINT:
9741 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
9742 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9743 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9744 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9745 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9746 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9747 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9748 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9749 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9750 Subtarget);
9751 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9752 case ISD::SHL:
9753 case ISD::SRL:
9754 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
9755 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
9756 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
9757 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
9758 case ISD::SRL_PARTS:
9759 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
9760 case ISD::CTTZ:
9761 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9762 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9763 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
9764 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
9765 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
9766 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9767 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9768 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9769 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9770 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9771 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9772 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9773 case ISD::MUL: return LowerMUL(Op, DAG);
9774 case ISD::SDIV:
9775 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9776 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9777 return LowerSDIV(Op, DAG, Subtarget);
9778 case ISD::UDIV:
9779 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9780 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9781 return LowerUDIV(Op, DAG, Subtarget);
9782 case ISD::ADDCARRY:
9783 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
9784 case ISD::SADDO:
9785 case ISD::SSUBO:
9786 return LowerSignedALUO(Op, DAG);
9787 case ISD::UADDO:
9788 case ISD::USUBO:
9789 return LowerUnsignedALUO(Op, DAG);
9790 case ISD::SADDSAT:
9791 case ISD::SSUBSAT:
9792 return LowerSADDSUBSAT(Op, DAG, Subtarget);
9793 case ISD::LOAD:
9794 return LowerPredicateLoad(Op, DAG);
9795 case ISD::STORE:
9796 return LowerSTORE(Op, DAG, Subtarget);
9797 case ISD::MLOAD:
9798 return LowerMLOAD(Op, DAG);
9799 case ISD::VECREDUCE_MUL:
9800 case ISD::VECREDUCE_AND:
9801 case ISD::VECREDUCE_OR:
9802 case ISD::VECREDUCE_XOR:
9803 return LowerVecReduce(Op, DAG, Subtarget);
9804 case ISD::VECREDUCE_FADD:
9805 case ISD::VECREDUCE_FMUL:
9806 case ISD::VECREDUCE_FMIN:
9807 case ISD::VECREDUCE_FMAX:
9808 return LowerVecReduceF(Op, DAG, Subtarget);
9809 case ISD::ATOMIC_LOAD:
9810 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
9811 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
9812 case ISD::SDIVREM:
9813 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
9814 case ISD::DYNAMIC_STACKALLOC:
9815 if (Subtarget->isTargetWindows())
9816 return LowerDYNAMIC_STACKALLOC(Op, DAG);
9817 llvm_unreachable("Don't know how to custom lower this!");
9818 case ISD::STRICT_FP_ROUND:
9819 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9820 case ISD::STRICT_FP_EXTEND:
9821 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9822 case ISD::STRICT_FSETCC:
9823 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
9824 case ARMISD::WIN__DBZCHK: return SDValue();
9825 }
9826 }
9827
ReplaceLongIntrinsic(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG)9828 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9829 SelectionDAG &DAG) {
9830 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9831 unsigned Opc = 0;
9832 if (IntNo == Intrinsic::arm_smlald)
9833 Opc = ARMISD::SMLALD;
9834 else if (IntNo == Intrinsic::arm_smlaldx)
9835 Opc = ARMISD::SMLALDX;
9836 else if (IntNo == Intrinsic::arm_smlsld)
9837 Opc = ARMISD::SMLSLD;
9838 else if (IntNo == Intrinsic::arm_smlsldx)
9839 Opc = ARMISD::SMLSLDX;
9840 else
9841 return;
9842
9843 SDLoc dl(N);
9844 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9845 N->getOperand(3),
9846 DAG.getConstant(0, dl, MVT::i32));
9847 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9848 N->getOperand(3),
9849 DAG.getConstant(1, dl, MVT::i32));
9850
9851 SDValue LongMul = DAG.getNode(Opc, dl,
9852 DAG.getVTList(MVT::i32, MVT::i32),
9853 N->getOperand(1), N->getOperand(2),
9854 Lo, Hi);
9855 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
9856 LongMul.getValue(0), LongMul.getValue(1)));
9857 }
9858
9859 /// ReplaceNodeResults - Replace the results of node with an illegal result
9860 /// type with new values built out of custom code.
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const9861 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9862 SmallVectorImpl<SDValue> &Results,
9863 SelectionDAG &DAG) const {
9864 SDValue Res;
9865 switch (N->getOpcode()) {
9866 default:
9867 llvm_unreachable("Don't know how to custom expand this!");
9868 case ISD::READ_REGISTER:
9869 ExpandREAD_REGISTER(N, Results, DAG);
9870 break;
9871 case ISD::BITCAST:
9872 Res = ExpandBITCAST(N, DAG, Subtarget);
9873 break;
9874 case ISD::SRL:
9875 case ISD::SRA:
9876 case ISD::SHL:
9877 Res = Expand64BitShift(N, DAG, Subtarget);
9878 break;
9879 case ISD::SREM:
9880 case ISD::UREM:
9881 Res = LowerREM(N, DAG);
9882 break;
9883 case ISD::SDIVREM:
9884 case ISD::UDIVREM:
9885 Res = LowerDivRem(SDValue(N, 0), DAG);
9886 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9887 Results.push_back(Res.getValue(0));
9888 Results.push_back(Res.getValue(1));
9889 return;
9890 case ISD::SADDSAT:
9891 case ISD::SSUBSAT:
9892 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9893 break;
9894 case ISD::READCYCLECOUNTER:
9895 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9896 return;
9897 case ISD::UDIV:
9898 case ISD::SDIV:
9899 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9900 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9901 Results);
9902 case ISD::ATOMIC_CMP_SWAP:
9903 ReplaceCMP_SWAP_64Results(N, Results, DAG);
9904 return;
9905 case ISD::INTRINSIC_WO_CHAIN:
9906 return ReplaceLongIntrinsic(N, Results, DAG);
9907 case ISD::ABS:
9908 lowerABS(N, Results, DAG);
9909 return ;
9910 case ISD::LOAD:
9911 LowerLOAD(N, Results, DAG);
9912 break;
9913 }
9914 if (Res.getNode())
9915 Results.push_back(Res);
9916 }
9917
9918 //===----------------------------------------------------------------------===//
9919 // ARM Scheduler Hooks
9920 //===----------------------------------------------------------------------===//
9921
9922 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9923 /// registers the function context.
SetupEntryBlockForSjLj(MachineInstr & MI,MachineBasicBlock * MBB,MachineBasicBlock * DispatchBB,int FI) const9924 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9925 MachineBasicBlock *MBB,
9926 MachineBasicBlock *DispatchBB,
9927 int FI) const {
9928 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9929 "ROPI/RWPI not currently supported with SjLj");
9930 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9931 DebugLoc dl = MI.getDebugLoc();
9932 MachineFunction *MF = MBB->getParent();
9933 MachineRegisterInfo *MRI = &MF->getRegInfo();
9934 MachineConstantPool *MCP = MF->getConstantPool();
9935 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9936 const Function &F = MF->getFunction();
9937
9938 bool isThumb = Subtarget->isThumb();
9939 bool isThumb2 = Subtarget->isThumb2();
9940
9941 unsigned PCLabelId = AFI->createPICLabelUId();
9942 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9943 ARMConstantPoolValue *CPV =
9944 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9945 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
9946
9947 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9948 : &ARM::GPRRegClass;
9949
9950 // Grab constant pool and fixed stack memory operands.
9951 MachineMemOperand *CPMMO =
9952 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9953 MachineMemOperand::MOLoad, 4, Align(4));
9954
9955 MachineMemOperand *FIMMOSt =
9956 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9957 MachineMemOperand::MOStore, 4, Align(4));
9958
9959 // Load the address of the dispatch MBB into the jump buffer.
9960 if (isThumb2) {
9961 // Incoming value: jbuf
9962 // ldr.n r5, LCPI1_1
9963 // orr r5, r5, #1
9964 // add r5, pc
9965 // str r5, [$jbuf, #+4] ; &jbuf[1]
9966 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9967 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9968 .addConstantPoolIndex(CPI)
9969 .addMemOperand(CPMMO)
9970 .add(predOps(ARMCC::AL));
9971 // Set the low bit because of thumb mode.
9972 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9973 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9974 .addReg(NewVReg1, RegState::Kill)
9975 .addImm(0x01)
9976 .add(predOps(ARMCC::AL))
9977 .add(condCodeOp());
9978 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9979 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9980 .addReg(NewVReg2, RegState::Kill)
9981 .addImm(PCLabelId);
9982 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9983 .addReg(NewVReg3, RegState::Kill)
9984 .addFrameIndex(FI)
9985 .addImm(36) // &jbuf[1] :: pc
9986 .addMemOperand(FIMMOSt)
9987 .add(predOps(ARMCC::AL));
9988 } else if (isThumb) {
9989 // Incoming value: jbuf
9990 // ldr.n r1, LCPI1_4
9991 // add r1, pc
9992 // mov r2, #1
9993 // orrs r1, r2
9994 // add r2, $jbuf, #+4 ; &jbuf[1]
9995 // str r1, [r2]
9996 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9997 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9998 .addConstantPoolIndex(CPI)
9999 .addMemOperand(CPMMO)
10000 .add(predOps(ARMCC::AL));
10001 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10002 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10003 .addReg(NewVReg1, RegState::Kill)
10004 .addImm(PCLabelId);
10005 // Set the low bit because of thumb mode.
10006 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10007 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10008 .addReg(ARM::CPSR, RegState::Define)
10009 .addImm(1)
10010 .add(predOps(ARMCC::AL));
10011 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10012 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10013 .addReg(ARM::CPSR, RegState::Define)
10014 .addReg(NewVReg2, RegState::Kill)
10015 .addReg(NewVReg3, RegState::Kill)
10016 .add(predOps(ARMCC::AL));
10017 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10018 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10019 .addFrameIndex(FI)
10020 .addImm(36); // &jbuf[1] :: pc
10021 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10022 .addReg(NewVReg4, RegState::Kill)
10023 .addReg(NewVReg5, RegState::Kill)
10024 .addImm(0)
10025 .addMemOperand(FIMMOSt)
10026 .add(predOps(ARMCC::AL));
10027 } else {
10028 // Incoming value: jbuf
10029 // ldr r1, LCPI1_1
10030 // add r1, pc, r1
10031 // str r1, [$jbuf, #+4] ; &jbuf[1]
10032 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10033 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10034 .addConstantPoolIndex(CPI)
10035 .addImm(0)
10036 .addMemOperand(CPMMO)
10037 .add(predOps(ARMCC::AL));
10038 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10039 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10040 .addReg(NewVReg1, RegState::Kill)
10041 .addImm(PCLabelId)
10042 .add(predOps(ARMCC::AL));
10043 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10044 .addReg(NewVReg2, RegState::Kill)
10045 .addFrameIndex(FI)
10046 .addImm(36) // &jbuf[1] :: pc
10047 .addMemOperand(FIMMOSt)
10048 .add(predOps(ARMCC::AL));
10049 }
10050 }
10051
EmitSjLjDispatchBlock(MachineInstr & MI,MachineBasicBlock * MBB) const10052 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10053 MachineBasicBlock *MBB) const {
10054 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10055 DebugLoc dl = MI.getDebugLoc();
10056 MachineFunction *MF = MBB->getParent();
10057 MachineRegisterInfo *MRI = &MF->getRegInfo();
10058 MachineFrameInfo &MFI = MF->getFrameInfo();
10059 int FI = MFI.getFunctionContextIndex();
10060
10061 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10062 : &ARM::GPRnopcRegClass;
10063
10064 // Get a mapping of the call site numbers to all of the landing pads they're
10065 // associated with.
10066 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10067 unsigned MaxCSNum = 0;
10068 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
10069 ++BB) {
10070 if (!BB->isEHPad()) continue;
10071
10072 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10073 // pad.
10074 for (MachineBasicBlock::iterator
10075 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
10076 if (!II->isEHLabel()) continue;
10077
10078 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
10079 if (!MF->hasCallSiteLandingPad(Sym)) continue;
10080
10081 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10082 for (SmallVectorImpl<unsigned>::iterator
10083 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
10084 CSI != CSE; ++CSI) {
10085 CallSiteNumToLPad[*CSI].push_back(&*BB);
10086 MaxCSNum = std::max(MaxCSNum, *CSI);
10087 }
10088 break;
10089 }
10090 }
10091
10092 // Get an ordered list of the machine basic blocks for the jump table.
10093 std::vector<MachineBasicBlock*> LPadList;
10094 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10095 LPadList.reserve(CallSiteNumToLPad.size());
10096 for (unsigned I = 1; I <= MaxCSNum; ++I) {
10097 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10098 for (SmallVectorImpl<MachineBasicBlock*>::iterator
10099 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
10100 LPadList.push_back(*II);
10101 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
10102 }
10103 }
10104
10105 assert(!LPadList.empty() &&
10106 "No landing pad destinations for the dispatch jump table!");
10107
10108 // Create the jump table and associated information.
10109 MachineJumpTableInfo *JTI =
10110 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10111 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10112
10113 // Create the MBBs for the dispatch code.
10114
10115 // Shove the dispatch's address into the return slot in the function context.
10116 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10117 DispatchBB->setIsEHPad();
10118
10119 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10120 unsigned trap_opcode;
10121 if (Subtarget->isThumb())
10122 trap_opcode = ARM::tTRAP;
10123 else
10124 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
10125
10126 BuildMI(TrapBB, dl, TII->get(trap_opcode));
10127 DispatchBB->addSuccessor(TrapBB);
10128
10129 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10130 DispatchBB->addSuccessor(DispContBB);
10131
10132 // Insert and MBBs.
10133 MF->insert(MF->end(), DispatchBB);
10134 MF->insert(MF->end(), DispContBB);
10135 MF->insert(MF->end(), TrapBB);
10136
10137 // Insert code into the entry block that creates and registers the function
10138 // context.
10139 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10140
10141 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10142 MachinePointerInfo::getFixedStack(*MF, FI),
10143 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
10144
10145 MachineInstrBuilder MIB;
10146 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10147
10148 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10149 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10150
10151 // Add a register mask with no preserved registers. This results in all
10152 // registers being marked as clobbered. This can't work if the dispatch block
10153 // is in a Thumb1 function and is linked with ARM code which uses the FP
10154 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10155 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
10156
10157 bool IsPositionIndependent = isPositionIndependent();
10158 unsigned NumLPads = LPadList.size();
10159 if (Subtarget->isThumb2()) {
10160 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10161 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10162 .addFrameIndex(FI)
10163 .addImm(4)
10164 .addMemOperand(FIMMOLd)
10165 .add(predOps(ARMCC::AL));
10166
10167 if (NumLPads < 256) {
10168 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10169 .addReg(NewVReg1)
10170 .addImm(LPadList.size())
10171 .add(predOps(ARMCC::AL));
10172 } else {
10173 Register VReg1 = MRI->createVirtualRegister(TRC);
10174 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10175 .addImm(NumLPads & 0xFFFF)
10176 .add(predOps(ARMCC::AL));
10177
10178 unsigned VReg2 = VReg1;
10179 if ((NumLPads & 0xFFFF0000) != 0) {
10180 VReg2 = MRI->createVirtualRegister(TRC);
10181 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10182 .addReg(VReg1)
10183 .addImm(NumLPads >> 16)
10184 .add(predOps(ARMCC::AL));
10185 }
10186
10187 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10188 .addReg(NewVReg1)
10189 .addReg(VReg2)
10190 .add(predOps(ARMCC::AL));
10191 }
10192
10193 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10194 .addMBB(TrapBB)
10195 .addImm(ARMCC::HI)
10196 .addReg(ARM::CPSR);
10197
10198 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10199 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10200 .addJumpTableIndex(MJTI)
10201 .add(predOps(ARMCC::AL));
10202
10203 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10204 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10205 .addReg(NewVReg3, RegState::Kill)
10206 .addReg(NewVReg1)
10207 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10208 .add(predOps(ARMCC::AL))
10209 .add(condCodeOp());
10210
10211 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10212 .addReg(NewVReg4, RegState::Kill)
10213 .addReg(NewVReg1)
10214 .addJumpTableIndex(MJTI);
10215 } else if (Subtarget->isThumb()) {
10216 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10217 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10218 .addFrameIndex(FI)
10219 .addImm(1)
10220 .addMemOperand(FIMMOLd)
10221 .add(predOps(ARMCC::AL));
10222
10223 if (NumLPads < 256) {
10224 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10225 .addReg(NewVReg1)
10226 .addImm(NumLPads)
10227 .add(predOps(ARMCC::AL));
10228 } else {
10229 MachineConstantPool *ConstantPool = MF->getConstantPool();
10230 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10231 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10232
10233 // MachineConstantPool wants an explicit alignment.
10234 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10235 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10236
10237 Register VReg1 = MRI->createVirtualRegister(TRC);
10238 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
10239 .addReg(VReg1, RegState::Define)
10240 .addConstantPoolIndex(Idx)
10241 .add(predOps(ARMCC::AL));
10242 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
10243 .addReg(NewVReg1)
10244 .addReg(VReg1)
10245 .add(predOps(ARMCC::AL));
10246 }
10247
10248 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
10249 .addMBB(TrapBB)
10250 .addImm(ARMCC::HI)
10251 .addReg(ARM::CPSR);
10252
10253 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10254 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
10255 .addReg(ARM::CPSR, RegState::Define)
10256 .addReg(NewVReg1)
10257 .addImm(2)
10258 .add(predOps(ARMCC::AL));
10259
10260 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10261 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
10262 .addJumpTableIndex(MJTI)
10263 .add(predOps(ARMCC::AL));
10264
10265 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10266 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
10267 .addReg(ARM::CPSR, RegState::Define)
10268 .addReg(NewVReg2, RegState::Kill)
10269 .addReg(NewVReg3)
10270 .add(predOps(ARMCC::AL));
10271
10272 MachineMemOperand *JTMMOLd =
10273 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10274 MachineMemOperand::MOLoad, 4, Align(4));
10275
10276 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10277 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
10278 .addReg(NewVReg4, RegState::Kill)
10279 .addImm(0)
10280 .addMemOperand(JTMMOLd)
10281 .add(predOps(ARMCC::AL));
10282
10283 unsigned NewVReg6 = NewVReg5;
10284 if (IsPositionIndependent) {
10285 NewVReg6 = MRI->createVirtualRegister(TRC);
10286 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
10287 .addReg(ARM::CPSR, RegState::Define)
10288 .addReg(NewVReg5, RegState::Kill)
10289 .addReg(NewVReg3)
10290 .add(predOps(ARMCC::AL));
10291 }
10292
10293 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
10294 .addReg(NewVReg6, RegState::Kill)
10295 .addJumpTableIndex(MJTI);
10296 } else {
10297 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10298 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
10299 .addFrameIndex(FI)
10300 .addImm(4)
10301 .addMemOperand(FIMMOLd)
10302 .add(predOps(ARMCC::AL));
10303
10304 if (NumLPads < 256) {
10305 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
10306 .addReg(NewVReg1)
10307 .addImm(NumLPads)
10308 .add(predOps(ARMCC::AL));
10309 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
10310 Register VReg1 = MRI->createVirtualRegister(TRC);
10311 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
10312 .addImm(NumLPads & 0xFFFF)
10313 .add(predOps(ARMCC::AL));
10314
10315 unsigned VReg2 = VReg1;
10316 if ((NumLPads & 0xFFFF0000) != 0) {
10317 VReg2 = MRI->createVirtualRegister(TRC);
10318 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
10319 .addReg(VReg1)
10320 .addImm(NumLPads >> 16)
10321 .add(predOps(ARMCC::AL));
10322 }
10323
10324 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10325 .addReg(NewVReg1)
10326 .addReg(VReg2)
10327 .add(predOps(ARMCC::AL));
10328 } else {
10329 MachineConstantPool *ConstantPool = MF->getConstantPool();
10330 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10331 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10332
10333 // MachineConstantPool wants an explicit alignment.
10334 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10335 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10336
10337 Register VReg1 = MRI->createVirtualRegister(TRC);
10338 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
10339 .addReg(VReg1, RegState::Define)
10340 .addConstantPoolIndex(Idx)
10341 .addImm(0)
10342 .add(predOps(ARMCC::AL));
10343 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10344 .addReg(NewVReg1)
10345 .addReg(VReg1, RegState::Kill)
10346 .add(predOps(ARMCC::AL));
10347 }
10348
10349 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
10350 .addMBB(TrapBB)
10351 .addImm(ARMCC::HI)
10352 .addReg(ARM::CPSR);
10353
10354 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10355 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
10356 .addReg(NewVReg1)
10357 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10358 .add(predOps(ARMCC::AL))
10359 .add(condCodeOp());
10360 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10361 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
10362 .addJumpTableIndex(MJTI)
10363 .add(predOps(ARMCC::AL));
10364
10365 MachineMemOperand *JTMMOLd =
10366 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10367 MachineMemOperand::MOLoad, 4, Align(4));
10368 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10369 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
10370 .addReg(NewVReg3, RegState::Kill)
10371 .addReg(NewVReg4)
10372 .addImm(0)
10373 .addMemOperand(JTMMOLd)
10374 .add(predOps(ARMCC::AL));
10375
10376 if (IsPositionIndependent) {
10377 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
10378 .addReg(NewVReg5, RegState::Kill)
10379 .addReg(NewVReg4)
10380 .addJumpTableIndex(MJTI);
10381 } else {
10382 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
10383 .addReg(NewVReg5, RegState::Kill)
10384 .addJumpTableIndex(MJTI);
10385 }
10386 }
10387
10388 // Add the jump table entries as successors to the MBB.
10389 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
10390 for (std::vector<MachineBasicBlock*>::iterator
10391 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
10392 MachineBasicBlock *CurMBB = *I;
10393 if (SeenMBBs.insert(CurMBB).second)
10394 DispContBB->addSuccessor(CurMBB);
10395 }
10396
10397 // N.B. the order the invoke BBs are processed in doesn't matter here.
10398 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
10399 SmallVector<MachineBasicBlock*, 64> MBBLPads;
10400 for (MachineBasicBlock *BB : InvokeBBs) {
10401
10402 // Remove the landing pad successor from the invoke block and replace it
10403 // with the new dispatch block.
10404 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
10405 BB->succ_end());
10406 while (!Successors.empty()) {
10407 MachineBasicBlock *SMBB = Successors.pop_back_val();
10408 if (SMBB->isEHPad()) {
10409 BB->removeSuccessor(SMBB);
10410 MBBLPads.push_back(SMBB);
10411 }
10412 }
10413
10414 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
10415 BB->normalizeSuccProbs();
10416
10417 // Find the invoke call and mark all of the callee-saved registers as
10418 // 'implicit defined' so that they're spilled. This prevents code from
10419 // moving instructions to before the EH block, where they will never be
10420 // executed.
10421 for (MachineBasicBlock::reverse_iterator
10422 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
10423 if (!II->isCall()) continue;
10424
10425 DenseMap<unsigned, bool> DefRegs;
10426 for (MachineInstr::mop_iterator
10427 OI = II->operands_begin(), OE = II->operands_end();
10428 OI != OE; ++OI) {
10429 if (!OI->isReg()) continue;
10430 DefRegs[OI->getReg()] = true;
10431 }
10432
10433 MachineInstrBuilder MIB(*MF, &*II);
10434
10435 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
10436 unsigned Reg = SavedRegs[i];
10437 if (Subtarget->isThumb2() &&
10438 !ARM::tGPRRegClass.contains(Reg) &&
10439 !ARM::hGPRRegClass.contains(Reg))
10440 continue;
10441 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
10442 continue;
10443 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
10444 continue;
10445 if (!DefRegs[Reg])
10446 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
10447 }
10448
10449 break;
10450 }
10451 }
10452
10453 // Mark all former landing pads as non-landing pads. The dispatch is the only
10454 // landing pad now.
10455 for (SmallVectorImpl<MachineBasicBlock*>::iterator
10456 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
10457 (*I)->setIsEHPad(false);
10458
10459 // The instruction is gone now.
10460 MI.eraseFromParent();
10461 }
10462
10463 static
OtherSucc(MachineBasicBlock * MBB,MachineBasicBlock * Succ)10464 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
10465 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
10466 E = MBB->succ_end(); I != E; ++I)
10467 if (*I != Succ)
10468 return *I;
10469 llvm_unreachable("Expecting a BB with two successors!");
10470 }
10471
10472 /// Return the load opcode for a given load size. If load size >= 8,
10473 /// neon opcode will be returned.
getLdOpcode(unsigned LdSize,bool IsThumb1,bool IsThumb2)10474 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
10475 if (LdSize >= 8)
10476 return LdSize == 16 ? ARM::VLD1q32wb_fixed
10477 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
10478 if (IsThumb1)
10479 return LdSize == 4 ? ARM::tLDRi
10480 : LdSize == 2 ? ARM::tLDRHi
10481 : LdSize == 1 ? ARM::tLDRBi : 0;
10482 if (IsThumb2)
10483 return LdSize == 4 ? ARM::t2LDR_POST
10484 : LdSize == 2 ? ARM::t2LDRH_POST
10485 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
10486 return LdSize == 4 ? ARM::LDR_POST_IMM
10487 : LdSize == 2 ? ARM::LDRH_POST
10488 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
10489 }
10490
10491 /// Return the store opcode for a given store size. If store size >= 8,
10492 /// neon opcode will be returned.
getStOpcode(unsigned StSize,bool IsThumb1,bool IsThumb2)10493 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
10494 if (StSize >= 8)
10495 return StSize == 16 ? ARM::VST1q32wb_fixed
10496 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
10497 if (IsThumb1)
10498 return StSize == 4 ? ARM::tSTRi
10499 : StSize == 2 ? ARM::tSTRHi
10500 : StSize == 1 ? ARM::tSTRBi : 0;
10501 if (IsThumb2)
10502 return StSize == 4 ? ARM::t2STR_POST
10503 : StSize == 2 ? ARM::t2STRH_POST
10504 : StSize == 1 ? ARM::t2STRB_POST : 0;
10505 return StSize == 4 ? ARM::STR_POST_IMM
10506 : StSize == 2 ? ARM::STRH_POST
10507 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
10508 }
10509
10510 /// Emit a post-increment load operation with given size. The instructions
10511 /// will be added to BB at Pos.
emitPostLd(MachineBasicBlock * BB,MachineBasicBlock::iterator Pos,const TargetInstrInfo * TII,const DebugLoc & dl,unsigned LdSize,unsigned Data,unsigned AddrIn,unsigned AddrOut,bool IsThumb1,bool IsThumb2)10512 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10513 const TargetInstrInfo *TII, const DebugLoc &dl,
10514 unsigned LdSize, unsigned Data, unsigned AddrIn,
10515 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10516 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
10517 assert(LdOpc != 0 && "Should have a load opcode");
10518 if (LdSize >= 8) {
10519 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10520 .addReg(AddrOut, RegState::Define)
10521 .addReg(AddrIn)
10522 .addImm(0)
10523 .add(predOps(ARMCC::AL));
10524 } else if (IsThumb1) {
10525 // load + update AddrIn
10526 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10527 .addReg(AddrIn)
10528 .addImm(0)
10529 .add(predOps(ARMCC::AL));
10530 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10531 .add(t1CondCodeOp())
10532 .addReg(AddrIn)
10533 .addImm(LdSize)
10534 .add(predOps(ARMCC::AL));
10535 } else if (IsThumb2) {
10536 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10537 .addReg(AddrOut, RegState::Define)
10538 .addReg(AddrIn)
10539 .addImm(LdSize)
10540 .add(predOps(ARMCC::AL));
10541 } else { // arm
10542 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10543 .addReg(AddrOut, RegState::Define)
10544 .addReg(AddrIn)
10545 .addReg(0)
10546 .addImm(LdSize)
10547 .add(predOps(ARMCC::AL));
10548 }
10549 }
10550
10551 /// Emit a post-increment store operation with given size. The instructions
10552 /// will be added to BB at Pos.
emitPostSt(MachineBasicBlock * BB,MachineBasicBlock::iterator Pos,const TargetInstrInfo * TII,const DebugLoc & dl,unsigned StSize,unsigned Data,unsigned AddrIn,unsigned AddrOut,bool IsThumb1,bool IsThumb2)10553 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10554 const TargetInstrInfo *TII, const DebugLoc &dl,
10555 unsigned StSize, unsigned Data, unsigned AddrIn,
10556 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10557 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
10558 assert(StOpc != 0 && "Should have a store opcode");
10559 if (StSize >= 8) {
10560 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10561 .addReg(AddrIn)
10562 .addImm(0)
10563 .addReg(Data)
10564 .add(predOps(ARMCC::AL));
10565 } else if (IsThumb1) {
10566 // store + update AddrIn
10567 BuildMI(*BB, Pos, dl, TII->get(StOpc))
10568 .addReg(Data)
10569 .addReg(AddrIn)
10570 .addImm(0)
10571 .add(predOps(ARMCC::AL));
10572 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10573 .add(t1CondCodeOp())
10574 .addReg(AddrIn)
10575 .addImm(StSize)
10576 .add(predOps(ARMCC::AL));
10577 } else if (IsThumb2) {
10578 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10579 .addReg(Data)
10580 .addReg(AddrIn)
10581 .addImm(StSize)
10582 .add(predOps(ARMCC::AL));
10583 } else { // arm
10584 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10585 .addReg(Data)
10586 .addReg(AddrIn)
10587 .addReg(0)
10588 .addImm(StSize)
10589 .add(predOps(ARMCC::AL));
10590 }
10591 }
10592
10593 MachineBasicBlock *
EmitStructByval(MachineInstr & MI,MachineBasicBlock * BB) const10594 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
10595 MachineBasicBlock *BB) const {
10596 // This pseudo instruction has 3 operands: dst, src, size
10597 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
10598 // Otherwise, we will generate unrolled scalar copies.
10599 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10600 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10601 MachineFunction::iterator It = ++BB->getIterator();
10602
10603 Register dest = MI.getOperand(0).getReg();
10604 Register src = MI.getOperand(1).getReg();
10605 unsigned SizeVal = MI.getOperand(2).getImm();
10606 unsigned Alignment = MI.getOperand(3).getImm();
10607 DebugLoc dl = MI.getDebugLoc();
10608
10609 MachineFunction *MF = BB->getParent();
10610 MachineRegisterInfo &MRI = MF->getRegInfo();
10611 unsigned UnitSize = 0;
10612 const TargetRegisterClass *TRC = nullptr;
10613 const TargetRegisterClass *VecTRC = nullptr;
10614
10615 bool IsThumb1 = Subtarget->isThumb1Only();
10616 bool IsThumb2 = Subtarget->isThumb2();
10617 bool IsThumb = Subtarget->isThumb();
10618
10619 if (Alignment & 1) {
10620 UnitSize = 1;
10621 } else if (Alignment & 2) {
10622 UnitSize = 2;
10623 } else {
10624 // Check whether we can use NEON instructions.
10625 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
10626 Subtarget->hasNEON()) {
10627 if ((Alignment % 16 == 0) && SizeVal >= 16)
10628 UnitSize = 16;
10629 else if ((Alignment % 8 == 0) && SizeVal >= 8)
10630 UnitSize = 8;
10631 }
10632 // Can't use NEON instructions.
10633 if (UnitSize == 0)
10634 UnitSize = 4;
10635 }
10636
10637 // Select the correct opcode and register class for unit size load/store
10638 bool IsNeon = UnitSize >= 8;
10639 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10640 if (IsNeon)
10641 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10642 : UnitSize == 8 ? &ARM::DPRRegClass
10643 : nullptr;
10644
10645 unsigned BytesLeft = SizeVal % UnitSize;
10646 unsigned LoopSize = SizeVal - BytesLeft;
10647
10648 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10649 // Use LDR and STR to copy.
10650 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10651 // [destOut] = STR_POST(scratch, destIn, UnitSize)
10652 unsigned srcIn = src;
10653 unsigned destIn = dest;
10654 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10655 Register srcOut = MRI.createVirtualRegister(TRC);
10656 Register destOut = MRI.createVirtualRegister(TRC);
10657 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10658 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10659 IsThumb1, IsThumb2);
10660 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10661 IsThumb1, IsThumb2);
10662 srcIn = srcOut;
10663 destIn = destOut;
10664 }
10665
10666 // Handle the leftover bytes with LDRB and STRB.
10667 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10668 // [destOut] = STRB_POST(scratch, destIn, 1)
10669 for (unsigned i = 0; i < BytesLeft; i++) {
10670 Register srcOut = MRI.createVirtualRegister(TRC);
10671 Register destOut = MRI.createVirtualRegister(TRC);
10672 Register scratch = MRI.createVirtualRegister(TRC);
10673 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10674 IsThumb1, IsThumb2);
10675 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10676 IsThumb1, IsThumb2);
10677 srcIn = srcOut;
10678 destIn = destOut;
10679 }
10680 MI.eraseFromParent(); // The instruction is gone now.
10681 return BB;
10682 }
10683
10684 // Expand the pseudo op to a loop.
10685 // thisMBB:
10686 // ...
10687 // movw varEnd, # --> with thumb2
10688 // movt varEnd, #
10689 // ldrcp varEnd, idx --> without thumb2
10690 // fallthrough --> loopMBB
10691 // loopMBB:
10692 // PHI varPhi, varEnd, varLoop
10693 // PHI srcPhi, src, srcLoop
10694 // PHI destPhi, dst, destLoop
10695 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10696 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10697 // subs varLoop, varPhi, #UnitSize
10698 // bne loopMBB
10699 // fallthrough --> exitMBB
10700 // exitMBB:
10701 // epilogue to handle left-over bytes
10702 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10703 // [destOut] = STRB_POST(scratch, destLoop, 1)
10704 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10705 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10706 MF->insert(It, loopMBB);
10707 MF->insert(It, exitMBB);
10708
10709 // Transfer the remainder of BB and its successor edges to exitMBB.
10710 exitMBB->splice(exitMBB->begin(), BB,
10711 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10712 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10713
10714 // Load an immediate to varEnd.
10715 Register varEnd = MRI.createVirtualRegister(TRC);
10716 if (Subtarget->useMovt()) {
10717 unsigned Vtmp = varEnd;
10718 if ((LoopSize & 0xFFFF0000) != 0)
10719 Vtmp = MRI.createVirtualRegister(TRC);
10720 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10721 .addImm(LoopSize & 0xFFFF)
10722 .add(predOps(ARMCC::AL));
10723
10724 if ((LoopSize & 0xFFFF0000) != 0)
10725 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10726 .addReg(Vtmp)
10727 .addImm(LoopSize >> 16)
10728 .add(predOps(ARMCC::AL));
10729 } else {
10730 MachineConstantPool *ConstantPool = MF->getConstantPool();
10731 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10732 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10733
10734 // MachineConstantPool wants an explicit alignment.
10735 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10736 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10737 MachineMemOperand *CPMMO =
10738 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10739 MachineMemOperand::MOLoad, 4, Align(4));
10740
10741 if (IsThumb)
10742 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10743 .addReg(varEnd, RegState::Define)
10744 .addConstantPoolIndex(Idx)
10745 .add(predOps(ARMCC::AL))
10746 .addMemOperand(CPMMO);
10747 else
10748 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10749 .addReg(varEnd, RegState::Define)
10750 .addConstantPoolIndex(Idx)
10751 .addImm(0)
10752 .add(predOps(ARMCC::AL))
10753 .addMemOperand(CPMMO);
10754 }
10755 BB->addSuccessor(loopMBB);
10756
10757 // Generate the loop body:
10758 // varPhi = PHI(varLoop, varEnd)
10759 // srcPhi = PHI(srcLoop, src)
10760 // destPhi = PHI(destLoop, dst)
10761 MachineBasicBlock *entryBB = BB;
10762 BB = loopMBB;
10763 Register varLoop = MRI.createVirtualRegister(TRC);
10764 Register varPhi = MRI.createVirtualRegister(TRC);
10765 Register srcLoop = MRI.createVirtualRegister(TRC);
10766 Register srcPhi = MRI.createVirtualRegister(TRC);
10767 Register destLoop = MRI.createVirtualRegister(TRC);
10768 Register destPhi = MRI.createVirtualRegister(TRC);
10769
10770 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10771 .addReg(varLoop).addMBB(loopMBB)
10772 .addReg(varEnd).addMBB(entryBB);
10773 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10774 .addReg(srcLoop).addMBB(loopMBB)
10775 .addReg(src).addMBB(entryBB);
10776 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10777 .addReg(destLoop).addMBB(loopMBB)
10778 .addReg(dest).addMBB(entryBB);
10779
10780 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10781 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10782 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10783 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10784 IsThumb1, IsThumb2);
10785 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10786 IsThumb1, IsThumb2);
10787
10788 // Decrement loop variable by UnitSize.
10789 if (IsThumb1) {
10790 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10791 .add(t1CondCodeOp())
10792 .addReg(varPhi)
10793 .addImm(UnitSize)
10794 .add(predOps(ARMCC::AL));
10795 } else {
10796 MachineInstrBuilder MIB =
10797 BuildMI(*BB, BB->end(), dl,
10798 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10799 MIB.addReg(varPhi)
10800 .addImm(UnitSize)
10801 .add(predOps(ARMCC::AL))
10802 .add(condCodeOp());
10803 MIB->getOperand(5).setReg(ARM::CPSR);
10804 MIB->getOperand(5).setIsDef(true);
10805 }
10806 BuildMI(*BB, BB->end(), dl,
10807 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10808 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10809
10810 // loopMBB can loop back to loopMBB or fall through to exitMBB.
10811 BB->addSuccessor(loopMBB);
10812 BB->addSuccessor(exitMBB);
10813
10814 // Add epilogue to handle BytesLeft.
10815 BB = exitMBB;
10816 auto StartOfExit = exitMBB->begin();
10817
10818 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10819 // [destOut] = STRB_POST(scratch, destLoop, 1)
10820 unsigned srcIn = srcLoop;
10821 unsigned destIn = destLoop;
10822 for (unsigned i = 0; i < BytesLeft; i++) {
10823 Register srcOut = MRI.createVirtualRegister(TRC);
10824 Register destOut = MRI.createVirtualRegister(TRC);
10825 Register scratch = MRI.createVirtualRegister(TRC);
10826 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10827 IsThumb1, IsThumb2);
10828 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10829 IsThumb1, IsThumb2);
10830 srcIn = srcOut;
10831 destIn = destOut;
10832 }
10833
10834 MI.eraseFromParent(); // The instruction is gone now.
10835 return BB;
10836 }
10837
10838 MachineBasicBlock *
EmitLowered__chkstk(MachineInstr & MI,MachineBasicBlock * MBB) const10839 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10840 MachineBasicBlock *MBB) const {
10841 const TargetMachine &TM = getTargetMachine();
10842 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10843 DebugLoc DL = MI.getDebugLoc();
10844
10845 assert(Subtarget->isTargetWindows() &&
10846 "__chkstk is only supported on Windows");
10847 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10848
10849 // __chkstk takes the number of words to allocate on the stack in R4, and
10850 // returns the stack adjustment in number of bytes in R4. This will not
10851 // clober any other registers (other than the obvious lr).
10852 //
10853 // Although, technically, IP should be considered a register which may be
10854 // clobbered, the call itself will not touch it. Windows on ARM is a pure
10855 // thumb-2 environment, so there is no interworking required. As a result, we
10856 // do not expect a veneer to be emitted by the linker, clobbering IP.
10857 //
10858 // Each module receives its own copy of __chkstk, so no import thunk is
10859 // required, again, ensuring that IP is not clobbered.
10860 //
10861 // Finally, although some linkers may theoretically provide a trampoline for
10862 // out of range calls (which is quite common due to a 32M range limitation of
10863 // branches for Thumb), we can generate the long-call version via
10864 // -mcmodel=large, alleviating the need for the trampoline which may clobber
10865 // IP.
10866
10867 switch (TM.getCodeModel()) {
10868 case CodeModel::Tiny:
10869 llvm_unreachable("Tiny code model not available on ARM.");
10870 case CodeModel::Small:
10871 case CodeModel::Medium:
10872 case CodeModel::Kernel:
10873 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10874 .add(predOps(ARMCC::AL))
10875 .addExternalSymbol("__chkstk")
10876 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10877 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10878 .addReg(ARM::R12,
10879 RegState::Implicit | RegState::Define | RegState::Dead)
10880 .addReg(ARM::CPSR,
10881 RegState::Implicit | RegState::Define | RegState::Dead);
10882 break;
10883 case CodeModel::Large: {
10884 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10885 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10886
10887 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10888 .addExternalSymbol("__chkstk");
10889 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10890 .add(predOps(ARMCC::AL))
10891 .addReg(Reg, RegState::Kill)
10892 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10893 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10894 .addReg(ARM::R12,
10895 RegState::Implicit | RegState::Define | RegState::Dead)
10896 .addReg(ARM::CPSR,
10897 RegState::Implicit | RegState::Define | RegState::Dead);
10898 break;
10899 }
10900 }
10901
10902 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10903 .addReg(ARM::SP, RegState::Kill)
10904 .addReg(ARM::R4, RegState::Kill)
10905 .setMIFlags(MachineInstr::FrameSetup)
10906 .add(predOps(ARMCC::AL))
10907 .add(condCodeOp());
10908
10909 MI.eraseFromParent();
10910 return MBB;
10911 }
10912
10913 MachineBasicBlock *
EmitLowered__dbzchk(MachineInstr & MI,MachineBasicBlock * MBB) const10914 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10915 MachineBasicBlock *MBB) const {
10916 DebugLoc DL = MI.getDebugLoc();
10917 MachineFunction *MF = MBB->getParent();
10918 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10919
10920 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10921 MF->insert(++MBB->getIterator(), ContBB);
10922 ContBB->splice(ContBB->begin(), MBB,
10923 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10924 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10925 MBB->addSuccessor(ContBB);
10926
10927 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10928 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10929 MF->push_back(TrapBB);
10930 MBB->addSuccessor(TrapBB);
10931
10932 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10933 .addReg(MI.getOperand(0).getReg())
10934 .addImm(0)
10935 .add(predOps(ARMCC::AL));
10936 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10937 .addMBB(TrapBB)
10938 .addImm(ARMCC::EQ)
10939 .addReg(ARM::CPSR);
10940
10941 MI.eraseFromParent();
10942 return ContBB;
10943 }
10944
10945 // The CPSR operand of SelectItr might be missing a kill marker
10946 // because there were multiple uses of CPSR, and ISel didn't know
10947 // which to mark. Figure out whether SelectItr should have had a
10948 // kill marker, and set it if it should. Returns the correct kill
10949 // marker value.
checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,MachineBasicBlock * BB,const TargetRegisterInfo * TRI)10950 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10951 MachineBasicBlock* BB,
10952 const TargetRegisterInfo* TRI) {
10953 // Scan forward through BB for a use/def of CPSR.
10954 MachineBasicBlock::iterator miI(std::next(SelectItr));
10955 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10956 const MachineInstr& mi = *miI;
10957 if (mi.readsRegister(ARM::CPSR))
10958 return false;
10959 if (mi.definesRegister(ARM::CPSR))
10960 break; // Should have kill-flag - update below.
10961 }
10962
10963 // If we hit the end of the block, check whether CPSR is live into a
10964 // successor.
10965 if (miI == BB->end()) {
10966 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10967 sEnd = BB->succ_end();
10968 sItr != sEnd; ++sItr) {
10969 MachineBasicBlock* succ = *sItr;
10970 if (succ->isLiveIn(ARM::CPSR))
10971 return false;
10972 }
10973 }
10974
10975 // We found a def, or hit the end of the basic block and CPSR wasn't live
10976 // out. SelectMI should have a kill flag on CPSR.
10977 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10978 return true;
10979 }
10980
10981 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const10982 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10983 MachineBasicBlock *BB) const {
10984 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10985 DebugLoc dl = MI.getDebugLoc();
10986 bool isThumb2 = Subtarget->isThumb2();
10987 switch (MI.getOpcode()) {
10988 default: {
10989 MI.print(errs());
10990 llvm_unreachable("Unexpected instr type to insert");
10991 }
10992
10993 // Thumb1 post-indexed loads are really just single-register LDMs.
10994 case ARM::tLDR_postidx: {
10995 MachineOperand Def(MI.getOperand(1));
10996 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10997 .add(Def) // Rn_wb
10998 .add(MI.getOperand(2)) // Rn
10999 .add(MI.getOperand(3)) // PredImm
11000 .add(MI.getOperand(4)) // PredReg
11001 .add(MI.getOperand(0)) // Rt
11002 .cloneMemRefs(MI);
11003 MI.eraseFromParent();
11004 return BB;
11005 }
11006
11007 // The Thumb2 pre-indexed stores have the same MI operands, they just
11008 // define them differently in the .td files from the isel patterns, so
11009 // they need pseudos.
11010 case ARM::t2STR_preidx:
11011 MI.setDesc(TII->get(ARM::t2STR_PRE));
11012 return BB;
11013 case ARM::t2STRB_preidx:
11014 MI.setDesc(TII->get(ARM::t2STRB_PRE));
11015 return BB;
11016 case ARM::t2STRH_preidx:
11017 MI.setDesc(TII->get(ARM::t2STRH_PRE));
11018 return BB;
11019
11020 case ARM::STRi_preidx:
11021 case ARM::STRBi_preidx: {
11022 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
11023 : ARM::STRB_PRE_IMM;
11024 // Decode the offset.
11025 unsigned Offset = MI.getOperand(4).getImm();
11026 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
11027 Offset = ARM_AM::getAM2Offset(Offset);
11028 if (isSub)
11029 Offset = -Offset;
11030
11031 MachineMemOperand *MMO = *MI.memoperands_begin();
11032 BuildMI(*BB, MI, dl, TII->get(NewOpc))
11033 .add(MI.getOperand(0)) // Rn_wb
11034 .add(MI.getOperand(1)) // Rt
11035 .add(MI.getOperand(2)) // Rn
11036 .addImm(Offset) // offset (skip GPR==zero_reg)
11037 .add(MI.getOperand(5)) // pred
11038 .add(MI.getOperand(6))
11039 .addMemOperand(MMO);
11040 MI.eraseFromParent();
11041 return BB;
11042 }
11043 case ARM::STRr_preidx:
11044 case ARM::STRBr_preidx:
11045 case ARM::STRH_preidx: {
11046 unsigned NewOpc;
11047 switch (MI.getOpcode()) {
11048 default: llvm_unreachable("unexpected opcode!");
11049 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
11050 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
11051 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
11052 }
11053 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
11054 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
11055 MIB.add(MI.getOperand(i));
11056 MI.eraseFromParent();
11057 return BB;
11058 }
11059
11060 case ARM::tMOVCCr_pseudo: {
11061 // To "insert" a SELECT_CC instruction, we actually have to insert the
11062 // diamond control-flow pattern. The incoming instruction knows the
11063 // destination vreg to set, the condition code register to branch on, the
11064 // true/false values to select between, and a branch opcode to use.
11065 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11066 MachineFunction::iterator It = ++BB->getIterator();
11067
11068 // thisMBB:
11069 // ...
11070 // TrueVal = ...
11071 // cmpTY ccX, r1, r2
11072 // bCC copy1MBB
11073 // fallthrough --> copy0MBB
11074 MachineBasicBlock *thisMBB = BB;
11075 MachineFunction *F = BB->getParent();
11076 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11077 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11078 F->insert(It, copy0MBB);
11079 F->insert(It, sinkMBB);
11080
11081 // Check whether CPSR is live past the tMOVCCr_pseudo.
11082 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
11083 if (!MI.killsRegister(ARM::CPSR) &&
11084 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
11085 copy0MBB->addLiveIn(ARM::CPSR);
11086 sinkMBB->addLiveIn(ARM::CPSR);
11087 }
11088
11089 // Transfer the remainder of BB and its successor edges to sinkMBB.
11090 sinkMBB->splice(sinkMBB->begin(), BB,
11091 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11092 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11093
11094 BB->addSuccessor(copy0MBB);
11095 BB->addSuccessor(sinkMBB);
11096
11097 BuildMI(BB, dl, TII->get(ARM::tBcc))
11098 .addMBB(sinkMBB)
11099 .addImm(MI.getOperand(3).getImm())
11100 .addReg(MI.getOperand(4).getReg());
11101
11102 // copy0MBB:
11103 // %FalseValue = ...
11104 // # fallthrough to sinkMBB
11105 BB = copy0MBB;
11106
11107 // Update machine-CFG edges
11108 BB->addSuccessor(sinkMBB);
11109
11110 // sinkMBB:
11111 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11112 // ...
11113 BB = sinkMBB;
11114 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
11115 .addReg(MI.getOperand(1).getReg())
11116 .addMBB(copy0MBB)
11117 .addReg(MI.getOperand(2).getReg())
11118 .addMBB(thisMBB);
11119
11120 MI.eraseFromParent(); // The pseudo instruction is gone now.
11121 return BB;
11122 }
11123
11124 case ARM::BCCi64:
11125 case ARM::BCCZi64: {
11126 // If there is an unconditional branch to the other successor, remove it.
11127 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
11128
11129 // Compare both parts that make up the double comparison separately for
11130 // equality.
11131 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
11132
11133 Register LHS1 = MI.getOperand(1).getReg();
11134 Register LHS2 = MI.getOperand(2).getReg();
11135 if (RHSisZero) {
11136 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11137 .addReg(LHS1)
11138 .addImm(0)
11139 .add(predOps(ARMCC::AL));
11140 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11141 .addReg(LHS2).addImm(0)
11142 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11143 } else {
11144 Register RHS1 = MI.getOperand(3).getReg();
11145 Register RHS2 = MI.getOperand(4).getReg();
11146 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11147 .addReg(LHS1)
11148 .addReg(RHS1)
11149 .add(predOps(ARMCC::AL));
11150 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11151 .addReg(LHS2).addReg(RHS2)
11152 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11153 }
11154
11155 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
11156 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
11157 if (MI.getOperand(0).getImm() == ARMCC::NE)
11158 std::swap(destMBB, exitMBB);
11159
11160 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
11161 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
11162 if (isThumb2)
11163 BuildMI(BB, dl, TII->get(ARM::t2B))
11164 .addMBB(exitMBB)
11165 .add(predOps(ARMCC::AL));
11166 else
11167 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
11168
11169 MI.eraseFromParent(); // The pseudo instruction is gone now.
11170 return BB;
11171 }
11172
11173 case ARM::Int_eh_sjlj_setjmp:
11174 case ARM::Int_eh_sjlj_setjmp_nofp:
11175 case ARM::tInt_eh_sjlj_setjmp:
11176 case ARM::t2Int_eh_sjlj_setjmp:
11177 case ARM::t2Int_eh_sjlj_setjmp_nofp:
11178 return BB;
11179
11180 case ARM::Int_eh_sjlj_setup_dispatch:
11181 EmitSjLjDispatchBlock(MI, BB);
11182 return BB;
11183
11184 case ARM::ABS:
11185 case ARM::t2ABS: {
11186 // To insert an ABS instruction, we have to insert the
11187 // diamond control-flow pattern. The incoming instruction knows the
11188 // source vreg to test against 0, the destination vreg to set,
11189 // the condition code register to branch on, the
11190 // true/false values to select between, and a branch opcode to use.
11191 // It transforms
11192 // V1 = ABS V0
11193 // into
11194 // V2 = MOVS V0
11195 // BCC (branch to SinkBB if V0 >= 0)
11196 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
11197 // SinkBB: V1 = PHI(V2, V3)
11198 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11199 MachineFunction::iterator BBI = ++BB->getIterator();
11200 MachineFunction *Fn = BB->getParent();
11201 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
11202 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
11203 Fn->insert(BBI, RSBBB);
11204 Fn->insert(BBI, SinkBB);
11205
11206 Register ABSSrcReg = MI.getOperand(1).getReg();
11207 Register ABSDstReg = MI.getOperand(0).getReg();
11208 bool ABSSrcKIll = MI.getOperand(1).isKill();
11209 bool isThumb2 = Subtarget->isThumb2();
11210 MachineRegisterInfo &MRI = Fn->getRegInfo();
11211 // In Thumb mode S must not be specified if source register is the SP or
11212 // PC and if destination register is the SP, so restrict register class
11213 Register NewRsbDstReg = MRI.createVirtualRegister(
11214 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
11215
11216 // Transfer the remainder of BB and its successor edges to sinkMBB.
11217 SinkBB->splice(SinkBB->begin(), BB,
11218 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11219 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
11220
11221 BB->addSuccessor(RSBBB);
11222 BB->addSuccessor(SinkBB);
11223
11224 // fall through to SinkMBB
11225 RSBBB->addSuccessor(SinkBB);
11226
11227 // insert a cmp at the end of BB
11228 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11229 .addReg(ABSSrcReg)
11230 .addImm(0)
11231 .add(predOps(ARMCC::AL));
11232
11233 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
11234 BuildMI(BB, dl,
11235 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
11236 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
11237
11238 // insert rsbri in RSBBB
11239 // Note: BCC and rsbri will be converted into predicated rsbmi
11240 // by if-conversion pass
11241 BuildMI(*RSBBB, RSBBB->begin(), dl,
11242 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
11243 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
11244 .addImm(0)
11245 .add(predOps(ARMCC::AL))
11246 .add(condCodeOp());
11247
11248 // insert PHI in SinkBB,
11249 // reuse ABSDstReg to not change uses of ABS instruction
11250 BuildMI(*SinkBB, SinkBB->begin(), dl,
11251 TII->get(ARM::PHI), ABSDstReg)
11252 .addReg(NewRsbDstReg).addMBB(RSBBB)
11253 .addReg(ABSSrcReg).addMBB(BB);
11254
11255 // remove ABS instruction
11256 MI.eraseFromParent();
11257
11258 // return last added BB
11259 return SinkBB;
11260 }
11261 case ARM::COPY_STRUCT_BYVAL_I32:
11262 ++NumLoopByVals;
11263 return EmitStructByval(MI, BB);
11264 case ARM::WIN__CHKSTK:
11265 return EmitLowered__chkstk(MI, BB);
11266 case ARM::WIN__DBZCHK:
11267 return EmitLowered__dbzchk(MI, BB);
11268 case ARM::t2DoLoopStart:
11269 // We are just here to set a register allocation hint, prefering lr for the
11270 // input register to make it more likely to be movable and removable, later
11271 // in the pipeline.
11272 Register R = MI.getOperand(1).getReg();
11273 MachineFunction *MF = MI.getParent()->getParent();
11274 MF->getRegInfo().setRegAllocationHint(R, ARMRI::RegLR, 0);
11275 return BB;
11276 }
11277 }
11278
11279 /// Attaches vregs to MEMCPY that it will use as scratch registers
11280 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
11281 /// instead of as a custom inserter because we need the use list from the SDNode.
attachMEMCPYScratchRegs(const ARMSubtarget * Subtarget,MachineInstr & MI,const SDNode * Node)11282 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
11283 MachineInstr &MI, const SDNode *Node) {
11284 bool isThumb1 = Subtarget->isThumb1Only();
11285
11286 DebugLoc DL = MI.getDebugLoc();
11287 MachineFunction *MF = MI.getParent()->getParent();
11288 MachineRegisterInfo &MRI = MF->getRegInfo();
11289 MachineInstrBuilder MIB(*MF, MI);
11290
11291 // If the new dst/src is unused mark it as dead.
11292 if (!Node->hasAnyUseOfValue(0)) {
11293 MI.getOperand(0).setIsDead(true);
11294 }
11295 if (!Node->hasAnyUseOfValue(1)) {
11296 MI.getOperand(1).setIsDead(true);
11297 }
11298
11299 // The MEMCPY both defines and kills the scratch registers.
11300 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
11301 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
11302 : &ARM::GPRRegClass);
11303 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
11304 }
11305 }
11306
AdjustInstrPostInstrSelection(MachineInstr & MI,SDNode * Node) const11307 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11308 SDNode *Node) const {
11309 if (MI.getOpcode() == ARM::MEMCPY) {
11310 attachMEMCPYScratchRegs(Subtarget, MI, Node);
11311 return;
11312 }
11313
11314 const MCInstrDesc *MCID = &MI.getDesc();
11315 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
11316 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
11317 // operand is still set to noreg. If needed, set the optional operand's
11318 // register to CPSR, and remove the redundant implicit def.
11319 //
11320 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
11321
11322 // Rename pseudo opcodes.
11323 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
11324 unsigned ccOutIdx;
11325 if (NewOpc) {
11326 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
11327 MCID = &TII->get(NewOpc);
11328
11329 assert(MCID->getNumOperands() ==
11330 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
11331 && "converted opcode should be the same except for cc_out"
11332 " (and, on Thumb1, pred)");
11333
11334 MI.setDesc(*MCID);
11335
11336 // Add the optional cc_out operand
11337 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
11338
11339 // On Thumb1, move all input operands to the end, then add the predicate
11340 if (Subtarget->isThumb1Only()) {
11341 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
11342 MI.addOperand(MI.getOperand(1));
11343 MI.RemoveOperand(1);
11344 }
11345
11346 // Restore the ties
11347 for (unsigned i = MI.getNumOperands(); i--;) {
11348 const MachineOperand& op = MI.getOperand(i);
11349 if (op.isReg() && op.isUse()) {
11350 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
11351 if (DefIdx != -1)
11352 MI.tieOperands(DefIdx, i);
11353 }
11354 }
11355
11356 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
11357 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
11358 ccOutIdx = 1;
11359 } else
11360 ccOutIdx = MCID->getNumOperands() - 1;
11361 } else
11362 ccOutIdx = MCID->getNumOperands() - 1;
11363
11364 // Any ARM instruction that sets the 's' bit should specify an optional
11365 // "cc_out" operand in the last operand position.
11366 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
11367 assert(!NewOpc && "Optional cc_out operand required");
11368 return;
11369 }
11370 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
11371 // since we already have an optional CPSR def.
11372 bool definesCPSR = false;
11373 bool deadCPSR = false;
11374 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
11375 ++i) {
11376 const MachineOperand &MO = MI.getOperand(i);
11377 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
11378 definesCPSR = true;
11379 if (MO.isDead())
11380 deadCPSR = true;
11381 MI.RemoveOperand(i);
11382 break;
11383 }
11384 }
11385 if (!definesCPSR) {
11386 assert(!NewOpc && "Optional cc_out operand required");
11387 return;
11388 }
11389 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
11390 if (deadCPSR) {
11391 assert(!MI.getOperand(ccOutIdx).getReg() &&
11392 "expect uninitialized optional cc_out operand");
11393 // Thumb1 instructions must have the S bit even if the CPSR is dead.
11394 if (!Subtarget->isThumb1Only())
11395 return;
11396 }
11397
11398 // If this instruction was defined with an optional CPSR def and its dag node
11399 // had a live implicit CPSR def, then activate the optional CPSR def.
11400 MachineOperand &MO = MI.getOperand(ccOutIdx);
11401 MO.setReg(ARM::CPSR);
11402 MO.setIsDef(true);
11403 }
11404
11405 //===----------------------------------------------------------------------===//
11406 // ARM Optimization Hooks
11407 //===----------------------------------------------------------------------===//
11408
11409 // Helper function that checks if N is a null or all ones constant.
isZeroOrAllOnes(SDValue N,bool AllOnes)11410 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
11411 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
11412 }
11413
11414 // Return true if N is conditionally 0 or all ones.
11415 // Detects these expressions where cc is an i1 value:
11416 //
11417 // (select cc 0, y) [AllOnes=0]
11418 // (select cc y, 0) [AllOnes=0]
11419 // (zext cc) [AllOnes=0]
11420 // (sext cc) [AllOnes=0/1]
11421 // (select cc -1, y) [AllOnes=1]
11422 // (select cc y, -1) [AllOnes=1]
11423 //
11424 // Invert is set when N is the null/all ones constant when CC is false.
11425 // OtherOp is set to the alternative value of N.
isConditionalZeroOrAllOnes(SDNode * N,bool AllOnes,SDValue & CC,bool & Invert,SDValue & OtherOp,SelectionDAG & DAG)11426 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
11427 SDValue &CC, bool &Invert,
11428 SDValue &OtherOp,
11429 SelectionDAG &DAG) {
11430 switch (N->getOpcode()) {
11431 default: return false;
11432 case ISD::SELECT: {
11433 CC = N->getOperand(0);
11434 SDValue N1 = N->getOperand(1);
11435 SDValue N2 = N->getOperand(2);
11436 if (isZeroOrAllOnes(N1, AllOnes)) {
11437 Invert = false;
11438 OtherOp = N2;
11439 return true;
11440 }
11441 if (isZeroOrAllOnes(N2, AllOnes)) {
11442 Invert = true;
11443 OtherOp = N1;
11444 return true;
11445 }
11446 return false;
11447 }
11448 case ISD::ZERO_EXTEND:
11449 // (zext cc) can never be the all ones value.
11450 if (AllOnes)
11451 return false;
11452 LLVM_FALLTHROUGH;
11453 case ISD::SIGN_EXTEND: {
11454 SDLoc dl(N);
11455 EVT VT = N->getValueType(0);
11456 CC = N->getOperand(0);
11457 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
11458 return false;
11459 Invert = !AllOnes;
11460 if (AllOnes)
11461 // When looking for an AllOnes constant, N is an sext, and the 'other'
11462 // value is 0.
11463 OtherOp = DAG.getConstant(0, dl, VT);
11464 else if (N->getOpcode() == ISD::ZERO_EXTEND)
11465 // When looking for a 0 constant, N can be zext or sext.
11466 OtherOp = DAG.getConstant(1, dl, VT);
11467 else
11468 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
11469 VT);
11470 return true;
11471 }
11472 }
11473 }
11474
11475 // Combine a constant select operand into its use:
11476 //
11477 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11478 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11479 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
11480 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
11481 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11482 //
11483 // The transform is rejected if the select doesn't have a constant operand that
11484 // is null, or all ones when AllOnes is set.
11485 //
11486 // Also recognize sext/zext from i1:
11487 //
11488 // (add (zext cc), x) -> (select cc (add x, 1), x)
11489 // (add (sext cc), x) -> (select cc (add x, -1), x)
11490 //
11491 // These transformations eventually create predicated instructions.
11492 //
11493 // @param N The node to transform.
11494 // @param Slct The N operand that is a select.
11495 // @param OtherOp The other N operand (x above).
11496 // @param DCI Context.
11497 // @param AllOnes Require the select constant to be all ones instead of null.
11498 // @returns The new node, or SDValue() on failure.
11499 static
combineSelectAndUse(SDNode * N,SDValue Slct,SDValue OtherOp,TargetLowering::DAGCombinerInfo & DCI,bool AllOnes=false)11500 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
11501 TargetLowering::DAGCombinerInfo &DCI,
11502 bool AllOnes = false) {
11503 SelectionDAG &DAG = DCI.DAG;
11504 EVT VT = N->getValueType(0);
11505 SDValue NonConstantVal;
11506 SDValue CCOp;
11507 bool SwapSelectOps;
11508 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
11509 NonConstantVal, DAG))
11510 return SDValue();
11511
11512 // Slct is now know to be the desired identity constant when CC is true.
11513 SDValue TrueVal = OtherOp;
11514 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11515 OtherOp, NonConstantVal);
11516 // Unless SwapSelectOps says CC should be false.
11517 if (SwapSelectOps)
11518 std::swap(TrueVal, FalseVal);
11519
11520 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
11521 CCOp, TrueVal, FalseVal);
11522 }
11523
11524 // Attempt combineSelectAndUse on each operand of a commutative operator N.
11525 static
combineSelectAndUseCommutative(SDNode * N,bool AllOnes,TargetLowering::DAGCombinerInfo & DCI)11526 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
11527 TargetLowering::DAGCombinerInfo &DCI) {
11528 SDValue N0 = N->getOperand(0);
11529 SDValue N1 = N->getOperand(1);
11530 if (N0.getNode()->hasOneUse())
11531 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
11532 return Result;
11533 if (N1.getNode()->hasOneUse())
11534 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
11535 return Result;
11536 return SDValue();
11537 }
11538
IsVUZPShuffleNode(SDNode * N)11539 static bool IsVUZPShuffleNode(SDNode *N) {
11540 // VUZP shuffle node.
11541 if (N->getOpcode() == ARMISD::VUZP)
11542 return true;
11543
11544 // "VUZP" on i32 is an alias for VTRN.
11545 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
11546 return true;
11547
11548 return false;
11549 }
11550
AddCombineToVPADD(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)11551 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
11552 TargetLowering::DAGCombinerInfo &DCI,
11553 const ARMSubtarget *Subtarget) {
11554 // Look for ADD(VUZP.0, VUZP.1).
11555 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
11556 N0 == N1)
11557 return SDValue();
11558
11559 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
11560 if (!N->getValueType(0).is64BitVector())
11561 return SDValue();
11562
11563 // Generate vpadd.
11564 SelectionDAG &DAG = DCI.DAG;
11565 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11566 SDLoc dl(N);
11567 SDNode *Unzip = N0.getNode();
11568 EVT VT = N->getValueType(0);
11569
11570 SmallVector<SDValue, 8> Ops;
11571 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
11572 TLI.getPointerTy(DAG.getDataLayout())));
11573 Ops.push_back(Unzip->getOperand(0));
11574 Ops.push_back(Unzip->getOperand(1));
11575
11576 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11577 }
11578
AddCombineVUZPToVPADDL(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)11579 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11580 TargetLowering::DAGCombinerInfo &DCI,
11581 const ARMSubtarget *Subtarget) {
11582 // Check for two extended operands.
11583 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
11584 N1.getOpcode() == ISD::SIGN_EXTEND) &&
11585 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
11586 N1.getOpcode() == ISD::ZERO_EXTEND))
11587 return SDValue();
11588
11589 SDValue N00 = N0.getOperand(0);
11590 SDValue N10 = N1.getOperand(0);
11591
11592 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
11593 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
11594 N00 == N10)
11595 return SDValue();
11596
11597 // We only recognize Q register paddl here; this can't be reached until
11598 // after type legalization.
11599 if (!N00.getValueType().is64BitVector() ||
11600 !N0.getValueType().is128BitVector())
11601 return SDValue();
11602
11603 // Generate vpaddl.
11604 SelectionDAG &DAG = DCI.DAG;
11605 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11606 SDLoc dl(N);
11607 EVT VT = N->getValueType(0);
11608
11609 SmallVector<SDValue, 8> Ops;
11610 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
11611 unsigned Opcode;
11612 if (N0.getOpcode() == ISD::SIGN_EXTEND)
11613 Opcode = Intrinsic::arm_neon_vpaddls;
11614 else
11615 Opcode = Intrinsic::arm_neon_vpaddlu;
11616 Ops.push_back(DAG.getConstant(Opcode, dl,
11617 TLI.getPointerTy(DAG.getDataLayout())));
11618 EVT ElemTy = N00.getValueType().getVectorElementType();
11619 unsigned NumElts = VT.getVectorNumElements();
11620 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
11621 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
11622 N00.getOperand(0), N00.getOperand(1));
11623 Ops.push_back(Concat);
11624
11625 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11626 }
11627
11628 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
11629 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
11630 // much easier to match.
11631 static SDValue
AddCombineBUILD_VECTORToVPADDL(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)11632 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11633 TargetLowering::DAGCombinerInfo &DCI,
11634 const ARMSubtarget *Subtarget) {
11635 // Only perform optimization if after legalize, and if NEON is available. We
11636 // also expected both operands to be BUILD_VECTORs.
11637 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
11638 || N0.getOpcode() != ISD::BUILD_VECTOR
11639 || N1.getOpcode() != ISD::BUILD_VECTOR)
11640 return SDValue();
11641
11642 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
11643 EVT VT = N->getValueType(0);
11644 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
11645 return SDValue();
11646
11647 // Check that the vector operands are of the right form.
11648 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11649 // operands, where N is the size of the formed vector.
11650 // Each EXTRACT_VECTOR should have the same input vector and odd or even
11651 // index such that we have a pair wise add pattern.
11652
11653 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11654 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11655 return SDValue();
11656 SDValue Vec = N0->getOperand(0)->getOperand(0);
11657 SDNode *V = Vec.getNode();
11658 unsigned nextIndex = 0;
11659
11660 // For each operands to the ADD which are BUILD_VECTORs,
11661 // check to see if each of their operands are an EXTRACT_VECTOR with
11662 // the same vector and appropriate index.
11663 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11664 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11665 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11666
11667 SDValue ExtVec0 = N0->getOperand(i);
11668 SDValue ExtVec1 = N1->getOperand(i);
11669
11670 // First operand is the vector, verify its the same.
11671 if (V != ExtVec0->getOperand(0).getNode() ||
11672 V != ExtVec1->getOperand(0).getNode())
11673 return SDValue();
11674
11675 // Second is the constant, verify its correct.
11676 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11677 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11678
11679 // For the constant, we want to see all the even or all the odd.
11680 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11681 || C1->getZExtValue() != nextIndex+1)
11682 return SDValue();
11683
11684 // Increment index.
11685 nextIndex+=2;
11686 } else
11687 return SDValue();
11688 }
11689
11690 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11691 // we're using the entire input vector, otherwise there's a size/legality
11692 // mismatch somewhere.
11693 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11694 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11695 return SDValue();
11696
11697 // Create VPADDL node.
11698 SelectionDAG &DAG = DCI.DAG;
11699 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11700
11701 SDLoc dl(N);
11702
11703 // Build operand list.
11704 SmallVector<SDValue, 8> Ops;
11705 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11706 TLI.getPointerTy(DAG.getDataLayout())));
11707
11708 // Input is the vector.
11709 Ops.push_back(Vec);
11710
11711 // Get widened type and narrowed type.
11712 MVT widenType;
11713 unsigned numElem = VT.getVectorNumElements();
11714
11715 EVT inputLaneType = Vec.getValueType().getVectorElementType();
11716 switch (inputLaneType.getSimpleVT().SimpleTy) {
11717 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11718 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11719 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11720 default:
11721 llvm_unreachable("Invalid vector element type for padd optimization.");
11722 }
11723
11724 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11725 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11726 return DAG.getNode(ExtOp, dl, VT, tmp);
11727 }
11728
findMUL_LOHI(SDValue V)11729 static SDValue findMUL_LOHI(SDValue V) {
11730 if (V->getOpcode() == ISD::UMUL_LOHI ||
11731 V->getOpcode() == ISD::SMUL_LOHI)
11732 return V;
11733 return SDValue();
11734 }
11735
AddCombineTo64BitSMLAL16(SDNode * AddcNode,SDNode * AddeNode,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)11736 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11737 TargetLowering::DAGCombinerInfo &DCI,
11738 const ARMSubtarget *Subtarget) {
11739 if (!Subtarget->hasBaseDSP())
11740 return SDValue();
11741
11742 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11743 // accumulates the product into a 64-bit value. The 16-bit values will
11744 // be sign extended somehow or SRA'd into 32-bit values
11745 // (addc (adde (mul 16bit, 16bit), lo), hi)
11746 SDValue Mul = AddcNode->getOperand(0);
11747 SDValue Lo = AddcNode->getOperand(1);
11748 if (Mul.getOpcode() != ISD::MUL) {
11749 Lo = AddcNode->getOperand(0);
11750 Mul = AddcNode->getOperand(1);
11751 if (Mul.getOpcode() != ISD::MUL)
11752 return SDValue();
11753 }
11754
11755 SDValue SRA = AddeNode->getOperand(0);
11756 SDValue Hi = AddeNode->getOperand(1);
11757 if (SRA.getOpcode() != ISD::SRA) {
11758 SRA = AddeNode->getOperand(1);
11759 Hi = AddeNode->getOperand(0);
11760 if (SRA.getOpcode() != ISD::SRA)
11761 return SDValue();
11762 }
11763 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11764 if (Const->getZExtValue() != 31)
11765 return SDValue();
11766 } else
11767 return SDValue();
11768
11769 if (SRA.getOperand(0) != Mul)
11770 return SDValue();
11771
11772 SelectionDAG &DAG = DCI.DAG;
11773 SDLoc dl(AddcNode);
11774 unsigned Opcode = 0;
11775 SDValue Op0;
11776 SDValue Op1;
11777
11778 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11779 Opcode = ARMISD::SMLALBB;
11780 Op0 = Mul.getOperand(0);
11781 Op1 = Mul.getOperand(1);
11782 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11783 Opcode = ARMISD::SMLALBT;
11784 Op0 = Mul.getOperand(0);
11785 Op1 = Mul.getOperand(1).getOperand(0);
11786 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11787 Opcode = ARMISD::SMLALTB;
11788 Op0 = Mul.getOperand(0).getOperand(0);
11789 Op1 = Mul.getOperand(1);
11790 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11791 Opcode = ARMISD::SMLALTT;
11792 Op0 = Mul->getOperand(0).getOperand(0);
11793 Op1 = Mul->getOperand(1).getOperand(0);
11794 }
11795
11796 if (!Op0 || !Op1)
11797 return SDValue();
11798
11799 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11800 Op0, Op1, Lo, Hi);
11801 // Replace the ADDs' nodes uses by the MLA node's values.
11802 SDValue HiMLALResult(SMLAL.getNode(), 1);
11803 SDValue LoMLALResult(SMLAL.getNode(), 0);
11804
11805 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11806 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11807
11808 // Return original node to notify the driver to stop replacing.
11809 SDValue resNode(AddcNode, 0);
11810 return resNode;
11811 }
11812
AddCombineTo64bitMLAL(SDNode * AddeSubeNode,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)11813 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11814 TargetLowering::DAGCombinerInfo &DCI,
11815 const ARMSubtarget *Subtarget) {
11816 // Look for multiply add opportunities.
11817 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11818 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11819 // a glue link from the first add to the second add.
11820 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11821 // a S/UMLAL instruction.
11822 // UMUL_LOHI
11823 // / :lo \ :hi
11824 // V \ [no multiline comment]
11825 // loAdd -> ADDC |
11826 // \ :carry /
11827 // V V
11828 // ADDE <- hiAdd
11829 //
11830 // In the special case where only the higher part of a signed result is used
11831 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11832 // a constant with the exact value of 0x80000000, we recognize we are dealing
11833 // with a "rounded multiply and add" (or subtract) and transform it into
11834 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11835
11836 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11837 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11838 "Expect an ADDE or SUBE");
11839
11840 assert(AddeSubeNode->getNumOperands() == 3 &&
11841 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11842 "ADDE node has the wrong inputs");
11843
11844 // Check that we are chained to the right ADDC or SUBC node.
11845 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11846 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11847 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11848 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11849 AddcSubcNode->getOpcode() != ARMISD::SUBC))
11850 return SDValue();
11851
11852 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11853 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11854
11855 // Check if the two operands are from the same mul_lohi node.
11856 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11857 return SDValue();
11858
11859 assert(AddcSubcNode->getNumValues() == 2 &&
11860 AddcSubcNode->getValueType(0) == MVT::i32 &&
11861 "Expect ADDC with two result values. First: i32");
11862
11863 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11864 // maybe a SMLAL which multiplies two 16-bit values.
11865 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11866 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11867 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11868 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11869 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11870 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11871
11872 // Check for the triangle shape.
11873 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11874 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11875
11876 // Make sure that the ADDE/SUBE operands are not coming from the same node.
11877 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11878 return SDValue();
11879
11880 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11881 bool IsLeftOperandMUL = false;
11882 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11883 if (MULOp == SDValue())
11884 MULOp = findMUL_LOHI(AddeSubeOp1);
11885 else
11886 IsLeftOperandMUL = true;
11887 if (MULOp == SDValue())
11888 return SDValue();
11889
11890 // Figure out the right opcode.
11891 unsigned Opc = MULOp->getOpcode();
11892 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11893
11894 // Figure out the high and low input values to the MLAL node.
11895 SDValue *HiAddSub = nullptr;
11896 SDValue *LoMul = nullptr;
11897 SDValue *LowAddSub = nullptr;
11898
11899 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11900 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11901 return SDValue();
11902
11903 if (IsLeftOperandMUL)
11904 HiAddSub = &AddeSubeOp1;
11905 else
11906 HiAddSub = &AddeSubeOp0;
11907
11908 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11909 // whose low result is fed to the ADDC/SUBC we are checking.
11910
11911 if (AddcSubcOp0 == MULOp.getValue(0)) {
11912 LoMul = &AddcSubcOp0;
11913 LowAddSub = &AddcSubcOp1;
11914 }
11915 if (AddcSubcOp1 == MULOp.getValue(0)) {
11916 LoMul = &AddcSubcOp1;
11917 LowAddSub = &AddcSubcOp0;
11918 }
11919
11920 if (!LoMul)
11921 return SDValue();
11922
11923 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11924 // the replacement below will create a cycle.
11925 if (AddcSubcNode == HiAddSub->getNode() ||
11926 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11927 return SDValue();
11928
11929 // Create the merged node.
11930 SelectionDAG &DAG = DCI.DAG;
11931
11932 // Start building operand list.
11933 SmallVector<SDValue, 8> Ops;
11934 Ops.push_back(LoMul->getOperand(0));
11935 Ops.push_back(LoMul->getOperand(1));
11936
11937 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
11938 // the case, we must be doing signed multiplication and only use the higher
11939 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11940 // addition or subtraction with the value of 0x800000.
11941 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11942 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11943 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11944 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11945 0x80000000) {
11946 Ops.push_back(*HiAddSub);
11947 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11948 FinalOpc = ARMISD::SMMLSR;
11949 } else {
11950 FinalOpc = ARMISD::SMMLAR;
11951 }
11952 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11953 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11954
11955 return SDValue(AddeSubeNode, 0);
11956 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11957 // SMMLS is generated during instruction selection and the rest of this
11958 // function can not handle the case where AddcSubcNode is a SUBC.
11959 return SDValue();
11960
11961 // Finish building the operand list for {U/S}MLAL
11962 Ops.push_back(*LowAddSub);
11963 Ops.push_back(*HiAddSub);
11964
11965 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11966 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11967
11968 // Replace the ADDs' nodes uses by the MLA node's values.
11969 SDValue HiMLALResult(MLALNode.getNode(), 1);
11970 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11971
11972 SDValue LoMLALResult(MLALNode.getNode(), 0);
11973 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11974
11975 // Return original node to notify the driver to stop replacing.
11976 return SDValue(AddeSubeNode, 0);
11977 }
11978
AddCombineTo64bitUMAAL(SDNode * AddeNode,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)11979 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11980 TargetLowering::DAGCombinerInfo &DCI,
11981 const ARMSubtarget *Subtarget) {
11982 // UMAAL is similar to UMLAL except that it adds two unsigned values.
11983 // While trying to combine for the other MLAL nodes, first search for the
11984 // chance to use UMAAL. Check if Addc uses a node which has already
11985 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11986 // as the addend, and it's handled in PerformUMLALCombine.
11987
11988 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11989 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11990
11991 // Check that we have a glued ADDC node.
11992 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11993 if (AddcNode->getOpcode() != ARMISD::ADDC)
11994 return SDValue();
11995
11996 // Find the converted UMAAL or quit if it doesn't exist.
11997 SDNode *UmlalNode = nullptr;
11998 SDValue AddHi;
11999 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
12000 UmlalNode = AddcNode->getOperand(0).getNode();
12001 AddHi = AddcNode->getOperand(1);
12002 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
12003 UmlalNode = AddcNode->getOperand(1).getNode();
12004 AddHi = AddcNode->getOperand(0);
12005 } else {
12006 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12007 }
12008
12009 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12010 // the ADDC as well as Zero.
12011 if (!isNullConstant(UmlalNode->getOperand(3)))
12012 return SDValue();
12013
12014 if ((isNullConstant(AddeNode->getOperand(0)) &&
12015 AddeNode->getOperand(1).getNode() == UmlalNode) ||
12016 (AddeNode->getOperand(0).getNode() == UmlalNode &&
12017 isNullConstant(AddeNode->getOperand(1)))) {
12018 SelectionDAG &DAG = DCI.DAG;
12019 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
12020 UmlalNode->getOperand(2), AddHi };
12021 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
12022 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12023
12024 // Replace the ADDs' nodes uses by the UMAAL node's values.
12025 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
12026 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
12027
12028 // Return original node to notify the driver to stop replacing.
12029 return SDValue(AddeNode, 0);
12030 }
12031 return SDValue();
12032 }
12033
PerformUMLALCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)12034 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
12035 const ARMSubtarget *Subtarget) {
12036 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12037 return SDValue();
12038
12039 // Check that we have a pair of ADDC and ADDE as operands.
12040 // Both addends of the ADDE must be zero.
12041 SDNode* AddcNode = N->getOperand(2).getNode();
12042 SDNode* AddeNode = N->getOperand(3).getNode();
12043 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
12044 (AddeNode->getOpcode() == ARMISD::ADDE) &&
12045 isNullConstant(AddeNode->getOperand(0)) &&
12046 isNullConstant(AddeNode->getOperand(1)) &&
12047 (AddeNode->getOperand(2).getNode() == AddcNode))
12048 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
12049 DAG.getVTList(MVT::i32, MVT::i32),
12050 {N->getOperand(0), N->getOperand(1),
12051 AddcNode->getOperand(0), AddcNode->getOperand(1)});
12052 else
12053 return SDValue();
12054 }
12055
PerformAddcSubcCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12056 static SDValue PerformAddcSubcCombine(SDNode *N,
12057 TargetLowering::DAGCombinerInfo &DCI,
12058 const ARMSubtarget *Subtarget) {
12059 SelectionDAG &DAG(DCI.DAG);
12060
12061 if (N->getOpcode() == ARMISD::SUBC) {
12062 // (SUBC (ADDE 0, 0, C), 1) -> C
12063 SDValue LHS = N->getOperand(0);
12064 SDValue RHS = N->getOperand(1);
12065 if (LHS->getOpcode() == ARMISD::ADDE &&
12066 isNullConstant(LHS->getOperand(0)) &&
12067 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
12068 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
12069 }
12070 }
12071
12072 if (Subtarget->isThumb1Only()) {
12073 SDValue RHS = N->getOperand(1);
12074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12075 int32_t imm = C->getSExtValue();
12076 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
12077 SDLoc DL(N);
12078 RHS = DAG.getConstant(-imm, DL, MVT::i32);
12079 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
12080 : ARMISD::ADDC;
12081 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
12082 }
12083 }
12084 }
12085
12086 return SDValue();
12087 }
12088
PerformAddeSubeCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12089 static SDValue PerformAddeSubeCombine(SDNode *N,
12090 TargetLowering::DAGCombinerInfo &DCI,
12091 const ARMSubtarget *Subtarget) {
12092 if (Subtarget->isThumb1Only()) {
12093 SelectionDAG &DAG = DCI.DAG;
12094 SDValue RHS = N->getOperand(1);
12095 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12096 int64_t imm = C->getSExtValue();
12097 if (imm < 0) {
12098 SDLoc DL(N);
12099
12100 // The with-carry-in form matches bitwise not instead of the negation.
12101 // Effectively, the inverse interpretation of the carry flag already
12102 // accounts for part of the negation.
12103 RHS = DAG.getConstant(~imm, DL, MVT::i32);
12104
12105 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
12106 : ARMISD::ADDE;
12107 return DAG.getNode(Opcode, DL, N->getVTList(),
12108 N->getOperand(0), RHS, N->getOperand(2));
12109 }
12110 }
12111 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
12112 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
12113 }
12114 return SDValue();
12115 }
12116
PerformSELECTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12117 static SDValue PerformSELECTCombine(SDNode *N,
12118 TargetLowering::DAGCombinerInfo &DCI,
12119 const ARMSubtarget *Subtarget) {
12120 if (!Subtarget->hasMVEIntegerOps())
12121 return SDValue();
12122
12123 SDLoc dl(N);
12124 SDValue SetCC;
12125 SDValue LHS;
12126 SDValue RHS;
12127 ISD::CondCode CC;
12128 SDValue TrueVal;
12129 SDValue FalseVal;
12130
12131 if (N->getOpcode() == ISD::SELECT &&
12132 N->getOperand(0)->getOpcode() == ISD::SETCC) {
12133 SetCC = N->getOperand(0);
12134 LHS = SetCC->getOperand(0);
12135 RHS = SetCC->getOperand(1);
12136 CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
12137 TrueVal = N->getOperand(1);
12138 FalseVal = N->getOperand(2);
12139 } else if (N->getOpcode() == ISD::SELECT_CC) {
12140 LHS = N->getOperand(0);
12141 RHS = N->getOperand(1);
12142 CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
12143 TrueVal = N->getOperand(2);
12144 FalseVal = N->getOperand(3);
12145 } else {
12146 return SDValue();
12147 }
12148
12149 unsigned int Opcode = 0;
12150 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
12151 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
12152 (CC == ISD::SETULT || CC == ISD::SETUGT)) {
12153 Opcode = ARMISD::VMINVu;
12154 if (CC == ISD::SETUGT)
12155 std::swap(TrueVal, FalseVal);
12156 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
12157 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
12158 (CC == ISD::SETLT || CC == ISD::SETGT)) {
12159 Opcode = ARMISD::VMINVs;
12160 if (CC == ISD::SETGT)
12161 std::swap(TrueVal, FalseVal);
12162 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
12163 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
12164 (CC == ISD::SETUGT || CC == ISD::SETULT)) {
12165 Opcode = ARMISD::VMAXVu;
12166 if (CC == ISD::SETULT)
12167 std::swap(TrueVal, FalseVal);
12168 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
12169 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
12170 (CC == ISD::SETGT || CC == ISD::SETLT)) {
12171 Opcode = ARMISD::VMAXVs;
12172 if (CC == ISD::SETLT)
12173 std::swap(TrueVal, FalseVal);
12174 } else
12175 return SDValue();
12176
12177 // Normalise to the right hand side being the vector reduction
12178 switch (TrueVal->getOpcode()) {
12179 case ISD::VECREDUCE_UMIN:
12180 case ISD::VECREDUCE_SMIN:
12181 case ISD::VECREDUCE_UMAX:
12182 case ISD::VECREDUCE_SMAX:
12183 std::swap(LHS, RHS);
12184 std::swap(TrueVal, FalseVal);
12185 break;
12186 }
12187
12188 EVT VectorType = FalseVal->getOperand(0).getValueType();
12189
12190 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
12191 VectorType != MVT::v4i32)
12192 return SDValue();
12193
12194 EVT VectorScalarType = VectorType.getVectorElementType();
12195
12196 // The values being selected must also be the ones being compared
12197 if (TrueVal != LHS || FalseVal != RHS)
12198 return SDValue();
12199
12200 EVT LeftType = LHS->getValueType(0);
12201 EVT RightType = RHS->getValueType(0);
12202
12203 // The types must match the reduced type too
12204 if (LeftType != VectorScalarType || RightType != VectorScalarType)
12205 return SDValue();
12206
12207 // Legalise the scalar to an i32
12208 if (VectorScalarType != MVT::i32)
12209 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12210
12211 // Generate the reduction as an i32 for legalisation purposes
12212 auto Reduction =
12213 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
12214
12215 // The result isn't actually an i32 so truncate it back to its original type
12216 if (VectorScalarType != MVT::i32)
12217 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
12218
12219 return Reduction;
12220 }
12221
12222 // A special combine for the vqdmulh family of instructions. This is one of the
12223 // potential set of patterns that could patch this instruction. The base pattern
12224 // you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
12225 // This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
12226 // which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
12227 // the max is unnecessary.
PerformVQDMULHCombine(SDNode * N,SelectionDAG & DAG)12228 static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
12229 EVT VT = N->getValueType(0);
12230 SDValue Shft;
12231 ConstantSDNode *Clamp;
12232
12233 if (N->getOpcode() == ISD::SMIN) {
12234 Shft = N->getOperand(0);
12235 Clamp = isConstOrConstSplat(N->getOperand(1));
12236 } else if (N->getOpcode() == ISD::VSELECT) {
12237 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
12238 SDValue Cmp = N->getOperand(0);
12239 if (Cmp.getOpcode() != ISD::SETCC ||
12240 cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT ||
12241 Cmp.getOperand(0) != N->getOperand(1) ||
12242 Cmp.getOperand(1) != N->getOperand(2))
12243 return SDValue();
12244 Shft = N->getOperand(1);
12245 Clamp = isConstOrConstSplat(N->getOperand(2));
12246 } else
12247 return SDValue();
12248
12249 if (!Clamp)
12250 return SDValue();
12251
12252 MVT ScalarType;
12253 int ShftAmt = 0;
12254 switch (Clamp->getSExtValue()) {
12255 case (1 << 7) - 1:
12256 ScalarType = MVT::i8;
12257 ShftAmt = 7;
12258 break;
12259 case (1 << 15) - 1:
12260 ScalarType = MVT::i16;
12261 ShftAmt = 15;
12262 break;
12263 case (1ULL << 31) - 1:
12264 ScalarType = MVT::i32;
12265 ShftAmt = 31;
12266 break;
12267 default:
12268 return SDValue();
12269 }
12270
12271 if (Shft.getOpcode() != ISD::SRA)
12272 return SDValue();
12273 ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1));
12274 if (!N1 || N1->getSExtValue() != ShftAmt)
12275 return SDValue();
12276
12277 SDValue Mul = Shft.getOperand(0);
12278 if (Mul.getOpcode() != ISD::MUL)
12279 return SDValue();
12280
12281 SDValue Ext0 = Mul.getOperand(0);
12282 SDValue Ext1 = Mul.getOperand(1);
12283 if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
12284 Ext1.getOpcode() != ISD::SIGN_EXTEND)
12285 return SDValue();
12286 EVT VecVT = Ext0.getOperand(0).getValueType();
12287 if (VecVT != MVT::v4i32 && VecVT != MVT::v8i16 && VecVT != MVT::v16i8)
12288 return SDValue();
12289 if (Ext1.getOperand(0).getValueType() != VecVT ||
12290 VecVT.getScalarType() != ScalarType ||
12291 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
12292 return SDValue();
12293
12294 SDLoc DL(Mul);
12295 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, VecVT, Ext0.getOperand(0),
12296 Ext1.getOperand(0));
12297 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, VQDMULH);
12298 }
12299
PerformVSELECTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12300 static SDValue PerformVSELECTCombine(SDNode *N,
12301 TargetLowering::DAGCombinerInfo &DCI,
12302 const ARMSubtarget *Subtarget) {
12303 if (!Subtarget->hasMVEIntegerOps())
12304 return SDValue();
12305
12306 if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
12307 return V;
12308
12309 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
12310 //
12311 // We need to re-implement this optimization here as the implementation in the
12312 // Target-Independent DAGCombiner does not handle the kind of constant we make
12313 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
12314 // good reason, allowing truncation there would break other targets).
12315 //
12316 // Currently, this is only done for MVE, as it's the only target that benefits
12317 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
12318 if (N->getOperand(0).getOpcode() != ISD::XOR)
12319 return SDValue();
12320 SDValue XOR = N->getOperand(0);
12321
12322 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
12323 // It is important to check with truncation allowed as the BUILD_VECTORs we
12324 // generate in those situations will truncate their operands.
12325 ConstantSDNode *Const =
12326 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
12327 /*AllowTruncation*/ true);
12328 if (!Const || !Const->isOne())
12329 return SDValue();
12330
12331 // Rewrite into vselect(cond, rhs, lhs).
12332 SDValue Cond = XOR->getOperand(0);
12333 SDValue LHS = N->getOperand(1);
12334 SDValue RHS = N->getOperand(2);
12335 EVT Type = N->getValueType(0);
12336 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
12337 }
12338
PerformABSCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12339 static SDValue PerformABSCombine(SDNode *N,
12340 TargetLowering::DAGCombinerInfo &DCI,
12341 const ARMSubtarget *Subtarget) {
12342 SDValue res;
12343 SelectionDAG &DAG = DCI.DAG;
12344 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12345
12346 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
12347 return SDValue();
12348
12349 if (!TLI.expandABS(N, res, DAG))
12350 return SDValue();
12351
12352 return res;
12353 }
12354
12355 /// PerformADDECombine - Target-specific dag combine transform from
12356 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
12357 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
PerformADDECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12358 static SDValue PerformADDECombine(SDNode *N,
12359 TargetLowering::DAGCombinerInfo &DCI,
12360 const ARMSubtarget *Subtarget) {
12361 // Only ARM and Thumb2 support UMLAL/SMLAL.
12362 if (Subtarget->isThumb1Only())
12363 return PerformAddeSubeCombine(N, DCI, Subtarget);
12364
12365 // Only perform the checks after legalize when the pattern is available.
12366 if (DCI.isBeforeLegalize()) return SDValue();
12367
12368 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
12369 }
12370
12371 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
12372 /// operands N0 and N1. This is a helper for PerformADDCombine that is
12373 /// called with the default operands, and if that fails, with commuted
12374 /// operands.
PerformADDCombineWithOperands(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12375 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
12376 TargetLowering::DAGCombinerInfo &DCI,
12377 const ARMSubtarget *Subtarget){
12378 // Attempt to create vpadd for this add.
12379 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
12380 return Result;
12381
12382 // Attempt to create vpaddl for this add.
12383 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
12384 return Result;
12385 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
12386 Subtarget))
12387 return Result;
12388
12389 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12390 if (N0.getNode()->hasOneUse())
12391 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
12392 return Result;
12393 return SDValue();
12394 }
12395
PerformADDVecReduce(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12396 static SDValue PerformADDVecReduce(SDNode *N,
12397 TargetLowering::DAGCombinerInfo &DCI,
12398 const ARMSubtarget *Subtarget) {
12399 if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64)
12400 return SDValue();
12401
12402 SDValue N0 = N->getOperand(0);
12403 SDValue N1 = N->getOperand(1);
12404
12405 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
12406 // will look like:
12407 // t1: i32,i32 = ARMISD::VADDLVs x
12408 // t2: i64 = build_pair t1, t1:1
12409 // t3: i64 = add t2, y
12410 // We also need to check for sext / zext and commutitive adds.
12411 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
12412 SDValue NB) {
12413 if (NB->getOpcode() != ISD::BUILD_PAIR)
12414 return SDValue();
12415 SDValue VecRed = NB->getOperand(0);
12416 if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 ||
12417 NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
12418 return SDValue();
12419
12420 SDLoc dl(N);
12421 SmallVector<SDValue, 4> Ops;
12422 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
12423 DCI.DAG.getConstant(0, dl, MVT::i32)));
12424 Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
12425 DCI.DAG.getConstant(1, dl, MVT::i32)));
12426 for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++)
12427 Ops.push_back(VecRed->getOperand(i));
12428 SDValue Red = DCI.DAG.getNode(OpcodeA, dl,
12429 DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops);
12430 return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
12431 SDValue(Red.getNode(), 1));
12432 };
12433
12434 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
12435 return M;
12436 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
12437 return M;
12438 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
12439 return M;
12440 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
12441 return M;
12442 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
12443 return M;
12444 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
12445 return M;
12446 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
12447 return M;
12448 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
12449 return M;
12450 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
12451 return M;
12452 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
12453 return M;
12454 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
12455 return M;
12456 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
12457 return M;
12458 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
12459 return M;
12460 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
12461 return M;
12462 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
12463 return M;
12464 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
12465 return M;
12466 return SDValue();
12467 }
12468
12469 bool
isDesirableToCommuteWithShift(const SDNode * N,CombineLevel Level) const12470 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
12471 CombineLevel Level) const {
12472 if (Level == BeforeLegalizeTypes)
12473 return true;
12474
12475 if (N->getOpcode() != ISD::SHL)
12476 return true;
12477
12478 if (Subtarget->isThumb1Only()) {
12479 // Avoid making expensive immediates by commuting shifts. (This logic
12480 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
12481 // for free.)
12482 if (N->getOpcode() != ISD::SHL)
12483 return true;
12484 SDValue N1 = N->getOperand(0);
12485 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
12486 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
12487 return true;
12488 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
12489 if (Const->getAPIntValue().ult(256))
12490 return false;
12491 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
12492 Const->getAPIntValue().sgt(-256))
12493 return false;
12494 }
12495 return true;
12496 }
12497
12498 // Turn off commute-with-shift transform after legalization, so it doesn't
12499 // conflict with PerformSHLSimplify. (We could try to detect when
12500 // PerformSHLSimplify would trigger more precisely, but it isn't
12501 // really necessary.)
12502 return false;
12503 }
12504
shouldFoldConstantShiftPairToMask(const SDNode * N,CombineLevel Level) const12505 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
12506 const SDNode *N, CombineLevel Level) const {
12507 if (!Subtarget->isThumb1Only())
12508 return true;
12509
12510 if (Level == BeforeLegalizeTypes)
12511 return true;
12512
12513 return false;
12514 }
12515
preferIncOfAddToSubOfNot(EVT VT) const12516 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12517 if (!Subtarget->hasNEON()) {
12518 if (Subtarget->isThumb1Only())
12519 return VT.getScalarSizeInBits() <= 32;
12520 return true;
12521 }
12522 return VT.isScalarInteger();
12523 }
12524
PerformSHLSimplify(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * ST)12525 static SDValue PerformSHLSimplify(SDNode *N,
12526 TargetLowering::DAGCombinerInfo &DCI,
12527 const ARMSubtarget *ST) {
12528 // Allow the generic combiner to identify potential bswaps.
12529 if (DCI.isBeforeLegalize())
12530 return SDValue();
12531
12532 // DAG combiner will fold:
12533 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
12534 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
12535 // Other code patterns that can be also be modified have the following form:
12536 // b + ((a << 1) | 510)
12537 // b + ((a << 1) & 510)
12538 // b + ((a << 1) ^ 510)
12539 // b + ((a << 1) + 510)
12540
12541 // Many instructions can perform the shift for free, but it requires both
12542 // the operands to be registers. If c1 << c2 is too large, a mov immediate
12543 // instruction will needed. So, unfold back to the original pattern if:
12544 // - if c1 and c2 are small enough that they don't require mov imms.
12545 // - the user(s) of the node can perform an shl
12546
12547 // No shifted operands for 16-bit instructions.
12548 if (ST->isThumb() && ST->isThumb1Only())
12549 return SDValue();
12550
12551 // Check that all the users could perform the shl themselves.
12552 for (auto U : N->uses()) {
12553 switch(U->getOpcode()) {
12554 default:
12555 return SDValue();
12556 case ISD::SUB:
12557 case ISD::ADD:
12558 case ISD::AND:
12559 case ISD::OR:
12560 case ISD::XOR:
12561 case ISD::SETCC:
12562 case ARMISD::CMP:
12563 // Check that the user isn't already using a constant because there
12564 // aren't any instructions that support an immediate operand and a
12565 // shifted operand.
12566 if (isa<ConstantSDNode>(U->getOperand(0)) ||
12567 isa<ConstantSDNode>(U->getOperand(1)))
12568 return SDValue();
12569
12570 // Check that it's not already using a shift.
12571 if (U->getOperand(0).getOpcode() == ISD::SHL ||
12572 U->getOperand(1).getOpcode() == ISD::SHL)
12573 return SDValue();
12574 break;
12575 }
12576 }
12577
12578 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
12579 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
12580 return SDValue();
12581
12582 if (N->getOperand(0).getOpcode() != ISD::SHL)
12583 return SDValue();
12584
12585 SDValue SHL = N->getOperand(0);
12586
12587 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
12588 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
12589 if (!C1ShlC2 || !C2)
12590 return SDValue();
12591
12592 APInt C2Int = C2->getAPIntValue();
12593 APInt C1Int = C1ShlC2->getAPIntValue();
12594
12595 // Check that performing a lshr will not lose any information.
12596 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
12597 C2Int.getBitWidth() - C2->getZExtValue());
12598 if ((C1Int & Mask) != C1Int)
12599 return SDValue();
12600
12601 // Shift the first constant.
12602 C1Int.lshrInPlace(C2Int);
12603
12604 // The immediates are encoded as an 8-bit value that can be rotated.
12605 auto LargeImm = [](const APInt &Imm) {
12606 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
12607 return Imm.getBitWidth() - Zeros > 8;
12608 };
12609
12610 if (LargeImm(C1Int) || LargeImm(C2Int))
12611 return SDValue();
12612
12613 SelectionDAG &DAG = DCI.DAG;
12614 SDLoc dl(N);
12615 SDValue X = SHL.getOperand(0);
12616 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
12617 DAG.getConstant(C1Int, dl, MVT::i32));
12618 // Shift left to compensate for the lshr of C1Int.
12619 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
12620
12621 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
12622 SHL.dump(); N->dump());
12623 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
12624 return Res;
12625 }
12626
12627
12628 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
12629 ///
PerformADDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12630 static SDValue PerformADDCombine(SDNode *N,
12631 TargetLowering::DAGCombinerInfo &DCI,
12632 const ARMSubtarget *Subtarget) {
12633 SDValue N0 = N->getOperand(0);
12634 SDValue N1 = N->getOperand(1);
12635
12636 // Only works one way, because it needs an immediate operand.
12637 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12638 return Result;
12639
12640 if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget))
12641 return Result;
12642
12643 // First try with the default operand order.
12644 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
12645 return Result;
12646
12647 // If that didn't work, try again with the operands commuted.
12648 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
12649 }
12650
12651 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
12652 ///
PerformSUBCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12653 static SDValue PerformSUBCombine(SDNode *N,
12654 TargetLowering::DAGCombinerInfo &DCI,
12655 const ARMSubtarget *Subtarget) {
12656 SDValue N0 = N->getOperand(0);
12657 SDValue N1 = N->getOperand(1);
12658
12659 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12660 if (N1.getNode()->hasOneUse())
12661 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
12662 return Result;
12663
12664 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
12665 return SDValue();
12666
12667 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
12668 // so that we can readily pattern match more mve instructions which can use
12669 // a scalar operand.
12670 SDValue VDup = N->getOperand(1);
12671 if (VDup->getOpcode() != ARMISD::VDUP)
12672 return SDValue();
12673
12674 SDValue VMov = N->getOperand(0);
12675 if (VMov->getOpcode() == ISD::BITCAST)
12676 VMov = VMov->getOperand(0);
12677
12678 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
12679 return SDValue();
12680
12681 SDLoc dl(N);
12682 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
12683 DCI.DAG.getConstant(0, dl, MVT::i32),
12684 VDup->getOperand(0));
12685 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
12686 }
12687
12688 /// PerformVMULCombine
12689 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
12690 /// special multiplier accumulator forwarding.
12691 /// vmul d3, d0, d2
12692 /// vmla d3, d1, d2
12693 /// is faster than
12694 /// vadd d3, d0, d1
12695 /// vmul d3, d3, d2
12696 // However, for (A + B) * (A + B),
12697 // vadd d2, d0, d1
12698 // vmul d3, d0, d2
12699 // vmla d3, d1, d2
12700 // is slower than
12701 // vadd d2, d0, d1
12702 // vmul d3, d2, d2
PerformVMULCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12703 static SDValue PerformVMULCombine(SDNode *N,
12704 TargetLowering::DAGCombinerInfo &DCI,
12705 const ARMSubtarget *Subtarget) {
12706 if (!Subtarget->hasVMLxForwarding())
12707 return SDValue();
12708
12709 SelectionDAG &DAG = DCI.DAG;
12710 SDValue N0 = N->getOperand(0);
12711 SDValue N1 = N->getOperand(1);
12712 unsigned Opcode = N0.getOpcode();
12713 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12714 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
12715 Opcode = N1.getOpcode();
12716 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12717 Opcode != ISD::FADD && Opcode != ISD::FSUB)
12718 return SDValue();
12719 std::swap(N0, N1);
12720 }
12721
12722 if (N0 == N1)
12723 return SDValue();
12724
12725 EVT VT = N->getValueType(0);
12726 SDLoc DL(N);
12727 SDValue N00 = N0->getOperand(0);
12728 SDValue N01 = N0->getOperand(1);
12729 return DAG.getNode(Opcode, DL, VT,
12730 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
12731 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
12732 }
12733
PerformMVEVMULLCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)12734 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
12735 const ARMSubtarget *Subtarget) {
12736 EVT VT = N->getValueType(0);
12737 if (VT != MVT::v2i64)
12738 return SDValue();
12739
12740 SDValue N0 = N->getOperand(0);
12741 SDValue N1 = N->getOperand(1);
12742
12743 auto IsSignExt = [&](SDValue Op) {
12744 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
12745 return SDValue();
12746 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
12747 if (VT.getScalarSizeInBits() == 32)
12748 return Op->getOperand(0);
12749 return SDValue();
12750 };
12751 auto IsZeroExt = [&](SDValue Op) {
12752 // Zero extends are a little more awkward. At the point we are matching
12753 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
12754 // That might be before of after a bitcast depending on how the and is
12755 // placed. Because this has to look through bitcasts, it is currently only
12756 // supported on LE.
12757 if (!Subtarget->isLittle())
12758 return SDValue();
12759
12760 SDValue And = Op;
12761 if (And->getOpcode() == ISD::BITCAST)
12762 And = And->getOperand(0);
12763 if (And->getOpcode() != ISD::AND)
12764 return SDValue();
12765 SDValue Mask = And->getOperand(1);
12766 if (Mask->getOpcode() == ISD::BITCAST)
12767 Mask = Mask->getOperand(0);
12768
12769 if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
12770 Mask.getValueType() != MVT::v4i32)
12771 return SDValue();
12772 if (isAllOnesConstant(Mask->getOperand(0)) &&
12773 isNullConstant(Mask->getOperand(1)) &&
12774 isAllOnesConstant(Mask->getOperand(2)) &&
12775 isNullConstant(Mask->getOperand(3)))
12776 return And->getOperand(0);
12777 return SDValue();
12778 };
12779
12780 SDLoc dl(N);
12781 if (SDValue Op0 = IsSignExt(N0)) {
12782 if (SDValue Op1 = IsSignExt(N1)) {
12783 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12784 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12785 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
12786 }
12787 }
12788 if (SDValue Op0 = IsZeroExt(N0)) {
12789 if (SDValue Op1 = IsZeroExt(N1)) {
12790 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12791 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12792 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
12793 }
12794 }
12795
12796 return SDValue();
12797 }
12798
PerformMULCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12799 static SDValue PerformMULCombine(SDNode *N,
12800 TargetLowering::DAGCombinerInfo &DCI,
12801 const ARMSubtarget *Subtarget) {
12802 SelectionDAG &DAG = DCI.DAG;
12803
12804 EVT VT = N->getValueType(0);
12805 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
12806 return PerformMVEVMULLCombine(N, DAG, Subtarget);
12807
12808 if (Subtarget->isThumb1Only())
12809 return SDValue();
12810
12811 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12812 return SDValue();
12813
12814 if (VT.is64BitVector() || VT.is128BitVector())
12815 return PerformVMULCombine(N, DCI, Subtarget);
12816 if (VT != MVT::i32)
12817 return SDValue();
12818
12819 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12820 if (!C)
12821 return SDValue();
12822
12823 int64_t MulAmt = C->getSExtValue();
12824 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
12825
12826 ShiftAmt = ShiftAmt & (32 - 1);
12827 SDValue V = N->getOperand(0);
12828 SDLoc DL(N);
12829
12830 SDValue Res;
12831 MulAmt >>= ShiftAmt;
12832
12833 if (MulAmt >= 0) {
12834 if (isPowerOf2_32(MulAmt - 1)) {
12835 // (mul x, 2^N + 1) => (add (shl x, N), x)
12836 Res = DAG.getNode(ISD::ADD, DL, VT,
12837 V,
12838 DAG.getNode(ISD::SHL, DL, VT,
12839 V,
12840 DAG.getConstant(Log2_32(MulAmt - 1), DL,
12841 MVT::i32)));
12842 } else if (isPowerOf2_32(MulAmt + 1)) {
12843 // (mul x, 2^N - 1) => (sub (shl x, N), x)
12844 Res = DAG.getNode(ISD::SUB, DL, VT,
12845 DAG.getNode(ISD::SHL, DL, VT,
12846 V,
12847 DAG.getConstant(Log2_32(MulAmt + 1), DL,
12848 MVT::i32)),
12849 V);
12850 } else
12851 return SDValue();
12852 } else {
12853 uint64_t MulAmtAbs = -MulAmt;
12854 if (isPowerOf2_32(MulAmtAbs + 1)) {
12855 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
12856 Res = DAG.getNode(ISD::SUB, DL, VT,
12857 V,
12858 DAG.getNode(ISD::SHL, DL, VT,
12859 V,
12860 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
12861 MVT::i32)));
12862 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
12863 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
12864 Res = DAG.getNode(ISD::ADD, DL, VT,
12865 V,
12866 DAG.getNode(ISD::SHL, DL, VT,
12867 V,
12868 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
12869 MVT::i32)));
12870 Res = DAG.getNode(ISD::SUB, DL, VT,
12871 DAG.getConstant(0, DL, MVT::i32), Res);
12872 } else
12873 return SDValue();
12874 }
12875
12876 if (ShiftAmt != 0)
12877 Res = DAG.getNode(ISD::SHL, DL, VT,
12878 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
12879
12880 // Do not add new nodes to DAG combiner worklist.
12881 DCI.CombineTo(N, Res, false);
12882 return SDValue();
12883 }
12884
CombineANDShift(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12885 static SDValue CombineANDShift(SDNode *N,
12886 TargetLowering::DAGCombinerInfo &DCI,
12887 const ARMSubtarget *Subtarget) {
12888 // Allow DAGCombine to pattern-match before we touch the canonical form.
12889 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12890 return SDValue();
12891
12892 if (N->getValueType(0) != MVT::i32)
12893 return SDValue();
12894
12895 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12896 if (!N1C)
12897 return SDValue();
12898
12899 uint32_t C1 = (uint32_t)N1C->getZExtValue();
12900 // Don't transform uxtb/uxth.
12901 if (C1 == 255 || C1 == 65535)
12902 return SDValue();
12903
12904 SDNode *N0 = N->getOperand(0).getNode();
12905 if (!N0->hasOneUse())
12906 return SDValue();
12907
12908 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
12909 return SDValue();
12910
12911 bool LeftShift = N0->getOpcode() == ISD::SHL;
12912
12913 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12914 if (!N01C)
12915 return SDValue();
12916
12917 uint32_t C2 = (uint32_t)N01C->getZExtValue();
12918 if (!C2 || C2 >= 32)
12919 return SDValue();
12920
12921 // Clear irrelevant bits in the mask.
12922 if (LeftShift)
12923 C1 &= (-1U << C2);
12924 else
12925 C1 &= (-1U >> C2);
12926
12927 SelectionDAG &DAG = DCI.DAG;
12928 SDLoc DL(N);
12929
12930 // We have a pattern of the form "(and (shl x, c2) c1)" or
12931 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
12932 // transform to a pair of shifts, to save materializing c1.
12933
12934 // First pattern: right shift, then mask off leading bits.
12935 // FIXME: Use demanded bits?
12936 if (!LeftShift && isMask_32(C1)) {
12937 uint32_t C3 = countLeadingZeros(C1);
12938 if (C2 < C3) {
12939 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12940 DAG.getConstant(C3 - C2, DL, MVT::i32));
12941 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12942 DAG.getConstant(C3, DL, MVT::i32));
12943 }
12944 }
12945
12946 // First pattern, reversed: left shift, then mask off trailing bits.
12947 if (LeftShift && isMask_32(~C1)) {
12948 uint32_t C3 = countTrailingZeros(C1);
12949 if (C2 < C3) {
12950 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12951 DAG.getConstant(C3 - C2, DL, MVT::i32));
12952 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12953 DAG.getConstant(C3, DL, MVT::i32));
12954 }
12955 }
12956
12957 // Second pattern: left shift, then mask off leading bits.
12958 // FIXME: Use demanded bits?
12959 if (LeftShift && isShiftedMask_32(C1)) {
12960 uint32_t Trailing = countTrailingZeros(C1);
12961 uint32_t C3 = countLeadingZeros(C1);
12962 if (Trailing == C2 && C2 + C3 < 32) {
12963 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12964 DAG.getConstant(C2 + C3, DL, MVT::i32));
12965 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12966 DAG.getConstant(C3, DL, MVT::i32));
12967 }
12968 }
12969
12970 // Second pattern, reversed: right shift, then mask off trailing bits.
12971 // FIXME: Handle other patterns of known/demanded bits.
12972 if (!LeftShift && isShiftedMask_32(C1)) {
12973 uint32_t Leading = countLeadingZeros(C1);
12974 uint32_t C3 = countTrailingZeros(C1);
12975 if (Leading == C2 && C2 + C3 < 32) {
12976 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12977 DAG.getConstant(C2 + C3, DL, MVT::i32));
12978 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12979 DAG.getConstant(C3, DL, MVT::i32));
12980 }
12981 }
12982
12983 // FIXME: Transform "(and (shl x, c2) c1)" ->
12984 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
12985 // c1.
12986 return SDValue();
12987 }
12988
PerformANDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12989 static SDValue PerformANDCombine(SDNode *N,
12990 TargetLowering::DAGCombinerInfo &DCI,
12991 const ARMSubtarget *Subtarget) {
12992 // Attempt to use immediate-form VBIC
12993 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12994 SDLoc dl(N);
12995 EVT VT = N->getValueType(0);
12996 SelectionDAG &DAG = DCI.DAG;
12997
12998 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 ||
12999 VT == MVT::v8i1 || VT == MVT::v16i1)
13000 return SDValue();
13001
13002 APInt SplatBits, SplatUndef;
13003 unsigned SplatBitSize;
13004 bool HasAnyUndefs;
13005 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
13006 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
13007 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
13008 SplatBitSize == 64) {
13009 EVT VbicVT;
13010 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
13011 SplatUndef.getZExtValue(), SplatBitSize,
13012 DAG, dl, VbicVT, VT, OtherModImm);
13013 if (Val.getNode()) {
13014 SDValue Input =
13015 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
13016 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
13017 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
13018 }
13019 }
13020 }
13021
13022 if (!Subtarget->isThumb1Only()) {
13023 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
13024 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
13025 return Result;
13026
13027 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13028 return Result;
13029 }
13030
13031 if (Subtarget->isThumb1Only())
13032 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
13033 return Result;
13034
13035 return SDValue();
13036 }
13037
13038 // Try combining OR nodes to SMULWB, SMULWT.
PerformORCombineToSMULWBT(SDNode * OR,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13039 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
13040 TargetLowering::DAGCombinerInfo &DCI,
13041 const ARMSubtarget *Subtarget) {
13042 if (!Subtarget->hasV6Ops() ||
13043 (Subtarget->isThumb() &&
13044 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
13045 return SDValue();
13046
13047 SDValue SRL = OR->getOperand(0);
13048 SDValue SHL = OR->getOperand(1);
13049
13050 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
13051 SRL = OR->getOperand(1);
13052 SHL = OR->getOperand(0);
13053 }
13054 if (!isSRL16(SRL) || !isSHL16(SHL))
13055 return SDValue();
13056
13057 // The first operands to the shifts need to be the two results from the
13058 // same smul_lohi node.
13059 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
13060 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
13061 return SDValue();
13062
13063 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
13064 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
13065 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
13066 return SDValue();
13067
13068 // Now we have:
13069 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
13070 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
13071 // For SMUWB the 16-bit value will signed extended somehow.
13072 // For SMULWT only the SRA is required.
13073 // Check both sides of SMUL_LOHI
13074 SDValue OpS16 = SMULLOHI->getOperand(0);
13075 SDValue OpS32 = SMULLOHI->getOperand(1);
13076
13077 SelectionDAG &DAG = DCI.DAG;
13078 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
13079 OpS16 = OpS32;
13080 OpS32 = SMULLOHI->getOperand(0);
13081 }
13082
13083 SDLoc dl(OR);
13084 unsigned Opcode = 0;
13085 if (isS16(OpS16, DAG))
13086 Opcode = ARMISD::SMULWB;
13087 else if (isSRA16(OpS16)) {
13088 Opcode = ARMISD::SMULWT;
13089 OpS16 = OpS16->getOperand(0);
13090 }
13091 else
13092 return SDValue();
13093
13094 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
13095 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
13096 return SDValue(OR, 0);
13097 }
13098
PerformORCombineToBFI(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13099 static SDValue PerformORCombineToBFI(SDNode *N,
13100 TargetLowering::DAGCombinerInfo &DCI,
13101 const ARMSubtarget *Subtarget) {
13102 // BFI is only available on V6T2+
13103 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
13104 return SDValue();
13105
13106 EVT VT = N->getValueType(0);
13107 SDValue N0 = N->getOperand(0);
13108 SDValue N1 = N->getOperand(1);
13109 SelectionDAG &DAG = DCI.DAG;
13110 SDLoc DL(N);
13111 // 1) or (and A, mask), val => ARMbfi A, val, mask
13112 // iff (val & mask) == val
13113 //
13114 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
13115 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
13116 // && mask == ~mask2
13117 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
13118 // && ~mask == mask2
13119 // (i.e., copy a bitfield value into another bitfield of the same width)
13120
13121 if (VT != MVT::i32)
13122 return SDValue();
13123
13124 SDValue N00 = N0.getOperand(0);
13125
13126 // The value and the mask need to be constants so we can verify this is
13127 // actually a bitfield set. If the mask is 0xffff, we can do better
13128 // via a movt instruction, so don't use BFI in that case.
13129 SDValue MaskOp = N0.getOperand(1);
13130 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
13131 if (!MaskC)
13132 return SDValue();
13133 unsigned Mask = MaskC->getZExtValue();
13134 if (Mask == 0xffff)
13135 return SDValue();
13136 SDValue Res;
13137 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
13138 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13139 if (N1C) {
13140 unsigned Val = N1C->getZExtValue();
13141 if ((Val & ~Mask) != Val)
13142 return SDValue();
13143
13144 if (ARM::isBitFieldInvertedMask(Mask)) {
13145 Val >>= countTrailingZeros(~Mask);
13146
13147 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
13148 DAG.getConstant(Val, DL, MVT::i32),
13149 DAG.getConstant(Mask, DL, MVT::i32));
13150
13151 DCI.CombineTo(N, Res, false);
13152 // Return value from the original node to inform the combiner than N is
13153 // now dead.
13154 return SDValue(N, 0);
13155 }
13156 } else if (N1.getOpcode() == ISD::AND) {
13157 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
13158 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
13159 if (!N11C)
13160 return SDValue();
13161 unsigned Mask2 = N11C->getZExtValue();
13162
13163 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
13164 // as is to match.
13165 if (ARM::isBitFieldInvertedMask(Mask) &&
13166 (Mask == ~Mask2)) {
13167 // The pack halfword instruction works better for masks that fit it,
13168 // so use that when it's available.
13169 if (Subtarget->hasDSP() &&
13170 (Mask == 0xffff || Mask == 0xffff0000))
13171 return SDValue();
13172 // 2a
13173 unsigned amt = countTrailingZeros(Mask2);
13174 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
13175 DAG.getConstant(amt, DL, MVT::i32));
13176 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
13177 DAG.getConstant(Mask, DL, MVT::i32));
13178 DCI.CombineTo(N, Res, false);
13179 // Return value from the original node to inform the combiner than N is
13180 // now dead.
13181 return SDValue(N, 0);
13182 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
13183 (~Mask == Mask2)) {
13184 // The pack halfword instruction works better for masks that fit it,
13185 // so use that when it's available.
13186 if (Subtarget->hasDSP() &&
13187 (Mask2 == 0xffff || Mask2 == 0xffff0000))
13188 return SDValue();
13189 // 2b
13190 unsigned lsb = countTrailingZeros(Mask);
13191 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
13192 DAG.getConstant(lsb, DL, MVT::i32));
13193 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
13194 DAG.getConstant(Mask2, DL, MVT::i32));
13195 DCI.CombineTo(N, Res, false);
13196 // Return value from the original node to inform the combiner than N is
13197 // now dead.
13198 return SDValue(N, 0);
13199 }
13200 }
13201
13202 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
13203 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
13204 ARM::isBitFieldInvertedMask(~Mask)) {
13205 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
13206 // where lsb(mask) == #shamt and masked bits of B are known zero.
13207 SDValue ShAmt = N00.getOperand(1);
13208 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
13209 unsigned LSB = countTrailingZeros(Mask);
13210 if (ShAmtC != LSB)
13211 return SDValue();
13212
13213 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
13214 DAG.getConstant(~Mask, DL, MVT::i32));
13215
13216 DCI.CombineTo(N, Res, false);
13217 // Return value from the original node to inform the combiner than N is
13218 // now dead.
13219 return SDValue(N, 0);
13220 }
13221
13222 return SDValue();
13223 }
13224
isValidMVECond(unsigned CC,bool IsFloat)13225 static bool isValidMVECond(unsigned CC, bool IsFloat) {
13226 switch (CC) {
13227 case ARMCC::EQ:
13228 case ARMCC::NE:
13229 case ARMCC::LE:
13230 case ARMCC::GT:
13231 case ARMCC::GE:
13232 case ARMCC::LT:
13233 return true;
13234 case ARMCC::HS:
13235 case ARMCC::HI:
13236 return !IsFloat;
13237 default:
13238 return false;
13239 };
13240 }
13241
getVCMPCondCode(SDValue N)13242 static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
13243 if (N->getOpcode() == ARMISD::VCMP)
13244 return (ARMCC::CondCodes)N->getConstantOperandVal(2);
13245 else if (N->getOpcode() == ARMISD::VCMPZ)
13246 return (ARMCC::CondCodes)N->getConstantOperandVal(1);
13247 else
13248 llvm_unreachable("Not a VCMP/VCMPZ!");
13249 }
13250
CanInvertMVEVCMP(SDValue N)13251 static bool CanInvertMVEVCMP(SDValue N) {
13252 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
13253 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
13254 }
13255
PerformORCombine_i1(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13256 static SDValue PerformORCombine_i1(SDNode *N,
13257 TargetLowering::DAGCombinerInfo &DCI,
13258 const ARMSubtarget *Subtarget) {
13259 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
13260 // together with predicates
13261 EVT VT = N->getValueType(0);
13262 SDLoc DL(N);
13263 SDValue N0 = N->getOperand(0);
13264 SDValue N1 = N->getOperand(1);
13265
13266 auto IsFreelyInvertable = [&](SDValue V) {
13267 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
13268 return CanInvertMVEVCMP(V);
13269 return false;
13270 };
13271
13272 // At least one operand must be freely invertable.
13273 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
13274 return SDValue();
13275
13276 SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT);
13277 SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT);
13278 SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
13279 return DCI.DAG.getLogicalNOT(DL, And, VT);
13280 }
13281
13282 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
PerformORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13283 static SDValue PerformORCombine(SDNode *N,
13284 TargetLowering::DAGCombinerInfo &DCI,
13285 const ARMSubtarget *Subtarget) {
13286 // Attempt to use immediate-form VORR
13287 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
13288 SDLoc dl(N);
13289 EVT VT = N->getValueType(0);
13290 SelectionDAG &DAG = DCI.DAG;
13291
13292 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13293 return SDValue();
13294
13295 if (Subtarget->hasMVEIntegerOps() &&
13296 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
13297 return PerformORCombine_i1(N, DCI, Subtarget);
13298
13299 APInt SplatBits, SplatUndef;
13300 unsigned SplatBitSize;
13301 bool HasAnyUndefs;
13302 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
13303 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
13304 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
13305 SplatBitSize == 64) {
13306 EVT VorrVT;
13307 SDValue Val =
13308 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
13309 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
13310 if (Val.getNode()) {
13311 SDValue Input =
13312 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
13313 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
13314 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
13315 }
13316 }
13317 }
13318
13319 if (!Subtarget->isThumb1Only()) {
13320 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
13321 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
13322 return Result;
13323 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
13324 return Result;
13325 }
13326
13327 SDValue N0 = N->getOperand(0);
13328 SDValue N1 = N->getOperand(1);
13329
13330 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
13331 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
13332 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13333
13334 // The code below optimizes (or (and X, Y), Z).
13335 // The AND operand needs to have a single user to make these optimizations
13336 // profitable.
13337 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
13338 return SDValue();
13339
13340 APInt SplatUndef;
13341 unsigned SplatBitSize;
13342 bool HasAnyUndefs;
13343
13344 APInt SplatBits0, SplatBits1;
13345 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
13346 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
13347 // Ensure that the second operand of both ands are constants
13348 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
13349 HasAnyUndefs) && !HasAnyUndefs) {
13350 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
13351 HasAnyUndefs) && !HasAnyUndefs) {
13352 // Ensure that the bit width of the constants are the same and that
13353 // the splat arguments are logical inverses as per the pattern we
13354 // are trying to simplify.
13355 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
13356 SplatBits0 == ~SplatBits1) {
13357 // Canonicalize the vector type to make instruction selection
13358 // simpler.
13359 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
13360 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
13361 N0->getOperand(1),
13362 N0->getOperand(0),
13363 N1->getOperand(0));
13364 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13365 }
13366 }
13367 }
13368 }
13369
13370 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
13371 // reasonable.
13372 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
13373 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
13374 return Res;
13375 }
13376
13377 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13378 return Result;
13379
13380 return SDValue();
13381 }
13382
PerformXORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13383 static SDValue PerformXORCombine(SDNode *N,
13384 TargetLowering::DAGCombinerInfo &DCI,
13385 const ARMSubtarget *Subtarget) {
13386 EVT VT = N->getValueType(0);
13387 SelectionDAG &DAG = DCI.DAG;
13388
13389 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13390 return SDValue();
13391
13392 if (!Subtarget->isThumb1Only()) {
13393 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
13394 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
13395 return Result;
13396
13397 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13398 return Result;
13399 }
13400
13401 if (Subtarget->hasMVEIntegerOps()) {
13402 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
13403 SDValue N0 = N->getOperand(0);
13404 SDValue N1 = N->getOperand(1);
13405 const TargetLowering *TLI = Subtarget->getTargetLowering();
13406 if (TLI->isConstTrueVal(N1.getNode()) &&
13407 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
13408 if (CanInvertMVEVCMP(N0)) {
13409 SDLoc DL(N0);
13410 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
13411
13412 SmallVector<SDValue, 4> Ops;
13413 Ops.push_back(N0->getOperand(0));
13414 if (N0->getOpcode() == ARMISD::VCMP)
13415 Ops.push_back(N0->getOperand(1));
13416 Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32));
13417 return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
13418 }
13419 }
13420 }
13421
13422 return SDValue();
13423 }
13424
13425 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
13426 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
13427 // their position in "to" (Rd).
ParseBFI(SDNode * N,APInt & ToMask,APInt & FromMask)13428 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
13429 assert(N->getOpcode() == ARMISD::BFI);
13430
13431 SDValue From = N->getOperand(1);
13432 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
13433 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
13434
13435 // If the Base came from a SHR #C, we can deduce that it is really testing bit
13436 // #C in the base of the SHR.
13437 if (From->getOpcode() == ISD::SRL &&
13438 isa<ConstantSDNode>(From->getOperand(1))) {
13439 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
13440 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
13441 FromMask <<= Shift.getLimitedValue(31);
13442 From = From->getOperand(0);
13443 }
13444
13445 return From;
13446 }
13447
13448 // If A and B contain one contiguous set of bits, does A | B == A . B?
13449 //
13450 // Neither A nor B must be zero.
BitsProperlyConcatenate(const APInt & A,const APInt & B)13451 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
13452 unsigned LastActiveBitInA = A.countTrailingZeros();
13453 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
13454 return LastActiveBitInA - 1 == FirstActiveBitInB;
13455 }
13456
FindBFIToCombineWith(SDNode * N)13457 static SDValue FindBFIToCombineWith(SDNode *N) {
13458 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
13459 // if one exists.
13460 APInt ToMask, FromMask;
13461 SDValue From = ParseBFI(N, ToMask, FromMask);
13462 SDValue To = N->getOperand(0);
13463
13464 // Now check for a compatible BFI to merge with. We can pass through BFIs that
13465 // aren't compatible, but not if they set the same bit in their destination as
13466 // we do (or that of any BFI we're going to combine with).
13467 SDValue V = To;
13468 APInt CombinedToMask = ToMask;
13469 while (V.getOpcode() == ARMISD::BFI) {
13470 APInt NewToMask, NewFromMask;
13471 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
13472 if (NewFrom != From) {
13473 // This BFI has a different base. Keep going.
13474 CombinedToMask |= NewToMask;
13475 V = V.getOperand(0);
13476 continue;
13477 }
13478
13479 // Do the written bits conflict with any we've seen so far?
13480 if ((NewToMask & CombinedToMask).getBoolValue())
13481 // Conflicting bits - bail out because going further is unsafe.
13482 return SDValue();
13483
13484 // Are the new bits contiguous when combined with the old bits?
13485 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
13486 BitsProperlyConcatenate(FromMask, NewFromMask))
13487 return V;
13488 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
13489 BitsProperlyConcatenate(NewFromMask, FromMask))
13490 return V;
13491
13492 // We've seen a write to some bits, so track it.
13493 CombinedToMask |= NewToMask;
13494 // Keep going...
13495 V = V.getOperand(0);
13496 }
13497
13498 return SDValue();
13499 }
13500
PerformBFICombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13501 static SDValue PerformBFICombine(SDNode *N,
13502 TargetLowering::DAGCombinerInfo &DCI) {
13503 SDValue N1 = N->getOperand(1);
13504 if (N1.getOpcode() == ISD::AND) {
13505 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
13506 // the bits being cleared by the AND are not demanded by the BFI.
13507 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
13508 if (!N11C)
13509 return SDValue();
13510 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13511 unsigned LSB = countTrailingZeros(~InvMask);
13512 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
13513 assert(Width <
13514 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
13515 "undefined behavior");
13516 unsigned Mask = (1u << Width) - 1;
13517 unsigned Mask2 = N11C->getZExtValue();
13518 if ((Mask & (~Mask2)) == 0)
13519 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
13520 N->getOperand(0), N1.getOperand(0),
13521 N->getOperand(2));
13522 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
13523 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
13524 // Keep track of any consecutive bits set that all come from the same base
13525 // value. We can combine these together into a single BFI.
13526 SDValue CombineBFI = FindBFIToCombineWith(N);
13527 if (CombineBFI == SDValue())
13528 return SDValue();
13529
13530 // We've found a BFI.
13531 APInt ToMask1, FromMask1;
13532 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
13533
13534 APInt ToMask2, FromMask2;
13535 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
13536 assert(From1 == From2);
13537 (void)From2;
13538
13539 // First, unlink CombineBFI.
13540 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
13541 // Then create a new BFI, combining the two together.
13542 APInt NewFromMask = FromMask1 | FromMask2;
13543 APInt NewToMask = ToMask1 | ToMask2;
13544
13545 EVT VT = N->getValueType(0);
13546 SDLoc dl(N);
13547
13548 if (NewFromMask[0] == 0)
13549 From1 = DCI.DAG.getNode(
13550 ISD::SRL, dl, VT, From1,
13551 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
13552 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
13553 DCI.DAG.getConstant(~NewToMask, dl, VT));
13554 }
13555 return SDValue();
13556 }
13557
13558 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
13559 /// ARMISD::VMOVRRD.
PerformVMOVRRDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13560 static SDValue PerformVMOVRRDCombine(SDNode *N,
13561 TargetLowering::DAGCombinerInfo &DCI,
13562 const ARMSubtarget *Subtarget) {
13563 // vmovrrd(vmovdrr x, y) -> x,y
13564 SDValue InDouble = N->getOperand(0);
13565 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
13566 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
13567
13568 // vmovrrd(load f64) -> (load i32), (load i32)
13569 SDNode *InNode = InDouble.getNode();
13570 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
13571 InNode->getValueType(0) == MVT::f64 &&
13572 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
13573 !cast<LoadSDNode>(InNode)->isVolatile()) {
13574 // TODO: Should this be done for non-FrameIndex operands?
13575 LoadSDNode *LD = cast<LoadSDNode>(InNode);
13576
13577 SelectionDAG &DAG = DCI.DAG;
13578 SDLoc DL(LD);
13579 SDValue BasePtr = LD->getBasePtr();
13580 SDValue NewLD1 =
13581 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
13582 LD->getAlignment(), LD->getMemOperand()->getFlags());
13583
13584 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13585 DAG.getConstant(4, DL, MVT::i32));
13586
13587 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
13588 LD->getPointerInfo().getWithOffset(4),
13589 std::min(4U, LD->getAlignment()),
13590 LD->getMemOperand()->getFlags());
13591
13592 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
13593 if (DCI.DAG.getDataLayout().isBigEndian())
13594 std::swap (NewLD1, NewLD2);
13595 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
13596 return Result;
13597 }
13598
13599 return SDValue();
13600 }
13601
13602 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
13603 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
PerformVMOVDRRCombine(SDNode * N,SelectionDAG & DAG)13604 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
13605 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
13606 SDValue Op0 = N->getOperand(0);
13607 SDValue Op1 = N->getOperand(1);
13608 if (Op0.getOpcode() == ISD::BITCAST)
13609 Op0 = Op0.getOperand(0);
13610 if (Op1.getOpcode() == ISD::BITCAST)
13611 Op1 = Op1.getOperand(0);
13612 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
13613 Op0.getNode() == Op1.getNode() &&
13614 Op0.getResNo() == 0 && Op1.getResNo() == 1)
13615 return DAG.getNode(ISD::BITCAST, SDLoc(N),
13616 N->getValueType(0), Op0.getOperand(0));
13617 return SDValue();
13618 }
13619
PerformVMOVhrCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13620 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13621 SDValue Op0 = N->getOperand(0);
13622
13623 // VMOVhr (VMOVrh (X)) -> X
13624 if (Op0->getOpcode() == ARMISD::VMOVrh)
13625 return Op0->getOperand(0);
13626
13627 // FullFP16: half values are passed in S-registers, and we don't
13628 // need any of the bitcast and moves:
13629 //
13630 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
13631 // t5: i32 = bitcast t2
13632 // t18: f16 = ARMISD::VMOVhr t5
13633 if (Op0->getOpcode() == ISD::BITCAST) {
13634 SDValue Copy = Op0->getOperand(0);
13635 if (Copy.getValueType() == MVT::f32 &&
13636 Copy->getOpcode() == ISD::CopyFromReg) {
13637 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
13638 SDValue NewCopy =
13639 DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops);
13640 return NewCopy;
13641 }
13642 }
13643
13644 // fold (VMOVhr (load x)) -> (load (f16*)x)
13645 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
13646 if (LN0->hasOneUse() && LN0->isUnindexed() &&
13647 LN0->getMemoryVT() == MVT::i16) {
13648 SDValue Load =
13649 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
13650 LN0->getBasePtr(), LN0->getMemOperand());
13651 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13652 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
13653 return Load;
13654 }
13655 }
13656
13657 // Only the bottom 16 bits of the source register are used.
13658 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
13659 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
13660 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
13661 return SDValue(N, 0);
13662
13663 return SDValue();
13664 }
13665
PerformVMOVrhCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13666 static SDValue PerformVMOVrhCombine(SDNode *N,
13667 TargetLowering::DAGCombinerInfo &DCI) {
13668 SDValue N0 = N->getOperand(0);
13669 EVT VT = N->getValueType(0);
13670
13671 // fold (VMOVrh (fpconst x)) -> const x
13672 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) {
13673 APFloat V = C->getValueAPF();
13674 return DCI.DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
13675 }
13676
13677 // fold (VMOVrh (load x)) -> (zextload (i16*)x)
13678 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
13679 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13680
13681 SDValue Load =
13682 DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
13683 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
13684 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13685 DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
13686 return Load;
13687 }
13688
13689 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
13690 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
13691 isa<ConstantSDNode>(N0->getOperand(1)))
13692 return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
13693 N0->getOperand(1));
13694
13695 return SDValue();
13696 }
13697
13698 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
13699 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
13700 /// i64 vector to have f64 elements, since the value can then be loaded
13701 /// directly into a VFP register.
hasNormalLoadOperand(SDNode * N)13702 static bool hasNormalLoadOperand(SDNode *N) {
13703 unsigned NumElts = N->getValueType(0).getVectorNumElements();
13704 for (unsigned i = 0; i < NumElts; ++i) {
13705 SDNode *Elt = N->getOperand(i).getNode();
13706 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
13707 return true;
13708 }
13709 return false;
13710 }
13711
13712 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
13713 /// ISD::BUILD_VECTOR.
PerformBUILD_VECTORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13714 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
13715 TargetLowering::DAGCombinerInfo &DCI,
13716 const ARMSubtarget *Subtarget) {
13717 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
13718 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
13719 // into a pair of GPRs, which is fine when the value is used as a scalar,
13720 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
13721 SelectionDAG &DAG = DCI.DAG;
13722 if (N->getNumOperands() == 2)
13723 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
13724 return RV;
13725
13726 // Load i64 elements as f64 values so that type legalization does not split
13727 // them up into i32 values.
13728 EVT VT = N->getValueType(0);
13729 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
13730 return SDValue();
13731 SDLoc dl(N);
13732 SmallVector<SDValue, 8> Ops;
13733 unsigned NumElts = VT.getVectorNumElements();
13734 for (unsigned i = 0; i < NumElts; ++i) {
13735 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
13736 Ops.push_back(V);
13737 // Make the DAGCombiner fold the bitcast.
13738 DCI.AddToWorklist(V.getNode());
13739 }
13740 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
13741 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
13742 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
13743 }
13744
13745 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
13746 static SDValue
PerformARMBUILD_VECTORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13747 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13748 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
13749 // At that time, we may have inserted bitcasts from integer to float.
13750 // If these bitcasts have survived DAGCombine, change the lowering of this
13751 // BUILD_VECTOR in something more vector friendly, i.e., that does not
13752 // force to use floating point types.
13753
13754 // Make sure we can change the type of the vector.
13755 // This is possible iff:
13756 // 1. The vector is only used in a bitcast to a integer type. I.e.,
13757 // 1.1. Vector is used only once.
13758 // 1.2. Use is a bit convert to an integer type.
13759 // 2. The size of its operands are 32-bits (64-bits are not legal).
13760 EVT VT = N->getValueType(0);
13761 EVT EltVT = VT.getVectorElementType();
13762
13763 // Check 1.1. and 2.
13764 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
13765 return SDValue();
13766
13767 // By construction, the input type must be float.
13768 assert(EltVT == MVT::f32 && "Unexpected type!");
13769
13770 // Check 1.2.
13771 SDNode *Use = *N->use_begin();
13772 if (Use->getOpcode() != ISD::BITCAST ||
13773 Use->getValueType(0).isFloatingPoint())
13774 return SDValue();
13775
13776 // Check profitability.
13777 // Model is, if more than half of the relevant operands are bitcast from
13778 // i32, turn the build_vector into a sequence of insert_vector_elt.
13779 // Relevant operands are everything that is not statically
13780 // (i.e., at compile time) bitcasted.
13781 unsigned NumOfBitCastedElts = 0;
13782 unsigned NumElts = VT.getVectorNumElements();
13783 unsigned NumOfRelevantElts = NumElts;
13784 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
13785 SDValue Elt = N->getOperand(Idx);
13786 if (Elt->getOpcode() == ISD::BITCAST) {
13787 // Assume only bit cast to i32 will go away.
13788 if (Elt->getOperand(0).getValueType() == MVT::i32)
13789 ++NumOfBitCastedElts;
13790 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
13791 // Constants are statically casted, thus do not count them as
13792 // relevant operands.
13793 --NumOfRelevantElts;
13794 }
13795
13796 // Check if more than half of the elements require a non-free bitcast.
13797 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
13798 return SDValue();
13799
13800 SelectionDAG &DAG = DCI.DAG;
13801 // Create the new vector type.
13802 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
13803 // Check if the type is legal.
13804 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13805 if (!TLI.isTypeLegal(VecVT))
13806 return SDValue();
13807
13808 // Combine:
13809 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
13810 // => BITCAST INSERT_VECTOR_ELT
13811 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
13812 // (BITCAST EN), N.
13813 SDValue Vec = DAG.getUNDEF(VecVT);
13814 SDLoc dl(N);
13815 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
13816 SDValue V = N->getOperand(Idx);
13817 if (V.isUndef())
13818 continue;
13819 if (V.getOpcode() == ISD::BITCAST &&
13820 V->getOperand(0).getValueType() == MVT::i32)
13821 // Fold obvious case.
13822 V = V.getOperand(0);
13823 else {
13824 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
13825 // Make the DAGCombiner fold the bitcasts.
13826 DCI.AddToWorklist(V.getNode());
13827 }
13828 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
13829 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
13830 }
13831 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
13832 // Make the DAGCombiner fold the bitcasts.
13833 DCI.AddToWorklist(Vec.getNode());
13834 return Vec;
13835 }
13836
13837 static SDValue
PerformPREDICATE_CASTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13838 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13839 EVT VT = N->getValueType(0);
13840 SDValue Op = N->getOperand(0);
13841 SDLoc dl(N);
13842
13843 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
13844 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
13845 // If the valuetypes are the same, we can remove the cast entirely.
13846 if (Op->getOperand(0).getValueType() == VT)
13847 return Op->getOperand(0);
13848 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
13849 }
13850
13851 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
13852 // more VPNOT which might get folded as else predicates.
13853 if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
13854 SDValue X =
13855 DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
13856 SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
13857 DCI.DAG.getConstant(65535, dl, MVT::i32));
13858 return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
13859 }
13860
13861 // Only the bottom 16 bits of the source register are used.
13862 if (Op.getValueType() == MVT::i32) {
13863 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
13864 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
13865 if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
13866 return SDValue(N, 0);
13867 }
13868 return SDValue();
13869 }
13870
13871 static SDValue
PerformVECTOR_REG_CASTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * ST)13872 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13873 const ARMSubtarget *ST) {
13874 EVT VT = N->getValueType(0);
13875 SDValue Op = N->getOperand(0);
13876 SDLoc dl(N);
13877
13878 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
13879 if (ST->isLittle())
13880 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op);
13881
13882 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
13883 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
13884 // If the valuetypes are the same, we can remove the cast entirely.
13885 if (Op->getOperand(0).getValueType() == VT)
13886 return Op->getOperand(0);
13887 return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
13888 }
13889
13890 return SDValue();
13891 }
13892
PerformVCMPCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13893 static SDValue PerformVCMPCombine(SDNode *N,
13894 TargetLowering::DAGCombinerInfo &DCI,
13895 const ARMSubtarget *Subtarget) {
13896 if (!Subtarget->hasMVEIntegerOps())
13897 return SDValue();
13898
13899 EVT VT = N->getValueType(0);
13900 SDValue Op0 = N->getOperand(0);
13901 SDValue Op1 = N->getOperand(1);
13902 ARMCC::CondCodes Cond =
13903 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13904 SDLoc dl(N);
13905
13906 // vcmp X, 0, cc -> vcmpz X, cc
13907 if (isZeroVector(Op1))
13908 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0,
13909 N->getOperand(2));
13910
13911 unsigned SwappedCond = getSwappedCondition(Cond);
13912 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
13913 // vcmp 0, X, cc -> vcmpz X, reversed(cc)
13914 if (isZeroVector(Op0))
13915 return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
13916 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13917 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
13918 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
13919 return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
13920 DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13921 }
13922
13923 return SDValue();
13924 }
13925
13926 /// PerformInsertEltCombine - Target-specific dag combine xforms for
13927 /// ISD::INSERT_VECTOR_ELT.
PerformInsertEltCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13928 static SDValue PerformInsertEltCombine(SDNode *N,
13929 TargetLowering::DAGCombinerInfo &DCI) {
13930 // Bitcast an i64 load inserted into a vector to f64.
13931 // Otherwise, the i64 value will be legalized to a pair of i32 values.
13932 EVT VT = N->getValueType(0);
13933 SDNode *Elt = N->getOperand(1).getNode();
13934 if (VT.getVectorElementType() != MVT::i64 ||
13935 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
13936 return SDValue();
13937
13938 SelectionDAG &DAG = DCI.DAG;
13939 SDLoc dl(N);
13940 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13941 VT.getVectorNumElements());
13942 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
13943 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
13944 // Make the DAGCombiner fold the bitcasts.
13945 DCI.AddToWorklist(Vec.getNode());
13946 DCI.AddToWorklist(V.getNode());
13947 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
13948 Vec, V, N->getOperand(2));
13949 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
13950 }
13951
PerformExtractEltCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)13952 static SDValue PerformExtractEltCombine(SDNode *N,
13953 TargetLowering::DAGCombinerInfo &DCI) {
13954 SDValue Op0 = N->getOperand(0);
13955 EVT VT = N->getValueType(0);
13956 SDLoc dl(N);
13957
13958 // extract (vdup x) -> x
13959 if (Op0->getOpcode() == ARMISD::VDUP) {
13960 SDValue X = Op0->getOperand(0);
13961 if (VT == MVT::f16 && X.getValueType() == MVT::i32)
13962 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
13963 if (VT == MVT::i32 && X.getValueType() == MVT::f16)
13964 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
13965
13966 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
13967 X = X->getOperand(0);
13968 if (X.getValueType() == VT)
13969 return X;
13970 }
13971
13972 return SDValue();
13973 }
13974
13975 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
13976 /// ISD::VECTOR_SHUFFLE.
PerformVECTOR_SHUFFLECombine(SDNode * N,SelectionDAG & DAG)13977 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
13978 // The LLVM shufflevector instruction does not require the shuffle mask
13979 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
13980 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
13981 // operands do not match the mask length, they are extended by concatenating
13982 // them with undef vectors. That is probably the right thing for other
13983 // targets, but for NEON it is better to concatenate two double-register
13984 // size vector operands into a single quad-register size vector. Do that
13985 // transformation here:
13986 // shuffle(concat(v1, undef), concat(v2, undef)) ->
13987 // shuffle(concat(v1, v2), undef)
13988 SDValue Op0 = N->getOperand(0);
13989 SDValue Op1 = N->getOperand(1);
13990 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
13991 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
13992 Op0.getNumOperands() != 2 ||
13993 Op1.getNumOperands() != 2)
13994 return SDValue();
13995 SDValue Concat0Op1 = Op0.getOperand(1);
13996 SDValue Concat1Op1 = Op1.getOperand(1);
13997 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
13998 return SDValue();
13999 // Skip the transformation if any of the types are illegal.
14000 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14001 EVT VT = N->getValueType(0);
14002 if (!TLI.isTypeLegal(VT) ||
14003 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
14004 !TLI.isTypeLegal(Concat1Op1.getValueType()))
14005 return SDValue();
14006
14007 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
14008 Op0.getOperand(0), Op1.getOperand(0));
14009 // Translate the shuffle mask.
14010 SmallVector<int, 16> NewMask;
14011 unsigned NumElts = VT.getVectorNumElements();
14012 unsigned HalfElts = NumElts/2;
14013 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14014 for (unsigned n = 0; n < NumElts; ++n) {
14015 int MaskElt = SVN->getMaskElt(n);
14016 int NewElt = -1;
14017 if (MaskElt < (int)HalfElts)
14018 NewElt = MaskElt;
14019 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
14020 NewElt = HalfElts + MaskElt - NumElts;
14021 NewMask.push_back(NewElt);
14022 }
14023 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
14024 DAG.getUNDEF(VT), NewMask);
14025 }
14026
14027 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
14028 /// NEON load/store intrinsics, and generic vector load/stores, to merge
14029 /// base address updates.
14030 /// For generic load/stores, the memory type is assumed to be a vector.
14031 /// The caller is assumed to have checked legality.
CombineBaseUpdate(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)14032 static SDValue CombineBaseUpdate(SDNode *N,
14033 TargetLowering::DAGCombinerInfo &DCI) {
14034 SelectionDAG &DAG = DCI.DAG;
14035 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
14036 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
14037 const bool isStore = N->getOpcode() == ISD::STORE;
14038 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
14039 SDValue Addr = N->getOperand(AddrOpIdx);
14040 MemSDNode *MemN = cast<MemSDNode>(N);
14041 SDLoc dl(N);
14042
14043 // Search for a use of the address operand that is an increment.
14044 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
14045 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
14046 SDNode *User = *UI;
14047 if (User->getOpcode() != ISD::ADD ||
14048 UI.getUse().getResNo() != Addr.getResNo())
14049 continue;
14050
14051 // Check that the add is independent of the load/store. Otherwise, folding
14052 // it would create a cycle. We can avoid searching through Addr as it's a
14053 // predecessor to both.
14054 SmallPtrSet<const SDNode *, 32> Visited;
14055 SmallVector<const SDNode *, 16> Worklist;
14056 Visited.insert(Addr.getNode());
14057 Worklist.push_back(N);
14058 Worklist.push_back(User);
14059 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
14060 SDNode::hasPredecessorHelper(User, Visited, Worklist))
14061 continue;
14062
14063 // Find the new opcode for the updating load/store.
14064 bool isLoadOp = true;
14065 bool isLaneOp = false;
14066 unsigned NewOpc = 0;
14067 unsigned NumVecs = 0;
14068 if (isIntrinsic) {
14069 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14070 switch (IntNo) {
14071 default: llvm_unreachable("unexpected intrinsic for Neon base update");
14072 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
14073 NumVecs = 1; break;
14074 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
14075 NumVecs = 2; break;
14076 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
14077 NumVecs = 3; break;
14078 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
14079 NumVecs = 4; break;
14080 case Intrinsic::arm_neon_vld1x2:
14081 case Intrinsic::arm_neon_vld1x3:
14082 case Intrinsic::arm_neon_vld1x4:
14083 case Intrinsic::arm_neon_vld2dup:
14084 case Intrinsic::arm_neon_vld3dup:
14085 case Intrinsic::arm_neon_vld4dup:
14086 // TODO: Support updating VLD1x and VLDxDUP nodes. For now, we just skip
14087 // combining base updates for such intrinsics.
14088 continue;
14089 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
14090 NumVecs = 2; isLaneOp = true; break;
14091 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
14092 NumVecs = 3; isLaneOp = true; break;
14093 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
14094 NumVecs = 4; isLaneOp = true; break;
14095 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
14096 NumVecs = 1; isLoadOp = false; break;
14097 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
14098 NumVecs = 2; isLoadOp = false; break;
14099 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
14100 NumVecs = 3; isLoadOp = false; break;
14101 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
14102 NumVecs = 4; isLoadOp = false; break;
14103 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
14104 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
14105 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
14106 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
14107 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
14108 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
14109 }
14110 } else {
14111 isLaneOp = true;
14112 switch (N->getOpcode()) {
14113 default: llvm_unreachable("unexpected opcode for Neon base update");
14114 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
14115 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
14116 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
14117 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
14118 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
14119 NumVecs = 1; isLaneOp = false; break;
14120 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
14121 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
14122 }
14123 }
14124
14125 // Find the size of memory referenced by the load/store.
14126 EVT VecTy;
14127 if (isLoadOp) {
14128 VecTy = N->getValueType(0);
14129 } else if (isIntrinsic) {
14130 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
14131 } else {
14132 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
14133 VecTy = N->getOperand(1).getValueType();
14134 }
14135
14136 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
14137 if (isLaneOp)
14138 NumBytes /= VecTy.getVectorNumElements();
14139
14140 // If the increment is a constant, it must match the memory ref size.
14141 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
14142 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
14143 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
14144 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
14145 // separate instructions that make it harder to use a non-constant update.
14146 continue;
14147 }
14148
14149 // OK, we found an ADD we can fold into the base update.
14150 // Now, create a _UPD node, taking care of not breaking alignment.
14151
14152 EVT AlignedVecTy = VecTy;
14153 unsigned Alignment = MemN->getAlignment();
14154
14155 // If this is a less-than-standard-aligned load/store, change the type to
14156 // match the standard alignment.
14157 // The alignment is overlooked when selecting _UPD variants; and it's
14158 // easier to introduce bitcasts here than fix that.
14159 // There are 3 ways to get to this base-update combine:
14160 // - intrinsics: they are assumed to be properly aligned (to the standard
14161 // alignment of the memory type), so we don't need to do anything.
14162 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
14163 // intrinsics, so, likewise, there's nothing to do.
14164 // - generic load/store instructions: the alignment is specified as an
14165 // explicit operand, rather than implicitly as the standard alignment
14166 // of the memory type (like the intrisics). We need to change the
14167 // memory type to match the explicit alignment. That way, we don't
14168 // generate non-standard-aligned ARMISD::VLDx nodes.
14169 if (isa<LSBaseSDNode>(N)) {
14170 if (Alignment == 0)
14171 Alignment = 1;
14172 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
14173 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
14174 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
14175 assert(!isLaneOp && "Unexpected generic load/store lane.");
14176 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
14177 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
14178 }
14179 // Don't set an explicit alignment on regular load/stores that we want
14180 // to transform to VLD/VST 1_UPD nodes.
14181 // This matches the behavior of regular load/stores, which only get an
14182 // explicit alignment if the MMO alignment is larger than the standard
14183 // alignment of the memory type.
14184 // Intrinsics, however, always get an explicit alignment, set to the
14185 // alignment of the MMO.
14186 Alignment = 1;
14187 }
14188
14189 // Create the new updating load/store node.
14190 // First, create an SDVTList for the new updating node's results.
14191 EVT Tys[6];
14192 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
14193 unsigned n;
14194 for (n = 0; n < NumResultVecs; ++n)
14195 Tys[n] = AlignedVecTy;
14196 Tys[n++] = MVT::i32;
14197 Tys[n] = MVT::Other;
14198 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
14199
14200 // Then, gather the new node's operands.
14201 SmallVector<SDValue, 8> Ops;
14202 Ops.push_back(N->getOperand(0)); // incoming chain
14203 Ops.push_back(N->getOperand(AddrOpIdx));
14204 Ops.push_back(Inc);
14205
14206 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
14207 // Try to match the intrinsic's signature
14208 Ops.push_back(StN->getValue());
14209 } else {
14210 // Loads (and of course intrinsics) match the intrinsics' signature,
14211 // so just add all but the alignment operand.
14212 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
14213 Ops.push_back(N->getOperand(i));
14214 }
14215
14216 // For all node types, the alignment operand is always the last one.
14217 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
14218
14219 // If this is a non-standard-aligned STORE, the penultimate operand is the
14220 // stored value. Bitcast it to the aligned type.
14221 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
14222 SDValue &StVal = Ops[Ops.size()-2];
14223 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
14224 }
14225
14226 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
14227 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
14228 MemN->getMemOperand());
14229
14230 // Update the uses.
14231 SmallVector<SDValue, 5> NewResults;
14232 for (unsigned i = 0; i < NumResultVecs; ++i)
14233 NewResults.push_back(SDValue(UpdN.getNode(), i));
14234
14235 // If this is an non-standard-aligned LOAD, the first result is the loaded
14236 // value. Bitcast it to the expected result type.
14237 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
14238 SDValue &LdVal = NewResults[0];
14239 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
14240 }
14241
14242 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
14243 DCI.CombineTo(N, NewResults);
14244 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
14245
14246 break;
14247 }
14248 return SDValue();
14249 }
14250
PerformVLDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)14251 static SDValue PerformVLDCombine(SDNode *N,
14252 TargetLowering::DAGCombinerInfo &DCI) {
14253 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14254 return SDValue();
14255
14256 return CombineBaseUpdate(N, DCI);
14257 }
14258
PerformMVEVLDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)14259 static SDValue PerformMVEVLDCombine(SDNode *N,
14260 TargetLowering::DAGCombinerInfo &DCI) {
14261 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14262 return SDValue();
14263
14264 SelectionDAG &DAG = DCI.DAG;
14265 SDValue Addr = N->getOperand(2);
14266 MemSDNode *MemN = cast<MemSDNode>(N);
14267 SDLoc dl(N);
14268
14269 // For the stores, where there are multiple intrinsics we only actually want
14270 // to post-inc the last of the them.
14271 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14272 if (IntNo == Intrinsic::arm_mve_vst2q &&
14273 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
14274 return SDValue();
14275 if (IntNo == Intrinsic::arm_mve_vst4q &&
14276 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
14277 return SDValue();
14278
14279 // Search for a use of the address operand that is an increment.
14280 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
14281 UE = Addr.getNode()->use_end();
14282 UI != UE; ++UI) {
14283 SDNode *User = *UI;
14284 if (User->getOpcode() != ISD::ADD ||
14285 UI.getUse().getResNo() != Addr.getResNo())
14286 continue;
14287
14288 // Check that the add is independent of the load/store. Otherwise, folding
14289 // it would create a cycle. We can avoid searching through Addr as it's a
14290 // predecessor to both.
14291 SmallPtrSet<const SDNode *, 32> Visited;
14292 SmallVector<const SDNode *, 16> Worklist;
14293 Visited.insert(Addr.getNode());
14294 Worklist.push_back(N);
14295 Worklist.push_back(User);
14296 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
14297 SDNode::hasPredecessorHelper(User, Visited, Worklist))
14298 continue;
14299
14300 // Find the new opcode for the updating load/store.
14301 bool isLoadOp = true;
14302 unsigned NewOpc = 0;
14303 unsigned NumVecs = 0;
14304 switch (IntNo) {
14305 default:
14306 llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
14307 case Intrinsic::arm_mve_vld2q:
14308 NewOpc = ARMISD::VLD2_UPD;
14309 NumVecs = 2;
14310 break;
14311 case Intrinsic::arm_mve_vld4q:
14312 NewOpc = ARMISD::VLD4_UPD;
14313 NumVecs = 4;
14314 break;
14315 case Intrinsic::arm_mve_vst2q:
14316 NewOpc = ARMISD::VST2_UPD;
14317 NumVecs = 2;
14318 isLoadOp = false;
14319 break;
14320 case Intrinsic::arm_mve_vst4q:
14321 NewOpc = ARMISD::VST4_UPD;
14322 NumVecs = 4;
14323 isLoadOp = false;
14324 break;
14325 }
14326
14327 // Find the size of memory referenced by the load/store.
14328 EVT VecTy;
14329 if (isLoadOp) {
14330 VecTy = N->getValueType(0);
14331 } else {
14332 VecTy = N->getOperand(3).getValueType();
14333 }
14334
14335 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
14336
14337 // If the increment is a constant, it must match the memory ref size.
14338 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
14339 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
14340 if (!CInc || CInc->getZExtValue() != NumBytes)
14341 continue;
14342
14343 // Create the new updating load/store node.
14344 // First, create an SDVTList for the new updating node's results.
14345 EVT Tys[6];
14346 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
14347 unsigned n;
14348 for (n = 0; n < NumResultVecs; ++n)
14349 Tys[n] = VecTy;
14350 Tys[n++] = MVT::i32;
14351 Tys[n] = MVT::Other;
14352 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
14353
14354 // Then, gather the new node's operands.
14355 SmallVector<SDValue, 8> Ops;
14356 Ops.push_back(N->getOperand(0)); // incoming chain
14357 Ops.push_back(N->getOperand(2)); // ptr
14358 Ops.push_back(Inc);
14359
14360 for (unsigned i = 3; i < N->getNumOperands(); ++i)
14361 Ops.push_back(N->getOperand(i));
14362
14363 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
14364 MemN->getMemOperand());
14365
14366 // Update the uses.
14367 SmallVector<SDValue, 5> NewResults;
14368 for (unsigned i = 0; i < NumResultVecs; ++i)
14369 NewResults.push_back(SDValue(UpdN.getNode(), i));
14370
14371 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
14372 DCI.CombineTo(N, NewResults);
14373 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
14374
14375 break;
14376 }
14377
14378 return SDValue();
14379 }
14380
14381 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
14382 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
14383 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
14384 /// return true.
CombineVLDDUP(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)14385 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14386 SelectionDAG &DAG = DCI.DAG;
14387 EVT VT = N->getValueType(0);
14388 // vldN-dup instructions only support 64-bit vectors for N > 1.
14389 if (!VT.is64BitVector())
14390 return false;
14391
14392 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
14393 SDNode *VLD = N->getOperand(0).getNode();
14394 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
14395 return false;
14396 unsigned NumVecs = 0;
14397 unsigned NewOpc = 0;
14398 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
14399 if (IntNo == Intrinsic::arm_neon_vld2lane) {
14400 NumVecs = 2;
14401 NewOpc = ARMISD::VLD2DUP;
14402 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
14403 NumVecs = 3;
14404 NewOpc = ARMISD::VLD3DUP;
14405 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
14406 NumVecs = 4;
14407 NewOpc = ARMISD::VLD4DUP;
14408 } else {
14409 return false;
14410 }
14411
14412 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
14413 // numbers match the load.
14414 unsigned VLDLaneNo =
14415 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
14416 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
14417 UI != UE; ++UI) {
14418 // Ignore uses of the chain result.
14419 if (UI.getUse().getResNo() == NumVecs)
14420 continue;
14421 SDNode *User = *UI;
14422 if (User->getOpcode() != ARMISD::VDUPLANE ||
14423 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
14424 return false;
14425 }
14426
14427 // Create the vldN-dup node.
14428 EVT Tys[5];
14429 unsigned n;
14430 for (n = 0; n < NumVecs; ++n)
14431 Tys[n] = VT;
14432 Tys[n] = MVT::Other;
14433 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
14434 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
14435 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
14436 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
14437 Ops, VLDMemInt->getMemoryVT(),
14438 VLDMemInt->getMemOperand());
14439
14440 // Update the uses.
14441 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
14442 UI != UE; ++UI) {
14443 unsigned ResNo = UI.getUse().getResNo();
14444 // Ignore uses of the chain result.
14445 if (ResNo == NumVecs)
14446 continue;
14447 SDNode *User = *UI;
14448 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
14449 }
14450
14451 // Now the vldN-lane intrinsic is dead except for its chain result.
14452 // Update uses of the chain.
14453 std::vector<SDValue> VLDDupResults;
14454 for (unsigned n = 0; n < NumVecs; ++n)
14455 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
14456 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
14457 DCI.CombineTo(VLD, VLDDupResults);
14458
14459 return true;
14460 }
14461
14462 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
14463 /// ARMISD::VDUPLANE.
PerformVDUPLANECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14464 static SDValue PerformVDUPLANECombine(SDNode *N,
14465 TargetLowering::DAGCombinerInfo &DCI,
14466 const ARMSubtarget *Subtarget) {
14467 SDValue Op = N->getOperand(0);
14468 EVT VT = N->getValueType(0);
14469
14470 // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
14471 if (Subtarget->hasMVEIntegerOps()) {
14472 EVT ExtractVT = VT.getVectorElementType();
14473 // We need to ensure we are creating a legal type.
14474 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
14475 ExtractVT = MVT::i32;
14476 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
14477 N->getOperand(0), N->getOperand(1));
14478 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
14479 }
14480
14481 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
14482 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
14483 if (CombineVLDDUP(N, DCI))
14484 return SDValue(N, 0);
14485
14486 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
14487 // redundant. Ignore bit_converts for now; element sizes are checked below.
14488 while (Op.getOpcode() == ISD::BITCAST)
14489 Op = Op.getOperand(0);
14490 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
14491 return SDValue();
14492
14493 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
14494 unsigned EltSize = Op.getScalarValueSizeInBits();
14495 // The canonical VMOV for a zero vector uses a 32-bit element size.
14496 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14497 unsigned EltBits;
14498 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
14499 EltSize = 8;
14500 if (EltSize > VT.getScalarSizeInBits())
14501 return SDValue();
14502
14503 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
14504 }
14505
14506 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
PerformVDUPCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14507 static SDValue PerformVDUPCombine(SDNode *N,
14508 TargetLowering::DAGCombinerInfo &DCI,
14509 const ARMSubtarget *Subtarget) {
14510 SelectionDAG &DAG = DCI.DAG;
14511 SDValue Op = N->getOperand(0);
14512 SDLoc dl(N);
14513
14514 if (Subtarget->hasMVEIntegerOps()) {
14515 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
14516 // need to come from a GPR.
14517 if (Op.getValueType() == MVT::f32)
14518 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
14519 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
14520 else if (Op.getValueType() == MVT::f16)
14521 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
14522 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
14523 }
14524
14525 if (!Subtarget->hasNEON())
14526 return SDValue();
14527
14528 // Match VDUP(LOAD) -> VLD1DUP.
14529 // We match this pattern here rather than waiting for isel because the
14530 // transform is only legal for unindexed loads.
14531 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
14532 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
14533 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
14534 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
14535 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
14536 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
14537 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
14538 Ops, LD->getMemoryVT(),
14539 LD->getMemOperand());
14540 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
14541 return VLDDup;
14542 }
14543
14544 return SDValue();
14545 }
14546
PerformLOADCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)14547 static SDValue PerformLOADCombine(SDNode *N,
14548 TargetLowering::DAGCombinerInfo &DCI) {
14549 EVT VT = N->getValueType(0);
14550
14551 // If this is a legal vector load, try to combine it into a VLD1_UPD.
14552 if (ISD::isNormalLoad(N) && VT.isVector() &&
14553 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14554 return CombineBaseUpdate(N, DCI);
14555
14556 return SDValue();
14557 }
14558
14559 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
14560 // pack all of the elements in one place. Next, store to memory in fewer
14561 // chunks.
PerformTruncatingStoreCombine(StoreSDNode * St,SelectionDAG & DAG)14562 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
14563 SelectionDAG &DAG) {
14564 SDValue StVal = St->getValue();
14565 EVT VT = StVal.getValueType();
14566 if (!St->isTruncatingStore() || !VT.isVector())
14567 return SDValue();
14568 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14569 EVT StVT = St->getMemoryVT();
14570 unsigned NumElems = VT.getVectorNumElements();
14571 assert(StVT != VT && "Cannot truncate to the same type");
14572 unsigned FromEltSz = VT.getScalarSizeInBits();
14573 unsigned ToEltSz = StVT.getScalarSizeInBits();
14574
14575 // From, To sizes and ElemCount must be pow of two
14576 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
14577 return SDValue();
14578
14579 // We are going to use the original vector elt for storing.
14580 // Accumulated smaller vector elements must be a multiple of the store size.
14581 if (0 != (NumElems * FromEltSz) % ToEltSz)
14582 return SDValue();
14583
14584 unsigned SizeRatio = FromEltSz / ToEltSz;
14585 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
14586
14587 // Create a type on which we perform the shuffle.
14588 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
14589 NumElems * SizeRatio);
14590 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14591
14592 SDLoc DL(St);
14593 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
14594 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14595 for (unsigned i = 0; i < NumElems; ++i)
14596 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
14597 : i * SizeRatio;
14598
14599 // Can't shuffle using an illegal type.
14600 if (!TLI.isTypeLegal(WideVecVT))
14601 return SDValue();
14602
14603 SDValue Shuff = DAG.getVectorShuffle(
14604 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
14605 // At this point all of the data is stored at the bottom of the
14606 // register. We now need to save it to mem.
14607
14608 // Find the largest store unit
14609 MVT StoreType = MVT::i8;
14610 for (MVT Tp : MVT::integer_valuetypes()) {
14611 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
14612 StoreType = Tp;
14613 }
14614 // Didn't find a legal store type.
14615 if (!TLI.isTypeLegal(StoreType))
14616 return SDValue();
14617
14618 // Bitcast the original vector into a vector of store-size units
14619 EVT StoreVecVT =
14620 EVT::getVectorVT(*DAG.getContext(), StoreType,
14621 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
14622 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14623 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
14624 SmallVector<SDValue, 8> Chains;
14625 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
14626 TLI.getPointerTy(DAG.getDataLayout()));
14627 SDValue BasePtr = St->getBasePtr();
14628
14629 // Perform one or more big stores into memory.
14630 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
14631 for (unsigned I = 0; I < E; I++) {
14632 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
14633 ShuffWide, DAG.getIntPtrConstant(I, DL));
14634 SDValue Ch =
14635 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
14636 St->getAlignment(), St->getMemOperand()->getFlags());
14637 BasePtr =
14638 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
14639 Chains.push_back(Ch);
14640 }
14641 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
14642 }
14643
14644 // Try taking a single vector store from an truncate (which would otherwise turn
14645 // into an expensive buildvector) and splitting it into a series of narrowing
14646 // stores.
PerformSplittingToNarrowingStores(StoreSDNode * St,SelectionDAG & DAG)14647 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
14648 SelectionDAG &DAG) {
14649 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
14650 return SDValue();
14651 SDValue Trunc = St->getValue();
14652 if (Trunc->getOpcode() != ISD::TRUNCATE && Trunc->getOpcode() != ISD::FP_ROUND)
14653 return SDValue();
14654 EVT FromVT = Trunc->getOperand(0).getValueType();
14655 EVT ToVT = Trunc.getValueType();
14656 if (!ToVT.isVector())
14657 return SDValue();
14658 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
14659 EVT ToEltVT = ToVT.getVectorElementType();
14660 EVT FromEltVT = FromVT.getVectorElementType();
14661
14662 unsigned NumElements = 0;
14663 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
14664 NumElements = 4;
14665 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
14666 NumElements = 8;
14667 if (FromEltVT == MVT::f32 && ToEltVT == MVT::f16)
14668 NumElements = 4;
14669 if (NumElements == 0 ||
14670 (FromEltVT != MVT::f32 && FromVT.getVectorNumElements() == NumElements) ||
14671 FromVT.getVectorNumElements() % NumElements != 0)
14672 return SDValue();
14673
14674 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
14675 // use the VMOVN over splitting the store. We are looking for patterns of:
14676 // !rev: 0 N 1 N+1 2 N+2 ...
14677 // rev: N 0 N+1 1 N+2 2 ...
14678 auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) {
14679 unsigned NumElts = ToVT.getVectorNumElements();
14680 if (NumElts != M.size())
14681 return false;
14682
14683 unsigned Off0 = rev ? NumElts : 0;
14684 unsigned Off1 = rev ? 0 : NumElts;
14685
14686 for (unsigned i = 0; i < NumElts; i += 2) {
14687 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
14688 return false;
14689 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
14690 return false;
14691 }
14692
14693 return true;
14694 };
14695
14696 // It may be preferable to keep the store unsplit as the trunc may end up
14697 // being removed. Check that here.
14698 if (Trunc.getOperand(0).getOpcode() == ISD::SMIN) {
14699 if (SDValue U = PerformVQDMULHCombine(Trunc.getOperand(0).getNode(), DAG)) {
14700 DAG.ReplaceAllUsesWith(Trunc.getOperand(0), U);
14701 return SDValue();
14702 }
14703 }
14704 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0)))
14705 if (isVMOVNOriginalMask(Shuffle->getMask(), false) ||
14706 isVMOVNOriginalMask(Shuffle->getMask(), true))
14707 return SDValue();
14708
14709 LLVMContext &C = *DAG.getContext();
14710 SDLoc DL(St);
14711 // Details about the old store
14712 SDValue Ch = St->getChain();
14713 SDValue BasePtr = St->getBasePtr();
14714 Align Alignment = St->getOriginalAlign();
14715 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
14716 AAMDNodes AAInfo = St->getAAInfo();
14717
14718 // We split the store into slices of NumElements. fp16 trunc stores are vcvt
14719 // and then stored as truncating integer stores.
14720 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
14721 EVT NewToVT = EVT::getVectorVT(
14722 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
14723
14724 SmallVector<SDValue, 4> Stores;
14725 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
14726 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
14727 SDValue NewPtr =
14728 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
14729
14730 SDValue Extract =
14731 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
14732 DAG.getConstant(i * NumElements, DL, MVT::i32));
14733
14734 if (ToEltVT == MVT::f16) {
14735 SDValue FPTrunc =
14736 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
14737 Extract, DAG.getConstant(0, DL, MVT::i32));
14738 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
14739 }
14740
14741 SDValue Store = DAG.getTruncStore(
14742 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
14743 NewToVT, Alignment.value(), MMOFlags, AAInfo);
14744 Stores.push_back(Store);
14745 }
14746 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
14747 }
14748
14749 /// PerformSTORECombine - Target-specific dag combine xforms for
14750 /// ISD::STORE.
PerformSTORECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14751 static SDValue PerformSTORECombine(SDNode *N,
14752 TargetLowering::DAGCombinerInfo &DCI,
14753 const ARMSubtarget *Subtarget) {
14754 StoreSDNode *St = cast<StoreSDNode>(N);
14755 if (St->isVolatile())
14756 return SDValue();
14757 SDValue StVal = St->getValue();
14758 EVT VT = StVal.getValueType();
14759
14760 if (Subtarget->hasNEON())
14761 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
14762 return Store;
14763
14764 if (Subtarget->hasMVEIntegerOps())
14765 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
14766 return NewToken;
14767
14768 if (!ISD::isNormalStore(St))
14769 return SDValue();
14770
14771 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
14772 // ARM stores of arguments in the same cache line.
14773 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
14774 StVal.getNode()->hasOneUse()) {
14775 SelectionDAG &DAG = DCI.DAG;
14776 bool isBigEndian = DAG.getDataLayout().isBigEndian();
14777 SDLoc DL(St);
14778 SDValue BasePtr = St->getBasePtr();
14779 SDValue NewST1 = DAG.getStore(
14780 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
14781 BasePtr, St->getPointerInfo(), St->getOriginalAlign(),
14782 St->getMemOperand()->getFlags());
14783
14784 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14785 DAG.getConstant(4, DL, MVT::i32));
14786 return DAG.getStore(NewST1.getValue(0), DL,
14787 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
14788 OffsetPtr, St->getPointerInfo().getWithOffset(4),
14789 St->getOriginalAlign(),
14790 St->getMemOperand()->getFlags());
14791 }
14792
14793 if (StVal.getValueType() == MVT::i64 &&
14794 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14795
14796 // Bitcast an i64 store extracted from a vector to f64.
14797 // Otherwise, the i64 value will be legalized to a pair of i32 values.
14798 SelectionDAG &DAG = DCI.DAG;
14799 SDLoc dl(StVal);
14800 SDValue IntVec = StVal.getOperand(0);
14801 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
14802 IntVec.getValueType().getVectorNumElements());
14803 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
14804 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14805 Vec, StVal.getOperand(1));
14806 dl = SDLoc(N);
14807 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
14808 // Make the DAGCombiner fold the bitcasts.
14809 DCI.AddToWorklist(Vec.getNode());
14810 DCI.AddToWorklist(ExtElt.getNode());
14811 DCI.AddToWorklist(V.getNode());
14812 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
14813 St->getPointerInfo(), St->getAlignment(),
14814 St->getMemOperand()->getFlags(), St->getAAInfo());
14815 }
14816
14817 // If this is a legal vector store, try to combine it into a VST1_UPD.
14818 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
14819 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14820 return CombineBaseUpdate(N, DCI);
14821
14822 return SDValue();
14823 }
14824
14825 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
14826 /// can replace combinations of VMUL and VCVT (floating-point to integer)
14827 /// when the VMUL has a constant operand that is a power of 2.
14828 ///
14829 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14830 /// vmul.f32 d16, d17, d16
14831 /// vcvt.s32.f32 d16, d16
14832 /// becomes:
14833 /// vcvt.s32.f32 d16, d16, #3
PerformVCVTCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)14834 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
14835 const ARMSubtarget *Subtarget) {
14836 if (!Subtarget->hasNEON())
14837 return SDValue();
14838
14839 SDValue Op = N->getOperand(0);
14840 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
14841 Op.getOpcode() != ISD::FMUL)
14842 return SDValue();
14843
14844 SDValue ConstVec = Op->getOperand(1);
14845 if (!isa<BuildVectorSDNode>(ConstVec))
14846 return SDValue();
14847
14848 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
14849 uint32_t FloatBits = FloatTy.getSizeInBits();
14850 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
14851 uint32_t IntBits = IntTy.getSizeInBits();
14852 unsigned NumLanes = Op.getValueType().getVectorNumElements();
14853 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14854 // These instructions only exist converting from f32 to i32. We can handle
14855 // smaller integers by generating an extra truncate, but larger ones would
14856 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14857 // these intructions only support v2i32/v4i32 types.
14858 return SDValue();
14859 }
14860
14861 BitVector UndefElements;
14862 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14863 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14864 if (C == -1 || C == 0 || C > 32)
14865 return SDValue();
14866
14867 SDLoc dl(N);
14868 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
14869 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
14870 Intrinsic::arm_neon_vcvtfp2fxu;
14871 SDValue FixConv = DAG.getNode(
14872 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14873 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
14874 DAG.getConstant(C, dl, MVT::i32));
14875
14876 if (IntBits < FloatBits)
14877 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
14878
14879 return FixConv;
14880 }
14881
14882 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
14883 /// can replace combinations of VCVT (integer to floating-point) and VDIV
14884 /// when the VDIV has a constant operand that is a power of 2.
14885 ///
14886 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14887 /// vcvt.f32.s32 d16, d16
14888 /// vdiv.f32 d16, d17, d16
14889 /// becomes:
14890 /// vcvt.f32.s32 d16, d16, #3
PerformVDIVCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)14891 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
14892 const ARMSubtarget *Subtarget) {
14893 if (!Subtarget->hasNEON())
14894 return SDValue();
14895
14896 SDValue Op = N->getOperand(0);
14897 unsigned OpOpcode = Op.getNode()->getOpcode();
14898 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
14899 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
14900 return SDValue();
14901
14902 SDValue ConstVec = N->getOperand(1);
14903 if (!isa<BuildVectorSDNode>(ConstVec))
14904 return SDValue();
14905
14906 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
14907 uint32_t FloatBits = FloatTy.getSizeInBits();
14908 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
14909 uint32_t IntBits = IntTy.getSizeInBits();
14910 unsigned NumLanes = Op.getValueType().getVectorNumElements();
14911 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14912 // These instructions only exist converting from i32 to f32. We can handle
14913 // smaller integers by generating an extra extend, but larger ones would
14914 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14915 // these intructions only support v2i32/v4i32 types.
14916 return SDValue();
14917 }
14918
14919 BitVector UndefElements;
14920 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14921 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14922 if (C == -1 || C == 0 || C > 32)
14923 return SDValue();
14924
14925 SDLoc dl(N);
14926 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
14927 SDValue ConvInput = Op.getOperand(0);
14928 if (IntBits < FloatBits)
14929 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
14930 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14931 ConvInput);
14932
14933 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
14934 Intrinsic::arm_neon_vcvtfxu2fp;
14935 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
14936 Op.getValueType(),
14937 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
14938 ConvInput, DAG.getConstant(C, dl, MVT::i32));
14939 }
14940
PerformVECREDUCE_ADDCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)14941 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
14942 const ARMSubtarget *ST) {
14943 if (!ST->hasMVEIntegerOps())
14944 return SDValue();
14945
14946 assert(N->getOpcode() == ISD::VECREDUCE_ADD);
14947 EVT ResVT = N->getValueType(0);
14948 SDValue N0 = N->getOperand(0);
14949 SDLoc dl(N);
14950
14951 // We are looking for something that will have illegal types if left alone,
14952 // but that we can convert to a single instruction undef MVE. For example
14953 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
14954 // or
14955 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
14956
14957 // Cases:
14958 // VADDV u/s 8/16/32
14959 // VMLAV u/s 8/16/32
14960 // VADDLV u/s 32
14961 // VMLALV u/s 16/32
14962
14963 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
14964 if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
14965 return SDValue();
14966 SDValue A = N0->getOperand(0);
14967 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14968 return A;
14969 return SDValue();
14970 };
14971 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
14972 ArrayRef<MVT> ExtTypes, SDValue &Mask) {
14973 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
14974 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
14975 return SDValue();
14976 Mask = N0->getOperand(0);
14977 SDValue Ext = N0->getOperand(1);
14978 if (Ext->getOpcode() != ExtendCode)
14979 return SDValue();
14980 SDValue A = Ext->getOperand(0);
14981 if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14982 return A;
14983 return SDValue();
14984 };
14985 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
14986 SDValue &A, SDValue &B) {
14987 // For a vmla we are trying to match a larger pattern:
14988 // ExtA = sext/zext A
14989 // ExtB = sext/zext B
14990 // Mul = mul ExtA, ExtB
14991 // vecreduce.add Mul
14992 // There might also be en extra extend between the mul and the addreduce, so
14993 // long as the bitwidth is high enough to make them equivalent (for example
14994 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
14995 if (ResVT != RetTy)
14996 return false;
14997 SDValue Mul = N0;
14998 if (Mul->getOpcode() == ExtendCode &&
14999 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
15000 ResVT.getScalarSizeInBits())
15001 Mul = Mul->getOperand(0);
15002 if (Mul->getOpcode() != ISD::MUL)
15003 return false;
15004 SDValue ExtA = Mul->getOperand(0);
15005 SDValue ExtB = Mul->getOperand(1);
15006 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
15007 return false;
15008 A = ExtA->getOperand(0);
15009 B = ExtB->getOperand(0);
15010 if (A.getValueType() == B.getValueType() &&
15011 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
15012 return true;
15013 return false;
15014 };
15015 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
15016 SDValue &A, SDValue &B, SDValue &Mask) {
15017 // Same as the pattern above with a select for the zero predicated lanes
15018 // ExtA = sext/zext A
15019 // ExtB = sext/zext B
15020 // Mul = mul ExtA, ExtB
15021 // N0 = select Mask, Mul, 0
15022 // vecreduce.add N0
15023 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
15024 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
15025 return false;
15026 Mask = N0->getOperand(0);
15027 SDValue Mul = N0->getOperand(1);
15028 if (Mul->getOpcode() == ExtendCode &&
15029 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
15030 ResVT.getScalarSizeInBits())
15031 Mul = Mul->getOperand(0);
15032 if (Mul->getOpcode() != ISD::MUL)
15033 return false;
15034 SDValue ExtA = Mul->getOperand(0);
15035 SDValue ExtB = Mul->getOperand(1);
15036 if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
15037 return false;
15038 A = ExtA->getOperand(0);
15039 B = ExtB->getOperand(0);
15040 if (A.getValueType() == B.getValueType() &&
15041 llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
15042 return true;
15043 return false;
15044 };
15045 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
15046 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
15047 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
15048 SDValue(Node.getNode(), 1));
15049 };
15050
15051 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
15052 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
15053 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
15054 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
15055 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
15056 return Create64bitNode(ARMISD::VADDLVs, {A});
15057 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
15058 return Create64bitNode(ARMISD::VADDLVu, {A});
15059 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
15060 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15061 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
15062 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
15063 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15064 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
15065
15066 SDValue Mask;
15067 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
15068 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
15069 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
15070 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
15071 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
15072 return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
15073 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
15074 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
15075 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
15076 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15077 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
15078 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
15079 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15080 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
15081
15082 SDValue A, B;
15083 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
15084 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
15085 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
15086 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
15087 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
15088 return Create64bitNode(ARMISD::VMLALVs, {A, B});
15089 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
15090 return Create64bitNode(ARMISD::VMLALVu, {A, B});
15091 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
15092 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15093 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
15094 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
15095 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15096 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
15097
15098 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask))
15099 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
15100 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask))
15101 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
15102 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask))
15103 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
15104 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask))
15105 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
15106 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
15107 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15108 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
15109 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
15110 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15111 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
15112
15113 // Some complications. We can get a case where the two inputs of the mul are
15114 // the same, then the output sext will have been helpfully converted to a
15115 // zext. Turn it back.
15116 SDValue Op = N0;
15117 if (Op->getOpcode() == ISD::VSELECT)
15118 Op = Op->getOperand(1);
15119 if (Op->getOpcode() == ISD::ZERO_EXTEND &&
15120 Op->getOperand(0)->getOpcode() == ISD::MUL) {
15121 SDValue Mul = Op->getOperand(0);
15122 if (Mul->getOperand(0) == Mul->getOperand(1) &&
15123 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
15124 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
15125 if (Op != N0)
15126 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
15127 N0->getOperand(0), Ext, N0->getOperand(2));
15128 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
15129 }
15130 }
15131
15132 return SDValue();
15133 }
15134
PerformVMOVNCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)15135 static SDValue PerformVMOVNCombine(SDNode *N,
15136 TargetLowering::DAGCombinerInfo &DCI) {
15137 SDValue Op0 = N->getOperand(0);
15138 SDValue Op1 = N->getOperand(1);
15139 unsigned IsTop = N->getConstantOperandVal(2);
15140
15141 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
15142 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
15143 if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
15144 Op1->getOpcode() == ARMISD::VQMOVNu) &&
15145 Op1->getConstantOperandVal(2) == 0)
15146 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
15147 Op0, Op1->getOperand(1), N->getOperand(2));
15148
15149 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
15150 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
15151 // into the top or bottom lanes.
15152 unsigned NumElts = N->getValueType(0).getVectorNumElements();
15153 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
15154 APInt Op0DemandedElts =
15155 IsTop ? Op1DemandedElts
15156 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
15157
15158 APInt KnownUndef, KnownZero;
15159 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15160 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
15161 KnownZero, DCI))
15162 return SDValue(N, 0);
15163 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef,
15164 KnownZero, DCI))
15165 return SDValue(N, 0);
15166
15167 return SDValue();
15168 }
15169
PerformVQMOVNCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)15170 static SDValue PerformVQMOVNCombine(SDNode *N,
15171 TargetLowering::DAGCombinerInfo &DCI) {
15172 SDValue Op0 = N->getOperand(0);
15173 unsigned IsTop = N->getConstantOperandVal(2);
15174
15175 unsigned NumElts = N->getValueType(0).getVectorNumElements();
15176 APInt Op0DemandedElts =
15177 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
15178 : APInt::getHighBitsSet(2, 1));
15179
15180 APInt KnownUndef, KnownZero;
15181 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15182 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
15183 KnownZero, DCI))
15184 return SDValue(N, 0);
15185 return SDValue();
15186 }
15187
PerformLongShiftCombine(SDNode * N,SelectionDAG & DAG)15188 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
15189 SDLoc DL(N);
15190 SDValue Op0 = N->getOperand(0);
15191 SDValue Op1 = N->getOperand(1);
15192
15193 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
15194 // uses of the intrinsics.
15195 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
15196 int ShiftAmt = C->getSExtValue();
15197 if (ShiftAmt == 0) {
15198 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
15199 DAG.ReplaceAllUsesWith(N, Merge.getNode());
15200 return SDValue();
15201 }
15202
15203 if (ShiftAmt >= -32 && ShiftAmt < 0) {
15204 unsigned NewOpcode =
15205 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
15206 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
15207 DAG.getConstant(-ShiftAmt, DL, MVT::i32));
15208 DAG.ReplaceAllUsesWith(N, NewShift.getNode());
15209 return NewShift;
15210 }
15211 }
15212
15213 return SDValue();
15214 }
15215
15216 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
PerformIntrinsicCombine(SDNode * N,DAGCombinerInfo & DCI) const15217 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
15218 DAGCombinerInfo &DCI) const {
15219 SelectionDAG &DAG = DCI.DAG;
15220 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15221 switch (IntNo) {
15222 default:
15223 // Don't do anything for most intrinsics.
15224 break;
15225
15226 // Vector shifts: check for immediate versions and lower them.
15227 // Note: This is done during DAG combining instead of DAG legalizing because
15228 // the build_vectors for 64-bit vector element shift counts are generally
15229 // not legal, and it is hard to see their values after they get legalized to
15230 // loads from a constant pool.
15231 case Intrinsic::arm_neon_vshifts:
15232 case Intrinsic::arm_neon_vshiftu:
15233 case Intrinsic::arm_neon_vrshifts:
15234 case Intrinsic::arm_neon_vrshiftu:
15235 case Intrinsic::arm_neon_vrshiftn:
15236 case Intrinsic::arm_neon_vqshifts:
15237 case Intrinsic::arm_neon_vqshiftu:
15238 case Intrinsic::arm_neon_vqshiftsu:
15239 case Intrinsic::arm_neon_vqshiftns:
15240 case Intrinsic::arm_neon_vqshiftnu:
15241 case Intrinsic::arm_neon_vqshiftnsu:
15242 case Intrinsic::arm_neon_vqrshiftns:
15243 case Intrinsic::arm_neon_vqrshiftnu:
15244 case Intrinsic::arm_neon_vqrshiftnsu: {
15245 EVT VT = N->getOperand(1).getValueType();
15246 int64_t Cnt;
15247 unsigned VShiftOpc = 0;
15248
15249 switch (IntNo) {
15250 case Intrinsic::arm_neon_vshifts:
15251 case Intrinsic::arm_neon_vshiftu:
15252 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
15253 VShiftOpc = ARMISD::VSHLIMM;
15254 break;
15255 }
15256 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
15257 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
15258 : ARMISD::VSHRuIMM);
15259 break;
15260 }
15261 return SDValue();
15262
15263 case Intrinsic::arm_neon_vrshifts:
15264 case Intrinsic::arm_neon_vrshiftu:
15265 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
15266 break;
15267 return SDValue();
15268
15269 case Intrinsic::arm_neon_vqshifts:
15270 case Intrinsic::arm_neon_vqshiftu:
15271 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
15272 break;
15273 return SDValue();
15274
15275 case Intrinsic::arm_neon_vqshiftsu:
15276 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
15277 break;
15278 llvm_unreachable("invalid shift count for vqshlu intrinsic");
15279
15280 case Intrinsic::arm_neon_vrshiftn:
15281 case Intrinsic::arm_neon_vqshiftns:
15282 case Intrinsic::arm_neon_vqshiftnu:
15283 case Intrinsic::arm_neon_vqshiftnsu:
15284 case Intrinsic::arm_neon_vqrshiftns:
15285 case Intrinsic::arm_neon_vqrshiftnu:
15286 case Intrinsic::arm_neon_vqrshiftnsu:
15287 // Narrowing shifts require an immediate right shift.
15288 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
15289 break;
15290 llvm_unreachable("invalid shift count for narrowing vector shift "
15291 "intrinsic");
15292
15293 default:
15294 llvm_unreachable("unhandled vector shift");
15295 }
15296
15297 switch (IntNo) {
15298 case Intrinsic::arm_neon_vshifts:
15299 case Intrinsic::arm_neon_vshiftu:
15300 // Opcode already set above.
15301 break;
15302 case Intrinsic::arm_neon_vrshifts:
15303 VShiftOpc = ARMISD::VRSHRsIMM;
15304 break;
15305 case Intrinsic::arm_neon_vrshiftu:
15306 VShiftOpc = ARMISD::VRSHRuIMM;
15307 break;
15308 case Intrinsic::arm_neon_vrshiftn:
15309 VShiftOpc = ARMISD::VRSHRNIMM;
15310 break;
15311 case Intrinsic::arm_neon_vqshifts:
15312 VShiftOpc = ARMISD::VQSHLsIMM;
15313 break;
15314 case Intrinsic::arm_neon_vqshiftu:
15315 VShiftOpc = ARMISD::VQSHLuIMM;
15316 break;
15317 case Intrinsic::arm_neon_vqshiftsu:
15318 VShiftOpc = ARMISD::VQSHLsuIMM;
15319 break;
15320 case Intrinsic::arm_neon_vqshiftns:
15321 VShiftOpc = ARMISD::VQSHRNsIMM;
15322 break;
15323 case Intrinsic::arm_neon_vqshiftnu:
15324 VShiftOpc = ARMISD::VQSHRNuIMM;
15325 break;
15326 case Intrinsic::arm_neon_vqshiftnsu:
15327 VShiftOpc = ARMISD::VQSHRNsuIMM;
15328 break;
15329 case Intrinsic::arm_neon_vqrshiftns:
15330 VShiftOpc = ARMISD::VQRSHRNsIMM;
15331 break;
15332 case Intrinsic::arm_neon_vqrshiftnu:
15333 VShiftOpc = ARMISD::VQRSHRNuIMM;
15334 break;
15335 case Intrinsic::arm_neon_vqrshiftnsu:
15336 VShiftOpc = ARMISD::VQRSHRNsuIMM;
15337 break;
15338 }
15339
15340 SDLoc dl(N);
15341 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
15342 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
15343 }
15344
15345 case Intrinsic::arm_neon_vshiftins: {
15346 EVT VT = N->getOperand(1).getValueType();
15347 int64_t Cnt;
15348 unsigned VShiftOpc = 0;
15349
15350 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
15351 VShiftOpc = ARMISD::VSLIIMM;
15352 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
15353 VShiftOpc = ARMISD::VSRIIMM;
15354 else {
15355 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
15356 }
15357
15358 SDLoc dl(N);
15359 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
15360 N->getOperand(1), N->getOperand(2),
15361 DAG.getConstant(Cnt, dl, MVT::i32));
15362 }
15363
15364 case Intrinsic::arm_neon_vqrshifts:
15365 case Intrinsic::arm_neon_vqrshiftu:
15366 // No immediate versions of these to check for.
15367 break;
15368
15369 case Intrinsic::arm_mve_vqdmlah:
15370 case Intrinsic::arm_mve_vqdmlash:
15371 case Intrinsic::arm_mve_vqrdmlah:
15372 case Intrinsic::arm_mve_vqrdmlash:
15373 case Intrinsic::arm_mve_vmla_n_predicated:
15374 case Intrinsic::arm_mve_vmlas_n_predicated:
15375 case Intrinsic::arm_mve_vqdmlah_predicated:
15376 case Intrinsic::arm_mve_vqdmlash_predicated:
15377 case Intrinsic::arm_mve_vqrdmlah_predicated:
15378 case Intrinsic::arm_mve_vqrdmlash_predicated: {
15379 // These intrinsics all take an i32 scalar operand which is narrowed to the
15380 // size of a single lane of the vector type they return. So we don't need
15381 // any bits of that operand above that point, which allows us to eliminate
15382 // uxth/sxth.
15383 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
15384 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
15385 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
15386 return SDValue();
15387 break;
15388 }
15389
15390 case Intrinsic::arm_mve_minv:
15391 case Intrinsic::arm_mve_maxv:
15392 case Intrinsic::arm_mve_minav:
15393 case Intrinsic::arm_mve_maxav:
15394 case Intrinsic::arm_mve_minv_predicated:
15395 case Intrinsic::arm_mve_maxv_predicated:
15396 case Intrinsic::arm_mve_minav_predicated:
15397 case Intrinsic::arm_mve_maxav_predicated: {
15398 // These intrinsics all take an i32 scalar operand which is narrowed to the
15399 // size of a single lane of the vector type they take as the other input.
15400 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
15401 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
15402 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15403 return SDValue();
15404 break;
15405 }
15406
15407 case Intrinsic::arm_mve_addv: {
15408 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
15409 // which allow PerformADDVecReduce to turn it into VADDLV when possible.
15410 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
15411 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
15412 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
15413 }
15414
15415 case Intrinsic::arm_mve_addlv:
15416 case Intrinsic::arm_mve_addlv_predicated: {
15417 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
15418 // which recombines the two outputs into an i64
15419 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
15420 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
15421 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
15422 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
15423
15424 SmallVector<SDValue, 4> Ops;
15425 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
15426 if (i != 2) // skip the unsigned flag
15427 Ops.push_back(N->getOperand(i));
15428
15429 SDLoc dl(N);
15430 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
15431 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
15432 val.getValue(1));
15433 }
15434 }
15435
15436 return SDValue();
15437 }
15438
15439 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
15440 /// lowers them. As with the vector shift intrinsics, this is done during DAG
15441 /// combining instead of DAG legalizing because the build_vectors for 64-bit
15442 /// vector element shift counts are generally not legal, and it is hard to see
15443 /// their values after they get legalized to loads from a constant pool.
PerformShiftCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * ST)15444 static SDValue PerformShiftCombine(SDNode *N,
15445 TargetLowering::DAGCombinerInfo &DCI,
15446 const ARMSubtarget *ST) {
15447 SelectionDAG &DAG = DCI.DAG;
15448 EVT VT = N->getValueType(0);
15449 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
15450 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
15451 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
15452 SDValue N1 = N->getOperand(1);
15453 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
15454 SDValue N0 = N->getOperand(0);
15455 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
15456 DAG.MaskedValueIsZero(N0.getOperand(0),
15457 APInt::getHighBitsSet(32, 16)))
15458 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
15459 }
15460 }
15461
15462 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
15463 N->getOperand(0)->getOpcode() == ISD::AND &&
15464 N->getOperand(0)->hasOneUse()) {
15465 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15466 return SDValue();
15467 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
15468 // usually show up because instcombine prefers to canonicalize it to
15469 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
15470 // out of GEP lowering in some cases.
15471 SDValue N0 = N->getOperand(0);
15472 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
15473 if (!ShiftAmtNode)
15474 return SDValue();
15475 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
15476 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15477 if (!AndMaskNode)
15478 return SDValue();
15479 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
15480 // Don't transform uxtb/uxth.
15481 if (AndMask == 255 || AndMask == 65535)
15482 return SDValue();
15483 if (isMask_32(AndMask)) {
15484 uint32_t MaskedBits = countLeadingZeros(AndMask);
15485 if (MaskedBits > ShiftAmt) {
15486 SDLoc DL(N);
15487 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
15488 DAG.getConstant(MaskedBits, DL, MVT::i32));
15489 return DAG.getNode(
15490 ISD::SRL, DL, MVT::i32, SHL,
15491 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
15492 }
15493 }
15494 }
15495
15496 // Nothing to be done for scalar shifts.
15497 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15498 if (!VT.isVector() || !TLI.isTypeLegal(VT))
15499 return SDValue();
15500 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
15501 return SDValue();
15502
15503 int64_t Cnt;
15504
15505 switch (N->getOpcode()) {
15506 default: llvm_unreachable("unexpected shift opcode");
15507
15508 case ISD::SHL:
15509 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
15510 SDLoc dl(N);
15511 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
15512 DAG.getConstant(Cnt, dl, MVT::i32));
15513 }
15514 break;
15515
15516 case ISD::SRA:
15517 case ISD::SRL:
15518 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
15519 unsigned VShiftOpc =
15520 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
15521 SDLoc dl(N);
15522 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
15523 DAG.getConstant(Cnt, dl, MVT::i32));
15524 }
15525 }
15526 return SDValue();
15527 }
15528
15529 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be
15530 // split into multiple extending loads, which are simpler to deal with than an
15531 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL
15532 // to convert the type to an f32.
PerformSplittingToWideningLoad(SDNode * N,SelectionDAG & DAG)15533 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
15534 SDValue N0 = N->getOperand(0);
15535 if (N0.getOpcode() != ISD::LOAD)
15536 return SDValue();
15537 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
15538 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
15539 LD->getExtensionType() != ISD::NON_EXTLOAD)
15540 return SDValue();
15541 EVT FromVT = LD->getValueType(0);
15542 EVT ToVT = N->getValueType(0);
15543 if (!ToVT.isVector())
15544 return SDValue();
15545 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
15546 EVT ToEltVT = ToVT.getVectorElementType();
15547 EVT FromEltVT = FromVT.getVectorElementType();
15548
15549 unsigned NumElements = 0;
15550 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
15551 NumElements = 4;
15552 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
15553 NumElements = 8;
15554 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
15555 NumElements = 4;
15556 if (NumElements == 0 ||
15557 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
15558 FromVT.getVectorNumElements() % NumElements != 0 ||
15559 !isPowerOf2_32(NumElements))
15560 return SDValue();
15561
15562 LLVMContext &C = *DAG.getContext();
15563 SDLoc DL(LD);
15564 // Details about the old load
15565 SDValue Ch = LD->getChain();
15566 SDValue BasePtr = LD->getBasePtr();
15567 Align Alignment = LD->getOriginalAlign();
15568 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
15569 AAMDNodes AAInfo = LD->getAAInfo();
15570
15571 ISD::LoadExtType NewExtType =
15572 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
15573 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
15574 EVT NewFromVT = EVT::getVectorVT(
15575 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
15576 EVT NewToVT = EVT::getVectorVT(
15577 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
15578
15579 SmallVector<SDValue, 4> Loads;
15580 SmallVector<SDValue, 4> Chains;
15581 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
15582 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
15583 SDValue NewPtr =
15584 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
15585
15586 SDValue NewLoad =
15587 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
15588 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
15589 Alignment, MMOFlags, AAInfo);
15590 Loads.push_back(NewLoad);
15591 Chains.push_back(SDValue(NewLoad.getNode(), 1));
15592 }
15593
15594 // Float truncs need to extended with VCVTB's into their floating point types.
15595 if (FromEltVT == MVT::f16) {
15596 SmallVector<SDValue, 4> Extends;
15597
15598 for (unsigned i = 0; i < Loads.size(); i++) {
15599 SDValue LoadBC =
15600 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
15601 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
15602 DAG.getConstant(0, DL, MVT::i32));
15603 Extends.push_back(FPExt);
15604 }
15605
15606 Loads = Extends;
15607 }
15608
15609 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
15610 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
15611 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
15612 }
15613
15614 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
15615 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
PerformExtendCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)15616 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
15617 const ARMSubtarget *ST) {
15618 SDValue N0 = N->getOperand(0);
15619
15620 // Check for sign- and zero-extensions of vector extract operations of 8- and
15621 // 16-bit vector elements. NEON and MVE support these directly. They are
15622 // handled during DAG combining because type legalization will promote them
15623 // to 32-bit types and it is messy to recognize the operations after that.
15624 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
15625 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15626 SDValue Vec = N0.getOperand(0);
15627 SDValue Lane = N0.getOperand(1);
15628 EVT VT = N->getValueType(0);
15629 EVT EltVT = N0.getValueType();
15630 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15631
15632 if (VT == MVT::i32 &&
15633 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
15634 TLI.isTypeLegal(Vec.getValueType()) &&
15635 isa<ConstantSDNode>(Lane)) {
15636
15637 unsigned Opc = 0;
15638 switch (N->getOpcode()) {
15639 default: llvm_unreachable("unexpected opcode");
15640 case ISD::SIGN_EXTEND:
15641 Opc = ARMISD::VGETLANEs;
15642 break;
15643 case ISD::ZERO_EXTEND:
15644 case ISD::ANY_EXTEND:
15645 Opc = ARMISD::VGETLANEu;
15646 break;
15647 }
15648 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
15649 }
15650 }
15651
15652 if (ST->hasMVEIntegerOps())
15653 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
15654 return NewLoad;
15655
15656 return SDValue();
15657 }
15658
PerformFPExtendCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)15659 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
15660 const ARMSubtarget *ST) {
15661 if (ST->hasMVEFloatOps())
15662 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
15663 return NewLoad;
15664
15665 return SDValue();
15666 }
15667
15668 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
15669 /// saturates.
PerformMinMaxCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)15670 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
15671 const ARMSubtarget *ST) {
15672 EVT VT = N->getValueType(0);
15673 SDValue N0 = N->getOperand(0);
15674 if (!ST->hasMVEIntegerOps())
15675 return SDValue();
15676
15677 if (SDValue V = PerformVQDMULHCombine(N, DAG))
15678 return V;
15679
15680 if (VT != MVT::v4i32 && VT != MVT::v8i16)
15681 return SDValue();
15682
15683 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
15684 // Check one is a smin and the other is a smax
15685 if (Min->getOpcode() != ISD::SMIN)
15686 std::swap(Min, Max);
15687 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
15688 return false;
15689
15690 APInt SaturateC;
15691 if (VT == MVT::v4i32)
15692 SaturateC = APInt(32, (1 << 15) - 1, true);
15693 else //if (VT == MVT::v8i16)
15694 SaturateC = APInt(16, (1 << 7) - 1, true);
15695
15696 APInt MinC, MaxC;
15697 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
15698 MinC != SaturateC)
15699 return false;
15700 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
15701 MaxC != ~SaturateC)
15702 return false;
15703 return true;
15704 };
15705
15706 if (IsSignedSaturate(N, N0.getNode())) {
15707 SDLoc DL(N);
15708 MVT ExtVT, HalfVT;
15709 if (VT == MVT::v4i32) {
15710 HalfVT = MVT::v8i16;
15711 ExtVT = MVT::v4i16;
15712 } else { // if (VT == MVT::v8i16)
15713 HalfVT = MVT::v16i8;
15714 ExtVT = MVT::v8i8;
15715 }
15716
15717 // Create a VQMOVNB with undef top lanes, then signed extended into the top
15718 // half. That extend will hopefully be removed if only the bottom bits are
15719 // demanded (though a truncating store, for example).
15720 SDValue VQMOVN =
15721 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
15722 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
15723 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
15724 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
15725 DAG.getValueType(ExtVT));
15726 }
15727
15728 auto IsUnsignedSaturate = [&](SDNode *Min) {
15729 // For unsigned, we just need to check for <= 0xffff
15730 if (Min->getOpcode() != ISD::UMIN)
15731 return false;
15732
15733 APInt SaturateC;
15734 if (VT == MVT::v4i32)
15735 SaturateC = APInt(32, (1 << 16) - 1, true);
15736 else //if (VT == MVT::v8i16)
15737 SaturateC = APInt(16, (1 << 8) - 1, true);
15738
15739 APInt MinC;
15740 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
15741 MinC != SaturateC)
15742 return false;
15743 return true;
15744 };
15745
15746 if (IsUnsignedSaturate(N)) {
15747 SDLoc DL(N);
15748 MVT HalfVT;
15749 unsigned ExtConst;
15750 if (VT == MVT::v4i32) {
15751 HalfVT = MVT::v8i16;
15752 ExtConst = 0x0000FFFF;
15753 } else { //if (VT == MVT::v8i16)
15754 HalfVT = MVT::v16i8;
15755 ExtConst = 0x00FF;
15756 }
15757
15758 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
15759 // an AND. That extend will hopefully be removed if only the bottom bits are
15760 // demanded (though a truncating store, for example).
15761 SDValue VQMOVN =
15762 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
15763 DAG.getConstant(0, DL, MVT::i32));
15764 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
15765 return DAG.getNode(ISD::AND, DL, VT, Bitcast,
15766 DAG.getConstant(ExtConst, DL, VT));
15767 }
15768
15769 return SDValue();
15770 }
15771
isPowerOf2Constant(SDValue V)15772 static const APInt *isPowerOf2Constant(SDValue V) {
15773 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
15774 if (!C)
15775 return nullptr;
15776 const APInt *CV = &C->getAPIntValue();
15777 return CV->isPowerOf2() ? CV : nullptr;
15778 }
15779
PerformCMOVToBFICombine(SDNode * CMOV,SelectionDAG & DAG) const15780 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
15781 // If we have a CMOV, OR and AND combination such as:
15782 // if (x & CN)
15783 // y |= CM;
15784 //
15785 // And:
15786 // * CN is a single bit;
15787 // * All bits covered by CM are known zero in y
15788 //
15789 // Then we can convert this into a sequence of BFI instructions. This will
15790 // always be a win if CM is a single bit, will always be no worse than the
15791 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
15792 // three bits (due to the extra IT instruction).
15793
15794 SDValue Op0 = CMOV->getOperand(0);
15795 SDValue Op1 = CMOV->getOperand(1);
15796 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
15797 auto CC = CCNode->getAPIntValue().getLimitedValue();
15798 SDValue CmpZ = CMOV->getOperand(4);
15799
15800 // The compare must be against zero.
15801 if (!isNullConstant(CmpZ->getOperand(1)))
15802 return SDValue();
15803
15804 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
15805 SDValue And = CmpZ->getOperand(0);
15806 if (And->getOpcode() != ISD::AND)
15807 return SDValue();
15808 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
15809 if (!AndC)
15810 return SDValue();
15811 SDValue X = And->getOperand(0);
15812
15813 if (CC == ARMCC::EQ) {
15814 // We're performing an "equal to zero" compare. Swap the operands so we
15815 // canonicalize on a "not equal to zero" compare.
15816 std::swap(Op0, Op1);
15817 } else {
15818 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
15819 }
15820
15821 if (Op1->getOpcode() != ISD::OR)
15822 return SDValue();
15823
15824 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
15825 if (!OrC)
15826 return SDValue();
15827 SDValue Y = Op1->getOperand(0);
15828
15829 if (Op0 != Y)
15830 return SDValue();
15831
15832 // Now, is it profitable to continue?
15833 APInt OrCI = OrC->getAPIntValue();
15834 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
15835 if (OrCI.countPopulation() > Heuristic)
15836 return SDValue();
15837
15838 // Lastly, can we determine that the bits defined by OrCI
15839 // are zero in Y?
15840 KnownBits Known = DAG.computeKnownBits(Y);
15841 if ((OrCI & Known.Zero) != OrCI)
15842 return SDValue();
15843
15844 // OK, we can do the combine.
15845 SDValue V = Y;
15846 SDLoc dl(X);
15847 EVT VT = X.getValueType();
15848 unsigned BitInX = AndC->logBase2();
15849
15850 if (BitInX != 0) {
15851 // We must shift X first.
15852 X = DAG.getNode(ISD::SRL, dl, VT, X,
15853 DAG.getConstant(BitInX, dl, VT));
15854 }
15855
15856 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
15857 BitInY < NumActiveBits; ++BitInY) {
15858 if (OrCI[BitInY] == 0)
15859 continue;
15860 APInt Mask(VT.getSizeInBits(), 0);
15861 Mask.setBit(BitInY);
15862 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
15863 // Confusingly, the operand is an *inverted* mask.
15864 DAG.getConstant(~Mask, dl, VT));
15865 }
15866
15867 return V;
15868 }
15869
15870 // Given N, the value controlling the conditional branch, search for the loop
15871 // intrinsic, returning it, along with how the value is used. We need to handle
15872 // patterns such as the following:
15873 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
15874 // (brcond (setcc (loop.decrement), 0, eq), exit)
15875 // (brcond (setcc (loop.decrement), 0, ne), header)
SearchLoopIntrinsic(SDValue N,ISD::CondCode & CC,int & Imm,bool & Negate)15876 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
15877 bool &Negate) {
15878 switch (N->getOpcode()) {
15879 default:
15880 break;
15881 case ISD::XOR: {
15882 if (!isa<ConstantSDNode>(N.getOperand(1)))
15883 return SDValue();
15884 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
15885 return SDValue();
15886 Negate = !Negate;
15887 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
15888 }
15889 case ISD::SETCC: {
15890 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
15891 if (!Const)
15892 return SDValue();
15893 if (Const->isNullValue())
15894 Imm = 0;
15895 else if (Const->isOne())
15896 Imm = 1;
15897 else
15898 return SDValue();
15899 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
15900 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
15901 }
15902 case ISD::INTRINSIC_W_CHAIN: {
15903 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
15904 if (IntOp != Intrinsic::test_set_loop_iterations &&
15905 IntOp != Intrinsic::loop_decrement_reg)
15906 return SDValue();
15907 return N;
15908 }
15909 }
15910 return SDValue();
15911 }
15912
PerformHWLoopCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * ST)15913 static SDValue PerformHWLoopCombine(SDNode *N,
15914 TargetLowering::DAGCombinerInfo &DCI,
15915 const ARMSubtarget *ST) {
15916
15917 // The hwloop intrinsics that we're interested are used for control-flow,
15918 // either for entering or exiting the loop:
15919 // - test.set.loop.iterations will test whether its operand is zero. If it
15920 // is zero, the proceeding branch should not enter the loop.
15921 // - loop.decrement.reg also tests whether its operand is zero. If it is
15922 // zero, the proceeding branch should not branch back to the beginning of
15923 // the loop.
15924 // So here, we need to check that how the brcond is using the result of each
15925 // of the intrinsics to ensure that we're branching to the right place at the
15926 // right time.
15927
15928 ISD::CondCode CC;
15929 SDValue Cond;
15930 int Imm = 1;
15931 bool Negate = false;
15932 SDValue Chain = N->getOperand(0);
15933 SDValue Dest;
15934
15935 if (N->getOpcode() == ISD::BRCOND) {
15936 CC = ISD::SETEQ;
15937 Cond = N->getOperand(1);
15938 Dest = N->getOperand(2);
15939 } else {
15940 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
15941 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15942 Cond = N->getOperand(2);
15943 Dest = N->getOperand(4);
15944 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
15945 if (!Const->isOne() && !Const->isNullValue())
15946 return SDValue();
15947 Imm = Const->getZExtValue();
15948 } else
15949 return SDValue();
15950 }
15951
15952 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
15953 if (!Int)
15954 return SDValue();
15955
15956 if (Negate)
15957 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
15958
15959 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
15960 return (CC == ISD::SETEQ && Imm == 0) ||
15961 (CC == ISD::SETNE && Imm == 1) ||
15962 (CC == ISD::SETLT && Imm == 1) ||
15963 (CC == ISD::SETULT && Imm == 1);
15964 };
15965
15966 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
15967 return (CC == ISD::SETEQ && Imm == 1) ||
15968 (CC == ISD::SETNE && Imm == 0) ||
15969 (CC == ISD::SETGT && Imm == 0) ||
15970 (CC == ISD::SETUGT && Imm == 0) ||
15971 (CC == ISD::SETGE && Imm == 1) ||
15972 (CC == ISD::SETUGE && Imm == 1);
15973 };
15974
15975 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
15976 "unsupported condition");
15977
15978 SDLoc dl(Int);
15979 SelectionDAG &DAG = DCI.DAG;
15980 SDValue Elements = Int.getOperand(2);
15981 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
15982 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
15983 && "expected single br user");
15984 SDNode *Br = *N->use_begin();
15985 SDValue OtherTarget = Br->getOperand(1);
15986
15987 // Update the unconditional branch to branch to the given Dest.
15988 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
15989 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
15990 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
15991 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
15992 };
15993
15994 if (IntOp == Intrinsic::test_set_loop_iterations) {
15995 SDValue Res;
15996 // We expect this 'instruction' to branch when the counter is zero.
15997 if (IsTrueIfZero(CC, Imm)) {
15998 SDValue Ops[] = { Chain, Elements, Dest };
15999 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
16000 } else {
16001 // The logic is the reverse of what we need for WLS, so find the other
16002 // basic block target: the target of the proceeding br.
16003 UpdateUncondBr(Br, Dest, DAG);
16004
16005 SDValue Ops[] = { Chain, Elements, OtherTarget };
16006 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
16007 }
16008 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
16009 return Res;
16010 } else {
16011 SDValue Size = DAG.getTargetConstant(
16012 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
16013 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
16014 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
16015 DAG.getVTList(MVT::i32, MVT::Other), Args);
16016 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
16017
16018 // We expect this instruction to branch when the count is not zero.
16019 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
16020
16021 // Update the unconditional branch to target the loop preheader if we've
16022 // found the condition has been reversed.
16023 if (Target == OtherTarget)
16024 UpdateUncondBr(Br, Dest, DAG);
16025
16026 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16027 SDValue(LoopDec.getNode(), 1), Chain);
16028
16029 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
16030 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
16031 }
16032 return SDValue();
16033 }
16034
16035 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
16036 SDValue
PerformBRCONDCombine(SDNode * N,SelectionDAG & DAG) const16037 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
16038 SDValue Cmp = N->getOperand(4);
16039 if (Cmp.getOpcode() != ARMISD::CMPZ)
16040 // Only looking at NE cases.
16041 return SDValue();
16042
16043 EVT VT = N->getValueType(0);
16044 SDLoc dl(N);
16045 SDValue LHS = Cmp.getOperand(0);
16046 SDValue RHS = Cmp.getOperand(1);
16047 SDValue Chain = N->getOperand(0);
16048 SDValue BB = N->getOperand(1);
16049 SDValue ARMcc = N->getOperand(2);
16050 ARMCC::CondCodes CC =
16051 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
16052
16053 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
16054 // -> (brcond Chain BB CC CPSR Cmp)
16055 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
16056 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
16057 LHS->getOperand(0)->hasOneUse()) {
16058 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
16059 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
16060 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
16061 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
16062 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
16063 (LHS01C && LHS01C->getZExtValue() == 1) &&
16064 (LHS1C && LHS1C->getZExtValue() == 1) &&
16065 (RHSC && RHSC->getZExtValue() == 0)) {
16066 return DAG.getNode(
16067 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
16068 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
16069 }
16070 }
16071
16072 return SDValue();
16073 }
16074
16075 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
16076 SDValue
PerformCMOVCombine(SDNode * N,SelectionDAG & DAG) const16077 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
16078 SDValue Cmp = N->getOperand(4);
16079 if (Cmp.getOpcode() != ARMISD::CMPZ)
16080 // Only looking at EQ and NE cases.
16081 return SDValue();
16082
16083 EVT VT = N->getValueType(0);
16084 SDLoc dl(N);
16085 SDValue LHS = Cmp.getOperand(0);
16086 SDValue RHS = Cmp.getOperand(1);
16087 SDValue FalseVal = N->getOperand(0);
16088 SDValue TrueVal = N->getOperand(1);
16089 SDValue ARMcc = N->getOperand(2);
16090 ARMCC::CondCodes CC =
16091 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
16092
16093 // BFI is only available on V6T2+.
16094 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
16095 SDValue R = PerformCMOVToBFICombine(N, DAG);
16096 if (R)
16097 return R;
16098 }
16099
16100 // Simplify
16101 // mov r1, r0
16102 // cmp r1, x
16103 // mov r0, y
16104 // moveq r0, x
16105 // to
16106 // cmp r0, x
16107 // movne r0, y
16108 //
16109 // mov r1, r0
16110 // cmp r1, x
16111 // mov r0, x
16112 // movne r0, y
16113 // to
16114 // cmp r0, x
16115 // movne r0, y
16116 /// FIXME: Turn this into a target neutral optimization?
16117 SDValue Res;
16118 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
16119 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
16120 N->getOperand(3), Cmp);
16121 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
16122 SDValue ARMcc;
16123 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
16124 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
16125 N->getOperand(3), NewCmp);
16126 }
16127
16128 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
16129 // -> (cmov F T CC CPSR Cmp)
16130 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
16131 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
16132 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
16133 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
16134 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
16135 (LHS1C && LHS1C->getZExtValue() == 1) &&
16136 (RHSC && RHSC->getZExtValue() == 0)) {
16137 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
16138 LHS->getOperand(2), LHS->getOperand(3),
16139 LHS->getOperand(4));
16140 }
16141 }
16142
16143 if (!VT.isInteger())
16144 return SDValue();
16145
16146 // Materialize a boolean comparison for integers so we can avoid branching.
16147 if (isNullConstant(FalseVal)) {
16148 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
16149 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
16150 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
16151 // right 5 bits will make that 32 be 1, otherwise it will be 0.
16152 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
16153 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
16154 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
16155 DAG.getConstant(5, dl, MVT::i32));
16156 } else {
16157 // CMOV 0, 1, ==, (CMPZ x, y) ->
16158 // (ADDCARRY (SUB x, y), t:0, t:1)
16159 // where t = (SUBCARRY 0, (SUB x, y), 0)
16160 //
16161 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
16162 // x != y. In other words, a carry C == 1 when x == y, C == 0
16163 // otherwise.
16164 // The final ADDCARRY computes
16165 // x - y + (0 - (x - y)) + C == C
16166 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
16167 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16168 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
16169 // ISD::SUBCARRY returns a borrow but we want the carry here
16170 // actually.
16171 SDValue Carry =
16172 DAG.getNode(ISD::SUB, dl, MVT::i32,
16173 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
16174 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
16175 }
16176 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
16177 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
16178 // This seems pointless but will allow us to combine it further below.
16179 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
16180 SDValue Sub =
16181 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
16182 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
16183 Sub.getValue(1), SDValue());
16184 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
16185 N->getOperand(3), CPSRGlue.getValue(1));
16186 FalseVal = Sub;
16187 }
16188 } else if (isNullConstant(TrueVal)) {
16189 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
16190 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
16191 // This seems pointless but will allow us to combine it further below
16192 // Note that we change == for != as this is the dual for the case above.
16193 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
16194 SDValue Sub =
16195 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
16196 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
16197 Sub.getValue(1), SDValue());
16198 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
16199 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
16200 N->getOperand(3), CPSRGlue.getValue(1));
16201 FalseVal = Sub;
16202 }
16203 }
16204
16205 // On Thumb1, the DAG above may be further combined if z is a power of 2
16206 // (z == 2 ^ K).
16207 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
16208 // t1 = (USUBO (SUB x, y), 1)
16209 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
16210 // Result = if K != 0 then (SHL t2:0, K) else t2:0
16211 //
16212 // This also handles the special case of comparing against zero; it's
16213 // essentially, the same pattern, except there's no SUBS:
16214 // CMOV x, z, !=, (CMPZ x, 0) ->
16215 // t1 = (USUBO x, 1)
16216 // t2 = (SUBCARRY x, t1:0, t1:1)
16217 // Result = if K != 0 then (SHL t2:0, K) else t2:0
16218 const APInt *TrueConst;
16219 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
16220 ((FalseVal.getOpcode() == ARMISD::SUBS &&
16221 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
16222 (FalseVal == LHS && isNullConstant(RHS))) &&
16223 (TrueConst = isPowerOf2Constant(TrueVal))) {
16224 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16225 unsigned ShiftAmount = TrueConst->logBase2();
16226 if (ShiftAmount)
16227 TrueVal = DAG.getConstant(1, dl, VT);
16228 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
16229 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
16230
16231 if (ShiftAmount)
16232 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
16233 DAG.getConstant(ShiftAmount, dl, MVT::i32));
16234 }
16235
16236 if (Res.getNode()) {
16237 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
16238 // Capture demanded bits information that would be otherwise lost.
16239 if (Known.Zero == 0xfffffffe)
16240 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16241 DAG.getValueType(MVT::i1));
16242 else if (Known.Zero == 0xffffff00)
16243 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16244 DAG.getValueType(MVT::i8));
16245 else if (Known.Zero == 0xffff0000)
16246 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16247 DAG.getValueType(MVT::i16));
16248 }
16249
16250 return Res;
16251 }
16252
PerformBITCASTCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)16253 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
16254 const ARMSubtarget *ST) {
16255 SDValue Src = N->getOperand(0);
16256 EVT DstVT = N->getValueType(0);
16257
16258 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
16259 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
16260 EVT SrcVT = Src.getValueType();
16261 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
16262 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
16263 }
16264
16265 // We may have a bitcast of something that has already had this bitcast
16266 // combine performed on it, so skip past any VECTOR_REG_CASTs.
16267 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
16268 Src = Src.getOperand(0);
16269
16270 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
16271 // would be generated is at least the width of the element type.
16272 EVT SrcVT = Src.getValueType();
16273 if ((Src.getOpcode() == ARMISD::VMOVIMM ||
16274 Src.getOpcode() == ARMISD::VMVNIMM ||
16275 Src.getOpcode() == ARMISD::VMOVFPIMM) &&
16276 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
16277 DAG.getDataLayout().isBigEndian())
16278 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
16279
16280 return SDValue();
16281 }
16282
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const16283 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
16284 DAGCombinerInfo &DCI) const {
16285 switch (N->getOpcode()) {
16286 default: break;
16287 case ISD::SELECT_CC:
16288 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget);
16289 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget);
16290 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
16291 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
16292 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
16293 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
16294 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget);
16295 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
16296 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
16297 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
16298 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
16299 case ISD::BRCOND:
16300 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
16301 case ARMISD::ADDC:
16302 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
16303 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
16304 case ARMISD::BFI: return PerformBFICombine(N, DCI);
16305 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
16306 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
16307 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI);
16308 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI);
16309 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
16310 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
16311 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
16312 case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI);
16313 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
16314 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
16315 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
16316 case ISD::FP_TO_SINT:
16317 case ISD::FP_TO_UINT:
16318 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
16319 case ISD::FDIV:
16320 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
16321 case ISD::INTRINSIC_WO_CHAIN:
16322 return PerformIntrinsicCombine(N, DCI);
16323 case ISD::SHL:
16324 case ISD::SRA:
16325 case ISD::SRL:
16326 return PerformShiftCombine(N, DCI, Subtarget);
16327 case ISD::SIGN_EXTEND:
16328 case ISD::ZERO_EXTEND:
16329 case ISD::ANY_EXTEND:
16330 return PerformExtendCombine(N, DCI.DAG, Subtarget);
16331 case ISD::FP_EXTEND:
16332 return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
16333 case ISD::SMIN:
16334 case ISD::UMIN:
16335 case ISD::SMAX:
16336 case ISD::UMAX:
16337 return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
16338 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
16339 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
16340 case ISD::LOAD: return PerformLOADCombine(N, DCI);
16341 case ARMISD::VLD1DUP:
16342 case ARMISD::VLD2DUP:
16343 case ARMISD::VLD3DUP:
16344 case ARMISD::VLD4DUP:
16345 return PerformVLDCombine(N, DCI);
16346 case ARMISD::BUILD_VECTOR:
16347 return PerformARMBUILD_VECTORCombine(N, DCI);
16348 case ISD::BITCAST:
16349 return PerformBITCASTCombine(N, DCI.DAG, Subtarget);
16350 case ARMISD::PREDICATE_CAST:
16351 return PerformPREDICATE_CASTCombine(N, DCI);
16352 case ARMISD::VECTOR_REG_CAST:
16353 return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget);
16354 case ARMISD::VCMP:
16355 return PerformVCMPCombine(N, DCI, Subtarget);
16356 case ISD::VECREDUCE_ADD:
16357 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
16358 case ARMISD::VMOVN:
16359 return PerformVMOVNCombine(N, DCI);
16360 case ARMISD::VQMOVNs:
16361 case ARMISD::VQMOVNu:
16362 return PerformVQMOVNCombine(N, DCI);
16363 case ARMISD::ASRL:
16364 case ARMISD::LSRL:
16365 case ARMISD::LSLL:
16366 return PerformLongShiftCombine(N, DCI.DAG);
16367 case ARMISD::SMULWB: {
16368 unsigned BitWidth = N->getValueType(0).getSizeInBits();
16369 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
16370 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
16371 return SDValue();
16372 break;
16373 }
16374 case ARMISD::SMULWT: {
16375 unsigned BitWidth = N->getValueType(0).getSizeInBits();
16376 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
16377 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
16378 return SDValue();
16379 break;
16380 }
16381 case ARMISD::SMLALBB:
16382 case ARMISD::QADD16b:
16383 case ARMISD::QSUB16b: {
16384 unsigned BitWidth = N->getValueType(0).getSizeInBits();
16385 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
16386 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16387 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16388 return SDValue();
16389 break;
16390 }
16391 case ARMISD::SMLALBT: {
16392 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
16393 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
16394 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
16395 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
16396 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
16397 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
16398 return SDValue();
16399 break;
16400 }
16401 case ARMISD::SMLALTB: {
16402 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
16403 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
16404 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
16405 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
16406 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
16407 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
16408 return SDValue();
16409 break;
16410 }
16411 case ARMISD::SMLALTT: {
16412 unsigned BitWidth = N->getValueType(0).getSizeInBits();
16413 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
16414 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16415 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16416 return SDValue();
16417 break;
16418 }
16419 case ARMISD::QADD8b:
16420 case ARMISD::QSUB8b: {
16421 unsigned BitWidth = N->getValueType(0).getSizeInBits();
16422 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
16423 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16424 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16425 return SDValue();
16426 break;
16427 }
16428 case ISD::INTRINSIC_VOID:
16429 case ISD::INTRINSIC_W_CHAIN:
16430 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
16431 case Intrinsic::arm_neon_vld1:
16432 case Intrinsic::arm_neon_vld1x2:
16433 case Intrinsic::arm_neon_vld1x3:
16434 case Intrinsic::arm_neon_vld1x4:
16435 case Intrinsic::arm_neon_vld2:
16436 case Intrinsic::arm_neon_vld3:
16437 case Intrinsic::arm_neon_vld4:
16438 case Intrinsic::arm_neon_vld2lane:
16439 case Intrinsic::arm_neon_vld3lane:
16440 case Intrinsic::arm_neon_vld4lane:
16441 case Intrinsic::arm_neon_vld2dup:
16442 case Intrinsic::arm_neon_vld3dup:
16443 case Intrinsic::arm_neon_vld4dup:
16444 case Intrinsic::arm_neon_vst1:
16445 case Intrinsic::arm_neon_vst1x2:
16446 case Intrinsic::arm_neon_vst1x3:
16447 case Intrinsic::arm_neon_vst1x4:
16448 case Intrinsic::arm_neon_vst2:
16449 case Intrinsic::arm_neon_vst3:
16450 case Intrinsic::arm_neon_vst4:
16451 case Intrinsic::arm_neon_vst2lane:
16452 case Intrinsic::arm_neon_vst3lane:
16453 case Intrinsic::arm_neon_vst4lane:
16454 return PerformVLDCombine(N, DCI);
16455 case Intrinsic::arm_mve_vld2q:
16456 case Intrinsic::arm_mve_vld4q:
16457 case Intrinsic::arm_mve_vst2q:
16458 case Intrinsic::arm_mve_vst4q:
16459 return PerformMVEVLDCombine(N, DCI);
16460 default: break;
16461 }
16462 break;
16463 }
16464 return SDValue();
16465 }
16466
isDesirableToTransformToIntegerOp(unsigned Opc,EVT VT) const16467 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
16468 EVT VT) const {
16469 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
16470 }
16471
allowsMisalignedMemoryAccesses(EVT VT,unsigned,unsigned Alignment,MachineMemOperand::Flags,bool * Fast) const16472 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
16473 unsigned Alignment,
16474 MachineMemOperand::Flags,
16475 bool *Fast) const {
16476 // Depends what it gets converted into if the type is weird.
16477 if (!VT.isSimple())
16478 return false;
16479
16480 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
16481 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
16482 auto Ty = VT.getSimpleVT().SimpleTy;
16483
16484 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
16485 // Unaligned access can use (for example) LRDB, LRDH, LDR
16486 if (AllowsUnaligned) {
16487 if (Fast)
16488 *Fast = Subtarget->hasV7Ops();
16489 return true;
16490 }
16491 }
16492
16493 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
16494 // For any little-endian targets with neon, we can support unaligned ld/st
16495 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
16496 // A big-endian target may also explicitly support unaligned accesses
16497 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
16498 if (Fast)
16499 *Fast = true;
16500 return true;
16501 }
16502 }
16503
16504 if (!Subtarget->hasMVEIntegerOps())
16505 return false;
16506
16507 // These are for predicates
16508 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
16509 if (Fast)
16510 *Fast = true;
16511 return true;
16512 }
16513
16514 // These are for truncated stores/narrowing loads. They are fine so long as
16515 // the alignment is at least the size of the item being loaded
16516 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
16517 Alignment >= VT.getScalarSizeInBits() / 8) {
16518 if (Fast)
16519 *Fast = true;
16520 return true;
16521 }
16522
16523 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
16524 // VSTRW.U32 all store the vector register in exactly the same format, and
16525 // differ only in the range of their immediate offset field and the required
16526 // alignment. So there is always a store that can be used, regardless of
16527 // actual type.
16528 //
16529 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
16530 // VREV64.8) pair and get the same effect. This will likely be better than
16531 // aligning the vector through the stack.
16532 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
16533 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
16534 Ty == MVT::v2f64) {
16535 if (Fast)
16536 *Fast = true;
16537 return true;
16538 }
16539
16540 return false;
16541 }
16542
16543
getOptimalMemOpType(const MemOp & Op,const AttributeList & FuncAttributes) const16544 EVT ARMTargetLowering::getOptimalMemOpType(
16545 const MemOp &Op, const AttributeList &FuncAttributes) const {
16546 // See if we can use NEON instructions for this...
16547 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
16548 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
16549 bool Fast;
16550 if (Op.size() >= 16 &&
16551 (Op.isAligned(Align(16)) ||
16552 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
16553 MachineMemOperand::MONone, &Fast) &&
16554 Fast))) {
16555 return MVT::v2f64;
16556 } else if (Op.size() >= 8 &&
16557 (Op.isAligned(Align(8)) ||
16558 (allowsMisalignedMemoryAccesses(
16559 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
16560 Fast))) {
16561 return MVT::f64;
16562 }
16563 }
16564
16565 // Let the target-independent logic figure it out.
16566 return MVT::Other;
16567 }
16568
16569 // 64-bit integers are split into their high and low parts and held in two
16570 // different registers, so the trunc is free since the low register can just
16571 // be used.
isTruncateFree(Type * SrcTy,Type * DstTy) const16572 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
16573 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
16574 return false;
16575 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
16576 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
16577 return (SrcBits == 64 && DestBits == 32);
16578 }
16579
isTruncateFree(EVT SrcVT,EVT DstVT) const16580 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
16581 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
16582 !DstVT.isInteger())
16583 return false;
16584 unsigned SrcBits = SrcVT.getSizeInBits();
16585 unsigned DestBits = DstVT.getSizeInBits();
16586 return (SrcBits == 64 && DestBits == 32);
16587 }
16588
isZExtFree(SDValue Val,EVT VT2) const16589 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16590 if (Val.getOpcode() != ISD::LOAD)
16591 return false;
16592
16593 EVT VT1 = Val.getValueType();
16594 if (!VT1.isSimple() || !VT1.isInteger() ||
16595 !VT2.isSimple() || !VT2.isInteger())
16596 return false;
16597
16598 switch (VT1.getSimpleVT().SimpleTy) {
16599 default: break;
16600 case MVT::i1:
16601 case MVT::i8:
16602 case MVT::i16:
16603 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
16604 return true;
16605 }
16606
16607 return false;
16608 }
16609
isFNegFree(EVT VT) const16610 bool ARMTargetLowering::isFNegFree(EVT VT) const {
16611 if (!VT.isSimple())
16612 return false;
16613
16614 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
16615 // negate values directly (fneg is free). So, we don't want to let the DAG
16616 // combiner rewrite fneg into xors and some other instructions. For f16 and
16617 // FullFP16 argument passing, some bitcast nodes may be introduced,
16618 // triggering this DAG combine rewrite, so we are avoiding that with this.
16619 switch (VT.getSimpleVT().SimpleTy) {
16620 default: break;
16621 case MVT::f16:
16622 return Subtarget->hasFullFP16();
16623 }
16624
16625 return false;
16626 }
16627
16628 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
16629 /// of the vector elements.
areExtractExts(Value * Ext1,Value * Ext2)16630 static bool areExtractExts(Value *Ext1, Value *Ext2) {
16631 auto areExtDoubled = [](Instruction *Ext) {
16632 return Ext->getType()->getScalarSizeInBits() ==
16633 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
16634 };
16635
16636 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
16637 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
16638 !areExtDoubled(cast<Instruction>(Ext1)) ||
16639 !areExtDoubled(cast<Instruction>(Ext2)))
16640 return false;
16641
16642 return true;
16643 }
16644
16645 /// Check if sinking \p I's operands to I's basic block is profitable, because
16646 /// the operands can be folded into a target instruction, e.g.
16647 /// sext/zext can be folded into vsubl.
shouldSinkOperands(Instruction * I,SmallVectorImpl<Use * > & Ops) const16648 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
16649 SmallVectorImpl<Use *> &Ops) const {
16650 if (!I->getType()->isVectorTy())
16651 return false;
16652
16653 if (Subtarget->hasNEON()) {
16654 switch (I->getOpcode()) {
16655 case Instruction::Sub:
16656 case Instruction::Add: {
16657 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
16658 return false;
16659 Ops.push_back(&I->getOperandUse(0));
16660 Ops.push_back(&I->getOperandUse(1));
16661 return true;
16662 }
16663 default:
16664 return false;
16665 }
16666 }
16667
16668 if (!Subtarget->hasMVEIntegerOps())
16669 return false;
16670
16671 auto IsFMSMul = [&](Instruction *I) {
16672 if (!I->hasOneUse())
16673 return false;
16674 auto *Sub = cast<Instruction>(*I->users().begin());
16675 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
16676 };
16677 auto IsFMS = [&](Instruction *I) {
16678 if (match(I->getOperand(0), m_FNeg(m_Value())) ||
16679 match(I->getOperand(1), m_FNeg(m_Value())))
16680 return true;
16681 return false;
16682 };
16683
16684 auto IsSinker = [&](Instruction *I, int Operand) {
16685 switch (I->getOpcode()) {
16686 case Instruction::Add:
16687 case Instruction::Mul:
16688 case Instruction::FAdd:
16689 case Instruction::ICmp:
16690 case Instruction::FCmp:
16691 return true;
16692 case Instruction::FMul:
16693 return !IsFMSMul(I);
16694 case Instruction::Sub:
16695 case Instruction::FSub:
16696 case Instruction::Shl:
16697 case Instruction::LShr:
16698 case Instruction::AShr:
16699 return Operand == 1;
16700 case Instruction::Call:
16701 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
16702 switch (II->getIntrinsicID()) {
16703 case Intrinsic::fma:
16704 return !IsFMS(I);
16705 case Intrinsic::arm_mve_add_predicated:
16706 case Intrinsic::arm_mve_mul_predicated:
16707 case Intrinsic::arm_mve_qadd_predicated:
16708 case Intrinsic::arm_mve_hadd_predicated:
16709 case Intrinsic::arm_mve_vqdmull_predicated:
16710 case Intrinsic::arm_mve_qdmulh_predicated:
16711 case Intrinsic::arm_mve_qrdmulh_predicated:
16712 case Intrinsic::arm_mve_fma_predicated:
16713 return true;
16714 case Intrinsic::arm_mve_sub_predicated:
16715 case Intrinsic::arm_mve_qsub_predicated:
16716 case Intrinsic::arm_mve_hsub_predicated:
16717 return Operand == 1;
16718 default:
16719 return false;
16720 }
16721 }
16722 return false;
16723 default:
16724 return false;
16725 }
16726 };
16727
16728 for (auto OpIdx : enumerate(I->operands())) {
16729 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
16730 // Make sure we are not already sinking this operand
16731 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
16732 continue;
16733
16734 Instruction *Shuffle = Op;
16735 if (Shuffle->getOpcode() == Instruction::BitCast)
16736 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
16737 // We are looking for a splat that can be sunk.
16738 if (!Shuffle ||
16739 !match(Shuffle, m_Shuffle(
16740 m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
16741 m_Undef(), m_ZeroMask())))
16742 continue;
16743 if (!IsSinker(I, OpIdx.index()))
16744 continue;
16745
16746 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
16747 // and vector registers
16748 for (Use &U : Op->uses()) {
16749 Instruction *Insn = cast<Instruction>(U.getUser());
16750 if (!IsSinker(Insn, U.getOperandNo()))
16751 return false;
16752 }
16753
16754 Ops.push_back(&Shuffle->getOperandUse(0));
16755 if (Shuffle != Op)
16756 Ops.push_back(&Op->getOperandUse(0));
16757 Ops.push_back(&OpIdx.value());
16758 }
16759 return true;
16760 }
16761
shouldConvertSplatType(ShuffleVectorInst * SVI) const16762 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
16763 if (!Subtarget->hasMVEIntegerOps())
16764 return nullptr;
16765 Type *SVIType = SVI->getType();
16766 Type *ScalarType = SVIType->getScalarType();
16767
16768 if (ScalarType->isFloatTy())
16769 return Type::getInt32Ty(SVIType->getContext());
16770 if (ScalarType->isHalfTy())
16771 return Type::getInt16Ty(SVIType->getContext());
16772 return nullptr;
16773 }
16774
isVectorLoadExtDesirable(SDValue ExtVal) const16775 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
16776 EVT VT = ExtVal.getValueType();
16777
16778 if (!isTypeLegal(VT))
16779 return false;
16780
16781 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
16782 if (Ld->isExpandingLoad())
16783 return false;
16784 }
16785
16786 if (Subtarget->hasMVEIntegerOps())
16787 return true;
16788
16789 // Don't create a loadext if we can fold the extension into a wide/long
16790 // instruction.
16791 // If there's more than one user instruction, the loadext is desirable no
16792 // matter what. There can be two uses by the same instruction.
16793 if (ExtVal->use_empty() ||
16794 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
16795 return true;
16796
16797 SDNode *U = *ExtVal->use_begin();
16798 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
16799 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
16800 return false;
16801
16802 return true;
16803 }
16804
allowTruncateForTailCall(Type * Ty1,Type * Ty2) const16805 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16806 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16807 return false;
16808
16809 if (!isTypeLegal(EVT::getEVT(Ty1)))
16810 return false;
16811
16812 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16813
16814 // Assuming the caller doesn't have a zeroext or signext return parameter,
16815 // truncation all the way down to i1 is valid.
16816 return true;
16817 }
16818
getScalingFactorCost(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS) const16819 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
16820 const AddrMode &AM, Type *Ty,
16821 unsigned AS) const {
16822 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
16823 if (Subtarget->hasFPAO())
16824 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
16825 return 0;
16826 }
16827 return -1;
16828 }
16829
16830 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
16831 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
16832 /// expanded to FMAs when this method returns true, otherwise fmuladd is
16833 /// expanded to fmul + fadd.
16834 ///
16835 /// ARM supports both fused and unfused multiply-add operations; we already
16836 /// lower a pair of fmul and fadd to the latter so it's not clear that there
16837 /// would be a gain or that the gain would be worthwhile enough to risk
16838 /// correctness bugs.
16839 ///
16840 /// For MVE, we set this to true as it helps simplify the need for some
16841 /// patterns (and we don't have the non-fused floating point instruction).
isFMAFasterThanFMulAndFAdd(const MachineFunction & MF,EVT VT) const16842 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16843 EVT VT) const {
16844 if (!VT.isSimple())
16845 return false;
16846
16847 switch (VT.getSimpleVT().SimpleTy) {
16848 case MVT::v4f32:
16849 case MVT::v8f16:
16850 return Subtarget->hasMVEFloatOps();
16851 case MVT::f16:
16852 return Subtarget->useFPVFMx16();
16853 case MVT::f32:
16854 return Subtarget->useFPVFMx();
16855 case MVT::f64:
16856 return Subtarget->useFPVFMx64();
16857 default:
16858 break;
16859 }
16860
16861 return false;
16862 }
16863
isLegalT1AddressImmediate(int64_t V,EVT VT)16864 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
16865 if (V < 0)
16866 return false;
16867
16868 unsigned Scale = 1;
16869 switch (VT.getSimpleVT().SimpleTy) {
16870 case MVT::i1:
16871 case MVT::i8:
16872 // Scale == 1;
16873 break;
16874 case MVT::i16:
16875 // Scale == 2;
16876 Scale = 2;
16877 break;
16878 default:
16879 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
16880 // Scale == 4;
16881 Scale = 4;
16882 break;
16883 }
16884
16885 if ((V & (Scale - 1)) != 0)
16886 return false;
16887 return isUInt<5>(V / Scale);
16888 }
16889
isLegalT2AddressImmediate(int64_t V,EVT VT,const ARMSubtarget * Subtarget)16890 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
16891 const ARMSubtarget *Subtarget) {
16892 if (!VT.isInteger() && !VT.isFloatingPoint())
16893 return false;
16894 if (VT.isVector() && Subtarget->hasNEON())
16895 return false;
16896 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
16897 !Subtarget->hasMVEFloatOps())
16898 return false;
16899
16900 bool IsNeg = false;
16901 if (V < 0) {
16902 IsNeg = true;
16903 V = -V;
16904 }
16905
16906 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
16907
16908 // MVE: size * imm7
16909 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
16910 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
16911 case MVT::i32:
16912 case MVT::f32:
16913 return isShiftedUInt<7,2>(V);
16914 case MVT::i16:
16915 case MVT::f16:
16916 return isShiftedUInt<7,1>(V);
16917 case MVT::i8:
16918 return isUInt<7>(V);
16919 default:
16920 return false;
16921 }
16922 }
16923
16924 // half VLDR: 2 * imm8
16925 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
16926 return isShiftedUInt<8, 1>(V);
16927 // VLDR and LDRD: 4 * imm8
16928 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
16929 return isShiftedUInt<8, 2>(V);
16930
16931 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
16932 // + imm12 or - imm8
16933 if (IsNeg)
16934 return isUInt<8>(V);
16935 return isUInt<12>(V);
16936 }
16937
16938 return false;
16939 }
16940
16941 /// isLegalAddressImmediate - Return true if the integer value can be used
16942 /// as the offset of the target addressing mode for load / store of the
16943 /// given type.
isLegalAddressImmediate(int64_t V,EVT VT,const ARMSubtarget * Subtarget)16944 static bool isLegalAddressImmediate(int64_t V, EVT VT,
16945 const ARMSubtarget *Subtarget) {
16946 if (V == 0)
16947 return true;
16948
16949 if (!VT.isSimple())
16950 return false;
16951
16952 if (Subtarget->isThumb1Only())
16953 return isLegalT1AddressImmediate(V, VT);
16954 else if (Subtarget->isThumb2())
16955 return isLegalT2AddressImmediate(V, VT, Subtarget);
16956
16957 // ARM mode.
16958 if (V < 0)
16959 V = - V;
16960 switch (VT.getSimpleVT().SimpleTy) {
16961 default: return false;
16962 case MVT::i1:
16963 case MVT::i8:
16964 case MVT::i32:
16965 // +- imm12
16966 return isUInt<12>(V);
16967 case MVT::i16:
16968 // +- imm8
16969 return isUInt<8>(V);
16970 case MVT::f32:
16971 case MVT::f64:
16972 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
16973 return false;
16974 return isShiftedUInt<8, 2>(V);
16975 }
16976 }
16977
isLegalT2ScaledAddressingMode(const AddrMode & AM,EVT VT) const16978 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
16979 EVT VT) const {
16980 int Scale = AM.Scale;
16981 if (Scale < 0)
16982 return false;
16983
16984 switch (VT.getSimpleVT().SimpleTy) {
16985 default: return false;
16986 case MVT::i1:
16987 case MVT::i8:
16988 case MVT::i16:
16989 case MVT::i32:
16990 if (Scale == 1)
16991 return true;
16992 // r + r << imm
16993 Scale = Scale & ~1;
16994 return Scale == 2 || Scale == 4 || Scale == 8;
16995 case MVT::i64:
16996 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
16997 // version in Thumb mode.
16998 // r + r
16999 if (Scale == 1)
17000 return true;
17001 // r * 2 (this can be lowered to r + r).
17002 if (!AM.HasBaseReg && Scale == 2)
17003 return true;
17004 return false;
17005 case MVT::isVoid:
17006 // Note, we allow "void" uses (basically, uses that aren't loads or
17007 // stores), because arm allows folding a scale into many arithmetic
17008 // operations. This should be made more precise and revisited later.
17009
17010 // Allow r << imm, but the imm has to be a multiple of two.
17011 if (Scale & 1) return false;
17012 return isPowerOf2_32(Scale);
17013 }
17014 }
17015
isLegalT1ScaledAddressingMode(const AddrMode & AM,EVT VT) const17016 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
17017 EVT VT) const {
17018 const int Scale = AM.Scale;
17019
17020 // Negative scales are not supported in Thumb1.
17021 if (Scale < 0)
17022 return false;
17023
17024 // Thumb1 addressing modes do not support register scaling excepting the
17025 // following cases:
17026 // 1. Scale == 1 means no scaling.
17027 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
17028 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
17029 }
17030
17031 /// isLegalAddressingMode - Return true if the addressing mode represented
17032 /// by AM is legal for this target, for a load/store of the specified type.
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const17033 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
17034 const AddrMode &AM, Type *Ty,
17035 unsigned AS, Instruction *I) const {
17036 EVT VT = getValueType(DL, Ty, true);
17037 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
17038 return false;
17039
17040 // Can never fold addr of global into load/store.
17041 if (AM.BaseGV)
17042 return false;
17043
17044 switch (AM.Scale) {
17045 case 0: // no scale reg, must be "r+i" or "r", or "i".
17046 break;
17047 default:
17048 // ARM doesn't support any R+R*scale+imm addr modes.
17049 if (AM.BaseOffs)
17050 return false;
17051
17052 if (!VT.isSimple())
17053 return false;
17054
17055 if (Subtarget->isThumb1Only())
17056 return isLegalT1ScaledAddressingMode(AM, VT);
17057
17058 if (Subtarget->isThumb2())
17059 return isLegalT2ScaledAddressingMode(AM, VT);
17060
17061 int Scale = AM.Scale;
17062 switch (VT.getSimpleVT().SimpleTy) {
17063 default: return false;
17064 case MVT::i1:
17065 case MVT::i8:
17066 case MVT::i32:
17067 if (Scale < 0) Scale = -Scale;
17068 if (Scale == 1)
17069 return true;
17070 // r + r << imm
17071 return isPowerOf2_32(Scale & ~1);
17072 case MVT::i16:
17073 case MVT::i64:
17074 // r +/- r
17075 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
17076 return true;
17077 // r * 2 (this can be lowered to r + r).
17078 if (!AM.HasBaseReg && Scale == 2)
17079 return true;
17080 return false;
17081
17082 case MVT::isVoid:
17083 // Note, we allow "void" uses (basically, uses that aren't loads or
17084 // stores), because arm allows folding a scale into many arithmetic
17085 // operations. This should be made more precise and revisited later.
17086
17087 // Allow r << imm, but the imm has to be a multiple of two.
17088 if (Scale & 1) return false;
17089 return isPowerOf2_32(Scale);
17090 }
17091 }
17092 return true;
17093 }
17094
17095 /// isLegalICmpImmediate - Return true if the specified immediate is legal
17096 /// icmp immediate, that is the target has icmp instructions which can compare
17097 /// a register against the immediate without having to materialize the
17098 /// immediate into a register.
isLegalICmpImmediate(int64_t Imm) const17099 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17100 // Thumb2 and ARM modes can use cmn for negative immediates.
17101 if (!Subtarget->isThumb())
17102 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
17103 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
17104 if (Subtarget->isThumb2())
17105 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
17106 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
17107 // Thumb1 doesn't have cmn, and only 8-bit immediates.
17108 return Imm >= 0 && Imm <= 255;
17109 }
17110
17111 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
17112 /// *or sub* immediate, that is the target has add or sub instructions which can
17113 /// add a register with the immediate without having to materialize the
17114 /// immediate into a register.
isLegalAddImmediate(int64_t Imm) const17115 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
17116 // Same encoding for add/sub, just flip the sign.
17117 int64_t AbsImm = std::abs(Imm);
17118 if (!Subtarget->isThumb())
17119 return ARM_AM::getSOImmVal(AbsImm) != -1;
17120 if (Subtarget->isThumb2())
17121 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
17122 // Thumb1 only has 8-bit unsigned immediate.
17123 return AbsImm >= 0 && AbsImm <= 255;
17124 }
17125
getARMIndexedAddressParts(SDNode * Ptr,EVT VT,bool isSEXTLoad,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)17126 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
17127 bool isSEXTLoad, SDValue &Base,
17128 SDValue &Offset, bool &isInc,
17129 SelectionDAG &DAG) {
17130 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
17131 return false;
17132
17133 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
17134 // AddressingMode 3
17135 Base = Ptr->getOperand(0);
17136 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
17137 int RHSC = (int)RHS->getZExtValue();
17138 if (RHSC < 0 && RHSC > -256) {
17139 assert(Ptr->getOpcode() == ISD::ADD);
17140 isInc = false;
17141 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17142 return true;
17143 }
17144 }
17145 isInc = (Ptr->getOpcode() == ISD::ADD);
17146 Offset = Ptr->getOperand(1);
17147 return true;
17148 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
17149 // AddressingMode 2
17150 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
17151 int RHSC = (int)RHS->getZExtValue();
17152 if (RHSC < 0 && RHSC > -0x1000) {
17153 assert(Ptr->getOpcode() == ISD::ADD);
17154 isInc = false;
17155 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17156 Base = Ptr->getOperand(0);
17157 return true;
17158 }
17159 }
17160
17161 if (Ptr->getOpcode() == ISD::ADD) {
17162 isInc = true;
17163 ARM_AM::ShiftOpc ShOpcVal=
17164 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
17165 if (ShOpcVal != ARM_AM::no_shift) {
17166 Base = Ptr->getOperand(1);
17167 Offset = Ptr->getOperand(0);
17168 } else {
17169 Base = Ptr->getOperand(0);
17170 Offset = Ptr->getOperand(1);
17171 }
17172 return true;
17173 }
17174
17175 isInc = (Ptr->getOpcode() == ISD::ADD);
17176 Base = Ptr->getOperand(0);
17177 Offset = Ptr->getOperand(1);
17178 return true;
17179 }
17180
17181 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
17182 return false;
17183 }
17184
getT2IndexedAddressParts(SDNode * Ptr,EVT VT,bool isSEXTLoad,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)17185 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
17186 bool isSEXTLoad, SDValue &Base,
17187 SDValue &Offset, bool &isInc,
17188 SelectionDAG &DAG) {
17189 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
17190 return false;
17191
17192 Base = Ptr->getOperand(0);
17193 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
17194 int RHSC = (int)RHS->getZExtValue();
17195 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
17196 assert(Ptr->getOpcode() == ISD::ADD);
17197 isInc = false;
17198 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17199 return true;
17200 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
17201 isInc = Ptr->getOpcode() == ISD::ADD;
17202 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
17203 return true;
17204 }
17205 }
17206
17207 return false;
17208 }
17209
getMVEIndexedAddressParts(SDNode * Ptr,EVT VT,Align Alignment,bool isSEXTLoad,bool IsMasked,bool isLE,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)17210 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
17211 bool isSEXTLoad, bool IsMasked, bool isLE,
17212 SDValue &Base, SDValue &Offset,
17213 bool &isInc, SelectionDAG &DAG) {
17214 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
17215 return false;
17216 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
17217 return false;
17218
17219 // We allow LE non-masked loads to change the type (for example use a vldrb.8
17220 // as opposed to a vldrw.32). This can allow extra addressing modes or
17221 // alignments for what is otherwise an equivalent instruction.
17222 bool CanChangeType = isLE && !IsMasked;
17223
17224 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
17225 int RHSC = (int)RHS->getZExtValue();
17226
17227 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
17228 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
17229 assert(Ptr->getOpcode() == ISD::ADD);
17230 isInc = false;
17231 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17232 return true;
17233 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
17234 isInc = Ptr->getOpcode() == ISD::ADD;
17235 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
17236 return true;
17237 }
17238 return false;
17239 };
17240
17241 // Try to find a matching instruction based on s/zext, Alignment, Offset and
17242 // (in BE/masked) type.
17243 Base = Ptr->getOperand(0);
17244 if (VT == MVT::v4i16) {
17245 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
17246 return true;
17247 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
17248 if (IsInRange(RHSC, 0x80, 1))
17249 return true;
17250 } else if (Alignment >= 4 &&
17251 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
17252 IsInRange(RHSC, 0x80, 4))
17253 return true;
17254 else if (Alignment >= 2 &&
17255 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
17256 IsInRange(RHSC, 0x80, 2))
17257 return true;
17258 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
17259 return true;
17260 return false;
17261 }
17262
17263 /// getPreIndexedAddressParts - returns true by value, base pointer and
17264 /// offset pointer and addressing mode by reference if the node's address
17265 /// can be legally represented as pre-indexed load / store address.
17266 bool
getPreIndexedAddressParts(SDNode * N,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const17267 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
17268 SDValue &Offset,
17269 ISD::MemIndexedMode &AM,
17270 SelectionDAG &DAG) const {
17271 if (Subtarget->isThumb1Only())
17272 return false;
17273
17274 EVT VT;
17275 SDValue Ptr;
17276 Align Alignment;
17277 bool isSEXTLoad = false;
17278 bool IsMasked = false;
17279 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17280 Ptr = LD->getBasePtr();
17281 VT = LD->getMemoryVT();
17282 Alignment = LD->getAlign();
17283 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17284 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17285 Ptr = ST->getBasePtr();
17286 VT = ST->getMemoryVT();
17287 Alignment = ST->getAlign();
17288 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
17289 Ptr = LD->getBasePtr();
17290 VT = LD->getMemoryVT();
17291 Alignment = LD->getAlign();
17292 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17293 IsMasked = true;
17294 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
17295 Ptr = ST->getBasePtr();
17296 VT = ST->getMemoryVT();
17297 Alignment = ST->getAlign();
17298 IsMasked = true;
17299 } else
17300 return false;
17301
17302 bool isInc;
17303 bool isLegal = false;
17304 if (VT.isVector())
17305 isLegal = Subtarget->hasMVEIntegerOps() &&
17306 getMVEIndexedAddressParts(
17307 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
17308 Subtarget->isLittle(), Base, Offset, isInc, DAG);
17309 else {
17310 if (Subtarget->isThumb2())
17311 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
17312 Offset, isInc, DAG);
17313 else
17314 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
17315 Offset, isInc, DAG);
17316 }
17317 if (!isLegal)
17318 return false;
17319
17320 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
17321 return true;
17322 }
17323
17324 /// getPostIndexedAddressParts - returns true by value, base pointer and
17325 /// offset pointer and addressing mode by reference if this node can be
17326 /// 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) const17327 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
17328 SDValue &Base,
17329 SDValue &Offset,
17330 ISD::MemIndexedMode &AM,
17331 SelectionDAG &DAG) const {
17332 EVT VT;
17333 SDValue Ptr;
17334 Align Alignment;
17335 bool isSEXTLoad = false, isNonExt;
17336 bool IsMasked = false;
17337 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17338 VT = LD->getMemoryVT();
17339 Ptr = LD->getBasePtr();
17340 Alignment = LD->getAlign();
17341 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17342 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
17343 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17344 VT = ST->getMemoryVT();
17345 Ptr = ST->getBasePtr();
17346 Alignment = ST->getAlign();
17347 isNonExt = !ST->isTruncatingStore();
17348 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
17349 VT = LD->getMemoryVT();
17350 Ptr = LD->getBasePtr();
17351 Alignment = LD->getAlign();
17352 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17353 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
17354 IsMasked = true;
17355 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
17356 VT = ST->getMemoryVT();
17357 Ptr = ST->getBasePtr();
17358 Alignment = ST->getAlign();
17359 isNonExt = !ST->isTruncatingStore();
17360 IsMasked = true;
17361 } else
17362 return false;
17363
17364 if (Subtarget->isThumb1Only()) {
17365 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
17366 // must be non-extending/truncating, i32, with an offset of 4.
17367 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
17368 if (Op->getOpcode() != ISD::ADD || !isNonExt)
17369 return false;
17370 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
17371 if (!RHS || RHS->getZExtValue() != 4)
17372 return false;
17373
17374 Offset = Op->getOperand(1);
17375 Base = Op->getOperand(0);
17376 AM = ISD::POST_INC;
17377 return true;
17378 }
17379
17380 bool isInc;
17381 bool isLegal = false;
17382 if (VT.isVector())
17383 isLegal = Subtarget->hasMVEIntegerOps() &&
17384 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
17385 Subtarget->isLittle(), Base, Offset,
17386 isInc, DAG);
17387 else {
17388 if (Subtarget->isThumb2())
17389 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
17390 isInc, DAG);
17391 else
17392 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
17393 isInc, DAG);
17394 }
17395 if (!isLegal)
17396 return false;
17397
17398 if (Ptr != Base) {
17399 // Swap base ptr and offset to catch more post-index load / store when
17400 // it's legal. In Thumb2 mode, offset must be an immediate.
17401 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
17402 !Subtarget->isThumb2())
17403 std::swap(Base, Offset);
17404
17405 // Post-indexed load / store update the base pointer.
17406 if (Ptr != Base)
17407 return false;
17408 }
17409
17410 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
17411 return true;
17412 }
17413
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const17414 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17415 KnownBits &Known,
17416 const APInt &DemandedElts,
17417 const SelectionDAG &DAG,
17418 unsigned Depth) const {
17419 unsigned BitWidth = Known.getBitWidth();
17420 Known.resetAll();
17421 switch (Op.getOpcode()) {
17422 default: break;
17423 case ARMISD::ADDC:
17424 case ARMISD::ADDE:
17425 case ARMISD::SUBC:
17426 case ARMISD::SUBE:
17427 // Special cases when we convert a carry to a boolean.
17428 if (Op.getResNo() == 0) {
17429 SDValue LHS = Op.getOperand(0);
17430 SDValue RHS = Op.getOperand(1);
17431 // (ADDE 0, 0, C) will give us a single bit.
17432 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
17433 isNullConstant(RHS)) {
17434 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17435 return;
17436 }
17437 }
17438 break;
17439 case ARMISD::CMOV: {
17440 // Bits are known zero/one if known on the LHS and RHS.
17441 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
17442 if (Known.isUnknown())
17443 return;
17444
17445 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
17446 Known = KnownBits::commonBits(Known, KnownRHS);
17447 return;
17448 }
17449 case ISD::INTRINSIC_W_CHAIN: {
17450 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
17451 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
17452 switch (IntID) {
17453 default: return;
17454 case Intrinsic::arm_ldaex:
17455 case Intrinsic::arm_ldrex: {
17456 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
17457 unsigned MemBits = VT.getScalarSizeInBits();
17458 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
17459 return;
17460 }
17461 }
17462 }
17463 case ARMISD::BFI: {
17464 // Conservatively, we can recurse down the first operand
17465 // and just mask out all affected bits.
17466 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
17467
17468 // The operand to BFI is already a mask suitable for removing the bits it
17469 // sets.
17470 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
17471 const APInt &Mask = CI->getAPIntValue();
17472 Known.Zero &= Mask;
17473 Known.One &= Mask;
17474 return;
17475 }
17476 case ARMISD::VGETLANEs:
17477 case ARMISD::VGETLANEu: {
17478 const SDValue &SrcSV = Op.getOperand(0);
17479 EVT VecVT = SrcSV.getValueType();
17480 assert(VecVT.isVector() && "VGETLANE expected a vector type");
17481 const unsigned NumSrcElts = VecVT.getVectorNumElements();
17482 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
17483 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
17484 "VGETLANE index out of bounds");
17485 unsigned Idx = Pos->getZExtValue();
17486 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
17487 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
17488
17489 EVT VT = Op.getValueType();
17490 const unsigned DstSz = VT.getScalarSizeInBits();
17491 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
17492 (void)SrcSz;
17493 assert(SrcSz == Known.getBitWidth());
17494 assert(DstSz > SrcSz);
17495 if (Op.getOpcode() == ARMISD::VGETLANEs)
17496 Known = Known.sext(DstSz);
17497 else {
17498 Known = Known.zext(DstSz);
17499 }
17500 assert(DstSz == Known.getBitWidth());
17501 break;
17502 }
17503 case ARMISD::VMOVrh: {
17504 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
17505 assert(KnownOp.getBitWidth() == 16);
17506 Known = KnownOp.zext(32);
17507 break;
17508 }
17509 }
17510 }
17511
targetShrinkDemandedConstant(SDValue Op,const APInt & DemandedBits,const APInt & DemandedElts,TargetLoweringOpt & TLO) const17512 bool ARMTargetLowering::targetShrinkDemandedConstant(
17513 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
17514 TargetLoweringOpt &TLO) const {
17515 // Delay optimization, so we don't have to deal with illegal types, or block
17516 // optimizations.
17517 if (!TLO.LegalOps)
17518 return false;
17519
17520 // Only optimize AND for now.
17521 if (Op.getOpcode() != ISD::AND)
17522 return false;
17523
17524 EVT VT = Op.getValueType();
17525
17526 // Ignore vectors.
17527 if (VT.isVector())
17528 return false;
17529
17530 assert(VT == MVT::i32 && "Unexpected integer type");
17531
17532 // Make sure the RHS really is a constant.
17533 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
17534 if (!C)
17535 return false;
17536
17537 unsigned Mask = C->getZExtValue();
17538
17539 unsigned Demanded = DemandedBits.getZExtValue();
17540 unsigned ShrunkMask = Mask & Demanded;
17541 unsigned ExpandedMask = Mask | ~Demanded;
17542
17543 // If the mask is all zeros, let the target-independent code replace the
17544 // result with zero.
17545 if (ShrunkMask == 0)
17546 return false;
17547
17548 // If the mask is all ones, erase the AND. (Currently, the target-independent
17549 // code won't do this, so we have to do it explicitly to avoid an infinite
17550 // loop in obscure cases.)
17551 if (ExpandedMask == ~0U)
17552 return TLO.CombineTo(Op, Op.getOperand(0));
17553
17554 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
17555 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
17556 };
17557 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
17558 if (NewMask == Mask)
17559 return true;
17560 SDLoc DL(Op);
17561 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
17562 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
17563 return TLO.CombineTo(Op, NewOp);
17564 };
17565
17566 // Prefer uxtb mask.
17567 if (IsLegalMask(0xFF))
17568 return UseMask(0xFF);
17569
17570 // Prefer uxth mask.
17571 if (IsLegalMask(0xFFFF))
17572 return UseMask(0xFFFF);
17573
17574 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
17575 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
17576 if (ShrunkMask < 256)
17577 return UseMask(ShrunkMask);
17578
17579 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
17580 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
17581 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
17582 return UseMask(ExpandedMask);
17583
17584 // Potential improvements:
17585 //
17586 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
17587 // We could try to prefer Thumb1 immediates which can be lowered to a
17588 // two-instruction sequence.
17589 // We could try to recognize more legal ARM/Thumb2 immediates here.
17590
17591 return false;
17592 }
17593
SimplifyDemandedBitsForTargetNode(SDValue Op,const APInt & OriginalDemandedBits,const APInt & OriginalDemandedElts,KnownBits & Known,TargetLoweringOpt & TLO,unsigned Depth) const17594 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
17595 SDValue Op, const APInt &OriginalDemandedBits,
17596 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
17597 unsigned Depth) const {
17598 unsigned Opc = Op.getOpcode();
17599
17600 switch (Opc) {
17601 case ARMISD::ASRL:
17602 case ARMISD::LSRL: {
17603 // If this is result 0 and the other result is unused, see if the demand
17604 // bits allow us to shrink this long shift into a standard small shift in
17605 // the opposite direction.
17606 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
17607 isa<ConstantSDNode>(Op->getOperand(2))) {
17608 unsigned ShAmt = Op->getConstantOperandVal(2);
17609 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(
17610 APInt::getAllOnesValue(32) << (32 - ShAmt)))
17611 return TLO.CombineTo(
17612 Op, TLO.DAG.getNode(
17613 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
17614 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
17615 }
17616 break;
17617 }
17618 }
17619
17620 return TargetLowering::SimplifyDemandedBitsForTargetNode(
17621 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
17622 }
17623
17624 //===----------------------------------------------------------------------===//
17625 // ARM Inline Assembly Support
17626 //===----------------------------------------------------------------------===//
17627
ExpandInlineAsm(CallInst * CI) const17628 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
17629 // Looking for "rev" which is V6+.
17630 if (!Subtarget->hasV6Ops())
17631 return false;
17632
17633 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
17634 std::string AsmStr = IA->getAsmString();
17635 SmallVector<StringRef, 4> AsmPieces;
17636 SplitString(AsmStr, AsmPieces, ";\n");
17637
17638 switch (AsmPieces.size()) {
17639 default: return false;
17640 case 1:
17641 AsmStr = std::string(AsmPieces[0]);
17642 AsmPieces.clear();
17643 SplitString(AsmStr, AsmPieces, " \t,");
17644
17645 // rev $0, $1
17646 if (AsmPieces.size() == 3 &&
17647 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
17648 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
17649 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17650 if (Ty && Ty->getBitWidth() == 32)
17651 return IntrinsicLowering::LowerToByteSwap(CI);
17652 }
17653 break;
17654 }
17655
17656 return false;
17657 }
17658
LowerXConstraint(EVT ConstraintVT) const17659 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
17660 // At this point, we have to lower this constraint to something else, so we
17661 // lower it to an "r" or "w". However, by doing this we will force the result
17662 // to be in register, while the X constraint is much more permissive.
17663 //
17664 // Although we are correct (we are free to emit anything, without
17665 // constraints), we might break use cases that would expect us to be more
17666 // efficient and emit something else.
17667 if (!Subtarget->hasVFP2Base())
17668 return "r";
17669 if (ConstraintVT.isFloatingPoint())
17670 return "w";
17671 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
17672 (ConstraintVT.getSizeInBits() == 64 ||
17673 ConstraintVT.getSizeInBits() == 128))
17674 return "w";
17675
17676 return "r";
17677 }
17678
17679 /// getConstraintType - Given a constraint letter, return the type of
17680 /// constraint it is for this target.
17681 ARMTargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const17682 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
17683 unsigned S = Constraint.size();
17684 if (S == 1) {
17685 switch (Constraint[0]) {
17686 default: break;
17687 case 'l': return C_RegisterClass;
17688 case 'w': return C_RegisterClass;
17689 case 'h': return C_RegisterClass;
17690 case 'x': return C_RegisterClass;
17691 case 't': return C_RegisterClass;
17692 case 'j': return C_Immediate; // Constant for movw.
17693 // An address with a single base register. Due to the way we
17694 // currently handle addresses it is the same as an 'r' memory constraint.
17695 case 'Q': return C_Memory;
17696 }
17697 } else if (S == 2) {
17698 switch (Constraint[0]) {
17699 default: break;
17700 case 'T': return C_RegisterClass;
17701 // All 'U+' constraints are addresses.
17702 case 'U': return C_Memory;
17703 }
17704 }
17705 return TargetLowering::getConstraintType(Constraint);
17706 }
17707
17708 /// Examine constraint type and operand type and determine a weight value.
17709 /// This object must already have been set up with the operand type
17710 /// and the current alternative constraint selected.
17711 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const17712 ARMTargetLowering::getSingleConstraintMatchWeight(
17713 AsmOperandInfo &info, const char *constraint) const {
17714 ConstraintWeight weight = CW_Invalid;
17715 Value *CallOperandVal = info.CallOperandVal;
17716 // If we don't have a value, we can't do a match,
17717 // but allow it at the lowest weight.
17718 if (!CallOperandVal)
17719 return CW_Default;
17720 Type *type = CallOperandVal->getType();
17721 // Look at the constraint type.
17722 switch (*constraint) {
17723 default:
17724 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17725 break;
17726 case 'l':
17727 if (type->isIntegerTy()) {
17728 if (Subtarget->isThumb())
17729 weight = CW_SpecificReg;
17730 else
17731 weight = CW_Register;
17732 }
17733 break;
17734 case 'w':
17735 if (type->isFloatingPointTy())
17736 weight = CW_Register;
17737 break;
17738 }
17739 return weight;
17740 }
17741
17742 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
17743
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const17744 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
17745 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
17746 switch (Constraint.size()) {
17747 case 1:
17748 // GCC ARM Constraint Letters
17749 switch (Constraint[0]) {
17750 case 'l': // Low regs or general regs.
17751 if (Subtarget->isThumb())
17752 return RCPair(0U, &ARM::tGPRRegClass);
17753 return RCPair(0U, &ARM::GPRRegClass);
17754 case 'h': // High regs or no regs.
17755 if (Subtarget->isThumb())
17756 return RCPair(0U, &ARM::hGPRRegClass);
17757 break;
17758 case 'r':
17759 if (Subtarget->isThumb1Only())
17760 return RCPair(0U, &ARM::tGPRRegClass);
17761 return RCPair(0U, &ARM::GPRRegClass);
17762 case 'w':
17763 if (VT == MVT::Other)
17764 break;
17765 if (VT == MVT::f32)
17766 return RCPair(0U, &ARM::SPRRegClass);
17767 if (VT.getSizeInBits() == 64)
17768 return RCPair(0U, &ARM::DPRRegClass);
17769 if (VT.getSizeInBits() == 128)
17770 return RCPair(0U, &ARM::QPRRegClass);
17771 break;
17772 case 'x':
17773 if (VT == MVT::Other)
17774 break;
17775 if (VT == MVT::f32)
17776 return RCPair(0U, &ARM::SPR_8RegClass);
17777 if (VT.getSizeInBits() == 64)
17778 return RCPair(0U, &ARM::DPR_8RegClass);
17779 if (VT.getSizeInBits() == 128)
17780 return RCPair(0U, &ARM::QPR_8RegClass);
17781 break;
17782 case 't':
17783 if (VT == MVT::Other)
17784 break;
17785 if (VT == MVT::f32 || VT == MVT::i32)
17786 return RCPair(0U, &ARM::SPRRegClass);
17787 if (VT.getSizeInBits() == 64)
17788 return RCPair(0U, &ARM::DPR_VFP2RegClass);
17789 if (VT.getSizeInBits() == 128)
17790 return RCPair(0U, &ARM::QPR_VFP2RegClass);
17791 break;
17792 }
17793 break;
17794
17795 case 2:
17796 if (Constraint[0] == 'T') {
17797 switch (Constraint[1]) {
17798 default:
17799 break;
17800 case 'e':
17801 return RCPair(0U, &ARM::tGPREvenRegClass);
17802 case 'o':
17803 return RCPair(0U, &ARM::tGPROddRegClass);
17804 }
17805 }
17806 break;
17807
17808 default:
17809 break;
17810 }
17811
17812 if (StringRef("{cc}").equals_lower(Constraint))
17813 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
17814
17815 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
17816 }
17817
17818 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17819 /// vector. If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const17820 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17821 std::string &Constraint,
17822 std::vector<SDValue>&Ops,
17823 SelectionDAG &DAG) const {
17824 SDValue Result;
17825
17826 // Currently only support length 1 constraints.
17827 if (Constraint.length() != 1) return;
17828
17829 char ConstraintLetter = Constraint[0];
17830 switch (ConstraintLetter) {
17831 default: break;
17832 case 'j':
17833 case 'I': case 'J': case 'K': case 'L':
17834 case 'M': case 'N': case 'O':
17835 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
17836 if (!C)
17837 return;
17838
17839 int64_t CVal64 = C->getSExtValue();
17840 int CVal = (int) CVal64;
17841 // None of these constraints allow values larger than 32 bits. Check
17842 // that the value fits in an int.
17843 if (CVal != CVal64)
17844 return;
17845
17846 switch (ConstraintLetter) {
17847 case 'j':
17848 // Constant suitable for movw, must be between 0 and
17849 // 65535.
17850 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
17851 if (CVal >= 0 && CVal <= 65535)
17852 break;
17853 return;
17854 case 'I':
17855 if (Subtarget->isThumb1Only()) {
17856 // This must be a constant between 0 and 255, for ADD
17857 // immediates.
17858 if (CVal >= 0 && CVal <= 255)
17859 break;
17860 } else if (Subtarget->isThumb2()) {
17861 // A constant that can be used as an immediate value in a
17862 // data-processing instruction.
17863 if (ARM_AM::getT2SOImmVal(CVal) != -1)
17864 break;
17865 } else {
17866 // A constant that can be used as an immediate value in a
17867 // data-processing instruction.
17868 if (ARM_AM::getSOImmVal(CVal) != -1)
17869 break;
17870 }
17871 return;
17872
17873 case 'J':
17874 if (Subtarget->isThumb1Only()) {
17875 // This must be a constant between -255 and -1, for negated ADD
17876 // immediates. This can be used in GCC with an "n" modifier that
17877 // prints the negated value, for use with SUB instructions. It is
17878 // not useful otherwise but is implemented for compatibility.
17879 if (CVal >= -255 && CVal <= -1)
17880 break;
17881 } else {
17882 // This must be a constant between -4095 and 4095. It is not clear
17883 // what this constraint is intended for. Implemented for
17884 // compatibility with GCC.
17885 if (CVal >= -4095 && CVal <= 4095)
17886 break;
17887 }
17888 return;
17889
17890 case 'K':
17891 if (Subtarget->isThumb1Only()) {
17892 // A 32-bit value where only one byte has a nonzero value. Exclude
17893 // zero to match GCC. This constraint is used by GCC internally for
17894 // constants that can be loaded with a move/shift combination.
17895 // It is not useful otherwise but is implemented for compatibility.
17896 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
17897 break;
17898 } else if (Subtarget->isThumb2()) {
17899 // A constant whose bitwise inverse can be used as an immediate
17900 // value in a data-processing instruction. This can be used in GCC
17901 // with a "B" modifier that prints the inverted value, for use with
17902 // BIC and MVN instructions. It is not useful otherwise but is
17903 // implemented for compatibility.
17904 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
17905 break;
17906 } else {
17907 // A constant whose bitwise inverse can be used as an immediate
17908 // value in a data-processing instruction. This can be used in GCC
17909 // with a "B" modifier that prints the inverted value, for use with
17910 // BIC and MVN instructions. It is not useful otherwise but is
17911 // implemented for compatibility.
17912 if (ARM_AM::getSOImmVal(~CVal) != -1)
17913 break;
17914 }
17915 return;
17916
17917 case 'L':
17918 if (Subtarget->isThumb1Only()) {
17919 // This must be a constant between -7 and 7,
17920 // for 3-operand ADD/SUB immediate instructions.
17921 if (CVal >= -7 && CVal < 7)
17922 break;
17923 } else if (Subtarget->isThumb2()) {
17924 // A constant whose negation can be used as an immediate value in a
17925 // data-processing instruction. This can be used in GCC with an "n"
17926 // modifier that prints the negated value, for use with SUB
17927 // instructions. It is not useful otherwise but is implemented for
17928 // compatibility.
17929 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
17930 break;
17931 } else {
17932 // A constant whose negation can be used as an immediate value in a
17933 // data-processing instruction. This can be used in GCC with an "n"
17934 // modifier that prints the negated value, for use with SUB
17935 // instructions. It is not useful otherwise but is implemented for
17936 // compatibility.
17937 if (ARM_AM::getSOImmVal(-CVal) != -1)
17938 break;
17939 }
17940 return;
17941
17942 case 'M':
17943 if (Subtarget->isThumb1Only()) {
17944 // This must be a multiple of 4 between 0 and 1020, for
17945 // ADD sp + immediate.
17946 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
17947 break;
17948 } else {
17949 // A power of two or a constant between 0 and 32. This is used in
17950 // GCC for the shift amount on shifted register operands, but it is
17951 // useful in general for any shift amounts.
17952 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
17953 break;
17954 }
17955 return;
17956
17957 case 'N':
17958 if (Subtarget->isThumb1Only()) {
17959 // This must be a constant between 0 and 31, for shift amounts.
17960 if (CVal >= 0 && CVal <= 31)
17961 break;
17962 }
17963 return;
17964
17965 case 'O':
17966 if (Subtarget->isThumb1Only()) {
17967 // This must be a multiple of 4 between -508 and 508, for
17968 // ADD/SUB sp = sp + immediate.
17969 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
17970 break;
17971 }
17972 return;
17973 }
17974 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
17975 break;
17976 }
17977
17978 if (Result.getNode()) {
17979 Ops.push_back(Result);
17980 return;
17981 }
17982 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17983 }
17984
getDivRemLibcall(const SDNode * N,MVT::SimpleValueType SVT)17985 static RTLIB::Libcall getDivRemLibcall(
17986 const SDNode *N, MVT::SimpleValueType SVT) {
17987 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
17988 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
17989 "Unhandled Opcode in getDivRemLibcall");
17990 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
17991 N->getOpcode() == ISD::SREM;
17992 RTLIB::Libcall LC;
17993 switch (SVT) {
17994 default: llvm_unreachable("Unexpected request for libcall!");
17995 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
17996 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
17997 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
17998 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
17999 }
18000 return LC;
18001 }
18002
getDivRemArgList(const SDNode * N,LLVMContext * Context,const ARMSubtarget * Subtarget)18003 static TargetLowering::ArgListTy getDivRemArgList(
18004 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
18005 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
18006 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
18007 "Unhandled Opcode in getDivRemArgList");
18008 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
18009 N->getOpcode() == ISD::SREM;
18010 TargetLowering::ArgListTy Args;
18011 TargetLowering::ArgListEntry Entry;
18012 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
18013 EVT ArgVT = N->getOperand(i).getValueType();
18014 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
18015 Entry.Node = N->getOperand(i);
18016 Entry.Ty = ArgTy;
18017 Entry.IsSExt = isSigned;
18018 Entry.IsZExt = !isSigned;
18019 Args.push_back(Entry);
18020 }
18021 if (Subtarget->isTargetWindows() && Args.size() >= 2)
18022 std::swap(Args[0], Args[1]);
18023 return Args;
18024 }
18025
LowerDivRem(SDValue Op,SelectionDAG & DAG) const18026 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
18027 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
18028 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
18029 Subtarget->isTargetWindows()) &&
18030 "Register-based DivRem lowering only");
18031 unsigned Opcode = Op->getOpcode();
18032 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
18033 "Invalid opcode for Div/Rem lowering");
18034 bool isSigned = (Opcode == ISD::SDIVREM);
18035 EVT VT = Op->getValueType(0);
18036 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
18037 SDLoc dl(Op);
18038
18039 // If the target has hardware divide, use divide + multiply + subtract:
18040 // div = a / b
18041 // rem = a - b * div
18042 // return {div, rem}
18043 // This should be lowered into UDIV/SDIV + MLS later on.
18044 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
18045 : Subtarget->hasDivideInARMMode();
18046 if (hasDivide && Op->getValueType(0).isSimple() &&
18047 Op->getSimpleValueType(0) == MVT::i32) {
18048 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
18049 const SDValue Dividend = Op->getOperand(0);
18050 const SDValue Divisor = Op->getOperand(1);
18051 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
18052 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
18053 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
18054
18055 SDValue Values[2] = {Div, Rem};
18056 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
18057 }
18058
18059 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
18060 VT.getSimpleVT().SimpleTy);
18061 SDValue InChain = DAG.getEntryNode();
18062
18063 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
18064 DAG.getContext(),
18065 Subtarget);
18066
18067 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18068 getPointerTy(DAG.getDataLayout()));
18069
18070 Type *RetTy = StructType::get(Ty, Ty);
18071
18072 if (Subtarget->isTargetWindows())
18073 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
18074
18075 TargetLowering::CallLoweringInfo CLI(DAG);
18076 CLI.setDebugLoc(dl).setChain(InChain)
18077 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
18078 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18079
18080 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18081 return CallInfo.first;
18082 }
18083
18084 // Lowers REM using divmod helpers
18085 // see RTABI section 4.2/4.3
LowerREM(SDNode * N,SelectionDAG & DAG) const18086 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
18087 // Build return types (div and rem)
18088 std::vector<Type*> RetTyParams;
18089 Type *RetTyElement;
18090
18091 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
18092 default: llvm_unreachable("Unexpected request for libcall!");
18093 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
18094 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
18095 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
18096 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
18097 }
18098
18099 RetTyParams.push_back(RetTyElement);
18100 RetTyParams.push_back(RetTyElement);
18101 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
18102 Type *RetTy = StructType::get(*DAG.getContext(), ret);
18103
18104 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
18105 SimpleTy);
18106 SDValue InChain = DAG.getEntryNode();
18107 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
18108 Subtarget);
18109 bool isSigned = N->getOpcode() == ISD::SREM;
18110 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18111 getPointerTy(DAG.getDataLayout()));
18112
18113 if (Subtarget->isTargetWindows())
18114 InChain = WinDBZCheckDenominator(DAG, N, InChain);
18115
18116 // Lower call
18117 CallLoweringInfo CLI(DAG);
18118 CLI.setChain(InChain)
18119 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
18120 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
18121 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
18122
18123 // Return second (rem) result operand (first contains div)
18124 SDNode *ResNode = CallResult.first.getNode();
18125 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
18126 return ResNode->getOperand(1);
18127 }
18128
18129 SDValue
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const18130 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
18131 assert(Subtarget->isTargetWindows() && "unsupported target platform");
18132 SDLoc DL(Op);
18133
18134 // Get the inputs.
18135 SDValue Chain = Op.getOperand(0);
18136 SDValue Size = Op.getOperand(1);
18137
18138 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
18139 "no-stack-arg-probe")) {
18140 MaybeAlign Align =
18141 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
18142 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
18143 Chain = SP.getValue(1);
18144 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
18145 if (Align)
18146 SP =
18147 DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
18148 DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32));
18149 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
18150 SDValue Ops[2] = { SP, Chain };
18151 return DAG.getMergeValues(Ops, DL);
18152 }
18153
18154 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
18155 DAG.getConstant(2, DL, MVT::i32));
18156
18157 SDValue Flag;
18158 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
18159 Flag = Chain.getValue(1);
18160
18161 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18162 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
18163
18164 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
18165 Chain = NewSP.getValue(1);
18166
18167 SDValue Ops[2] = { NewSP, Chain };
18168 return DAG.getMergeValues(Ops, DL);
18169 }
18170
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG) const18171 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
18172 bool IsStrict = Op->isStrictFPOpcode();
18173 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
18174 const unsigned DstSz = Op.getValueType().getSizeInBits();
18175 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
18176 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
18177 "Unexpected type for custom-lowering FP_EXTEND");
18178
18179 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
18180 "With both FP DP and 16, any FP conversion is legal!");
18181
18182 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
18183 "With FP16, 16 to 32 conversion is legal!");
18184
18185 // Converting from 32 -> 64 is valid if we have FP64.
18186 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
18187 // FIXME: Remove this when we have strict fp instruction selection patterns
18188 if (IsStrict) {
18189 SDLoc Loc(Op);
18190 SDValue Result = DAG.getNode(ISD::FP_EXTEND,
18191 Loc, Op.getValueType(), SrcVal);
18192 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
18193 }
18194 return Op;
18195 }
18196
18197 // Either we are converting from 16 -> 64, without FP16 and/or
18198 // FP.double-precision or without Armv8-fp. So we must do it in two
18199 // steps.
18200 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
18201 // without FP16. So we must do a function call.
18202 SDLoc Loc(Op);
18203 RTLIB::Libcall LC;
18204 MakeLibCallOptions CallOptions;
18205 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
18206 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
18207 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
18208 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
18209 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
18210 if (Supported) {
18211 if (IsStrict) {
18212 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
18213 {DstVT, MVT::Other}, {Chain, SrcVal});
18214 Chain = SrcVal.getValue(1);
18215 } else {
18216 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
18217 }
18218 } else {
18219 LC = RTLIB::getFPEXT(SrcVT, DstVT);
18220 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
18221 "Unexpected type for custom-lowering FP_EXTEND");
18222 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
18223 Loc, Chain);
18224 }
18225 }
18226
18227 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
18228 }
18229
LowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const18230 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
18231 bool IsStrict = Op->isStrictFPOpcode();
18232
18233 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
18234 EVT SrcVT = SrcVal.getValueType();
18235 EVT DstVT = Op.getValueType();
18236 const unsigned DstSz = Op.getValueType().getSizeInBits();
18237 const unsigned SrcSz = SrcVT.getSizeInBits();
18238 (void)DstSz;
18239 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
18240 "Unexpected type for custom-lowering FP_ROUND");
18241
18242 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
18243 "With both FP DP and 16, any FP conversion is legal!");
18244
18245 SDLoc Loc(Op);
18246
18247 // Instruction from 32 -> 16 if hasFP16 is valid
18248 if (SrcSz == 32 && Subtarget->hasFP16())
18249 return Op;
18250
18251 // Lib call from 32 -> 16 / 64 -> [32, 16]
18252 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
18253 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
18254 "Unexpected type for custom-lowering FP_ROUND");
18255 MakeLibCallOptions CallOptions;
18256 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
18257 SDValue Result;
18258 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
18259 Loc, Chain);
18260 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
18261 }
18262
lowerABS(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const18263 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
18264 SelectionDAG &DAG) const {
18265 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
18266 MVT HalfT = MVT::i32;
18267 SDLoc dl(N);
18268 SDValue Hi, Lo, Tmp;
18269
18270 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
18271 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
18272 return ;
18273
18274 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
18275 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
18276
18277 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
18278 DAG.getConstant(0, dl, HalfT));
18279 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
18280 DAG.getConstant(1, dl, HalfT));
18281
18282 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
18283 DAG.getConstant(OpTypeBits - 1, dl,
18284 getShiftAmountTy(HalfT, DAG.getDataLayout())));
18285 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
18286 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
18287 SDValue(Lo.getNode(), 1));
18288 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
18289 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
18290
18291 Results.push_back(Lo);
18292 Results.push_back(Hi);
18293 }
18294
18295 bool
isOffsetFoldingLegal(const GlobalAddressSDNode * GA) const18296 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
18297 // The ARM target isn't yet aware of offsets.
18298 return false;
18299 }
18300
isBitFieldInvertedMask(unsigned v)18301 bool ARM::isBitFieldInvertedMask(unsigned v) {
18302 if (v == 0xffffffff)
18303 return false;
18304
18305 // there can be 1's on either or both "outsides", all the "inside"
18306 // bits must be 0's
18307 return isShiftedMask_32(~v);
18308 }
18309
18310 /// isFPImmLegal - Returns true if the target can instruction select the
18311 /// specified FP immediate natively. If false, the legalizer will
18312 /// materialize the FP immediate as a load from a constant pool.
isFPImmLegal(const APFloat & Imm,EVT VT,bool ForCodeSize) const18313 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
18314 bool ForCodeSize) const {
18315 if (!Subtarget->hasVFP3Base())
18316 return false;
18317 if (VT == MVT::f16 && Subtarget->hasFullFP16())
18318 return ARM_AM::getFP16Imm(Imm) != -1;
18319 if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
18320 ARM_AM::getFP32FP16Imm(Imm) != -1)
18321 return true;
18322 if (VT == MVT::f32)
18323 return ARM_AM::getFP32Imm(Imm) != -1;
18324 if (VT == MVT::f64 && Subtarget->hasFP64())
18325 return ARM_AM::getFP64Imm(Imm) != -1;
18326 return false;
18327 }
18328
18329 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
18330 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
18331 /// specified in the intrinsic calls.
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const18332 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
18333 const CallInst &I,
18334 MachineFunction &MF,
18335 unsigned Intrinsic) const {
18336 switch (Intrinsic) {
18337 case Intrinsic::arm_neon_vld1:
18338 case Intrinsic::arm_neon_vld2:
18339 case Intrinsic::arm_neon_vld3:
18340 case Intrinsic::arm_neon_vld4:
18341 case Intrinsic::arm_neon_vld2lane:
18342 case Intrinsic::arm_neon_vld3lane:
18343 case Intrinsic::arm_neon_vld4lane:
18344 case Intrinsic::arm_neon_vld2dup:
18345 case Intrinsic::arm_neon_vld3dup:
18346 case Intrinsic::arm_neon_vld4dup: {
18347 Info.opc = ISD::INTRINSIC_W_CHAIN;
18348 // Conservatively set memVT to the entire set of vectors loaded.
18349 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18350 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
18351 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18352 Info.ptrVal = I.getArgOperand(0);
18353 Info.offset = 0;
18354 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
18355 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
18356 // volatile loads with NEON intrinsics not supported
18357 Info.flags = MachineMemOperand::MOLoad;
18358 return true;
18359 }
18360 case Intrinsic::arm_neon_vld1x2:
18361 case Intrinsic::arm_neon_vld1x3:
18362 case Intrinsic::arm_neon_vld1x4: {
18363 Info.opc = ISD::INTRINSIC_W_CHAIN;
18364 // Conservatively set memVT to the entire set of vectors loaded.
18365 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18366 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
18367 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18368 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
18369 Info.offset = 0;
18370 Info.align.reset();
18371 // volatile loads with NEON intrinsics not supported
18372 Info.flags = MachineMemOperand::MOLoad;
18373 return true;
18374 }
18375 case Intrinsic::arm_neon_vst1:
18376 case Intrinsic::arm_neon_vst2:
18377 case Intrinsic::arm_neon_vst3:
18378 case Intrinsic::arm_neon_vst4:
18379 case Intrinsic::arm_neon_vst2lane:
18380 case Intrinsic::arm_neon_vst3lane:
18381 case Intrinsic::arm_neon_vst4lane: {
18382 Info.opc = ISD::INTRINSIC_VOID;
18383 // Conservatively set memVT to the entire set of vectors stored.
18384 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18385 unsigned NumElts = 0;
18386 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
18387 Type *ArgTy = I.getArgOperand(ArgI)->getType();
18388 if (!ArgTy->isVectorTy())
18389 break;
18390 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
18391 }
18392 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18393 Info.ptrVal = I.getArgOperand(0);
18394 Info.offset = 0;
18395 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
18396 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
18397 // volatile stores with NEON intrinsics not supported
18398 Info.flags = MachineMemOperand::MOStore;
18399 return true;
18400 }
18401 case Intrinsic::arm_neon_vst1x2:
18402 case Intrinsic::arm_neon_vst1x3:
18403 case Intrinsic::arm_neon_vst1x4: {
18404 Info.opc = ISD::INTRINSIC_VOID;
18405 // Conservatively set memVT to the entire set of vectors stored.
18406 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18407 unsigned NumElts = 0;
18408 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
18409 Type *ArgTy = I.getArgOperand(ArgI)->getType();
18410 if (!ArgTy->isVectorTy())
18411 break;
18412 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
18413 }
18414 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18415 Info.ptrVal = I.getArgOperand(0);
18416 Info.offset = 0;
18417 Info.align.reset();
18418 // volatile stores with NEON intrinsics not supported
18419 Info.flags = MachineMemOperand::MOStore;
18420 return true;
18421 }
18422 case Intrinsic::arm_mve_vld2q:
18423 case Intrinsic::arm_mve_vld4q: {
18424 Info.opc = ISD::INTRINSIC_W_CHAIN;
18425 // Conservatively set memVT to the entire set of vectors loaded.
18426 Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
18427 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
18428 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
18429 Info.ptrVal = I.getArgOperand(0);
18430 Info.offset = 0;
18431 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
18432 // volatile loads with MVE intrinsics not supported
18433 Info.flags = MachineMemOperand::MOLoad;
18434 return true;
18435 }
18436 case Intrinsic::arm_mve_vst2q:
18437 case Intrinsic::arm_mve_vst4q: {
18438 Info.opc = ISD::INTRINSIC_VOID;
18439 // Conservatively set memVT to the entire set of vectors stored.
18440 Type *VecTy = I.getArgOperand(1)->getType();
18441 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
18442 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
18443 Info.ptrVal = I.getArgOperand(0);
18444 Info.offset = 0;
18445 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
18446 // volatile stores with MVE intrinsics not supported
18447 Info.flags = MachineMemOperand::MOStore;
18448 return true;
18449 }
18450 case Intrinsic::arm_ldaex:
18451 case Intrinsic::arm_ldrex: {
18452 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18453 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
18454 Info.opc = ISD::INTRINSIC_W_CHAIN;
18455 Info.memVT = MVT::getVT(PtrTy->getElementType());
18456 Info.ptrVal = I.getArgOperand(0);
18457 Info.offset = 0;
18458 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
18459 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
18460 return true;
18461 }
18462 case Intrinsic::arm_stlex:
18463 case Intrinsic::arm_strex: {
18464 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18465 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
18466 Info.opc = ISD::INTRINSIC_W_CHAIN;
18467 Info.memVT = MVT::getVT(PtrTy->getElementType());
18468 Info.ptrVal = I.getArgOperand(1);
18469 Info.offset = 0;
18470 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
18471 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
18472 return true;
18473 }
18474 case Intrinsic::arm_stlexd:
18475 case Intrinsic::arm_strexd:
18476 Info.opc = ISD::INTRINSIC_W_CHAIN;
18477 Info.memVT = MVT::i64;
18478 Info.ptrVal = I.getArgOperand(2);
18479 Info.offset = 0;
18480 Info.align = Align(8);
18481 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
18482 return true;
18483
18484 case Intrinsic::arm_ldaexd:
18485 case Intrinsic::arm_ldrexd:
18486 Info.opc = ISD::INTRINSIC_W_CHAIN;
18487 Info.memVT = MVT::i64;
18488 Info.ptrVal = I.getArgOperand(0);
18489 Info.offset = 0;
18490 Info.align = Align(8);
18491 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
18492 return true;
18493
18494 default:
18495 break;
18496 }
18497
18498 return false;
18499 }
18500
18501 /// Returns true if it is beneficial to convert a load of a constant
18502 /// to just the constant itself.
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const18503 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
18504 Type *Ty) const {
18505 assert(Ty->isIntegerTy());
18506
18507 unsigned Bits = Ty->getPrimitiveSizeInBits();
18508 if (Bits == 0 || Bits > 32)
18509 return false;
18510 return true;
18511 }
18512
isExtractSubvectorCheap(EVT ResVT,EVT SrcVT,unsigned Index) const18513 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
18514 unsigned Index) const {
18515 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
18516 return false;
18517
18518 return (Index == 0 || Index == ResVT.getVectorNumElements());
18519 }
18520
makeDMB(IRBuilder<> & Builder,ARM_MB::MemBOpt Domain) const18521 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
18522 ARM_MB::MemBOpt Domain) const {
18523 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18524
18525 // First, if the target has no DMB, see what fallback we can use.
18526 if (!Subtarget->hasDataBarrier()) {
18527 // Some ARMv6 cpus can support data barriers with an mcr instruction.
18528 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
18529 // here.
18530 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
18531 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
18532 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
18533 Builder.getInt32(0), Builder.getInt32(7),
18534 Builder.getInt32(10), Builder.getInt32(5)};
18535 return Builder.CreateCall(MCR, args);
18536 } else {
18537 // Instead of using barriers, atomic accesses on these subtargets use
18538 // libcalls.
18539 llvm_unreachable("makeDMB on a target so old that it has no barriers");
18540 }
18541 } else {
18542 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
18543 // Only a full system barrier exists in the M-class architectures.
18544 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
18545 Constant *CDomain = Builder.getInt32(Domain);
18546 return Builder.CreateCall(DMB, CDomain);
18547 }
18548 }
18549
18550 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
emitLeadingFence(IRBuilder<> & Builder,Instruction * Inst,AtomicOrdering Ord) const18551 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
18552 Instruction *Inst,
18553 AtomicOrdering Ord) const {
18554 switch (Ord) {
18555 case AtomicOrdering::NotAtomic:
18556 case AtomicOrdering::Unordered:
18557 llvm_unreachable("Invalid fence: unordered/non-atomic");
18558 case AtomicOrdering::Monotonic:
18559 case AtomicOrdering::Acquire:
18560 return nullptr; // Nothing to do
18561 case AtomicOrdering::SequentiallyConsistent:
18562 if (!Inst->hasAtomicStore())
18563 return nullptr; // Nothing to do
18564 LLVM_FALLTHROUGH;
18565 case AtomicOrdering::Release:
18566 case AtomicOrdering::AcquireRelease:
18567 if (Subtarget->preferISHSTBarriers())
18568 return makeDMB(Builder, ARM_MB::ISHST);
18569 // FIXME: add a comment with a link to documentation justifying this.
18570 else
18571 return makeDMB(Builder, ARM_MB::ISH);
18572 }
18573 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
18574 }
18575
emitTrailingFence(IRBuilder<> & Builder,Instruction * Inst,AtomicOrdering Ord) const18576 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
18577 Instruction *Inst,
18578 AtomicOrdering Ord) const {
18579 switch (Ord) {
18580 case AtomicOrdering::NotAtomic:
18581 case AtomicOrdering::Unordered:
18582 llvm_unreachable("Invalid fence: unordered/not-atomic");
18583 case AtomicOrdering::Monotonic:
18584 case AtomicOrdering::Release:
18585 return nullptr; // Nothing to do
18586 case AtomicOrdering::Acquire:
18587 case AtomicOrdering::AcquireRelease:
18588 case AtomicOrdering::SequentiallyConsistent:
18589 return makeDMB(Builder, ARM_MB::ISH);
18590 }
18591 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
18592 }
18593
18594 // Loads and stores less than 64-bits are already atomic; ones above that
18595 // are doomed anyway, so defer to the default libcall and blame the OS when
18596 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
18597 // anything for those.
shouldExpandAtomicStoreInIR(StoreInst * SI) const18598 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18599 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
18600 return (Size == 64) && !Subtarget->isMClass();
18601 }
18602
18603 // Loads and stores less than 64-bits are already atomic; ones above that
18604 // are doomed anyway, so defer to the default libcall and blame the OS when
18605 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
18606 // anything for those.
18607 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
18608 // guarantee, see DDI0406C ARM architecture reference manual,
18609 // sections A8.8.72-74 LDRD)
18610 TargetLowering::AtomicExpansionKind
shouldExpandAtomicLoadInIR(LoadInst * LI) const18611 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18612 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
18613 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
18614 : AtomicExpansionKind::None;
18615 }
18616
18617 // For the real atomic operations, we have ldrex/strex up to 32 bits,
18618 // and up to 64 bits on the non-M profiles
18619 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const18620 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18621 if (AI->isFloatingPointOperation())
18622 return AtomicExpansionKind::CmpXChg;
18623
18624 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18625 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
18626 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
18627 ? AtomicExpansionKind::LLSC
18628 : AtomicExpansionKind::None;
18629 }
18630
18631 TargetLowering::AtomicExpansionKind
shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst * AI) const18632 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18633 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
18634 // implement cmpxchg without spilling. If the address being exchanged is also
18635 // on the stack and close enough to the spill slot, this can lead to a
18636 // situation where the monitor always gets cleared and the atomic operation
18637 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
18638 bool HasAtomicCmpXchg =
18639 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
18640 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
18641 return AtomicExpansionKind::LLSC;
18642 return AtomicExpansionKind::None;
18643 }
18644
shouldInsertFencesForAtomic(const Instruction * I) const18645 bool ARMTargetLowering::shouldInsertFencesForAtomic(
18646 const Instruction *I) const {
18647 return InsertFencesForAtomic;
18648 }
18649
18650 // This has so far only been implemented for MachO.
useLoadStackGuardNode() const18651 bool ARMTargetLowering::useLoadStackGuardNode() const {
18652 return Subtarget->isTargetMachO();
18653 }
18654
insertSSPDeclarations(Module & M) const18655 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
18656 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18657 return TargetLowering::insertSSPDeclarations(M);
18658
18659 // MSVC CRT has a global variable holding security cookie.
18660 M.getOrInsertGlobal("__security_cookie",
18661 Type::getInt8PtrTy(M.getContext()));
18662
18663 // MSVC CRT has a function to validate security cookie.
18664 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
18665 "__security_check_cookie", Type::getVoidTy(M.getContext()),
18666 Type::getInt8PtrTy(M.getContext()));
18667 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
18668 F->addAttribute(1, Attribute::AttrKind::InReg);
18669 }
18670
getSDagStackGuard(const Module & M) const18671 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
18672 // MSVC CRT has a global variable holding security cookie.
18673 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18674 return M.getGlobalVariable("__security_cookie");
18675 return TargetLowering::getSDagStackGuard(M);
18676 }
18677
getSSPStackGuardCheck(const Module & M) const18678 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
18679 // MSVC CRT has a function to validate security cookie.
18680 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18681 return M.getFunction("__security_check_cookie");
18682 return TargetLowering::getSSPStackGuardCheck(M);
18683 }
18684
canCombineStoreAndExtract(Type * VectorTy,Value * Idx,unsigned & Cost) const18685 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
18686 unsigned &Cost) const {
18687 // If we do not have NEON, vector types are not natively supported.
18688 if (!Subtarget->hasNEON())
18689 return false;
18690
18691 // Floating point values and vector values map to the same register file.
18692 // Therefore, although we could do a store extract of a vector type, this is
18693 // better to leave at float as we have more freedom in the addressing mode for
18694 // those.
18695 if (VectorTy->isFPOrFPVectorTy())
18696 return false;
18697
18698 // If the index is unknown at compile time, this is very expensive to lower
18699 // and it is not possible to combine the store with the extract.
18700 if (!isa<ConstantInt>(Idx))
18701 return false;
18702
18703 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
18704 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
18705 // We can do a store + vector extract on any vector that fits perfectly in a D
18706 // or Q register.
18707 if (BitWidth == 64 || BitWidth == 128) {
18708 Cost = 0;
18709 return true;
18710 }
18711 return false;
18712 }
18713
isCheapToSpeculateCttz() const18714 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
18715 return Subtarget->hasV6T2Ops();
18716 }
18717
isCheapToSpeculateCtlz() const18718 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
18719 return Subtarget->hasV6T2Ops();
18720 }
18721
shouldExpandShift(SelectionDAG & DAG,SDNode * N) const18722 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
18723 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
18724 }
18725
emitLoadLinked(IRBuilder<> & Builder,Value * Addr,AtomicOrdering Ord) const18726 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
18727 AtomicOrdering Ord) const {
18728 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18729 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
18730 bool IsAcquire = isAcquireOrStronger(Ord);
18731
18732 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
18733 // intrinsic must return {i32, i32} and we have to recombine them into a
18734 // single i64 here.
18735 if (ValTy->getPrimitiveSizeInBits() == 64) {
18736 Intrinsic::ID Int =
18737 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
18738 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
18739
18740 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18741 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
18742
18743 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18744 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18745 if (!Subtarget->isLittle())
18746 std::swap (Lo, Hi);
18747 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18748 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18749 return Builder.CreateOr(
18750 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
18751 }
18752
18753 Type *Tys[] = { Addr->getType() };
18754 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
18755 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
18756
18757 return Builder.CreateTruncOrBitCast(
18758 Builder.CreateCall(Ldrex, Addr),
18759 cast<PointerType>(Addr->getType())->getElementType());
18760 }
18761
emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> & Builder) const18762 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
18763 IRBuilder<> &Builder) const {
18764 if (!Subtarget->hasV7Ops())
18765 return;
18766 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18767 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
18768 }
18769
emitStoreConditional(IRBuilder<> & Builder,Value * Val,Value * Addr,AtomicOrdering Ord) const18770 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
18771 Value *Addr,
18772 AtomicOrdering Ord) const {
18773 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18774 bool IsRelease = isReleaseOrStronger(Ord);
18775
18776 // Since the intrinsics must have legal type, the i64 intrinsics take two
18777 // parameters: "i32, i32". We must marshal Val into the appropriate form
18778 // before the call.
18779 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
18780 Intrinsic::ID Int =
18781 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
18782 Function *Strex = Intrinsic::getDeclaration(M, Int);
18783 Type *Int32Ty = Type::getInt32Ty(M->getContext());
18784
18785 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
18786 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
18787 if (!Subtarget->isLittle())
18788 std::swap(Lo, Hi);
18789 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18790 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
18791 }
18792
18793 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
18794 Type *Tys[] = { Addr->getType() };
18795 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
18796
18797 return Builder.CreateCall(
18798 Strex, {Builder.CreateZExtOrBitCast(
18799 Val, Strex->getFunctionType()->getParamType(0)),
18800 Addr});
18801 }
18802
18803
alignLoopsWithOptSize() const18804 bool ARMTargetLowering::alignLoopsWithOptSize() const {
18805 return Subtarget->isMClass();
18806 }
18807
18808 /// A helper function for determining the number of interleaved accesses we
18809 /// will generate when lowering accesses of the given type.
18810 unsigned
getNumInterleavedAccesses(VectorType * VecTy,const DataLayout & DL) const18811 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
18812 const DataLayout &DL) const {
18813 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
18814 }
18815
isLegalInterleavedAccessType(unsigned Factor,FixedVectorType * VecTy,const DataLayout & DL) const18816 bool ARMTargetLowering::isLegalInterleavedAccessType(
18817 unsigned Factor, FixedVectorType *VecTy, const DataLayout &DL) const {
18818
18819 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
18820 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
18821
18822 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
18823 return false;
18824
18825 // Ensure the vector doesn't have f16 elements. Even though we could do an
18826 // i16 vldN, we can't hold the f16 vectors and will end up converting via
18827 // f32.
18828 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
18829 return false;
18830 if (Subtarget->hasMVEIntegerOps() && Factor == 3)
18831 return false;
18832
18833 // Ensure the number of vector elements is greater than 1.
18834 if (VecTy->getNumElements() < 2)
18835 return false;
18836
18837 // Ensure the element type is legal.
18838 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
18839 return false;
18840
18841 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
18842 // 128 will be split into multiple interleaved accesses.
18843 if (Subtarget->hasNEON() && VecSize == 64)
18844 return true;
18845 return VecSize % 128 == 0;
18846 }
18847
getMaxSupportedInterleaveFactor() const18848 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
18849 if (Subtarget->hasNEON())
18850 return 4;
18851 if (Subtarget->hasMVEIntegerOps())
18852 return MVEMaxSupportedInterleaveFactor;
18853 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
18854 }
18855
18856 /// Lower an interleaved load into a vldN intrinsic.
18857 ///
18858 /// E.g. Lower an interleaved load (Factor = 2):
18859 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
18860 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
18861 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
18862 ///
18863 /// Into:
18864 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
18865 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
18866 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
lowerInterleavedLoad(LoadInst * LI,ArrayRef<ShuffleVectorInst * > Shuffles,ArrayRef<unsigned> Indices,unsigned Factor) const18867 bool ARMTargetLowering::lowerInterleavedLoad(
18868 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
18869 ArrayRef<unsigned> Indices, unsigned Factor) const {
18870 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
18871 "Invalid interleave factor");
18872 assert(!Shuffles.empty() && "Empty shufflevector input");
18873 assert(Shuffles.size() == Indices.size() &&
18874 "Unmatched number of shufflevectors and indices");
18875
18876 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
18877 Type *EltTy = VecTy->getElementType();
18878
18879 const DataLayout &DL = LI->getModule()->getDataLayout();
18880
18881 // Skip if we do not have NEON and skip illegal vector types. We can
18882 // "legalize" wide vector types into multiple interleaved accesses as long as
18883 // the vector types are divisible by 128.
18884 if (!isLegalInterleavedAccessType(Factor, VecTy, DL))
18885 return false;
18886
18887 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
18888
18889 // A pointer vector can not be the return type of the ldN intrinsics. Need to
18890 // load integer vectors first and then convert to pointer vectors.
18891 if (EltTy->isPointerTy())
18892 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
18893
18894 IRBuilder<> Builder(LI);
18895
18896 // The base address of the load.
18897 Value *BaseAddr = LI->getPointerOperand();
18898
18899 if (NumLoads > 1) {
18900 // If we're going to generate more than one load, reset the sub-vector type
18901 // to something legal.
18902 VecTy = FixedVectorType::get(VecTy->getElementType(),
18903 VecTy->getNumElements() / NumLoads);
18904
18905 // We will compute the pointer operand of each load from the original base
18906 // address using GEPs. Cast the base address to a pointer to the scalar
18907 // element type.
18908 BaseAddr = Builder.CreateBitCast(
18909 BaseAddr,
18910 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
18911 }
18912
18913 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
18914
18915 auto createLoadIntrinsic = [&](Value *BaseAddr) {
18916 if (Subtarget->hasNEON()) {
18917 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
18918 Type *Tys[] = {VecTy, Int8Ptr};
18919 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
18920 Intrinsic::arm_neon_vld3,
18921 Intrinsic::arm_neon_vld4};
18922 Function *VldnFunc =
18923 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
18924
18925 SmallVector<Value *, 2> Ops;
18926 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
18927 Ops.push_back(Builder.getInt32(LI->getAlignment()));
18928
18929 return Builder.CreateCall(VldnFunc, Ops, "vldN");
18930 } else {
18931 assert((Factor == 2 || Factor == 4) &&
18932 "expected interleave factor of 2 or 4 for MVE");
18933 Intrinsic::ID LoadInts =
18934 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
18935 Type *VecEltTy =
18936 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
18937 Type *Tys[] = {VecTy, VecEltTy};
18938 Function *VldnFunc =
18939 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
18940
18941 SmallVector<Value *, 2> Ops;
18942 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
18943 return Builder.CreateCall(VldnFunc, Ops, "vldN");
18944 }
18945 };
18946
18947 // Holds sub-vectors extracted from the load intrinsic return values. The
18948 // sub-vectors are associated with the shufflevector instructions they will
18949 // replace.
18950 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
18951
18952 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
18953 // If we're generating more than one load, compute the base address of
18954 // subsequent loads as an offset from the previous.
18955 if (LoadCount > 0)
18956 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
18957 VecTy->getNumElements() * Factor);
18958
18959 CallInst *VldN = createLoadIntrinsic(BaseAddr);
18960
18961 // Replace uses of each shufflevector with the corresponding vector loaded
18962 // by ldN.
18963 for (unsigned i = 0; i < Shuffles.size(); i++) {
18964 ShuffleVectorInst *SV = Shuffles[i];
18965 unsigned Index = Indices[i];
18966
18967 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
18968
18969 // Convert the integer vector to pointer vector if the element is pointer.
18970 if (EltTy->isPointerTy())
18971 SubVec = Builder.CreateIntToPtr(
18972 SubVec,
18973 FixedVectorType::get(SV->getType()->getElementType(), VecTy));
18974
18975 SubVecs[SV].push_back(SubVec);
18976 }
18977 }
18978
18979 // Replace uses of the shufflevector instructions with the sub-vectors
18980 // returned by the load intrinsic. If a shufflevector instruction is
18981 // associated with more than one sub-vector, those sub-vectors will be
18982 // concatenated into a single wide vector.
18983 for (ShuffleVectorInst *SVI : Shuffles) {
18984 auto &SubVec = SubVecs[SVI];
18985 auto *WideVec =
18986 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
18987 SVI->replaceAllUsesWith(WideVec);
18988 }
18989
18990 return true;
18991 }
18992
18993 /// Lower an interleaved store into a vstN intrinsic.
18994 ///
18995 /// E.g. Lower an interleaved store (Factor = 3):
18996 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
18997 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
18998 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
18999 ///
19000 /// Into:
19001 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
19002 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
19003 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
19004 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
19005 ///
19006 /// Note that the new shufflevectors will be removed and we'll only generate one
19007 /// vst3 instruction in CodeGen.
19008 ///
19009 /// Example for a more general valid mask (Factor 3). Lower:
19010 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
19011 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
19012 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
19013 ///
19014 /// Into:
19015 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
19016 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
19017 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
19018 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
lowerInterleavedStore(StoreInst * SI,ShuffleVectorInst * SVI,unsigned Factor) const19019 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
19020 ShuffleVectorInst *SVI,
19021 unsigned Factor) const {
19022 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
19023 "Invalid interleave factor");
19024
19025 auto *VecTy = cast<FixedVectorType>(SVI->getType());
19026 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
19027
19028 unsigned LaneLen = VecTy->getNumElements() / Factor;
19029 Type *EltTy = VecTy->getElementType();
19030 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
19031
19032 const DataLayout &DL = SI->getModule()->getDataLayout();
19033
19034 // Skip if we do not have NEON and skip illegal vector types. We can
19035 // "legalize" wide vector types into multiple interleaved accesses as long as
19036 // the vector types are divisible by 128.
19037 if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL))
19038 return false;
19039
19040 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
19041
19042 Value *Op0 = SVI->getOperand(0);
19043 Value *Op1 = SVI->getOperand(1);
19044 IRBuilder<> Builder(SI);
19045
19046 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
19047 // vectors to integer vectors.
19048 if (EltTy->isPointerTy()) {
19049 Type *IntTy = DL.getIntPtrType(EltTy);
19050
19051 // Convert to the corresponding integer vector.
19052 auto *IntVecTy =
19053 FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
19054 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
19055 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
19056
19057 SubVecTy = FixedVectorType::get(IntTy, LaneLen);
19058 }
19059
19060 // The base address of the store.
19061 Value *BaseAddr = SI->getPointerOperand();
19062
19063 if (NumStores > 1) {
19064 // If we're going to generate more than one store, reset the lane length
19065 // and sub-vector type to something legal.
19066 LaneLen /= NumStores;
19067 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
19068
19069 // We will compute the pointer operand of each store from the original base
19070 // address using GEPs. Cast the base address to a pointer to the scalar
19071 // element type.
19072 BaseAddr = Builder.CreateBitCast(
19073 BaseAddr,
19074 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
19075 }
19076
19077 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
19078
19079 auto Mask = SVI->getShuffleMask();
19080
19081 auto createStoreIntrinsic = [&](Value *BaseAddr,
19082 SmallVectorImpl<Value *> &Shuffles) {
19083 if (Subtarget->hasNEON()) {
19084 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
19085 Intrinsic::arm_neon_vst3,
19086 Intrinsic::arm_neon_vst4};
19087 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
19088 Type *Tys[] = {Int8Ptr, SubVecTy};
19089
19090 Function *VstNFunc = Intrinsic::getDeclaration(
19091 SI->getModule(), StoreInts[Factor - 2], Tys);
19092
19093 SmallVector<Value *, 6> Ops;
19094 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
19095 for (auto S : Shuffles)
19096 Ops.push_back(S);
19097 Ops.push_back(Builder.getInt32(SI->getAlignment()));
19098 Builder.CreateCall(VstNFunc, Ops);
19099 } else {
19100 assert((Factor == 2 || Factor == 4) &&
19101 "expected interleave factor of 2 or 4 for MVE");
19102 Intrinsic::ID StoreInts =
19103 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
19104 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
19105 SI->getPointerAddressSpace());
19106 Type *Tys[] = {EltPtrTy, SubVecTy};
19107 Function *VstNFunc =
19108 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
19109
19110 SmallVector<Value *, 6> Ops;
19111 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
19112 for (auto S : Shuffles)
19113 Ops.push_back(S);
19114 for (unsigned F = 0; F < Factor; F++) {
19115 Ops.push_back(Builder.getInt32(F));
19116 Builder.CreateCall(VstNFunc, Ops);
19117 Ops.pop_back();
19118 }
19119 }
19120 };
19121
19122 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
19123 // If we generating more than one store, we compute the base address of
19124 // subsequent stores as an offset from the previous.
19125 if (StoreCount > 0)
19126 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
19127 BaseAddr, LaneLen * Factor);
19128
19129 SmallVector<Value *, 4> Shuffles;
19130
19131 // Split the shufflevector operands into sub vectors for the new vstN call.
19132 for (unsigned i = 0; i < Factor; i++) {
19133 unsigned IdxI = StoreCount * LaneLen * Factor + i;
19134 if (Mask[IdxI] >= 0) {
19135 Shuffles.push_back(Builder.CreateShuffleVector(
19136 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
19137 } else {
19138 unsigned StartMask = 0;
19139 for (unsigned j = 1; j < LaneLen; j++) {
19140 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
19141 if (Mask[IdxJ * Factor + IdxI] >= 0) {
19142 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
19143 break;
19144 }
19145 }
19146 // Note: If all elements in a chunk are undefs, StartMask=0!
19147 // Note: Filling undef gaps with random elements is ok, since
19148 // those elements were being written anyway (with undefs).
19149 // In the case of all undefs we're defaulting to using elems from 0
19150 // Note: StartMask cannot be negative, it's checked in
19151 // isReInterleaveMask
19152 Shuffles.push_back(Builder.CreateShuffleVector(
19153 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
19154 }
19155 }
19156
19157 createStoreIntrinsic(BaseAddr, Shuffles);
19158 }
19159 return true;
19160 }
19161
19162 enum HABaseType {
19163 HA_UNKNOWN = 0,
19164 HA_FLOAT,
19165 HA_DOUBLE,
19166 HA_VECT64,
19167 HA_VECT128
19168 };
19169
isHomogeneousAggregate(Type * Ty,HABaseType & Base,uint64_t & Members)19170 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
19171 uint64_t &Members) {
19172 if (auto *ST = dyn_cast<StructType>(Ty)) {
19173 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
19174 uint64_t SubMembers = 0;
19175 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
19176 return false;
19177 Members += SubMembers;
19178 }
19179 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
19180 uint64_t SubMembers = 0;
19181 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
19182 return false;
19183 Members += SubMembers * AT->getNumElements();
19184 } else if (Ty->isFloatTy()) {
19185 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
19186 return false;
19187 Members = 1;
19188 Base = HA_FLOAT;
19189 } else if (Ty->isDoubleTy()) {
19190 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
19191 return false;
19192 Members = 1;
19193 Base = HA_DOUBLE;
19194 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
19195 Members = 1;
19196 switch (Base) {
19197 case HA_FLOAT:
19198 case HA_DOUBLE:
19199 return false;
19200 case HA_VECT64:
19201 return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
19202 case HA_VECT128:
19203 return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
19204 case HA_UNKNOWN:
19205 switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
19206 case 64:
19207 Base = HA_VECT64;
19208 return true;
19209 case 128:
19210 Base = HA_VECT128;
19211 return true;
19212 default:
19213 return false;
19214 }
19215 }
19216 }
19217
19218 return (Members > 0 && Members <= 4);
19219 }
19220
19221 /// Return the correct alignment for the current calling convention.
getABIAlignmentForCallingConv(Type * ArgTy,DataLayout DL) const19222 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
19223 DataLayout DL) const {
19224 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
19225 if (!ArgTy->isVectorTy())
19226 return ABITypeAlign;
19227
19228 // Avoid over-aligning vector parameters. It would require realigning the
19229 // stack and waste space for no real benefit.
19230 return std::min(ABITypeAlign, DL.getStackAlignment());
19231 }
19232
19233 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
19234 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
19235 /// passing according to AAPCS rules.
functionArgumentNeedsConsecutiveRegisters(Type * Ty,CallingConv::ID CallConv,bool isVarArg) const19236 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
19237 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
19238 if (getEffectiveCallingConv(CallConv, isVarArg) !=
19239 CallingConv::ARM_AAPCS_VFP)
19240 return false;
19241
19242 HABaseType Base = HA_UNKNOWN;
19243 uint64_t Members = 0;
19244 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
19245 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
19246
19247 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
19248 return IsHA || IsIntArray;
19249 }
19250
getExceptionPointerRegister(const Constant * PersonalityFn) const19251 Register ARMTargetLowering::getExceptionPointerRegister(
19252 const Constant *PersonalityFn) const {
19253 // Platforms which do not use SjLj EH may return values in these registers
19254 // via the personality function.
19255 return Subtarget->useSjLjEH() ? Register() : ARM::R0;
19256 }
19257
getExceptionSelectorRegister(const Constant * PersonalityFn) const19258 Register ARMTargetLowering::getExceptionSelectorRegister(
19259 const Constant *PersonalityFn) const {
19260 // Platforms which do not use SjLj EH may return values in these registers
19261 // via the personality function.
19262 return Subtarget->useSjLjEH() ? Register() : ARM::R1;
19263 }
19264
initializeSplitCSR(MachineBasicBlock * Entry) const19265 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
19266 // Update IsSplitCSR in ARMFunctionInfo.
19267 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
19268 AFI->setIsSplitCSR(true);
19269 }
19270
insertCopiesSplitCSR(MachineBasicBlock * Entry,const SmallVectorImpl<MachineBasicBlock * > & Exits) const19271 void ARMTargetLowering::insertCopiesSplitCSR(
19272 MachineBasicBlock *Entry,
19273 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
19274 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
19275 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
19276 if (!IStart)
19277 return;
19278
19279 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19280 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
19281 MachineBasicBlock::iterator MBBI = Entry->begin();
19282 for (const MCPhysReg *I = IStart; *I; ++I) {
19283 const TargetRegisterClass *RC = nullptr;
19284 if (ARM::GPRRegClass.contains(*I))
19285 RC = &ARM::GPRRegClass;
19286 else if (ARM::DPRRegClass.contains(*I))
19287 RC = &ARM::DPRRegClass;
19288 else
19289 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
19290
19291 Register NewVR = MRI->createVirtualRegister(RC);
19292 // Create copy from CSR to a virtual register.
19293 // FIXME: this currently does not emit CFI pseudo-instructions, it works
19294 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
19295 // nounwind. If we want to generalize this later, we may need to emit
19296 // CFI pseudo-instructions.
19297 assert(Entry->getParent()->getFunction().hasFnAttribute(
19298 Attribute::NoUnwind) &&
19299 "Function should be nounwind in insertCopiesSplitCSR!");
19300 Entry->addLiveIn(*I);
19301 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
19302 .addReg(*I);
19303
19304 // Insert the copy-back instructions right before the terminator.
19305 for (auto *Exit : Exits)
19306 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
19307 TII->get(TargetOpcode::COPY), *I)
19308 .addReg(NewVR);
19309 }
19310 }
19311
finalizeLowering(MachineFunction & MF) const19312 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
19313 MF.getFrameInfo().computeMaxCallFrameSize(MF);
19314 TargetLoweringBase::finalizeLowering(MF);
19315 }
19316