[Alignment][NFC] Remove unneeded llvm:: scoping on Align types
[llvm-core.git] / lib / Target / ARM / ARMISelLowering.cpp
blob989c9477b7e20000c2b2172e9506ae22100b2885
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.
12 //===----------------------------------------------------------------------===//
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/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCInstrDesc.h"
87 #include "llvm/MC/MCInstrItineraries.h"
88 #include "llvm/MC/MCRegisterInfo.h"
89 #include "llvm/MC/MCSchedule.h"
90 #include "llvm/Support/AtomicOrdering.h"
91 #include "llvm/Support/BranchProbability.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CodeGen.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/KnownBits.h"
99 #include "llvm/Support/MachineValueType.h"
100 #include "llvm/Support/MathExtras.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
115 using namespace llvm;
116 using namespace llvm::PatternMatch;
118 #define DEBUG_TYPE "arm-isel"
120 STATISTIC(NumTailCalls, "Number of tail calls");
121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
123 STATISTIC(NumConstpoolPromoted,
124 "Number of constants with their storage promoted into constant pools");
126 static cl::opt<bool>
127 ARMInterworking("arm-interworking", cl::Hidden,
128 cl::desc("Enable / disable ARM interworking (for debugging only)"),
129 cl::init(true));
131 static cl::opt<bool> EnableConstpoolPromotion(
132 "arm-promote-constant", cl::Hidden,
133 cl::desc("Enable / disable promotion of unnamed_addr constants into "
134 "constant pools"),
135 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
136 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
137 "arm-promote-constant-max-size", cl::Hidden,
138 cl::desc("Maximum size of constant to promote into a constant pool"),
139 cl::init(64));
140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
141 "arm-promote-constant-max-total", cl::Hidden,
142 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
143 cl::init(128));
145 // The APCS parameter registers.
146 static const MCPhysReg GPRArgRegs[] = {
147 ARM::R0, ARM::R1, ARM::R2, ARM::R3
150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
151 MVT PromotedBitwiseVT) {
152 if (VT != PromotedLdStVT) {
153 setOperationAction(ISD::LOAD, VT, Promote);
154 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
156 setOperationAction(ISD::STORE, VT, Promote);
157 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
160 MVT ElemTy = VT.getVectorElementType();
161 if (ElemTy != MVT::f64)
162 setOperationAction(ISD::SETCC, VT, Custom);
163 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
164 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
165 if (ElemTy == MVT::i32) {
166 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
167 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
168 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
169 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
170 } else {
171 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
172 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
173 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
174 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
176 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
177 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
178 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
179 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
180 setOperationAction(ISD::SELECT, VT, Expand);
181 setOperationAction(ISD::SELECT_CC, VT, Expand);
182 setOperationAction(ISD::VSELECT, VT, Expand);
183 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
184 if (VT.isInteger()) {
185 setOperationAction(ISD::SHL, VT, Custom);
186 setOperationAction(ISD::SRA, VT, Custom);
187 setOperationAction(ISD::SRL, VT, Custom);
190 // Promote all bit-wise operations.
191 if (VT.isInteger() && VT != PromotedBitwiseVT) {
192 setOperationAction(ISD::AND, VT, Promote);
193 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
194 setOperationAction(ISD::OR, VT, Promote);
195 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
196 setOperationAction(ISD::XOR, VT, Promote);
197 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
200 // Neon does not support vector divide/remainder operations.
201 setOperationAction(ISD::SDIV, VT, Expand);
202 setOperationAction(ISD::UDIV, VT, Expand);
203 setOperationAction(ISD::FDIV, VT, Expand);
204 setOperationAction(ISD::SREM, VT, Expand);
205 setOperationAction(ISD::UREM, VT, Expand);
206 setOperationAction(ISD::FREM, VT, Expand);
208 if (!VT.isFloatingPoint() &&
209 VT != MVT::v2i64 && VT != MVT::v1i64)
210 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
211 setOperationAction(Opcode, VT, Legal);
214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
215 addRegisterClass(VT, &ARM::DPRRegClass);
216 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
220 addRegisterClass(VT, &ARM::DPairRegClass);
221 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
224 void ARMTargetLowering::setAllExpand(MVT VT) {
225 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
226 setOperationAction(Opc, VT, Expand);
228 // We support these really simple operations even on types where all
229 // the actual arithmetic has to be broken down into simpler
230 // operations or turned into library calls.
231 setOperationAction(ISD::BITCAST, VT, Legal);
232 setOperationAction(ISD::LOAD, VT, Legal);
233 setOperationAction(ISD::STORE, VT, Legal);
234 setOperationAction(ISD::UNDEF, VT, Legal);
237 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
238 LegalizeAction Action) {
239 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
240 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
241 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
244 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
245 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
247 for (auto VT : IntTypes) {
248 addRegisterClass(VT, &ARM::MQPRRegClass);
249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
250 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
251 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
252 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
253 setOperationAction(ISD::SHL, VT, Custom);
254 setOperationAction(ISD::SRA, VT, Custom);
255 setOperationAction(ISD::SRL, VT, Custom);
256 setOperationAction(ISD::SMIN, VT, Legal);
257 setOperationAction(ISD::SMAX, VT, Legal);
258 setOperationAction(ISD::UMIN, VT, Legal);
259 setOperationAction(ISD::UMAX, VT, Legal);
260 setOperationAction(ISD::ABS, VT, Legal);
261 setOperationAction(ISD::SETCC, VT, Custom);
262 setOperationAction(ISD::MLOAD, VT, Custom);
263 setOperationAction(ISD::MSTORE, VT, Legal);
264 setOperationAction(ISD::CTLZ, VT, Legal);
265 setOperationAction(ISD::CTTZ, VT, Custom);
266 setOperationAction(ISD::BITREVERSE, VT, Legal);
267 setOperationAction(ISD::BSWAP, VT, Legal);
269 // No native support for these.
270 setOperationAction(ISD::UDIV, VT, Expand);
271 setOperationAction(ISD::SDIV, VT, Expand);
272 setOperationAction(ISD::UREM, VT, Expand);
273 setOperationAction(ISD::SREM, VT, Expand);
274 setOperationAction(ISD::CTPOP, VT, Expand);
276 // Vector reductions
277 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
278 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
279 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
280 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
281 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
283 if (!HasMVEFP) {
284 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
285 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
286 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
287 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
290 // Pre and Post inc are supported on loads and stores
291 for (unsigned im = (unsigned)ISD::PRE_INC;
292 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
293 setIndexedLoadAction(im, VT, Legal);
294 setIndexedStoreAction(im, VT, Legal);
298 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
299 for (auto VT : FloatTypes) {
300 addRegisterClass(VT, &ARM::MQPRRegClass);
301 if (!HasMVEFP)
302 setAllExpand(VT);
304 // These are legal or custom whether we have MVE.fp or not
305 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
306 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
307 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
308 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
309 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
310 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
311 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
312 setOperationAction(ISD::SETCC, VT, Custom);
313 setOperationAction(ISD::MLOAD, VT, Custom);
314 setOperationAction(ISD::MSTORE, VT, Legal);
316 // Pre and Post inc are supported on loads and stores
317 for (unsigned im = (unsigned)ISD::PRE_INC;
318 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
319 setIndexedLoadAction(im, VT, Legal);
320 setIndexedStoreAction(im, VT, Legal);
323 if (HasMVEFP) {
324 setOperationAction(ISD::FMINNUM, VT, Legal);
325 setOperationAction(ISD::FMAXNUM, VT, Legal);
326 setOperationAction(ISD::FROUND, VT, Legal);
328 // No native support for these.
329 setOperationAction(ISD::FDIV, VT, Expand);
330 setOperationAction(ISD::FREM, VT, Expand);
331 setOperationAction(ISD::FSQRT, VT, Expand);
332 setOperationAction(ISD::FSIN, VT, Expand);
333 setOperationAction(ISD::FCOS, VT, Expand);
334 setOperationAction(ISD::FPOW, VT, Expand);
335 setOperationAction(ISD::FLOG, VT, Expand);
336 setOperationAction(ISD::FLOG2, VT, Expand);
337 setOperationAction(ISD::FLOG10, VT, Expand);
338 setOperationAction(ISD::FEXP, VT, Expand);
339 setOperationAction(ISD::FEXP2, VT, Expand);
340 setOperationAction(ISD::FNEARBYINT, VT, Expand);
344 // We 'support' these types up to bitcast/load/store level, regardless of
345 // MVE integer-only / float support. Only doing FP data processing on the FP
346 // vector types is inhibited at integer-only level.
347 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
348 for (auto VT : LongTypes) {
349 addRegisterClass(VT, &ARM::MQPRRegClass);
350 setAllExpand(VT);
351 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
352 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
353 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
355 // We can do bitwise operations on v2i64 vectors
356 setOperationAction(ISD::AND, MVT::v2i64, Legal);
357 setOperationAction(ISD::OR, MVT::v2i64, Legal);
358 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
360 // It is legal to extload from v4i8 to v4i16 or v4i32.
361 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
362 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
363 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
365 // Some truncating stores are legal too.
366 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
367 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
368 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
370 // Pre and Post inc on these are legal, given the correct extends
371 for (unsigned im = (unsigned)ISD::PRE_INC;
372 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
373 setIndexedLoadAction(im, MVT::v8i8, Legal);
374 setIndexedStoreAction(im, MVT::v8i8, Legal);
375 setIndexedLoadAction(im, MVT::v4i8, Legal);
376 setIndexedStoreAction(im, MVT::v4i8, Legal);
377 setIndexedLoadAction(im, MVT::v4i16, Legal);
378 setIndexedStoreAction(im, MVT::v4i16, Legal);
381 // Predicate types
382 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
383 for (auto VT : pTypes) {
384 addRegisterClass(VT, &ARM::VCCRRegClass);
385 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
386 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
387 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
388 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
389 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
391 setOperationAction(ISD::SETCC, VT, Custom);
392 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
393 setOperationAction(ISD::LOAD, VT, Custom);
394 setOperationAction(ISD::STORE, VT, Custom);
398 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
399 const ARMSubtarget &STI)
400 : TargetLowering(TM), Subtarget(&STI) {
401 RegInfo = Subtarget->getRegisterInfo();
402 Itins = Subtarget->getInstrItineraryData();
404 setBooleanContents(ZeroOrOneBooleanContent);
405 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
407 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
408 !Subtarget->isTargetWatchOS()) {
409 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
410 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
411 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
412 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
413 : CallingConv::ARM_AAPCS);
416 if (Subtarget->isTargetMachO()) {
417 // Uses VFP for Thumb libfuncs if available.
418 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
419 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
420 static const struct {
421 const RTLIB::Libcall Op;
422 const char * const Name;
423 const ISD::CondCode Cond;
424 } LibraryCalls[] = {
425 // Single-precision floating-point arithmetic.
426 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
427 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
428 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
429 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
431 // Double-precision floating-point arithmetic.
432 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
433 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
434 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
435 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
437 // Single-precision comparisons.
438 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
439 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
440 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
441 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
442 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
443 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
444 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
445 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
447 // Double-precision comparisons.
448 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
449 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
450 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
451 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
452 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
453 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
454 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
455 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
457 // Floating-point to integer conversions.
458 // i64 conversions are done via library routines even when generating VFP
459 // instructions, so use the same ones.
460 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
461 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
462 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
463 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
465 // Conversions between floating types.
466 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
467 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
469 // Integer to floating-point conversions.
470 // i64 conversions are done via library routines even when generating VFP
471 // instructions, so use the same ones.
472 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
473 // e.g., __floatunsidf vs. __floatunssidfvfp.
474 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
475 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
476 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
477 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
480 for (const auto &LC : LibraryCalls) {
481 setLibcallName(LC.Op, LC.Name);
482 if (LC.Cond != ISD::SETCC_INVALID)
483 setCmpLibcallCC(LC.Op, LC.Cond);
488 // These libcalls are not available in 32-bit.
489 setLibcallName(RTLIB::SHL_I128, nullptr);
490 setLibcallName(RTLIB::SRL_I128, nullptr);
491 setLibcallName(RTLIB::SRA_I128, nullptr);
493 // RTLIB
494 if (Subtarget->isAAPCS_ABI() &&
495 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
496 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
497 static const struct {
498 const RTLIB::Libcall Op;
499 const char * const Name;
500 const CallingConv::ID CC;
501 const ISD::CondCode Cond;
502 } LibraryCalls[] = {
503 // Double-precision floating-point arithmetic helper functions
504 // RTABI chapter 4.1.2, Table 2
505 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
506 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
507 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
508 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510 // Double-precision floating-point comparison helper functions
511 // RTABI chapter 4.1.2, Table 3
512 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
513 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
514 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
515 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
516 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
517 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
518 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
519 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
521 // Single-precision floating-point arithmetic helper functions
522 // RTABI chapter 4.1.2, Table 4
523 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
524 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
525 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
526 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528 // Single-precision floating-point comparison helper functions
529 // RTABI chapter 4.1.2, Table 5
530 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
531 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
532 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
533 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
534 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
535 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
536 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
537 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
539 // Floating-point to integer conversions.
540 // RTABI chapter 4.1.2, Table 6
541 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
542 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
543 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
544 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
545 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
546 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
547 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
548 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
550 // Conversions between floating types.
551 // RTABI chapter 4.1.2, Table 7
552 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
553 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
554 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
556 // Integer to floating-point conversions.
557 // RTABI chapter 4.1.2, Table 8
558 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
559 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
560 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
561 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
562 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
563 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
564 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567 // Long long helper functions
568 // RTABI chapter 4.2, Table 9
569 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
570 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
571 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
572 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
574 // Integer division functions
575 // RTABI chapter 4.3.1
576 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
577 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
578 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
579 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
580 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
581 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
582 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
583 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
586 for (const auto &LC : LibraryCalls) {
587 setLibcallName(LC.Op, LC.Name);
588 setLibcallCallingConv(LC.Op, LC.CC);
589 if (LC.Cond != ISD::SETCC_INVALID)
590 setCmpLibcallCC(LC.Op, LC.Cond);
593 // EABI dependent RTLIB
594 if (TM.Options.EABIVersion == EABI::EABI4 ||
595 TM.Options.EABIVersion == EABI::EABI5) {
596 static const struct {
597 const RTLIB::Libcall Op;
598 const char *const Name;
599 const CallingConv::ID CC;
600 const ISD::CondCode Cond;
601 } MemOpsLibraryCalls[] = {
602 // Memory operations
603 // RTABI chapter 4.3.4
604 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
605 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
606 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
609 for (const auto &LC : MemOpsLibraryCalls) {
610 setLibcallName(LC.Op, LC.Name);
611 setLibcallCallingConv(LC.Op, LC.CC);
612 if (LC.Cond != ISD::SETCC_INVALID)
613 setCmpLibcallCC(LC.Op, LC.Cond);
618 if (Subtarget->isTargetWindows()) {
619 static const struct {
620 const RTLIB::Libcall Op;
621 const char * const Name;
622 const CallingConv::ID CC;
623 } LibraryCalls[] = {
624 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
625 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
626 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
627 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
628 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
629 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
630 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
631 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
634 for (const auto &LC : LibraryCalls) {
635 setLibcallName(LC.Op, LC.Name);
636 setLibcallCallingConv(LC.Op, LC.CC);
640 // Use divmod compiler-rt calls for iOS 5.0 and later.
641 if (Subtarget->isTargetMachO() &&
642 !(Subtarget->isTargetIOS() &&
643 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
644 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
645 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
648 // The half <-> float conversion functions are always soft-float on
649 // non-watchos platforms, but are needed for some targets which use a
650 // hard-float calling convention by default.
651 if (!Subtarget->isTargetWatchABI()) {
652 if (Subtarget->isAAPCS_ABI()) {
653 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
654 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
655 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
656 } else {
657 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
658 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
659 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
663 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
664 // a __gnu_ prefix (which is the default).
665 if (Subtarget->isTargetAEABI()) {
666 static const struct {
667 const RTLIB::Libcall Op;
668 const char * const Name;
669 const CallingConv::ID CC;
670 } LibraryCalls[] = {
671 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
672 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
673 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
676 for (const auto &LC : LibraryCalls) {
677 setLibcallName(LC.Op, LC.Name);
678 setLibcallCallingConv(LC.Op, LC.CC);
682 if (Subtarget->isThumb1Only())
683 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
684 else
685 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
687 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
688 Subtarget->hasFPRegs()) {
689 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
690 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
691 if (!Subtarget->hasVFP2Base())
692 setAllExpand(MVT::f32);
693 if (!Subtarget->hasFP64())
694 setAllExpand(MVT::f64);
697 if (Subtarget->hasFullFP16()) {
698 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
699 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
700 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
701 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
703 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
704 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
707 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
708 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
709 setTruncStoreAction(VT, InnerVT, Expand);
710 addAllExtLoads(VT, InnerVT, Expand);
713 setOperationAction(ISD::MULHS, VT, Expand);
714 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
715 setOperationAction(ISD::MULHU, VT, Expand);
716 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
718 setOperationAction(ISD::BSWAP, VT, Expand);
721 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
722 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
724 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
725 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
727 if (Subtarget->hasMVEIntegerOps())
728 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
730 // Combine low-overhead loop intrinsics so that we can lower i1 types.
731 if (Subtarget->hasLOB()) {
732 setTargetDAGCombine(ISD::BRCOND);
733 setTargetDAGCombine(ISD::BR_CC);
736 if (Subtarget->hasNEON()) {
737 addDRTypeForNEON(MVT::v2f32);
738 addDRTypeForNEON(MVT::v8i8);
739 addDRTypeForNEON(MVT::v4i16);
740 addDRTypeForNEON(MVT::v2i32);
741 addDRTypeForNEON(MVT::v1i64);
743 addQRTypeForNEON(MVT::v4f32);
744 addQRTypeForNEON(MVT::v2f64);
745 addQRTypeForNEON(MVT::v16i8);
746 addQRTypeForNEON(MVT::v8i16);
747 addQRTypeForNEON(MVT::v4i32);
748 addQRTypeForNEON(MVT::v2i64);
750 if (Subtarget->hasFullFP16()) {
751 addQRTypeForNEON(MVT::v8f16);
752 addDRTypeForNEON(MVT::v4f16);
756 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
757 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
758 // none of Neon, MVE or VFP supports any arithmetic operations on it.
759 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
760 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
761 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
762 // FIXME: Code duplication: FDIV and FREM are expanded always, see
763 // ARMTargetLowering::addTypeForNEON method for details.
764 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
765 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
766 // FIXME: Create unittest.
767 // In another words, find a way when "copysign" appears in DAG with vector
768 // operands.
769 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
770 // FIXME: Code duplication: SETCC has custom operation action, see
771 // ARMTargetLowering::addTypeForNEON method for details.
772 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
773 // FIXME: Create unittest for FNEG and for FABS.
774 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
775 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
776 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
777 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
778 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
779 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
780 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
781 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
782 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
783 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
784 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
785 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
786 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
787 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
788 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
789 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
790 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
791 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
794 if (Subtarget->hasNEON()) {
795 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
796 // supported for v4f32.
797 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
798 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
799 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
800 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
801 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
802 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
803 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
804 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
805 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
806 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
807 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
808 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
809 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
810 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
812 // Mark v2f32 intrinsics.
813 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
814 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
815 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
816 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
817 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
818 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
819 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
820 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
821 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
822 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
823 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
824 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
825 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
826 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
828 // Neon does not support some operations on v1i64 and v2i64 types.
829 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
830 // Custom handling for some quad-vector types to detect VMULL.
831 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
832 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
833 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
834 // Custom handling for some vector types to avoid expensive expansions
835 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
836 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
837 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
838 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
839 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
840 // a destination type that is wider than the source, and nor does
841 // it have a FP_TO_[SU]INT instruction with a narrower destination than
842 // source.
843 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
844 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
845 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
846 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
847 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
848 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
849 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
850 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
852 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
853 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
855 // NEON does not have single instruction CTPOP for vectors with element
856 // types wider than 8-bits. However, custom lowering can leverage the
857 // v8i8/v16i8 vcnt instruction.
858 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
859 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
860 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
861 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
862 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
863 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
865 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
866 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
868 // NEON does not have single instruction CTTZ for vectors.
869 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
870 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
871 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
872 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
874 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
875 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
876 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
877 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
879 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
880 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
881 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
882 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
884 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
885 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
886 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
887 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
889 // NEON only has FMA instructions as of VFP4.
890 if (!Subtarget->hasVFP4Base()) {
891 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
892 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
895 setTargetDAGCombine(ISD::INTRINSIC_VOID);
896 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
897 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
898 setTargetDAGCombine(ISD::SHL);
899 setTargetDAGCombine(ISD::SRL);
900 setTargetDAGCombine(ISD::SRA);
901 setTargetDAGCombine(ISD::FP_TO_SINT);
902 setTargetDAGCombine(ISD::FP_TO_UINT);
903 setTargetDAGCombine(ISD::FDIV);
904 setTargetDAGCombine(ISD::LOAD);
906 // It is legal to extload from v4i8 to v4i16 or v4i32.
907 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
908 MVT::v2i32}) {
909 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
910 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
911 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
912 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
917 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
918 setTargetDAGCombine(ISD::BUILD_VECTOR);
919 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
920 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
921 setTargetDAGCombine(ISD::STORE);
922 setTargetDAGCombine(ISD::SIGN_EXTEND);
923 setTargetDAGCombine(ISD::ZERO_EXTEND);
924 setTargetDAGCombine(ISD::ANY_EXTEND);
927 if (!Subtarget->hasFP64()) {
928 // When targeting a floating-point unit with only single-precision
929 // operations, f64 is legal for the few double-precision instructions which
930 // are present However, no double-precision operations other than moves,
931 // loads and stores are provided by the hardware.
932 setOperationAction(ISD::FADD, MVT::f64, Expand);
933 setOperationAction(ISD::FSUB, MVT::f64, Expand);
934 setOperationAction(ISD::FMUL, MVT::f64, Expand);
935 setOperationAction(ISD::FMA, MVT::f64, Expand);
936 setOperationAction(ISD::FDIV, MVT::f64, Expand);
937 setOperationAction(ISD::FREM, MVT::f64, Expand);
938 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
939 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
940 setOperationAction(ISD::FNEG, MVT::f64, Expand);
941 setOperationAction(ISD::FABS, MVT::f64, Expand);
942 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
943 setOperationAction(ISD::FSIN, MVT::f64, Expand);
944 setOperationAction(ISD::FCOS, MVT::f64, Expand);
945 setOperationAction(ISD::FPOW, MVT::f64, Expand);
946 setOperationAction(ISD::FLOG, MVT::f64, Expand);
947 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
948 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
949 setOperationAction(ISD::FEXP, MVT::f64, Expand);
950 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
951 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
952 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
953 setOperationAction(ISD::FRINT, MVT::f64, Expand);
954 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
955 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
956 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
957 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
958 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
959 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
960 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
961 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
962 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
965 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
966 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
967 if (Subtarget->hasFullFP16())
968 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
971 if (!Subtarget->hasFP16())
972 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
974 if (!Subtarget->hasFP64())
975 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
977 computeRegisterProperties(Subtarget->getRegisterInfo());
979 // ARM does not have floating-point extending loads.
980 for (MVT VT : MVT::fp_valuetypes()) {
981 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
982 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
985 // ... or truncating stores
986 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
987 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
988 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
990 // ARM does not have i1 sign extending load.
991 for (MVT VT : MVT::integer_valuetypes())
992 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
994 // ARM supports all 4 flavors of integer indexed load / store.
995 if (!Subtarget->isThumb1Only()) {
996 for (unsigned im = (unsigned)ISD::PRE_INC;
997 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
998 setIndexedLoadAction(im, MVT::i1, Legal);
999 setIndexedLoadAction(im, MVT::i8, Legal);
1000 setIndexedLoadAction(im, MVT::i16, Legal);
1001 setIndexedLoadAction(im, MVT::i32, Legal);
1002 setIndexedStoreAction(im, MVT::i1, Legal);
1003 setIndexedStoreAction(im, MVT::i8, Legal);
1004 setIndexedStoreAction(im, MVT::i16, Legal);
1005 setIndexedStoreAction(im, MVT::i32, Legal);
1007 } else {
1008 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1009 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1010 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1013 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1014 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1015 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1016 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1018 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1019 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1021 // i64 operation support.
1022 setOperationAction(ISD::MUL, MVT::i64, Expand);
1023 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1024 if (Subtarget->isThumb1Only()) {
1025 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1026 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1028 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1029 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1030 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1032 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1033 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1034 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1035 setOperationAction(ISD::SRL, MVT::i64, Custom);
1036 setOperationAction(ISD::SRA, MVT::i64, Custom);
1037 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1038 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1040 // MVE lowers 64 bit shifts to lsll and lsrl
1041 // assuming that ISD::SRL and SRA of i64 are already marked custom
1042 if (Subtarget->hasMVEIntegerOps())
1043 setOperationAction(ISD::SHL, MVT::i64, Custom);
1045 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1046 if (Subtarget->isThumb1Only()) {
1047 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1048 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1049 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1052 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1053 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1055 // ARM does not have ROTL.
1056 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1057 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1058 setOperationAction(ISD::ROTL, VT, Expand);
1059 setOperationAction(ISD::ROTR, VT, Expand);
1061 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1062 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1063 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1064 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1065 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1068 // @llvm.readcyclecounter requires the Performance Monitors extension.
1069 // Default to the 0 expansion on unsupported platforms.
1070 // FIXME: Technically there are older ARM CPUs that have
1071 // implementation-specific ways of obtaining this information.
1072 if (Subtarget->hasPerfMon())
1073 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1075 // Only ARMv6 has BSWAP.
1076 if (!Subtarget->hasV6Ops())
1077 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1079 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1080 : Subtarget->hasDivideInARMMode();
1081 if (!hasDivide) {
1082 // These are expanded into libcalls if the cpu doesn't have HW divider.
1083 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1084 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1087 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1088 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1089 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1091 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1092 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1095 setOperationAction(ISD::SREM, MVT::i32, Expand);
1096 setOperationAction(ISD::UREM, MVT::i32, Expand);
1098 // Register based DivRem for AEABI (RTABI 4.2)
1099 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1100 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1101 Subtarget->isTargetWindows()) {
1102 setOperationAction(ISD::SREM, MVT::i64, Custom);
1103 setOperationAction(ISD::UREM, MVT::i64, Custom);
1104 HasStandaloneRem = false;
1106 if (Subtarget->isTargetWindows()) {
1107 const struct {
1108 const RTLIB::Libcall Op;
1109 const char * const Name;
1110 const CallingConv::ID CC;
1111 } LibraryCalls[] = {
1112 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1113 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1114 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1115 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1117 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1118 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1119 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1120 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1123 for (const auto &LC : LibraryCalls) {
1124 setLibcallName(LC.Op, LC.Name);
1125 setLibcallCallingConv(LC.Op, LC.CC);
1127 } else {
1128 const struct {
1129 const RTLIB::Libcall Op;
1130 const char * const Name;
1131 const CallingConv::ID CC;
1132 } LibraryCalls[] = {
1133 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1134 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1135 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1136 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1138 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1139 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1140 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1141 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1144 for (const auto &LC : LibraryCalls) {
1145 setLibcallName(LC.Op, LC.Name);
1146 setLibcallCallingConv(LC.Op, LC.CC);
1150 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1151 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1152 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1153 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1154 } else {
1155 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1159 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
1160 for (auto &VT : {MVT::f32, MVT::f64})
1161 setOperationAction(ISD::FPOWI, VT, Custom);
1163 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1164 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1165 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1166 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1168 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1169 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1171 // Use the default implementation.
1172 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1173 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1174 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1175 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1176 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1177 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1179 if (Subtarget->isTargetWindows())
1180 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1181 else
1182 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1184 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1185 // the default expansion.
1186 InsertFencesForAtomic = false;
1187 if (Subtarget->hasAnyDataBarrier() &&
1188 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1189 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1190 // to ldrex/strex loops already.
1191 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1192 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1193 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1195 // On v8, we have particularly efficient implementations of atomic fences
1196 // if they can be combined with nearby atomic loads and stores.
1197 if (!Subtarget->hasAcquireRelease() ||
1198 getTargetMachine().getOptLevel() == 0) {
1199 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1200 InsertFencesForAtomic = true;
1202 } else {
1203 // If there's anything we can use as a barrier, go through custom lowering
1204 // for ATOMIC_FENCE.
1205 // If target has DMB in thumb, Fences can be inserted.
1206 if (Subtarget->hasDataBarrier())
1207 InsertFencesForAtomic = true;
1209 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1210 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1212 // Set them all for expansion, which will force libcalls.
1213 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1214 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1215 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1216 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1217 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1218 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1219 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1220 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1221 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1222 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1223 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1224 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1225 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1226 // Unordered/Monotonic case.
1227 if (!InsertFencesForAtomic) {
1228 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1229 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1233 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1235 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1236 if (!Subtarget->hasV6Ops()) {
1237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1242 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1243 !Subtarget->isThumb1Only()) {
1244 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1245 // iff target supports vfp2.
1246 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1247 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1250 // We want to custom lower some of our intrinsics.
1251 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1252 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1253 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1254 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1255 if (Subtarget->useSjLjEH())
1256 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1258 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1259 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1260 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1261 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1262 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1263 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1264 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1265 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1266 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1267 if (Subtarget->hasFullFP16()) {
1268 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1269 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1270 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1273 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1275 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1276 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1277 if (Subtarget->hasFullFP16())
1278 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1279 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1280 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1281 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1283 // We don't support sin/cos/fmod/copysign/pow
1284 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1285 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1286 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1287 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1288 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1289 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1290 setOperationAction(ISD::FREM, MVT::f64, Expand);
1291 setOperationAction(ISD::FREM, MVT::f32, Expand);
1292 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1293 !Subtarget->isThumb1Only()) {
1294 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1295 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1297 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1298 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1300 if (!Subtarget->hasVFP4Base()) {
1301 setOperationAction(ISD::FMA, MVT::f64, Expand);
1302 setOperationAction(ISD::FMA, MVT::f32, Expand);
1305 // Various VFP goodness
1306 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1307 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1308 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1309 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1310 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1313 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1314 if (!Subtarget->hasFP16()) {
1315 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1316 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1320 // Use __sincos_stret if available.
1321 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1322 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1323 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1324 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1327 // FP-ARMv8 implements a lot of rounding-like FP operations.
1328 if (Subtarget->hasFPARMv8Base()) {
1329 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1330 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1331 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1332 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1333 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1334 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1335 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1336 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1337 if (Subtarget->hasNEON()) {
1338 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1339 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1340 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1341 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1344 if (Subtarget->hasFP64()) {
1345 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1346 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1347 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1348 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1349 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1350 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1351 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1352 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1356 // FP16 often need to be promoted to call lib functions
1357 if (Subtarget->hasFullFP16()) {
1358 setOperationAction(ISD::FREM, MVT::f16, Promote);
1359 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1360 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1361 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1362 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1363 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1364 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1365 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1366 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1367 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1368 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1369 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1371 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1374 if (Subtarget->hasNEON()) {
1375 // vmin and vmax aren't available in a scalar form, so we use
1376 // a NEON instruction with an undef lane instead.
1377 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1378 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1379 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1380 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1381 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1382 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1383 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1384 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1386 if (Subtarget->hasFullFP16()) {
1387 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1388 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1389 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1390 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1392 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1393 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1394 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1395 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1399 // We have target-specific dag combine patterns for the following nodes:
1400 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1401 setTargetDAGCombine(ISD::ADD);
1402 setTargetDAGCombine(ISD::SUB);
1403 setTargetDAGCombine(ISD::MUL);
1404 setTargetDAGCombine(ISD::AND);
1405 setTargetDAGCombine(ISD::OR);
1406 setTargetDAGCombine(ISD::XOR);
1408 if (Subtarget->hasV6Ops())
1409 setTargetDAGCombine(ISD::SRL);
1410 if (Subtarget->isThumb1Only())
1411 setTargetDAGCombine(ISD::SHL);
1413 setStackPointerRegisterToSaveRestore(ARM::SP);
1415 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1416 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1417 setSchedulingPreference(Sched::RegPressure);
1418 else
1419 setSchedulingPreference(Sched::Hybrid);
1421 //// temporary - rewrite interface to use type
1422 MaxStoresPerMemset = 8;
1423 MaxStoresPerMemsetOptSize = 4;
1424 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1425 MaxStoresPerMemcpyOptSize = 2;
1426 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1427 MaxStoresPerMemmoveOptSize = 2;
1429 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1430 // are at least 4 bytes aligned.
1431 setMinStackArgumentAlignment(Align(4));
1433 // Prefer likely predicted branches to selects on out-of-order cores.
1434 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1436 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1438 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1440 if (Subtarget->isThumb() || Subtarget->isThumb2())
1441 setTargetDAGCombine(ISD::ABS);
1444 bool ARMTargetLowering::useSoftFloat() const {
1445 return Subtarget->useSoftFloat();
1448 // FIXME: It might make sense to define the representative register class as the
1449 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1450 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1451 // SPR's representative would be DPR_VFP2. This should work well if register
1452 // pressure tracking were modified such that a register use would increment the
1453 // pressure of the register class's representative and all of it's super
1454 // classes' representatives transitively. We have not implemented this because
1455 // of the difficulty prior to coalescing of modeling operand register classes
1456 // due to the common occurrence of cross class copies and subregister insertions
1457 // and extractions.
1458 std::pair<const TargetRegisterClass *, uint8_t>
1459 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1460 MVT VT) const {
1461 const TargetRegisterClass *RRC = nullptr;
1462 uint8_t Cost = 1;
1463 switch (VT.SimpleTy) {
1464 default:
1465 return TargetLowering::findRepresentativeClass(TRI, VT);
1466 // Use DPR as representative register class for all floating point
1467 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1468 // the cost is 1 for both f32 and f64.
1469 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1470 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1471 RRC = &ARM::DPRRegClass;
1472 // When NEON is used for SP, only half of the register file is available
1473 // because operations that define both SP and DP results will be constrained
1474 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1475 // coalescing by double-counting the SP regs. See the FIXME above.
1476 if (Subtarget->useNEONForSinglePrecisionFP())
1477 Cost = 2;
1478 break;
1479 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1480 case MVT::v4f32: case MVT::v2f64:
1481 RRC = &ARM::DPRRegClass;
1482 Cost = 2;
1483 break;
1484 case MVT::v4i64:
1485 RRC = &ARM::DPRRegClass;
1486 Cost = 4;
1487 break;
1488 case MVT::v8i64:
1489 RRC = &ARM::DPRRegClass;
1490 Cost = 8;
1491 break;
1493 return std::make_pair(RRC, Cost);
1496 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1497 switch ((ARMISD::NodeType)Opcode) {
1498 case ARMISD::FIRST_NUMBER: break;
1499 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1500 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1501 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1502 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1503 case ARMISD::CALL: return "ARMISD::CALL";
1504 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1505 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1506 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1507 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1508 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1509 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1510 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1511 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1512 case ARMISD::CMP: return "ARMISD::CMP";
1513 case ARMISD::CMN: return "ARMISD::CMN";
1514 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1515 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1516 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1517 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1518 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1520 case ARMISD::CMOV: return "ARMISD::CMOV";
1521 case ARMISD::SUBS: return "ARMISD::SUBS";
1523 case ARMISD::SSAT: return "ARMISD::SSAT";
1524 case ARMISD::USAT: return "ARMISD::USAT";
1526 case ARMISD::ASRL: return "ARMISD::ASRL";
1527 case ARMISD::LSRL: return "ARMISD::LSRL";
1528 case ARMISD::LSLL: return "ARMISD::LSLL";
1530 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1531 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1532 case ARMISD::RRX: return "ARMISD::RRX";
1534 case ARMISD::ADDC: return "ARMISD::ADDC";
1535 case ARMISD::ADDE: return "ARMISD::ADDE";
1536 case ARMISD::SUBC: return "ARMISD::SUBC";
1537 case ARMISD::SUBE: return "ARMISD::SUBE";
1538 case ARMISD::LSLS: return "ARMISD::LSLS";
1540 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1541 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1542 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1543 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1544 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1546 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1547 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1548 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1550 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1552 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1554 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1556 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1558 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1560 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1561 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1563 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1564 case ARMISD::VCMP: return "ARMISD::VCMP";
1565 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1566 case ARMISD::VTST: return "ARMISD::VTST";
1568 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1569 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1570 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1571 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1572 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1573 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1574 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1575 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1576 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1577 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1578 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1579 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1580 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1581 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1582 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1583 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1584 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1585 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1586 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1587 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1588 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1589 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1590 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1591 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1592 case ARMISD::VDUP: return "ARMISD::VDUP";
1593 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1594 case ARMISD::VEXT: return "ARMISD::VEXT";
1595 case ARMISD::VREV64: return "ARMISD::VREV64";
1596 case ARMISD::VREV32: return "ARMISD::VREV32";
1597 case ARMISD::VREV16: return "ARMISD::VREV16";
1598 case ARMISD::VZIP: return "ARMISD::VZIP";
1599 case ARMISD::VUZP: return "ARMISD::VUZP";
1600 case ARMISD::VTRN: return "ARMISD::VTRN";
1601 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1602 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1603 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1604 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1605 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1606 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1607 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1608 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1609 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1610 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1611 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1612 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1613 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1614 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1615 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1616 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1617 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1618 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1619 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1620 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1621 case ARMISD::BFI: return "ARMISD::BFI";
1622 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1623 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1624 case ARMISD::VBSL: return "ARMISD::VBSL";
1625 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1626 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1627 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1628 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1629 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1630 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1631 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1632 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1633 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1634 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1635 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1636 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1637 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1638 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1639 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1640 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1641 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1642 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1643 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1644 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1645 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1646 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1647 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1648 case ARMISD::WLS: return "ARMISD::WLS";
1649 case ARMISD::LE: return "ARMISD::LE";
1650 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1651 case ARMISD::CSINV: return "ARMISD::CSINV";
1652 case ARMISD::CSNEG: return "ARMISD::CSNEG";
1653 case ARMISD::CSINC: return "ARMISD::CSINC";
1655 return nullptr;
1658 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1659 EVT VT) const {
1660 if (!VT.isVector())
1661 return getPointerTy(DL);
1663 // MVE has a predicate register.
1664 if (Subtarget->hasMVEIntegerOps() &&
1665 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1666 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1667 return VT.changeVectorElementTypeToInteger();
1670 /// getRegClassFor - Return the register class that should be used for the
1671 /// specified value type.
1672 const TargetRegisterClass *
1673 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1674 (void)isDivergent;
1675 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1676 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1677 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1678 // MVE Q registers.
1679 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1680 if (VT == MVT::v4i64)
1681 return &ARM::QQPRRegClass;
1682 if (VT == MVT::v8i64)
1683 return &ARM::QQQQPRRegClass;
1685 return TargetLowering::getRegClassFor(VT);
1688 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1689 // source/dest is aligned and the copy size is large enough. We therefore want
1690 // to align such objects passed to memory intrinsics.
1691 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1692 unsigned &PrefAlign) const {
1693 if (!isa<MemIntrinsic>(CI))
1694 return false;
1695 MinSize = 8;
1696 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1697 // cycle faster than 4-byte aligned LDM.
1698 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1699 return true;
1702 // Create a fast isel object.
1703 FastISel *
1704 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1705 const TargetLibraryInfo *libInfo) const {
1706 return ARM::createFastISel(funcInfo, libInfo);
1709 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1710 unsigned NumVals = N->getNumValues();
1711 if (!NumVals)
1712 return Sched::RegPressure;
1714 for (unsigned i = 0; i != NumVals; ++i) {
1715 EVT VT = N->getValueType(i);
1716 if (VT == MVT::Glue || VT == MVT::Other)
1717 continue;
1718 if (VT.isFloatingPoint() || VT.isVector())
1719 return Sched::ILP;
1722 if (!N->isMachineOpcode())
1723 return Sched::RegPressure;
1725 // Load are scheduled for latency even if there instruction itinerary
1726 // is not available.
1727 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1728 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1730 if (MCID.getNumDefs() == 0)
1731 return Sched::RegPressure;
1732 if (!Itins->isEmpty() &&
1733 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1734 return Sched::ILP;
1736 return Sched::RegPressure;
1739 //===----------------------------------------------------------------------===//
1740 // Lowering Code
1741 //===----------------------------------------------------------------------===//
1743 static bool isSRL16(const SDValue &Op) {
1744 if (Op.getOpcode() != ISD::SRL)
1745 return false;
1746 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1747 return Const->getZExtValue() == 16;
1748 return false;
1751 static bool isSRA16(const SDValue &Op) {
1752 if (Op.getOpcode() != ISD::SRA)
1753 return false;
1754 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1755 return Const->getZExtValue() == 16;
1756 return false;
1759 static bool isSHL16(const SDValue &Op) {
1760 if (Op.getOpcode() != ISD::SHL)
1761 return false;
1762 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1763 return Const->getZExtValue() == 16;
1764 return false;
1767 // Check for a signed 16-bit value. We special case SRA because it makes it
1768 // more simple when also looking for SRAs that aren't sign extending a
1769 // smaller value. Without the check, we'd need to take extra care with
1770 // checking order for some operations.
1771 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1772 if (isSRA16(Op))
1773 return isSHL16(Op.getOperand(0));
1774 return DAG.ComputeNumSignBits(Op) == 17;
1777 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1778 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1779 switch (CC) {
1780 default: llvm_unreachable("Unknown condition code!");
1781 case ISD::SETNE: return ARMCC::NE;
1782 case ISD::SETEQ: return ARMCC::EQ;
1783 case ISD::SETGT: return ARMCC::GT;
1784 case ISD::SETGE: return ARMCC::GE;
1785 case ISD::SETLT: return ARMCC::LT;
1786 case ISD::SETLE: return ARMCC::LE;
1787 case ISD::SETUGT: return ARMCC::HI;
1788 case ISD::SETUGE: return ARMCC::HS;
1789 case ISD::SETULT: return ARMCC::LO;
1790 case ISD::SETULE: return ARMCC::LS;
1794 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1795 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1796 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1797 CondCode2 = ARMCC::AL;
1798 InvalidOnQNaN = true;
1799 switch (CC) {
1800 default: llvm_unreachable("Unknown FP condition!");
1801 case ISD::SETEQ:
1802 case ISD::SETOEQ:
1803 CondCode = ARMCC::EQ;
1804 InvalidOnQNaN = false;
1805 break;
1806 case ISD::SETGT:
1807 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1808 case ISD::SETGE:
1809 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1810 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1811 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1812 case ISD::SETONE:
1813 CondCode = ARMCC::MI;
1814 CondCode2 = ARMCC::GT;
1815 InvalidOnQNaN = false;
1816 break;
1817 case ISD::SETO: CondCode = ARMCC::VC; break;
1818 case ISD::SETUO: CondCode = ARMCC::VS; break;
1819 case ISD::SETUEQ:
1820 CondCode = ARMCC::EQ;
1821 CondCode2 = ARMCC::VS;
1822 InvalidOnQNaN = false;
1823 break;
1824 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1825 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1826 case ISD::SETLT:
1827 case ISD::SETULT: CondCode = ARMCC::LT; break;
1828 case ISD::SETLE:
1829 case ISD::SETULE: CondCode = ARMCC::LE; break;
1830 case ISD::SETNE:
1831 case ISD::SETUNE:
1832 CondCode = ARMCC::NE;
1833 InvalidOnQNaN = false;
1834 break;
1838 //===----------------------------------------------------------------------===//
1839 // Calling Convention Implementation
1840 //===----------------------------------------------------------------------===//
1842 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1843 /// account presence of floating point hardware and calling convention
1844 /// limitations, such as support for variadic functions.
1845 CallingConv::ID
1846 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1847 bool isVarArg) const {
1848 switch (CC) {
1849 default:
1850 report_fatal_error("Unsupported calling convention");
1851 case CallingConv::ARM_AAPCS:
1852 case CallingConv::ARM_APCS:
1853 case CallingConv::GHC:
1854 return CC;
1855 case CallingConv::PreserveMost:
1856 return CallingConv::PreserveMost;
1857 case CallingConv::ARM_AAPCS_VFP:
1858 case CallingConv::Swift:
1859 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1860 case CallingConv::C:
1861 if (!Subtarget->isAAPCS_ABI())
1862 return CallingConv::ARM_APCS;
1863 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1864 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1865 !isVarArg)
1866 return CallingConv::ARM_AAPCS_VFP;
1867 else
1868 return CallingConv::ARM_AAPCS;
1869 case CallingConv::Fast:
1870 case CallingConv::CXX_FAST_TLS:
1871 if (!Subtarget->isAAPCS_ABI()) {
1872 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1873 return CallingConv::Fast;
1874 return CallingConv::ARM_APCS;
1875 } else if (Subtarget->hasVFP2Base() &&
1876 !Subtarget->isThumb1Only() && !isVarArg)
1877 return CallingConv::ARM_AAPCS_VFP;
1878 else
1879 return CallingConv::ARM_AAPCS;
1883 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1884 bool isVarArg) const {
1885 return CCAssignFnForNode(CC, false, isVarArg);
1888 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1889 bool isVarArg) const {
1890 return CCAssignFnForNode(CC, true, isVarArg);
1893 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1894 /// CallingConvention.
1895 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1896 bool Return,
1897 bool isVarArg) const {
1898 switch (getEffectiveCallingConv(CC, isVarArg)) {
1899 default:
1900 report_fatal_error("Unsupported calling convention");
1901 case CallingConv::ARM_APCS:
1902 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1903 case CallingConv::ARM_AAPCS:
1904 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1905 case CallingConv::ARM_AAPCS_VFP:
1906 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1907 case CallingConv::Fast:
1908 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1909 case CallingConv::GHC:
1910 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1911 case CallingConv::PreserveMost:
1912 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1916 /// LowerCallResult - Lower the result values of a call into the
1917 /// appropriate copies out of appropriate physical registers.
1918 SDValue ARMTargetLowering::LowerCallResult(
1919 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1920 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1921 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1922 SDValue ThisVal) const {
1923 // Assign locations to each value returned by this call.
1924 SmallVector<CCValAssign, 16> RVLocs;
1925 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1926 *DAG.getContext());
1927 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1929 // Copy all of the result registers out of their specified physreg.
1930 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1931 CCValAssign VA = RVLocs[i];
1933 // Pass 'this' value directly from the argument to return value, to avoid
1934 // reg unit interference
1935 if (i == 0 && isThisReturn) {
1936 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1937 "unexpected return calling convention register assignment");
1938 InVals.push_back(ThisVal);
1939 continue;
1942 SDValue Val;
1943 if (VA.needsCustom()) {
1944 // Handle f64 or half of a v2f64.
1945 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1946 InFlag);
1947 Chain = Lo.getValue(1);
1948 InFlag = Lo.getValue(2);
1949 VA = RVLocs[++i]; // skip ahead to next loc
1950 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1951 InFlag);
1952 Chain = Hi.getValue(1);
1953 InFlag = Hi.getValue(2);
1954 if (!Subtarget->isLittle())
1955 std::swap (Lo, Hi);
1956 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1958 if (VA.getLocVT() == MVT::v2f64) {
1959 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1960 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1961 DAG.getConstant(0, dl, MVT::i32));
1963 VA = RVLocs[++i]; // skip ahead to next loc
1964 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1965 Chain = Lo.getValue(1);
1966 InFlag = Lo.getValue(2);
1967 VA = RVLocs[++i]; // skip ahead to next loc
1968 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1969 Chain = Hi.getValue(1);
1970 InFlag = Hi.getValue(2);
1971 if (!Subtarget->isLittle())
1972 std::swap (Lo, Hi);
1973 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1974 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1975 DAG.getConstant(1, dl, MVT::i32));
1977 } else {
1978 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1979 InFlag);
1980 Chain = Val.getValue(1);
1981 InFlag = Val.getValue(2);
1984 switch (VA.getLocInfo()) {
1985 default: llvm_unreachable("Unknown loc info!");
1986 case CCValAssign::Full: break;
1987 case CCValAssign::BCvt:
1988 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1989 break;
1992 InVals.push_back(Val);
1995 return Chain;
1998 /// LowerMemOpCallTo - Store the argument to the stack.
1999 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2000 SDValue Arg, const SDLoc &dl,
2001 SelectionDAG &DAG,
2002 const CCValAssign &VA,
2003 ISD::ArgFlagsTy Flags) const {
2004 unsigned LocMemOffset = VA.getLocMemOffset();
2005 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2006 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2007 StackPtr, PtrOff);
2008 return DAG.getStore(
2009 Chain, dl, Arg, PtrOff,
2010 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2013 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2014 SDValue Chain, SDValue &Arg,
2015 RegsToPassVector &RegsToPass,
2016 CCValAssign &VA, CCValAssign &NextVA,
2017 SDValue &StackPtr,
2018 SmallVectorImpl<SDValue> &MemOpChains,
2019 ISD::ArgFlagsTy Flags) const {
2020 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2021 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2022 unsigned id = Subtarget->isLittle() ? 0 : 1;
2023 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2025 if (NextVA.isRegLoc())
2026 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2027 else {
2028 assert(NextVA.isMemLoc());
2029 if (!StackPtr.getNode())
2030 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2031 getPointerTy(DAG.getDataLayout()));
2033 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2034 dl, DAG, NextVA,
2035 Flags));
2039 /// LowerCall - Lowering a call into a callseq_start <-
2040 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2041 /// nodes.
2042 SDValue
2043 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2044 SmallVectorImpl<SDValue> &InVals) const {
2045 SelectionDAG &DAG = CLI.DAG;
2046 SDLoc &dl = CLI.DL;
2047 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2048 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2049 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2050 SDValue Chain = CLI.Chain;
2051 SDValue Callee = CLI.Callee;
2052 bool &isTailCall = CLI.IsTailCall;
2053 CallingConv::ID CallConv = CLI.CallConv;
2054 bool doesNotRet = CLI.DoesNotReturn;
2055 bool isVarArg = CLI.IsVarArg;
2057 MachineFunction &MF = DAG.getMachineFunction();
2058 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2059 bool isThisReturn = false;
2060 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2061 bool PreferIndirect = false;
2063 // Disable tail calls if they're not supported.
2064 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2065 isTailCall = false;
2067 if (isa<GlobalAddressSDNode>(Callee)) {
2068 // If we're optimizing for minimum size and the function is called three or
2069 // more times in this block, we can improve codesize by calling indirectly
2070 // as BLXr has a 16-bit encoding.
2071 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2072 if (CLI.CS) {
2073 auto *BB = CLI.CS.getParent();
2074 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2075 count_if(GV->users(), [&BB](const User *U) {
2076 return isa<Instruction>(U) &&
2077 cast<Instruction>(U)->getParent() == BB;
2078 }) > 2;
2081 if (isTailCall) {
2082 // Check if it's really possible to do a tail call.
2083 isTailCall = IsEligibleForTailCallOptimization(
2084 Callee, CallConv, isVarArg, isStructRet,
2085 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2086 PreferIndirect);
2087 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2088 report_fatal_error("failed to perform tail call elimination on a call "
2089 "site marked musttail");
2090 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2091 // detected sibcalls.
2092 if (isTailCall)
2093 ++NumTailCalls;
2096 // Analyze operands of the call, assigning locations to each operand.
2097 SmallVector<CCValAssign, 16> ArgLocs;
2098 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2099 *DAG.getContext());
2100 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2102 // Get a count of how many bytes are to be pushed on the stack.
2103 unsigned NumBytes = CCInfo.getNextStackOffset();
2105 if (isTailCall) {
2106 // For tail calls, memory operands are available in our caller's stack.
2107 NumBytes = 0;
2108 } else {
2109 // Adjust the stack pointer for the new arguments...
2110 // These operations are automatically eliminated by the prolog/epilog pass
2111 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2114 SDValue StackPtr =
2115 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2117 RegsToPassVector RegsToPass;
2118 SmallVector<SDValue, 8> MemOpChains;
2120 // Walk the register/memloc assignments, inserting copies/loads. In the case
2121 // of tail call optimization, arguments are handled later.
2122 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2123 i != e;
2124 ++i, ++realArgIdx) {
2125 CCValAssign &VA = ArgLocs[i];
2126 SDValue Arg = OutVals[realArgIdx];
2127 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2128 bool isByVal = Flags.isByVal();
2130 // Promote the value if needed.
2131 switch (VA.getLocInfo()) {
2132 default: llvm_unreachable("Unknown loc info!");
2133 case CCValAssign::Full: break;
2134 case CCValAssign::SExt:
2135 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2136 break;
2137 case CCValAssign::ZExt:
2138 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2139 break;
2140 case CCValAssign::AExt:
2141 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2142 break;
2143 case CCValAssign::BCvt:
2144 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2145 break;
2148 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2149 if (VA.needsCustom()) {
2150 if (VA.getLocVT() == MVT::v2f64) {
2151 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2152 DAG.getConstant(0, dl, MVT::i32));
2153 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2154 DAG.getConstant(1, dl, MVT::i32));
2156 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2157 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2159 VA = ArgLocs[++i]; // skip ahead to next loc
2160 if (VA.isRegLoc()) {
2161 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2162 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2163 } else {
2164 assert(VA.isMemLoc());
2166 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2167 dl, DAG, VA, Flags));
2169 } else {
2170 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2171 StackPtr, MemOpChains, Flags);
2173 } else if (VA.isRegLoc()) {
2174 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2175 Outs[0].VT == MVT::i32) {
2176 assert(VA.getLocVT() == MVT::i32 &&
2177 "unexpected calling convention register assignment");
2178 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2179 "unexpected use of 'returned'");
2180 isThisReturn = true;
2182 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2183 } else if (isByVal) {
2184 assert(VA.isMemLoc());
2185 unsigned offset = 0;
2187 // True if this byval aggregate will be split between registers
2188 // and memory.
2189 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2190 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2192 if (CurByValIdx < ByValArgsCount) {
2194 unsigned RegBegin, RegEnd;
2195 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2197 EVT PtrVT =
2198 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2199 unsigned int i, j;
2200 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2201 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2202 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2203 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2204 MachinePointerInfo(),
2205 DAG.InferPtrAlignment(AddArg));
2206 MemOpChains.push_back(Load.getValue(1));
2207 RegsToPass.push_back(std::make_pair(j, Load));
2210 // If parameter size outsides register area, "offset" value
2211 // helps us to calculate stack slot for remained part properly.
2212 offset = RegEnd - RegBegin;
2214 CCInfo.nextInRegsParam();
2217 if (Flags.getByValSize() > 4*offset) {
2218 auto PtrVT = getPointerTy(DAG.getDataLayout());
2219 unsigned LocMemOffset = VA.getLocMemOffset();
2220 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2221 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2222 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2223 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2224 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2225 MVT::i32);
2226 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2227 MVT::i32);
2229 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2230 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2231 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2232 Ops));
2234 } else if (!isTailCall) {
2235 assert(VA.isMemLoc());
2237 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2238 dl, DAG, VA, Flags));
2242 if (!MemOpChains.empty())
2243 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2245 // Build a sequence of copy-to-reg nodes chained together with token chain
2246 // and flag operands which copy the outgoing args into the appropriate regs.
2247 SDValue InFlag;
2248 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2249 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2250 RegsToPass[i].second, InFlag);
2251 InFlag = Chain.getValue(1);
2254 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2255 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2256 // node so that legalize doesn't hack it.
2257 bool isDirect = false;
2259 const TargetMachine &TM = getTargetMachine();
2260 const Module *Mod = MF.getFunction().getParent();
2261 const GlobalValue *GV = nullptr;
2262 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2263 GV = G->getGlobal();
2264 bool isStub =
2265 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2267 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2268 bool isLocalARMFunc = false;
2269 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2270 auto PtrVt = getPointerTy(DAG.getDataLayout());
2272 if (Subtarget->genLongCalls()) {
2273 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2274 "long-calls codegen is not position independent!");
2275 // Handle a global address or an external symbol. If it's not one of
2276 // those, the target's already in a register, so we don't need to do
2277 // anything extra.
2278 if (isa<GlobalAddressSDNode>(Callee)) {
2279 // Create a constant pool entry for the callee address
2280 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2281 ARMConstantPoolValue *CPV =
2282 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2284 // Get the address of the callee into a register
2285 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2286 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2287 Callee = DAG.getLoad(
2288 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2289 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2290 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2291 const char *Sym = S->getSymbol();
2293 // Create a constant pool entry for the callee address
2294 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2295 ARMConstantPoolValue *CPV =
2296 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2297 ARMPCLabelIndex, 0);
2298 // Get the address of the callee into a register
2299 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2300 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2301 Callee = DAG.getLoad(
2302 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2303 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2305 } else if (isa<GlobalAddressSDNode>(Callee)) {
2306 if (!PreferIndirect) {
2307 isDirect = true;
2308 bool isDef = GV->isStrongDefinitionForLinker();
2310 // ARM call to a local ARM function is predicable.
2311 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2312 // tBX takes a register source operand.
2313 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2314 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2315 Callee = DAG.getNode(
2316 ARMISD::WrapperPIC, dl, PtrVt,
2317 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2318 Callee = DAG.getLoad(
2319 PtrVt, dl, DAG.getEntryNode(), Callee,
2320 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2321 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2322 MachineMemOperand::MOInvariant);
2323 } else if (Subtarget->isTargetCOFF()) {
2324 assert(Subtarget->isTargetWindows() &&
2325 "Windows is the only supported COFF target");
2326 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2327 ? ARMII::MO_DLLIMPORT
2328 : ARMII::MO_NO_FLAG;
2329 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2330 TargetFlags);
2331 if (GV->hasDLLImportStorageClass())
2332 Callee =
2333 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2334 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2335 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2336 } else {
2337 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2340 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2341 isDirect = true;
2342 // tBX takes a register source operand.
2343 const char *Sym = S->getSymbol();
2344 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2345 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2346 ARMConstantPoolValue *CPV =
2347 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2348 ARMPCLabelIndex, 4);
2349 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2350 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2351 Callee = DAG.getLoad(
2352 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2353 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2354 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2355 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2356 } else {
2357 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2361 // FIXME: handle tail calls differently.
2362 unsigned CallOpc;
2363 if (Subtarget->isThumb()) {
2364 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2365 CallOpc = ARMISD::CALL_NOLINK;
2366 else
2367 CallOpc = ARMISD::CALL;
2368 } else {
2369 if (!isDirect && !Subtarget->hasV5TOps())
2370 CallOpc = ARMISD::CALL_NOLINK;
2371 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2372 // Emit regular call when code size is the priority
2373 !Subtarget->hasMinSize())
2374 // "mov lr, pc; b _foo" to avoid confusing the RSP
2375 CallOpc = ARMISD::CALL_NOLINK;
2376 else
2377 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2380 std::vector<SDValue> Ops;
2381 Ops.push_back(Chain);
2382 Ops.push_back(Callee);
2384 // Add argument registers to the end of the list so that they are known live
2385 // into the call.
2386 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2387 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2388 RegsToPass[i].second.getValueType()));
2390 // Add a register mask operand representing the call-preserved registers.
2391 if (!isTailCall) {
2392 const uint32_t *Mask;
2393 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2394 if (isThisReturn) {
2395 // For 'this' returns, use the R0-preserving mask if applicable
2396 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2397 if (!Mask) {
2398 // Set isThisReturn to false if the calling convention is not one that
2399 // allows 'returned' to be modeled in this way, so LowerCallResult does
2400 // not try to pass 'this' straight through
2401 isThisReturn = false;
2402 Mask = ARI->getCallPreservedMask(MF, CallConv);
2404 } else
2405 Mask = ARI->getCallPreservedMask(MF, CallConv);
2407 assert(Mask && "Missing call preserved mask for calling convention");
2408 Ops.push_back(DAG.getRegisterMask(Mask));
2411 if (InFlag.getNode())
2412 Ops.push_back(InFlag);
2414 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2415 if (isTailCall) {
2416 MF.getFrameInfo().setHasTailCall();
2417 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2420 // Returns a chain and a flag for retval copy to use.
2421 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2422 InFlag = Chain.getValue(1);
2424 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2425 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2426 if (!Ins.empty())
2427 InFlag = Chain.getValue(1);
2429 // Handle result values, copying them out of physregs into vregs that we
2430 // return.
2431 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2432 InVals, isThisReturn,
2433 isThisReturn ? OutVals[0] : SDValue());
2436 /// HandleByVal - Every parameter *after* a byval parameter is passed
2437 /// on the stack. Remember the next parameter register to allocate,
2438 /// and then confiscate the rest of the parameter registers to insure
2439 /// this.
2440 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2441 unsigned Align) const {
2442 // Byval (as with any stack) slots are always at least 4 byte aligned.
2443 Align = std::max(Align, 4U);
2445 unsigned Reg = State->AllocateReg(GPRArgRegs);
2446 if (!Reg)
2447 return;
2449 unsigned AlignInRegs = Align / 4;
2450 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2451 for (unsigned i = 0; i < Waste; ++i)
2452 Reg = State->AllocateReg(GPRArgRegs);
2454 if (!Reg)
2455 return;
2457 unsigned Excess = 4 * (ARM::R4 - Reg);
2459 // Special case when NSAA != SP and parameter size greater than size of
2460 // all remained GPR regs. In that case we can't split parameter, we must
2461 // send it to stack. We also must set NCRN to R4, so waste all
2462 // remained registers.
2463 const unsigned NSAAOffset = State->getNextStackOffset();
2464 if (NSAAOffset != 0 && Size > Excess) {
2465 while (State->AllocateReg(GPRArgRegs))
2467 return;
2470 // First register for byval parameter is the first register that wasn't
2471 // allocated before this method call, so it would be "reg".
2472 // If parameter is small enough to be saved in range [reg, r4), then
2473 // the end (first after last) register would be reg + param-size-in-regs,
2474 // else parameter would be splitted between registers and stack,
2475 // end register would be r4 in this case.
2476 unsigned ByValRegBegin = Reg;
2477 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2478 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2479 // Note, first register is allocated in the beginning of function already,
2480 // allocate remained amount of registers we need.
2481 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2482 State->AllocateReg(GPRArgRegs);
2483 // A byval parameter that is split between registers and memory needs its
2484 // size truncated here.
2485 // In the case where the entire structure fits in registers, we set the
2486 // size in memory to zero.
2487 Size = std::max<int>(Size - Excess, 0);
2490 /// MatchingStackOffset - Return true if the given stack call argument is
2491 /// already available in the same position (relatively) of the caller's
2492 /// incoming argument stack.
2493 static
2494 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2495 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2496 const TargetInstrInfo *TII) {
2497 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2498 int FI = std::numeric_limits<int>::max();
2499 if (Arg.getOpcode() == ISD::CopyFromReg) {
2500 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2501 if (!Register::isVirtualRegister(VR))
2502 return false;
2503 MachineInstr *Def = MRI->getVRegDef(VR);
2504 if (!Def)
2505 return false;
2506 if (!Flags.isByVal()) {
2507 if (!TII->isLoadFromStackSlot(*Def, FI))
2508 return false;
2509 } else {
2510 return false;
2512 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2513 if (Flags.isByVal())
2514 // ByVal argument is passed in as a pointer but it's now being
2515 // dereferenced. e.g.
2516 // define @foo(%struct.X* %A) {
2517 // tail call @bar(%struct.X* byval %A)
2518 // }
2519 return false;
2520 SDValue Ptr = Ld->getBasePtr();
2521 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2522 if (!FINode)
2523 return false;
2524 FI = FINode->getIndex();
2525 } else
2526 return false;
2528 assert(FI != std::numeric_limits<int>::max());
2529 if (!MFI.isFixedObjectIndex(FI))
2530 return false;
2531 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2534 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2535 /// for tail call optimization. Targets which want to do tail call
2536 /// optimization should implement this function.
2537 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2538 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2539 bool isCalleeStructRet, bool isCallerStructRet,
2540 const SmallVectorImpl<ISD::OutputArg> &Outs,
2541 const SmallVectorImpl<SDValue> &OutVals,
2542 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2543 const bool isIndirect) const {
2544 MachineFunction &MF = DAG.getMachineFunction();
2545 const Function &CallerF = MF.getFunction();
2546 CallingConv::ID CallerCC = CallerF.getCallingConv();
2548 assert(Subtarget->supportsTailCall());
2550 // Indirect tail calls cannot be optimized for Thumb1 if the args
2551 // to the call take up r0-r3. The reason is that there are no legal registers
2552 // left to hold the pointer to the function to be called.
2553 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2554 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2555 return false;
2557 // Look for obvious safe cases to perform tail call optimization that do not
2558 // require ABI changes. This is what gcc calls sibcall.
2560 // Exception-handling functions need a special set of instructions to indicate
2561 // a return to the hardware. Tail-calling another function would probably
2562 // break this.
2563 if (CallerF.hasFnAttribute("interrupt"))
2564 return false;
2566 // Also avoid sibcall optimization if either caller or callee uses struct
2567 // return semantics.
2568 if (isCalleeStructRet || isCallerStructRet)
2569 return false;
2571 // Externally-defined functions with weak linkage should not be
2572 // tail-called on ARM when the OS does not support dynamic
2573 // pre-emption of symbols, as the AAELF spec requires normal calls
2574 // to undefined weak functions to be replaced with a NOP or jump to the
2575 // next instruction. The behaviour of branch instructions in this
2576 // situation (as used for tail calls) is implementation-defined, so we
2577 // cannot rely on the linker replacing the tail call with a return.
2578 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2579 const GlobalValue *GV = G->getGlobal();
2580 const Triple &TT = getTargetMachine().getTargetTriple();
2581 if (GV->hasExternalWeakLinkage() &&
2582 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2583 return false;
2586 // Check that the call results are passed in the same way.
2587 LLVMContext &C = *DAG.getContext();
2588 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2589 CCAssignFnForReturn(CalleeCC, isVarArg),
2590 CCAssignFnForReturn(CallerCC, isVarArg)))
2591 return false;
2592 // The callee has to preserve all registers the caller needs to preserve.
2593 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2594 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2595 if (CalleeCC != CallerCC) {
2596 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2597 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2598 return false;
2601 // If Caller's vararg or byval argument has been split between registers and
2602 // stack, do not perform tail call, since part of the argument is in caller's
2603 // local frame.
2604 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2605 if (AFI_Caller->getArgRegsSaveSize())
2606 return false;
2608 // If the callee takes no arguments then go on to check the results of the
2609 // call.
2610 if (!Outs.empty()) {
2611 // Check if stack adjustment is needed. For now, do not do this if any
2612 // argument is passed on the stack.
2613 SmallVector<CCValAssign, 16> ArgLocs;
2614 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2615 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2616 if (CCInfo.getNextStackOffset()) {
2617 // Check if the arguments are already laid out in the right way as
2618 // the caller's fixed stack objects.
2619 MachineFrameInfo &MFI = MF.getFrameInfo();
2620 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2621 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2622 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2623 i != e;
2624 ++i, ++realArgIdx) {
2625 CCValAssign &VA = ArgLocs[i];
2626 EVT RegVT = VA.getLocVT();
2627 SDValue Arg = OutVals[realArgIdx];
2628 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2629 if (VA.getLocInfo() == CCValAssign::Indirect)
2630 return false;
2631 if (VA.needsCustom()) {
2632 // f64 and vector types are split into multiple registers or
2633 // register/stack-slot combinations. The types will not match
2634 // the registers; give up on memory f64 refs until we figure
2635 // out what to do about this.
2636 if (!VA.isRegLoc())
2637 return false;
2638 if (!ArgLocs[++i].isRegLoc())
2639 return false;
2640 if (RegVT == MVT::v2f64) {
2641 if (!ArgLocs[++i].isRegLoc())
2642 return false;
2643 if (!ArgLocs[++i].isRegLoc())
2644 return false;
2646 } else if (!VA.isRegLoc()) {
2647 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2648 MFI, MRI, TII))
2649 return false;
2654 const MachineRegisterInfo &MRI = MF.getRegInfo();
2655 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2656 return false;
2659 return true;
2662 bool
2663 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2664 MachineFunction &MF, bool isVarArg,
2665 const SmallVectorImpl<ISD::OutputArg> &Outs,
2666 LLVMContext &Context) const {
2667 SmallVector<CCValAssign, 16> RVLocs;
2668 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2669 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2672 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2673 const SDLoc &DL, SelectionDAG &DAG) {
2674 const MachineFunction &MF = DAG.getMachineFunction();
2675 const Function &F = MF.getFunction();
2677 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2679 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2680 // version of the "preferred return address". These offsets affect the return
2681 // instruction if this is a return from PL1 without hypervisor extensions.
2682 // IRQ/FIQ: +4 "subs pc, lr, #4"
2683 // SWI: 0 "subs pc, lr, #0"
2684 // ABORT: +4 "subs pc, lr, #4"
2685 // UNDEF: +4/+2 "subs pc, lr, #0"
2686 // UNDEF varies depending on where the exception came from ARM or Thumb
2687 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2689 int64_t LROffset;
2690 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2691 IntKind == "ABORT")
2692 LROffset = 4;
2693 else if (IntKind == "SWI" || IntKind == "UNDEF")
2694 LROffset = 0;
2695 else
2696 report_fatal_error("Unsupported interrupt attribute. If present, value "
2697 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2699 RetOps.insert(RetOps.begin() + 1,
2700 DAG.getConstant(LROffset, DL, MVT::i32, false));
2702 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2705 SDValue
2706 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2707 bool isVarArg,
2708 const SmallVectorImpl<ISD::OutputArg> &Outs,
2709 const SmallVectorImpl<SDValue> &OutVals,
2710 const SDLoc &dl, SelectionDAG &DAG) const {
2711 // CCValAssign - represent the assignment of the return value to a location.
2712 SmallVector<CCValAssign, 16> RVLocs;
2714 // CCState - Info about the registers and stack slots.
2715 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2716 *DAG.getContext());
2718 // Analyze outgoing return values.
2719 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2721 SDValue Flag;
2722 SmallVector<SDValue, 4> RetOps;
2723 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2724 bool isLittleEndian = Subtarget->isLittle();
2726 MachineFunction &MF = DAG.getMachineFunction();
2727 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2728 AFI->setReturnRegsCount(RVLocs.size());
2730 // Copy the result values into the output registers.
2731 for (unsigned i = 0, realRVLocIdx = 0;
2732 i != RVLocs.size();
2733 ++i, ++realRVLocIdx) {
2734 CCValAssign &VA = RVLocs[i];
2735 assert(VA.isRegLoc() && "Can only return in registers!");
2737 SDValue Arg = OutVals[realRVLocIdx];
2738 bool ReturnF16 = false;
2740 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2741 // Half-precision return values can be returned like this:
2743 // t11 f16 = fadd ...
2744 // t12: i16 = bitcast t11
2745 // t13: i32 = zero_extend t12
2746 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2748 // to avoid code generation for bitcasts, we simply set Arg to the node
2749 // that produces the f16 value, t11 in this case.
2751 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2752 SDValue ZE = Arg.getOperand(0);
2753 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2754 SDValue BC = ZE.getOperand(0);
2755 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2756 Arg = BC.getOperand(0);
2757 ReturnF16 = true;
2763 switch (VA.getLocInfo()) {
2764 default: llvm_unreachable("Unknown loc info!");
2765 case CCValAssign::Full: break;
2766 case CCValAssign::BCvt:
2767 if (!ReturnF16)
2768 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2769 break;
2772 if (VA.needsCustom()) {
2773 if (VA.getLocVT() == MVT::v2f64) {
2774 // Extract the first half and return it in two registers.
2775 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2776 DAG.getConstant(0, dl, MVT::i32));
2777 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2778 DAG.getVTList(MVT::i32, MVT::i32), Half);
2780 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2781 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2782 Flag);
2783 Flag = Chain.getValue(1);
2784 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2785 VA = RVLocs[++i]; // skip ahead to next loc
2786 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2787 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2788 Flag);
2789 Flag = Chain.getValue(1);
2790 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2791 VA = RVLocs[++i]; // skip ahead to next loc
2793 // Extract the 2nd half and fall through to handle it as an f64 value.
2794 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2795 DAG.getConstant(1, dl, MVT::i32));
2797 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2798 // available.
2799 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2800 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2801 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2802 fmrrd.getValue(isLittleEndian ? 0 : 1),
2803 Flag);
2804 Flag = Chain.getValue(1);
2805 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2806 VA = RVLocs[++i]; // skip ahead to next loc
2807 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2808 fmrrd.getValue(isLittleEndian ? 1 : 0),
2809 Flag);
2810 } else
2811 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2813 // Guarantee that all emitted copies are
2814 // stuck together, avoiding something bad.
2815 Flag = Chain.getValue(1);
2816 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2817 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2819 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2820 const MCPhysReg *I =
2821 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2822 if (I) {
2823 for (; *I; ++I) {
2824 if (ARM::GPRRegClass.contains(*I))
2825 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2826 else if (ARM::DPRRegClass.contains(*I))
2827 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2828 else
2829 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2833 // Update chain and glue.
2834 RetOps[0] = Chain;
2835 if (Flag.getNode())
2836 RetOps.push_back(Flag);
2838 // CPUs which aren't M-class use a special sequence to return from
2839 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2840 // though we use "subs pc, lr, #N").
2842 // M-class CPUs actually use a normal return sequence with a special
2843 // (hardware-provided) value in LR, so the normal code path works.
2844 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2845 !Subtarget->isMClass()) {
2846 if (Subtarget->isThumb1Only())
2847 report_fatal_error("interrupt attribute is not supported in Thumb1");
2848 return LowerInterruptReturn(RetOps, dl, DAG);
2851 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2854 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2855 if (N->getNumValues() != 1)
2856 return false;
2857 if (!N->hasNUsesOfValue(1, 0))
2858 return false;
2860 SDValue TCChain = Chain;
2861 SDNode *Copy = *N->use_begin();
2862 if (Copy->getOpcode() == ISD::CopyToReg) {
2863 // If the copy has a glue operand, we conservatively assume it isn't safe to
2864 // perform a tail call.
2865 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2866 return false;
2867 TCChain = Copy->getOperand(0);
2868 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2869 SDNode *VMov = Copy;
2870 // f64 returned in a pair of GPRs.
2871 SmallPtrSet<SDNode*, 2> Copies;
2872 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2873 UI != UE; ++UI) {
2874 if (UI->getOpcode() != ISD::CopyToReg)
2875 return false;
2876 Copies.insert(*UI);
2878 if (Copies.size() > 2)
2879 return false;
2881 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2882 UI != UE; ++UI) {
2883 SDValue UseChain = UI->getOperand(0);
2884 if (Copies.count(UseChain.getNode()))
2885 // Second CopyToReg
2886 Copy = *UI;
2887 else {
2888 // We are at the top of this chain.
2889 // If the copy has a glue operand, we conservatively assume it
2890 // isn't safe to perform a tail call.
2891 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2892 return false;
2893 // First CopyToReg
2894 TCChain = UseChain;
2897 } else if (Copy->getOpcode() == ISD::BITCAST) {
2898 // f32 returned in a single GPR.
2899 if (!Copy->hasOneUse())
2900 return false;
2901 Copy = *Copy->use_begin();
2902 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2903 return false;
2904 // If the copy has a glue operand, we conservatively assume it isn't safe to
2905 // perform a tail call.
2906 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2907 return false;
2908 TCChain = Copy->getOperand(0);
2909 } else {
2910 return false;
2913 bool HasRet = false;
2914 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2915 UI != UE; ++UI) {
2916 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2917 UI->getOpcode() != ARMISD::INTRET_FLAG)
2918 return false;
2919 HasRet = true;
2922 if (!HasRet)
2923 return false;
2925 Chain = TCChain;
2926 return true;
2929 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2930 if (!Subtarget->supportsTailCall())
2931 return false;
2933 auto Attr =
2934 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2935 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2936 return false;
2938 return true;
2941 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2942 // and pass the lower and high parts through.
2943 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2944 SDLoc DL(Op);
2945 SDValue WriteValue = Op->getOperand(2);
2947 // This function is only supposed to be called for i64 type argument.
2948 assert(WriteValue.getValueType() == MVT::i64
2949 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2951 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2952 DAG.getConstant(0, DL, MVT::i32));
2953 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2954 DAG.getConstant(1, DL, MVT::i32));
2955 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2956 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2959 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2960 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2961 // one of the above mentioned nodes. It has to be wrapped because otherwise
2962 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2963 // be used to form addressing mode. These wrapped nodes will be selected
2964 // into MOVi.
2965 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2966 SelectionDAG &DAG) const {
2967 EVT PtrVT = Op.getValueType();
2968 // FIXME there is no actual debug info here
2969 SDLoc dl(Op);
2970 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2971 SDValue Res;
2973 // When generating execute-only code Constant Pools must be promoted to the
2974 // global data section. It's a bit ugly that we can't share them across basic
2975 // blocks, but this way we guarantee that execute-only behaves correct with
2976 // position-independent addressing modes.
2977 if (Subtarget->genExecuteOnly()) {
2978 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2979 auto T = const_cast<Type*>(CP->getType());
2980 auto C = const_cast<Constant*>(CP->getConstVal());
2981 auto M = const_cast<Module*>(DAG.getMachineFunction().
2982 getFunction().getParent());
2983 auto GV = new GlobalVariable(
2984 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2985 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2986 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2987 Twine(AFI->createPICLabelUId())
2989 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2990 dl, PtrVT);
2991 return LowerGlobalAddress(GA, DAG);
2994 if (CP->isMachineConstantPoolEntry())
2995 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2996 CP->getAlignment());
2997 else
2998 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2999 CP->getAlignment());
3000 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3003 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3004 return MachineJumpTableInfo::EK_Inline;
3007 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3008 SelectionDAG &DAG) const {
3009 MachineFunction &MF = DAG.getMachineFunction();
3010 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3011 unsigned ARMPCLabelIndex = 0;
3012 SDLoc DL(Op);
3013 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3014 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3015 SDValue CPAddr;
3016 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3017 if (!IsPositionIndependent) {
3018 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3019 } else {
3020 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3021 ARMPCLabelIndex = AFI->createPICLabelUId();
3022 ARMConstantPoolValue *CPV =
3023 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3024 ARMCP::CPBlockAddress, PCAdj);
3025 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3027 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3028 SDValue Result = DAG.getLoad(
3029 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3030 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3031 if (!IsPositionIndependent)
3032 return Result;
3033 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3034 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3037 /// Convert a TLS address reference into the correct sequence of loads
3038 /// and calls to compute the variable's address for Darwin, and return an
3039 /// SDValue containing the final node.
3041 /// Darwin only has one TLS scheme which must be capable of dealing with the
3042 /// fully general situation, in the worst case. This means:
3043 /// + "extern __thread" declaration.
3044 /// + Defined in a possibly unknown dynamic library.
3046 /// The general system is that each __thread variable has a [3 x i32] descriptor
3047 /// which contains information used by the runtime to calculate the address. The
3048 /// only part of this the compiler needs to know about is the first word, which
3049 /// contains a function pointer that must be called with the address of the
3050 /// entire descriptor in "r0".
3052 /// Since this descriptor may be in a different unit, in general access must
3053 /// proceed along the usual ARM rules. A common sequence to produce is:
3055 /// movw rT1, :lower16:_var$non_lazy_ptr
3056 /// movt rT1, :upper16:_var$non_lazy_ptr
3057 /// ldr r0, [rT1]
3058 /// ldr rT2, [r0]
3059 /// blx rT2
3060 /// [...address now in r0...]
3061 SDValue
3062 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3063 SelectionDAG &DAG) const {
3064 assert(Subtarget->isTargetDarwin() &&
3065 "This function expects a Darwin target");
3066 SDLoc DL(Op);
3068 // First step is to get the address of the actua global symbol. This is where
3069 // the TLS descriptor lives.
3070 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3072 // The first entry in the descriptor is a function pointer that we must call
3073 // to obtain the address of the variable.
3074 SDValue Chain = DAG.getEntryNode();
3075 SDValue FuncTLVGet = DAG.getLoad(
3076 MVT::i32, DL, Chain, DescAddr,
3077 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3078 /* Alignment = */ 4,
3079 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3080 MachineMemOperand::MOInvariant);
3081 Chain = FuncTLVGet.getValue(1);
3083 MachineFunction &F = DAG.getMachineFunction();
3084 MachineFrameInfo &MFI = F.getFrameInfo();
3085 MFI.setAdjustsStack(true);
3087 // TLS calls preserve all registers except those that absolutely must be
3088 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3089 // silly).
3090 auto TRI =
3091 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3092 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3093 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3095 // Finally, we can make the call. This is just a degenerate version of a
3096 // normal AArch64 call node: r0 takes the address of the descriptor, and
3097 // returns the address of the variable in this thread.
3098 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3099 Chain =
3100 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3101 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3102 DAG.getRegisterMask(Mask), Chain.getValue(1));
3103 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3106 SDValue
3107 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3108 SelectionDAG &DAG) const {
3109 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3111 SDValue Chain = DAG.getEntryNode();
3112 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3113 SDLoc DL(Op);
3115 // Load the current TEB (thread environment block)
3116 SDValue Ops[] = {Chain,
3117 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3118 DAG.getTargetConstant(15, DL, MVT::i32),
3119 DAG.getTargetConstant(0, DL, MVT::i32),
3120 DAG.getTargetConstant(13, DL, MVT::i32),
3121 DAG.getTargetConstant(0, DL, MVT::i32),
3122 DAG.getTargetConstant(2, DL, MVT::i32)};
3123 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3124 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3126 SDValue TEB = CurrentTEB.getValue(0);
3127 Chain = CurrentTEB.getValue(1);
3129 // Load the ThreadLocalStoragePointer from the TEB
3130 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3131 SDValue TLSArray =
3132 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3133 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3135 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3136 // offset into the TLSArray.
3138 // Load the TLS index from the C runtime
3139 SDValue TLSIndex =
3140 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3141 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3142 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3144 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3145 DAG.getConstant(2, DL, MVT::i32));
3146 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3147 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3148 MachinePointerInfo());
3150 // Get the offset of the start of the .tls section (section base)
3151 const auto *GA = cast<GlobalAddressSDNode>(Op);
3152 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3153 SDValue Offset = DAG.getLoad(
3154 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3155 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3156 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3158 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3161 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3162 SDValue
3163 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3164 SelectionDAG &DAG) const {
3165 SDLoc dl(GA);
3166 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3167 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3168 MachineFunction &MF = DAG.getMachineFunction();
3169 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3170 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3171 ARMConstantPoolValue *CPV =
3172 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3173 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3174 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3175 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3176 Argument = DAG.getLoad(
3177 PtrVT, dl, DAG.getEntryNode(), Argument,
3178 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3179 SDValue Chain = Argument.getValue(1);
3181 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3182 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3184 // call __tls_get_addr.
3185 ArgListTy Args;
3186 ArgListEntry Entry;
3187 Entry.Node = Argument;
3188 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3189 Args.push_back(Entry);
3191 // FIXME: is there useful debug info available here?
3192 TargetLowering::CallLoweringInfo CLI(DAG);
3193 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3194 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3195 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3197 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3198 return CallResult.first;
3201 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3202 // "local exec" model.
3203 SDValue
3204 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3205 SelectionDAG &DAG,
3206 TLSModel::Model model) const {
3207 const GlobalValue *GV = GA->getGlobal();
3208 SDLoc dl(GA);
3209 SDValue Offset;
3210 SDValue Chain = DAG.getEntryNode();
3211 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3212 // Get the Thread Pointer
3213 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3215 if (model == TLSModel::InitialExec) {
3216 MachineFunction &MF = DAG.getMachineFunction();
3217 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3218 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3219 // Initial exec model.
3220 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3221 ARMConstantPoolValue *CPV =
3222 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3223 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3224 true);
3225 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3226 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3227 Offset = DAG.getLoad(
3228 PtrVT, dl, Chain, Offset,
3229 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3230 Chain = Offset.getValue(1);
3232 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3233 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3235 Offset = DAG.getLoad(
3236 PtrVT, dl, Chain, Offset,
3237 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3238 } else {
3239 // local exec model
3240 assert(model == TLSModel::LocalExec);
3241 ARMConstantPoolValue *CPV =
3242 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3243 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3244 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3245 Offset = DAG.getLoad(
3246 PtrVT, dl, Chain, Offset,
3247 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3250 // The address of the thread local variable is the add of the thread
3251 // pointer with the offset of the variable.
3252 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3255 SDValue
3256 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3257 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3258 if (DAG.getTarget().useEmulatedTLS())
3259 return LowerToTLSEmulatedModel(GA, DAG);
3261 if (Subtarget->isTargetDarwin())
3262 return LowerGlobalTLSAddressDarwin(Op, DAG);
3264 if (Subtarget->isTargetWindows())
3265 return LowerGlobalTLSAddressWindows(Op, DAG);
3267 // TODO: implement the "local dynamic" model
3268 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3269 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3271 switch (model) {
3272 case TLSModel::GeneralDynamic:
3273 case TLSModel::LocalDynamic:
3274 return LowerToTLSGeneralDynamicModel(GA, DAG);
3275 case TLSModel::InitialExec:
3276 case TLSModel::LocalExec:
3277 return LowerToTLSExecModels(GA, DAG, model);
3279 llvm_unreachable("bogus TLS model");
3282 /// Return true if all users of V are within function F, looking through
3283 /// ConstantExprs.
3284 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3285 SmallVector<const User*,4> Worklist;
3286 for (auto *U : V->users())
3287 Worklist.push_back(U);
3288 while (!Worklist.empty()) {
3289 auto *U = Worklist.pop_back_val();
3290 if (isa<ConstantExpr>(U)) {
3291 for (auto *UU : U->users())
3292 Worklist.push_back(UU);
3293 continue;
3296 auto *I = dyn_cast<Instruction>(U);
3297 if (!I || I->getParent()->getParent() != F)
3298 return false;
3300 return true;
3303 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3304 const GlobalValue *GV, SelectionDAG &DAG,
3305 EVT PtrVT, const SDLoc &dl) {
3306 // If we're creating a pool entry for a constant global with unnamed address,
3307 // and the global is small enough, we can emit it inline into the constant pool
3308 // to save ourselves an indirection.
3310 // This is a win if the constant is only used in one function (so it doesn't
3311 // need to be duplicated) or duplicating the constant wouldn't increase code
3312 // size (implying the constant is no larger than 4 bytes).
3313 const Function &F = DAG.getMachineFunction().getFunction();
3315 // We rely on this decision to inline being idemopotent and unrelated to the
3316 // use-site. We know that if we inline a variable at one use site, we'll
3317 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3318 // doesn't know about this optimization, so bail out if it's enabled else
3319 // we could decide to inline here (and thus never emit the GV) but require
3320 // the GV from fast-isel generated code.
3321 if (!EnableConstpoolPromotion ||
3322 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3323 return SDValue();
3325 auto *GVar = dyn_cast<GlobalVariable>(GV);
3326 if (!GVar || !GVar->hasInitializer() ||
3327 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3328 !GVar->hasLocalLinkage())
3329 return SDValue();
3331 // If we inline a value that contains relocations, we move the relocations
3332 // from .data to .text. This is not allowed in position-independent code.
3333 auto *Init = GVar->getInitializer();
3334 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3335 Init->needsRelocation())
3336 return SDValue();
3338 // The constant islands pass can only really deal with alignment requests
3339 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3340 // any type wanting greater alignment requirements than 4 bytes. We also
3341 // can only promote constants that are multiples of 4 bytes in size or
3342 // are paddable to a multiple of 4. Currently we only try and pad constants
3343 // that are strings for simplicity.
3344 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3345 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3346 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3347 unsigned RequiredPadding = 4 - (Size % 4);
3348 bool PaddingPossible =
3349 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3350 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3351 Size == 0)
3352 return SDValue();
3354 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3355 MachineFunction &MF = DAG.getMachineFunction();
3356 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3358 // We can't bloat the constant pool too much, else the ConstantIslands pass
3359 // may fail to converge. If we haven't promoted this global yet (it may have
3360 // multiple uses), and promoting it would increase the constant pool size (Sz
3361 // > 4), ensure we have space to do so up to MaxTotal.
3362 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3363 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3364 ConstpoolPromotionMaxTotal)
3365 return SDValue();
3367 // This is only valid if all users are in a single function; we can't clone
3368 // the constant in general. The LLVM IR unnamed_addr allows merging
3369 // constants, but not cloning them.
3371 // We could potentially allow cloning if we could prove all uses of the
3372 // constant in the current function don't care about the address, like
3373 // printf format strings. But that isn't implemented for now.
3374 if (!allUsersAreInFunction(GVar, &F))
3375 return SDValue();
3377 // We're going to inline this global. Pad it out if needed.
3378 if (RequiredPadding != 4) {
3379 StringRef S = CDAInit->getAsString();
3381 SmallVector<uint8_t,16> V(S.size());
3382 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3383 while (RequiredPadding--)
3384 V.push_back(0);
3385 Init = ConstantDataArray::get(*DAG.getContext(), V);
3388 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3389 SDValue CPAddr =
3390 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3391 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3392 AFI->markGlobalAsPromotedToConstantPool(GVar);
3393 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3394 PaddedSize - 4);
3396 ++NumConstpoolPromoted;
3397 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3400 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3401 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3402 if (!(GV = GA->getBaseObject()))
3403 return false;
3404 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3405 return V->isConstant();
3406 return isa<Function>(GV);
3409 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3410 SelectionDAG &DAG) const {
3411 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3412 default: llvm_unreachable("unknown object format");
3413 case Triple::COFF:
3414 return LowerGlobalAddressWindows(Op, DAG);
3415 case Triple::ELF:
3416 return LowerGlobalAddressELF(Op, DAG);
3417 case Triple::MachO:
3418 return LowerGlobalAddressDarwin(Op, DAG);
3422 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3423 SelectionDAG &DAG) const {
3424 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3425 SDLoc dl(Op);
3426 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3427 const TargetMachine &TM = getTargetMachine();
3428 bool IsRO = isReadOnly(GV);
3430 // promoteToConstantPool only if not generating XO text section
3431 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3432 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3433 return V;
3435 if (isPositionIndependent()) {
3436 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3437 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3438 UseGOT_PREL ? ARMII::MO_GOT : 0);
3439 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3440 if (UseGOT_PREL)
3441 Result =
3442 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3443 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3444 return Result;
3445 } else if (Subtarget->isROPI() && IsRO) {
3446 // PC-relative.
3447 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3448 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3449 return Result;
3450 } else if (Subtarget->isRWPI() && !IsRO) {
3451 // SB-relative.
3452 SDValue RelAddr;
3453 if (Subtarget->useMovt()) {
3454 ++NumMovwMovt;
3455 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3456 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3457 } else { // use literal pool for address constant
3458 ARMConstantPoolValue *CPV =
3459 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3460 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3461 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3462 RelAddr = DAG.getLoad(
3463 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3464 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3466 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3467 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3468 return Result;
3471 // If we have T2 ops, we can materialize the address directly via movt/movw
3472 // pair. This is always cheaper.
3473 if (Subtarget->useMovt()) {
3474 ++NumMovwMovt;
3475 // FIXME: Once remat is capable of dealing with instructions with register
3476 // operands, expand this into two nodes.
3477 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3478 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3479 } else {
3480 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3481 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3482 return DAG.getLoad(
3483 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3484 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3488 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3489 SelectionDAG &DAG) const {
3490 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3491 "ROPI/RWPI not currently supported for Darwin");
3492 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3493 SDLoc dl(Op);
3494 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3496 if (Subtarget->useMovt())
3497 ++NumMovwMovt;
3499 // FIXME: Once remat is capable of dealing with instructions with register
3500 // operands, expand this into multiple nodes
3501 unsigned Wrapper =
3502 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3504 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3505 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3507 if (Subtarget->isGVIndirectSymbol(GV))
3508 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3509 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3510 return Result;
3513 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3514 SelectionDAG &DAG) const {
3515 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3516 assert(Subtarget->useMovt() &&
3517 "Windows on ARM expects to use movw/movt");
3518 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3519 "ROPI/RWPI not currently supported for Windows");
3521 const TargetMachine &TM = getTargetMachine();
3522 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3523 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3524 if (GV->hasDLLImportStorageClass())
3525 TargetFlags = ARMII::MO_DLLIMPORT;
3526 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3527 TargetFlags = ARMII::MO_COFFSTUB;
3528 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3529 SDValue Result;
3530 SDLoc DL(Op);
3532 ++NumMovwMovt;
3534 // FIXME: Once remat is capable of dealing with instructions with register
3535 // operands, expand this into two nodes.
3536 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3537 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3538 TargetFlags));
3539 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3540 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3541 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3542 return Result;
3545 SDValue
3546 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3547 SDLoc dl(Op);
3548 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3549 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3550 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3551 Op.getOperand(1), Val);
3554 SDValue
3555 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3556 SDLoc dl(Op);
3557 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3558 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3561 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3562 SelectionDAG &DAG) const {
3563 SDLoc dl(Op);
3564 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3565 Op.getOperand(0));
3568 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3569 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3570 unsigned IntNo =
3571 cast<ConstantSDNode>(
3572 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3573 ->getZExtValue();
3574 switch (IntNo) {
3575 default:
3576 return SDValue(); // Don't custom lower most intrinsics.
3577 case Intrinsic::arm_gnu_eabi_mcount: {
3578 MachineFunction &MF = DAG.getMachineFunction();
3579 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3580 SDLoc dl(Op);
3581 SDValue Chain = Op.getOperand(0);
3582 // call "\01__gnu_mcount_nc"
3583 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3584 const uint32_t *Mask =
3585 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3586 assert(Mask && "Missing call preserved mask for calling convention");
3587 // Mark LR an implicit live-in.
3588 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3589 SDValue ReturnAddress =
3590 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3591 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue};
3592 SDValue Callee =
3593 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3594 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3595 if (Subtarget->isThumb())
3596 return SDValue(
3597 DAG.getMachineNode(
3598 ARM::tBL_PUSHLR, dl, ResultTys,
3599 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3600 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3602 return SDValue(
3603 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3604 {ReturnAddress, Callee, RegisterMask, Chain}),
3610 SDValue
3611 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3612 const ARMSubtarget *Subtarget) const {
3613 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3614 SDLoc dl(Op);
3615 switch (IntNo) {
3616 default: return SDValue(); // Don't custom lower most intrinsics.
3617 case Intrinsic::thread_pointer: {
3618 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3619 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3621 case Intrinsic::eh_sjlj_lsda: {
3622 MachineFunction &MF = DAG.getMachineFunction();
3623 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3624 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3625 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3626 SDValue CPAddr;
3627 bool IsPositionIndependent = isPositionIndependent();
3628 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3629 ARMConstantPoolValue *CPV =
3630 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3631 ARMCP::CPLSDA, PCAdj);
3632 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3633 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3634 SDValue Result = DAG.getLoad(
3635 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3636 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3638 if (IsPositionIndependent) {
3639 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3640 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3642 return Result;
3644 case Intrinsic::arm_neon_vabs:
3645 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3646 Op.getOperand(1));
3647 case Intrinsic::arm_neon_vmulls:
3648 case Intrinsic::arm_neon_vmullu: {
3649 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3650 ? ARMISD::VMULLs : ARMISD::VMULLu;
3651 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3652 Op.getOperand(1), Op.getOperand(2));
3654 case Intrinsic::arm_neon_vminnm:
3655 case Intrinsic::arm_neon_vmaxnm: {
3656 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3657 ? ISD::FMINNUM : ISD::FMAXNUM;
3658 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3659 Op.getOperand(1), Op.getOperand(2));
3661 case Intrinsic::arm_neon_vminu:
3662 case Intrinsic::arm_neon_vmaxu: {
3663 if (Op.getValueType().isFloatingPoint())
3664 return SDValue();
3665 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3666 ? ISD::UMIN : ISD::UMAX;
3667 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3668 Op.getOperand(1), Op.getOperand(2));
3670 case Intrinsic::arm_neon_vmins:
3671 case Intrinsic::arm_neon_vmaxs: {
3672 // v{min,max}s is overloaded between signed integers and floats.
3673 if (!Op.getValueType().isFloatingPoint()) {
3674 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3675 ? ISD::SMIN : ISD::SMAX;
3676 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3677 Op.getOperand(1), Op.getOperand(2));
3679 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3680 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3681 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3682 Op.getOperand(1), Op.getOperand(2));
3684 case Intrinsic::arm_neon_vtbl1:
3685 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3686 Op.getOperand(1), Op.getOperand(2));
3687 case Intrinsic::arm_neon_vtbl2:
3688 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3689 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3693 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3694 const ARMSubtarget *Subtarget) {
3695 SDLoc dl(Op);
3696 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3697 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3698 if (SSID == SyncScope::SingleThread)
3699 return Op;
3701 if (!Subtarget->hasDataBarrier()) {
3702 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3703 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3704 // here.
3705 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3706 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3707 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3708 DAG.getConstant(0, dl, MVT::i32));
3711 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3712 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3713 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3714 if (Subtarget->isMClass()) {
3715 // Only a full system barrier exists in the M-class architectures.
3716 Domain = ARM_MB::SY;
3717 } else if (Subtarget->preferISHSTBarriers() &&
3718 Ord == AtomicOrdering::Release) {
3719 // Swift happens to implement ISHST barriers in a way that's compatible with
3720 // Release semantics but weaker than ISH so we'd be fools not to use
3721 // it. Beware: other processors probably don't!
3722 Domain = ARM_MB::ISHST;
3725 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3726 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3727 DAG.getConstant(Domain, dl, MVT::i32));
3730 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3731 const ARMSubtarget *Subtarget) {
3732 // ARM pre v5TE and Thumb1 does not have preload instructions.
3733 if (!(Subtarget->isThumb2() ||
3734 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3735 // Just preserve the chain.
3736 return Op.getOperand(0);
3738 SDLoc dl(Op);
3739 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3740 if (!isRead &&
3741 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3742 // ARMv7 with MP extension has PLDW.
3743 return Op.getOperand(0);
3745 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3746 if (Subtarget->isThumb()) {
3747 // Invert the bits.
3748 isRead = ~isRead & 1;
3749 isData = ~isData & 1;
3752 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3753 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3754 DAG.getConstant(isData, dl, MVT::i32));
3757 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3758 MachineFunction &MF = DAG.getMachineFunction();
3759 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3761 // vastart just stores the address of the VarArgsFrameIndex slot into the
3762 // memory location argument.
3763 SDLoc dl(Op);
3764 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3765 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3766 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3767 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3768 MachinePointerInfo(SV));
3771 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3772 CCValAssign &NextVA,
3773 SDValue &Root,
3774 SelectionDAG &DAG,
3775 const SDLoc &dl) const {
3776 MachineFunction &MF = DAG.getMachineFunction();
3777 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3779 const TargetRegisterClass *RC;
3780 if (AFI->isThumb1OnlyFunction())
3781 RC = &ARM::tGPRRegClass;
3782 else
3783 RC = &ARM::GPRRegClass;
3785 // Transform the arguments stored in physical registers into virtual ones.
3786 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3787 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3789 SDValue ArgValue2;
3790 if (NextVA.isMemLoc()) {
3791 MachineFrameInfo &MFI = MF.getFrameInfo();
3792 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3794 // Create load node to retrieve arguments from the stack.
3795 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3796 ArgValue2 = DAG.getLoad(
3797 MVT::i32, dl, Root, FIN,
3798 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3799 } else {
3800 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3801 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3803 if (!Subtarget->isLittle())
3804 std::swap (ArgValue, ArgValue2);
3805 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3808 // The remaining GPRs hold either the beginning of variable-argument
3809 // data, or the beginning of an aggregate passed by value (usually
3810 // byval). Either way, we allocate stack slots adjacent to the data
3811 // provided by our caller, and store the unallocated registers there.
3812 // If this is a variadic function, the va_list pointer will begin with
3813 // these values; otherwise, this reassembles a (byval) structure that
3814 // was split between registers and memory.
3815 // Return: The frame index registers were stored into.
3816 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3817 const SDLoc &dl, SDValue &Chain,
3818 const Value *OrigArg,
3819 unsigned InRegsParamRecordIdx,
3820 int ArgOffset, unsigned ArgSize) const {
3821 // Currently, two use-cases possible:
3822 // Case #1. Non-var-args function, and we meet first byval parameter.
3823 // Setup first unallocated register as first byval register;
3824 // eat all remained registers
3825 // (these two actions are performed by HandleByVal method).
3826 // Then, here, we initialize stack frame with
3827 // "store-reg" instructions.
3828 // Case #2. Var-args function, that doesn't contain byval parameters.
3829 // The same: eat all remained unallocated registers,
3830 // initialize stack frame.
3832 MachineFunction &MF = DAG.getMachineFunction();
3833 MachineFrameInfo &MFI = MF.getFrameInfo();
3834 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3835 unsigned RBegin, REnd;
3836 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3837 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3838 } else {
3839 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3840 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3841 REnd = ARM::R4;
3844 if (REnd != RBegin)
3845 ArgOffset = -4 * (ARM::R4 - RBegin);
3847 auto PtrVT = getPointerTy(DAG.getDataLayout());
3848 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3849 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3851 SmallVector<SDValue, 4> MemOps;
3852 const TargetRegisterClass *RC =
3853 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3855 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3856 unsigned VReg = MF.addLiveIn(Reg, RC);
3857 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3858 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3859 MachinePointerInfo(OrigArg, 4 * i));
3860 MemOps.push_back(Store);
3861 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3864 if (!MemOps.empty())
3865 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3866 return FrameIndex;
3869 // Setup stack frame, the va_list pointer will start from.
3870 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3871 const SDLoc &dl, SDValue &Chain,
3872 unsigned ArgOffset,
3873 unsigned TotalArgRegsSaveSize,
3874 bool ForceMutable) const {
3875 MachineFunction &MF = DAG.getMachineFunction();
3876 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3878 // Try to store any remaining integer argument regs
3879 // to their spots on the stack so that they may be loaded by dereferencing
3880 // the result of va_next.
3881 // If there is no regs to be stored, just point address after last
3882 // argument passed via stack.
3883 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3884 CCInfo.getInRegsParamsCount(),
3885 CCInfo.getNextStackOffset(),
3886 std::max(4U, TotalArgRegsSaveSize));
3887 AFI->setVarArgsFrameIndex(FrameIndex);
3890 SDValue ARMTargetLowering::LowerFormalArguments(
3891 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3892 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3893 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3894 MachineFunction &MF = DAG.getMachineFunction();
3895 MachineFrameInfo &MFI = MF.getFrameInfo();
3897 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3899 // Assign locations to all of the incoming arguments.
3900 SmallVector<CCValAssign, 16> ArgLocs;
3901 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3902 *DAG.getContext());
3903 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3905 SmallVector<SDValue, 16> ArgValues;
3906 SDValue ArgValue;
3907 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3908 unsigned CurArgIdx = 0;
3910 // Initially ArgRegsSaveSize is zero.
3911 // Then we increase this value each time we meet byval parameter.
3912 // We also increase this value in case of varargs function.
3913 AFI->setArgRegsSaveSize(0);
3915 // Calculate the amount of stack space that we need to allocate to store
3916 // byval and variadic arguments that are passed in registers.
3917 // We need to know this before we allocate the first byval or variadic
3918 // argument, as they will be allocated a stack slot below the CFA (Canonical
3919 // Frame Address, the stack pointer at entry to the function).
3920 unsigned ArgRegBegin = ARM::R4;
3921 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3922 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3923 break;
3925 CCValAssign &VA = ArgLocs[i];
3926 unsigned Index = VA.getValNo();
3927 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3928 if (!Flags.isByVal())
3929 continue;
3931 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3932 unsigned RBegin, REnd;
3933 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3934 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3936 CCInfo.nextInRegsParam();
3938 CCInfo.rewindByValRegsInfo();
3940 int lastInsIndex = -1;
3941 if (isVarArg && MFI.hasVAStart()) {
3942 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3943 if (RegIdx != array_lengthof(GPRArgRegs))
3944 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3947 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3948 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3949 auto PtrVT = getPointerTy(DAG.getDataLayout());
3951 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3952 CCValAssign &VA = ArgLocs[i];
3953 if (Ins[VA.getValNo()].isOrigArg()) {
3954 std::advance(CurOrigArg,
3955 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3956 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3958 // Arguments stored in registers.
3959 if (VA.isRegLoc()) {
3960 EVT RegVT = VA.getLocVT();
3962 if (VA.needsCustom()) {
3963 // f64 and vector types are split up into multiple registers or
3964 // combinations of registers and stack slots.
3965 if (VA.getLocVT() == MVT::v2f64) {
3966 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3967 Chain, DAG, dl);
3968 VA = ArgLocs[++i]; // skip ahead to next loc
3969 SDValue ArgValue2;
3970 if (VA.isMemLoc()) {
3971 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3972 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3973 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3974 MachinePointerInfo::getFixedStack(
3975 DAG.getMachineFunction(), FI));
3976 } else {
3977 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3978 Chain, DAG, dl);
3980 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3981 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3982 ArgValue, ArgValue1,
3983 DAG.getIntPtrConstant(0, dl));
3984 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3985 ArgValue, ArgValue2,
3986 DAG.getIntPtrConstant(1, dl));
3987 } else
3988 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3989 } else {
3990 const TargetRegisterClass *RC;
3993 if (RegVT == MVT::f16)
3994 RC = &ARM::HPRRegClass;
3995 else if (RegVT == MVT::f32)
3996 RC = &ARM::SPRRegClass;
3997 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3998 RC = &ARM::DPRRegClass;
3999 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
4000 RC = &ARM::QPRRegClass;
4001 else if (RegVT == MVT::i32)
4002 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4003 : &ARM::GPRRegClass;
4004 else
4005 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4007 // Transform the arguments in physical registers into virtual ones.
4008 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4009 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4011 // If this value is passed in r0 and has the returned attribute (e.g.
4012 // C++ 'structors), record this fact for later use.
4013 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4014 AFI->setPreservesR0();
4018 // If this is an 8 or 16-bit value, it is really passed promoted
4019 // to 32 bits. Insert an assert[sz]ext to capture this, then
4020 // truncate to the right size.
4021 switch (VA.getLocInfo()) {
4022 default: llvm_unreachable("Unknown loc info!");
4023 case CCValAssign::Full: break;
4024 case CCValAssign::BCvt:
4025 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4026 break;
4027 case CCValAssign::SExt:
4028 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4029 DAG.getValueType(VA.getValVT()));
4030 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4031 break;
4032 case CCValAssign::ZExt:
4033 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4034 DAG.getValueType(VA.getValVT()));
4035 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4036 break;
4039 InVals.push_back(ArgValue);
4040 } else { // VA.isRegLoc()
4041 // sanity check
4042 assert(VA.isMemLoc());
4043 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4045 int index = VA.getValNo();
4047 // Some Ins[] entries become multiple ArgLoc[] entries.
4048 // Process them only once.
4049 if (index != lastInsIndex)
4051 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4052 // FIXME: For now, all byval parameter objects are marked mutable.
4053 // This can be changed with more analysis.
4054 // In case of tail call optimization mark all arguments mutable.
4055 // Since they could be overwritten by lowering of arguments in case of
4056 // a tail call.
4057 if (Flags.isByVal()) {
4058 assert(Ins[index].isOrigArg() &&
4059 "Byval arguments cannot be implicit");
4060 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4062 int FrameIndex = StoreByValRegs(
4063 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4064 VA.getLocMemOffset(), Flags.getByValSize());
4065 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4066 CCInfo.nextInRegsParam();
4067 } else {
4068 unsigned FIOffset = VA.getLocMemOffset();
4069 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4070 FIOffset, true);
4072 // Create load nodes to retrieve arguments from the stack.
4073 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4074 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4075 MachinePointerInfo::getFixedStack(
4076 DAG.getMachineFunction(), FI)));
4078 lastInsIndex = index;
4083 // varargs
4084 if (isVarArg && MFI.hasVAStart())
4085 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4086 CCInfo.getNextStackOffset(),
4087 TotalArgRegsSaveSize);
4089 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4091 return Chain;
4094 /// isFloatingPointZero - Return true if this is +0.0.
4095 static bool isFloatingPointZero(SDValue Op) {
4096 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4097 return CFP->getValueAPF().isPosZero();
4098 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4099 // Maybe this has already been legalized into the constant pool?
4100 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4101 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4102 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4103 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4104 return CFP->getValueAPF().isPosZero();
4106 } else if (Op->getOpcode() == ISD::BITCAST &&
4107 Op->getValueType(0) == MVT::f64) {
4108 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4109 // created by LowerConstantFP().
4110 SDValue BitcastOp = Op->getOperand(0);
4111 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4112 isNullConstant(BitcastOp->getOperand(0)))
4113 return true;
4115 return false;
4118 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4119 /// the given operands.
4120 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4121 SDValue &ARMcc, SelectionDAG &DAG,
4122 const SDLoc &dl) const {
4123 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4124 unsigned C = RHSC->getZExtValue();
4125 if (!isLegalICmpImmediate((int32_t)C)) {
4126 // Constant does not fit, try adjusting it by one.
4127 switch (CC) {
4128 default: break;
4129 case ISD::SETLT:
4130 case ISD::SETGE:
4131 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4132 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4133 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4135 break;
4136 case ISD::SETULT:
4137 case ISD::SETUGE:
4138 if (C != 0 && isLegalICmpImmediate(C-1)) {
4139 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4140 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4142 break;
4143 case ISD::SETLE:
4144 case ISD::SETGT:
4145 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4146 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4147 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4149 break;
4150 case ISD::SETULE:
4151 case ISD::SETUGT:
4152 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4153 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4154 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4156 break;
4159 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4160 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4161 // In ARM and Thumb-2, the compare instructions can shift their second
4162 // operand.
4163 CC = ISD::getSetCCSwappedOperands(CC);
4164 std::swap(LHS, RHS);
4167 // Thumb1 has very limited immediate modes, so turning an "and" into a
4168 // shift can save multiple instructions.
4170 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4171 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4172 // own. If it's the operand to an unsigned comparison with an immediate,
4173 // we can eliminate one of the shifts: we transform
4174 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4176 // We avoid transforming cases which aren't profitable due to encoding
4177 // details:
4179 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4180 // would not; in that case, we're essentially trading one immediate load for
4181 // another.
4182 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4183 // 3. C2 is zero; we have other code for this special case.
4185 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4186 // instruction, since the AND is always one instruction anyway, but we could
4187 // use narrow instructions in some cases.
4188 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4189 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4190 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4191 !isSignedIntSetCC(CC)) {
4192 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4193 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4194 uint64_t RHSV = RHSC->getZExtValue();
4195 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4196 unsigned ShiftBits = countLeadingZeros(Mask);
4197 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4198 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4199 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4200 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4205 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4206 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4207 // way a cmp would.
4208 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4209 // some tweaks to the heuristics for the previous and->shift transform.
4210 // FIXME: Optimize cases where the LHS isn't a shift.
4211 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4212 isa<ConstantSDNode>(RHS) &&
4213 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4214 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4215 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4216 unsigned ShiftAmt =
4217 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4218 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4219 DAG.getVTList(MVT::i32, MVT::i32),
4220 LHS.getOperand(0),
4221 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4222 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4223 Shift.getValue(1), SDValue());
4224 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4225 return Chain.getValue(1);
4228 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4230 // If the RHS is a constant zero then the V (overflow) flag will never be
4231 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4232 // simpler for other passes (like the peephole optimiser) to deal with.
4233 if (isNullConstant(RHS)) {
4234 switch (CondCode) {
4235 default: break;
4236 case ARMCC::GE:
4237 CondCode = ARMCC::PL;
4238 break;
4239 case ARMCC::LT:
4240 CondCode = ARMCC::MI;
4241 break;
4245 ARMISD::NodeType CompareType;
4246 switch (CondCode) {
4247 default:
4248 CompareType = ARMISD::CMP;
4249 break;
4250 case ARMCC::EQ:
4251 case ARMCC::NE:
4252 // Uses only Z Flag
4253 CompareType = ARMISD::CMPZ;
4254 break;
4256 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4257 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4260 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4261 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4262 SelectionDAG &DAG, const SDLoc &dl,
4263 bool InvalidOnQNaN) const {
4264 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4265 SDValue Cmp;
4266 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
4267 if (!isFloatingPointZero(RHS))
4268 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
4269 else
4270 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
4271 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4274 /// duplicateCmp - Glue values can have only one use, so this function
4275 /// duplicates a comparison node.
4276 SDValue
4277 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4278 unsigned Opc = Cmp.getOpcode();
4279 SDLoc DL(Cmp);
4280 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4281 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4283 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4284 Cmp = Cmp.getOperand(0);
4285 Opc = Cmp.getOpcode();
4286 if (Opc == ARMISD::CMPFP)
4287 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4288 Cmp.getOperand(1), Cmp.getOperand(2));
4289 else {
4290 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4291 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4292 Cmp.getOperand(1));
4294 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4297 // This function returns three things: the arithmetic computation itself
4298 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4299 // comparison and the condition code define the case in which the arithmetic
4300 // computation *does not* overflow.
4301 std::pair<SDValue, SDValue>
4302 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4303 SDValue &ARMcc) const {
4304 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4306 SDValue Value, OverflowCmp;
4307 SDValue LHS = Op.getOperand(0);
4308 SDValue RHS = Op.getOperand(1);
4309 SDLoc dl(Op);
4311 // FIXME: We are currently always generating CMPs because we don't support
4312 // generating CMN through the backend. This is not as good as the natural
4313 // CMP case because it causes a register dependency and cannot be folded
4314 // later.
4316 switch (Op.getOpcode()) {
4317 default:
4318 llvm_unreachable("Unknown overflow instruction!");
4319 case ISD::SADDO:
4320 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4321 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4322 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4323 break;
4324 case ISD::UADDO:
4325 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4326 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4327 // We do not use it in the USUBO case as Value may not be used.
4328 Value = DAG.getNode(ARMISD::ADDC, dl,
4329 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4330 .getValue(0);
4331 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4332 break;
4333 case ISD::SSUBO:
4334 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4335 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4336 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4337 break;
4338 case ISD::USUBO:
4339 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4340 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4341 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4342 break;
4343 case ISD::UMULO:
4344 // We generate a UMUL_LOHI and then check if the high word is 0.
4345 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4346 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4347 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4348 LHS, RHS);
4349 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4350 DAG.getConstant(0, dl, MVT::i32));
4351 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4352 break;
4353 case ISD::SMULO:
4354 // We generate a SMUL_LOHI and then check if all the bits of the high word
4355 // are the same as the sign bit of the low word.
4356 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4357 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4358 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4359 LHS, RHS);
4360 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4361 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4362 Value.getValue(0),
4363 DAG.getConstant(31, dl, MVT::i32)));
4364 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4365 break;
4366 } // switch (...)
4368 return std::make_pair(Value, OverflowCmp);
4371 SDValue
4372 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4373 // Let legalize expand this if it isn't a legal type yet.
4374 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4375 return SDValue();
4377 SDValue Value, OverflowCmp;
4378 SDValue ARMcc;
4379 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4380 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4381 SDLoc dl(Op);
4382 // We use 0 and 1 as false and true values.
4383 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4384 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4385 EVT VT = Op.getValueType();
4387 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4388 ARMcc, CCR, OverflowCmp);
4390 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4391 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4394 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4395 SelectionDAG &DAG) {
4396 SDLoc DL(BoolCarry);
4397 EVT CarryVT = BoolCarry.getValueType();
4399 // This converts the boolean value carry into the carry flag by doing
4400 // ARMISD::SUBC Carry, 1
4401 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4402 DAG.getVTList(CarryVT, MVT::i32),
4403 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4404 return Carry.getValue(1);
4407 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4408 SelectionDAG &DAG) {
4409 SDLoc DL(Flags);
4411 // Now convert the carry flag into a boolean carry. We do this
4412 // using ARMISD:ADDE 0, 0, Carry
4413 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4414 DAG.getConstant(0, DL, MVT::i32),
4415 DAG.getConstant(0, DL, MVT::i32), Flags);
4418 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4419 SelectionDAG &DAG) const {
4420 // Let legalize expand this if it isn't a legal type yet.
4421 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4422 return SDValue();
4424 SDValue LHS = Op.getOperand(0);
4425 SDValue RHS = Op.getOperand(1);
4426 SDLoc dl(Op);
4428 EVT VT = Op.getValueType();
4429 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4430 SDValue Value;
4431 SDValue Overflow;
4432 switch (Op.getOpcode()) {
4433 default:
4434 llvm_unreachable("Unknown overflow instruction!");
4435 case ISD::UADDO:
4436 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4437 // Convert the carry flag into a boolean value.
4438 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4439 break;
4440 case ISD::USUBO: {
4441 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4442 // Convert the carry flag into a boolean value.
4443 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4444 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4445 // value. So compute 1 - C.
4446 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4447 DAG.getConstant(1, dl, MVT::i32), Overflow);
4448 break;
4452 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4455 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4456 SDValue Cond = Op.getOperand(0);
4457 SDValue SelectTrue = Op.getOperand(1);
4458 SDValue SelectFalse = Op.getOperand(2);
4459 SDLoc dl(Op);
4460 unsigned Opc = Cond.getOpcode();
4462 if (Cond.getResNo() == 1 &&
4463 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4464 Opc == ISD::USUBO)) {
4465 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4466 return SDValue();
4468 SDValue Value, OverflowCmp;
4469 SDValue ARMcc;
4470 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4471 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4472 EVT VT = Op.getValueType();
4474 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4475 OverflowCmp, DAG);
4478 // Convert:
4480 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4481 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4483 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4484 const ConstantSDNode *CMOVTrue =
4485 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4486 const ConstantSDNode *CMOVFalse =
4487 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4489 if (CMOVTrue && CMOVFalse) {
4490 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4491 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4493 SDValue True;
4494 SDValue False;
4495 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4496 True = SelectTrue;
4497 False = SelectFalse;
4498 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4499 True = SelectFalse;
4500 False = SelectTrue;
4503 if (True.getNode() && False.getNode()) {
4504 EVT VT = Op.getValueType();
4505 SDValue ARMcc = Cond.getOperand(2);
4506 SDValue CCR = Cond.getOperand(3);
4507 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4508 assert(True.getValueType() == VT);
4509 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4514 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4515 // undefined bits before doing a full-word comparison with zero.
4516 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4517 DAG.getConstant(1, dl, Cond.getValueType()));
4519 return DAG.getSelectCC(dl, Cond,
4520 DAG.getConstant(0, dl, Cond.getValueType()),
4521 SelectTrue, SelectFalse, ISD::SETNE);
4524 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4525 bool &swpCmpOps, bool &swpVselOps) {
4526 // Start by selecting the GE condition code for opcodes that return true for
4527 // 'equality'
4528 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4529 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4530 CondCode = ARMCC::GE;
4532 // and GT for opcodes that return false for 'equality'.
4533 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4534 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4535 CondCode = ARMCC::GT;
4537 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4538 // to swap the compare operands.
4539 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4540 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4541 swpCmpOps = true;
4543 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4544 // If we have an unordered opcode, we need to swap the operands to the VSEL
4545 // instruction (effectively negating the condition).
4547 // This also has the effect of swapping which one of 'less' or 'greater'
4548 // returns true, so we also swap the compare operands. It also switches
4549 // whether we return true for 'equality', so we compensate by picking the
4550 // opposite condition code to our original choice.
4551 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4552 CC == ISD::SETUGT) {
4553 swpCmpOps = !swpCmpOps;
4554 swpVselOps = !swpVselOps;
4555 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4558 // 'ordered' is 'anything but unordered', so use the VS condition code and
4559 // swap the VSEL operands.
4560 if (CC == ISD::SETO) {
4561 CondCode = ARMCC::VS;
4562 swpVselOps = true;
4565 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4566 // code and swap the VSEL operands. Also do this if we don't care about the
4567 // unordered case.
4568 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4569 CondCode = ARMCC::EQ;
4570 swpVselOps = true;
4574 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4575 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4576 SDValue Cmp, SelectionDAG &DAG) const {
4577 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4578 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4579 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4580 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4581 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4583 SDValue TrueLow = TrueVal.getValue(0);
4584 SDValue TrueHigh = TrueVal.getValue(1);
4585 SDValue FalseLow = FalseVal.getValue(0);
4586 SDValue FalseHigh = FalseVal.getValue(1);
4588 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4589 ARMcc, CCR, Cmp);
4590 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4591 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4593 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4594 } else {
4595 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4596 Cmp);
4600 static bool isGTorGE(ISD::CondCode CC) {
4601 return CC == ISD::SETGT || CC == ISD::SETGE;
4604 static bool isLTorLE(ISD::CondCode CC) {
4605 return CC == ISD::SETLT || CC == ISD::SETLE;
4608 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4609 // All of these conditions (and their <= and >= counterparts) will do:
4610 // x < k ? k : x
4611 // x > k ? x : k
4612 // k < x ? x : k
4613 // k > x ? k : x
4614 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4615 const SDValue TrueVal, const SDValue FalseVal,
4616 const ISD::CondCode CC, const SDValue K) {
4617 return (isGTorGE(CC) &&
4618 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4619 (isLTorLE(CC) &&
4620 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4623 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4624 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4625 const SDValue TrueVal, const SDValue FalseVal,
4626 const ISD::CondCode CC, const SDValue K) {
4627 return (isGTorGE(CC) &&
4628 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4629 (isLTorLE(CC) &&
4630 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4633 // Check if two chained conditionals could be converted into SSAT or USAT.
4635 // SSAT can replace a set of two conditional selectors that bound a number to an
4636 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4638 // x < -k ? -k : (x > k ? k : x)
4639 // x < -k ? -k : (x < k ? x : k)
4640 // x > -k ? (x > k ? k : x) : -k
4641 // x < k ? (x < -k ? -k : x) : k
4642 // etc.
4644 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4645 // a power of 2.
4647 // It returns true if the conversion can be done, false otherwise.
4648 // Additionally, the variable is returned in parameter V, the constant in K and
4649 // usat is set to true if the conditional represents an unsigned saturation
4650 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4651 uint64_t &K, bool &usat) {
4652 SDValue LHS1 = Op.getOperand(0);
4653 SDValue RHS1 = Op.getOperand(1);
4654 SDValue TrueVal1 = Op.getOperand(2);
4655 SDValue FalseVal1 = Op.getOperand(3);
4656 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4658 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4659 if (Op2.getOpcode() != ISD::SELECT_CC)
4660 return false;
4662 SDValue LHS2 = Op2.getOperand(0);
4663 SDValue RHS2 = Op2.getOperand(1);
4664 SDValue TrueVal2 = Op2.getOperand(2);
4665 SDValue FalseVal2 = Op2.getOperand(3);
4666 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4668 // Find out which are the constants and which are the variables
4669 // in each conditional
4670 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4671 ? &RHS1
4672 : nullptr;
4673 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4674 ? &RHS2
4675 : nullptr;
4676 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4677 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4678 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4679 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4681 // We must detect cases where the original operations worked with 16- or
4682 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4683 // must work with sign-extended values but the select operations return
4684 // the original non-extended value.
4685 SDValue V2TmpReg = V2Tmp;
4686 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4687 V2TmpReg = V2Tmp->getOperand(0);
4689 // Check that the registers and the constants have the correct values
4690 // in both conditionals
4691 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4692 V2TmpReg != V2)
4693 return false;
4695 // Figure out which conditional is saturating the lower/upper bound.
4696 const SDValue *LowerCheckOp =
4697 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4698 ? &Op
4699 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4700 ? &Op2
4701 : nullptr;
4702 const SDValue *UpperCheckOp =
4703 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4704 ? &Op
4705 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4706 ? &Op2
4707 : nullptr;
4709 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4710 return false;
4712 // Check that the constant in the lower-bound check is
4713 // the opposite of the constant in the upper-bound check
4714 // in 1's complement.
4715 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4716 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4717 int64_t PosVal = std::max(Val1, Val2);
4718 int64_t NegVal = std::min(Val1, Val2);
4720 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4721 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4722 isPowerOf2_64(PosVal + 1)) {
4724 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4725 if (Val1 == ~Val2)
4726 usat = false;
4727 else if (NegVal == 0)
4728 usat = true;
4729 else
4730 return false;
4732 V = V2;
4733 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4735 return true;
4738 return false;
4741 // Check if a condition of the type x < k ? k : x can be converted into a
4742 // bit operation instead of conditional moves.
4743 // Currently this is allowed given:
4744 // - The conditions and values match up
4745 // - k is 0 or -1 (all ones)
4746 // This function will not check the last condition, thats up to the caller
4747 // It returns true if the transformation can be made, and in such case
4748 // returns x in V, and k in SatK.
4749 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4750 SDValue &SatK)
4752 SDValue LHS = Op.getOperand(0);
4753 SDValue RHS = Op.getOperand(1);
4754 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4755 SDValue TrueVal = Op.getOperand(2);
4756 SDValue FalseVal = Op.getOperand(3);
4758 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4759 ? &RHS
4760 : nullptr;
4762 // No constant operation in comparison, early out
4763 if (!K)
4764 return false;
4766 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4767 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4768 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4770 // If the constant on left and right side, or variable on left and right,
4771 // does not match, early out
4772 if (*K != KTmp || V != VTmp)
4773 return false;
4775 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4776 SatK = *K;
4777 return true;
4780 return false;
4783 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4784 if (VT == MVT::f32)
4785 return !Subtarget->hasVFP2Base();
4786 if (VT == MVT::f64)
4787 return !Subtarget->hasFP64();
4788 if (VT == MVT::f16)
4789 return !Subtarget->hasFullFP16();
4790 return false;
4793 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4794 EVT VT = Op.getValueType();
4795 SDLoc dl(Op);
4797 // Try to convert two saturating conditional selects into a single SSAT
4798 SDValue SatValue;
4799 uint64_t SatConstant;
4800 bool SatUSat;
4801 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4802 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4803 if (SatUSat)
4804 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4805 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4806 else
4807 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4808 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4811 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4812 // into more efficient bit operations, which is possible when k is 0 or -1
4813 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4814 // single instructions. On Thumb the shift and the bit operation will be two
4815 // instructions.
4816 // Only allow this transformation on full-width (32-bit) operations
4817 SDValue LowerSatConstant;
4818 if (VT == MVT::i32 &&
4819 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4820 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4821 DAG.getConstant(31, dl, VT));
4822 if (isNullConstant(LowerSatConstant)) {
4823 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4824 DAG.getAllOnesConstant(dl, VT));
4825 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4826 } else if (isAllOnesConstant(LowerSatConstant))
4827 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4830 SDValue LHS = Op.getOperand(0);
4831 SDValue RHS = Op.getOperand(1);
4832 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4833 SDValue TrueVal = Op.getOperand(2);
4834 SDValue FalseVal = Op.getOperand(3);
4835 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
4836 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
4838 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
4839 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
4840 unsigned TVal = CTVal->getZExtValue();
4841 unsigned FVal = CFVal->getZExtValue();
4842 unsigned Opcode = 0;
4844 if (TVal == ~FVal) {
4845 Opcode = ARMISD::CSINV;
4846 } else if (TVal == ~FVal + 1) {
4847 Opcode = ARMISD::CSNEG;
4848 } else if (TVal + 1 == FVal) {
4849 Opcode = ARMISD::CSINC;
4850 } else if (TVal == FVal + 1) {
4851 Opcode = ARMISD::CSINC;
4852 std::swap(TrueVal, FalseVal);
4853 std::swap(TVal, FVal);
4854 CC = ISD::getSetCCInverse(CC, true);
4857 if (Opcode) {
4858 // If one of the constants is cheaper than another, materialise the
4859 // cheaper one and let the csel generate the other.
4860 if (Opcode != ARMISD::CSINC &&
4861 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
4862 std::swap(TrueVal, FalseVal);
4863 std::swap(TVal, FVal);
4864 CC = ISD::getSetCCInverse(CC, true);
4867 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
4868 // to get there. CSINC not is invertable like the other two (~(~a) == a,
4869 // -(-a) == a, but (a+1)+1 != a).
4870 if (FVal == 0 && Opcode != ARMISD::CSINC) {
4871 std::swap(TrueVal, FalseVal);
4872 std::swap(TVal, FVal);
4873 CC = ISD::getSetCCInverse(CC, true);
4875 if (TVal == 0)
4876 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
4878 // Drops F's value because we can get it by inverting/negating TVal.
4879 FalseVal = TrueVal;
4881 SDValue ARMcc;
4882 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4883 EVT VT = TrueVal.getValueType();
4884 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
4888 if (isUnsupportedFloatingType(LHS.getValueType())) {
4889 DAG.getTargetLoweringInfo().softenSetCCOperands(
4890 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
4892 // If softenSetCCOperands only returned one value, we should compare it to
4893 // zero.
4894 if (!RHS.getNode()) {
4895 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4896 CC = ISD::SETNE;
4900 if (LHS.getValueType() == MVT::i32) {
4901 // Try to generate VSEL on ARMv8.
4902 // The VSEL instruction can't use all the usual ARM condition
4903 // codes: it only has two bits to select the condition code, so it's
4904 // constrained to use only GE, GT, VS and EQ.
4906 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4907 // swap the operands of the previous compare instruction (effectively
4908 // inverting the compare condition, swapping 'less' and 'greater') and
4909 // sometimes need to swap the operands to the VSEL (which inverts the
4910 // condition in the sense of firing whenever the previous condition didn't)
4911 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4912 TrueVal.getValueType() == MVT::f32 ||
4913 TrueVal.getValueType() == MVT::f64)) {
4914 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4915 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4916 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4917 CC = ISD::getSetCCInverse(CC, true);
4918 std::swap(TrueVal, FalseVal);
4922 SDValue ARMcc;
4923 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4924 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4925 // Choose GE over PL, which vsel does now support
4926 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4927 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4928 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4931 ARMCC::CondCodes CondCode, CondCode2;
4932 bool InvalidOnQNaN;
4933 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4935 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4936 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4937 // must use VSEL (limited condition codes), due to not having conditional f16
4938 // moves.
4939 if (Subtarget->hasFPARMv8Base() &&
4940 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4941 (TrueVal.getValueType() == MVT::f16 ||
4942 TrueVal.getValueType() == MVT::f32 ||
4943 TrueVal.getValueType() == MVT::f64)) {
4944 bool swpCmpOps = false;
4945 bool swpVselOps = false;
4946 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4948 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4949 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4950 if (swpCmpOps)
4951 std::swap(LHS, RHS);
4952 if (swpVselOps)
4953 std::swap(TrueVal, FalseVal);
4957 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4958 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4959 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4960 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4961 if (CondCode2 != ARMCC::AL) {
4962 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4963 // FIXME: Needs another CMP because flag can have but one use.
4964 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4965 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4967 return Result;
4970 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4971 /// to morph to an integer compare sequence.
4972 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4973 const ARMSubtarget *Subtarget) {
4974 SDNode *N = Op.getNode();
4975 if (!N->hasOneUse())
4976 // Otherwise it requires moving the value from fp to integer registers.
4977 return false;
4978 if (!N->getNumValues())
4979 return false;
4980 EVT VT = Op.getValueType();
4981 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4982 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4983 // vmrs are very slow, e.g. cortex-a8.
4984 return false;
4986 if (isFloatingPointZero(Op)) {
4987 SeenZero = true;
4988 return true;
4990 return ISD::isNormalLoad(N);
4993 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4994 if (isFloatingPointZero(Op))
4995 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4997 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4998 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4999 Ld->getPointerInfo(), Ld->getAlignment(),
5000 Ld->getMemOperand()->getFlags());
5002 llvm_unreachable("Unknown VFP cmp argument!");
5005 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5006 SDValue &RetVal1, SDValue &RetVal2) {
5007 SDLoc dl(Op);
5009 if (isFloatingPointZero(Op)) {
5010 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5011 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5012 return;
5015 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5016 SDValue Ptr = Ld->getBasePtr();
5017 RetVal1 =
5018 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5019 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5021 EVT PtrType = Ptr.getValueType();
5022 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5023 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5024 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5025 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5026 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5027 Ld->getMemOperand()->getFlags());
5028 return;
5031 llvm_unreachable("Unknown VFP cmp argument!");
5034 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5035 /// f32 and even f64 comparisons to integer ones.
5036 SDValue
5037 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5038 SDValue Chain = Op.getOperand(0);
5039 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5040 SDValue LHS = Op.getOperand(2);
5041 SDValue RHS = Op.getOperand(3);
5042 SDValue Dest = Op.getOperand(4);
5043 SDLoc dl(Op);
5045 bool LHSSeenZero = false;
5046 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5047 bool RHSSeenZero = false;
5048 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5049 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5050 // If unsafe fp math optimization is enabled and there are no other uses of
5051 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5052 // to an integer comparison.
5053 if (CC == ISD::SETOEQ)
5054 CC = ISD::SETEQ;
5055 else if (CC == ISD::SETUNE)
5056 CC = ISD::SETNE;
5058 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5059 SDValue ARMcc;
5060 if (LHS.getValueType() == MVT::f32) {
5061 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5062 bitcastf32Toi32(LHS, DAG), Mask);
5063 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5064 bitcastf32Toi32(RHS, DAG), Mask);
5065 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5066 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5067 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5068 Chain, Dest, ARMcc, CCR, Cmp);
5071 SDValue LHS1, LHS2;
5072 SDValue RHS1, RHS2;
5073 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5074 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5075 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5076 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5077 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5078 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5079 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5080 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5081 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5084 return SDValue();
5087 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5088 SDValue Chain = Op.getOperand(0);
5089 SDValue Cond = Op.getOperand(1);
5090 SDValue Dest = Op.getOperand(2);
5091 SDLoc dl(Op);
5093 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5094 // instruction.
5095 unsigned Opc = Cond.getOpcode();
5096 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5097 !Subtarget->isThumb1Only();
5098 if (Cond.getResNo() == 1 &&
5099 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5100 Opc == ISD::USUBO || OptimizeMul)) {
5101 // Only lower legal XALUO ops.
5102 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5103 return SDValue();
5105 // The actual operation with overflow check.
5106 SDValue Value, OverflowCmp;
5107 SDValue ARMcc;
5108 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5110 // Reverse the condition code.
5111 ARMCC::CondCodes CondCode =
5112 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5113 CondCode = ARMCC::getOppositeCondition(CondCode);
5114 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5115 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5117 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5118 OverflowCmp);
5121 return SDValue();
5124 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5125 SDValue Chain = Op.getOperand(0);
5126 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5127 SDValue LHS = Op.getOperand(2);
5128 SDValue RHS = Op.getOperand(3);
5129 SDValue Dest = Op.getOperand(4);
5130 SDLoc dl(Op);
5132 if (isUnsupportedFloatingType(LHS.getValueType())) {
5133 DAG.getTargetLoweringInfo().softenSetCCOperands(
5134 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5136 // If softenSetCCOperands only returned one value, we should compare it to
5137 // zero.
5138 if (!RHS.getNode()) {
5139 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5140 CC = ISD::SETNE;
5144 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5145 // instruction.
5146 unsigned Opc = LHS.getOpcode();
5147 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5148 !Subtarget->isThumb1Only();
5149 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5150 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5151 Opc == ISD::USUBO || OptimizeMul) &&
5152 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5153 // Only lower legal XALUO ops.
5154 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5155 return SDValue();
5157 // The actual operation with overflow check.
5158 SDValue Value, OverflowCmp;
5159 SDValue ARMcc;
5160 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5162 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5163 // Reverse the condition code.
5164 ARMCC::CondCodes CondCode =
5165 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5166 CondCode = ARMCC::getOppositeCondition(CondCode);
5167 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5169 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5171 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5172 OverflowCmp);
5175 if (LHS.getValueType() == MVT::i32) {
5176 SDValue ARMcc;
5177 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5178 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5179 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5180 Chain, Dest, ARMcc, CCR, Cmp);
5183 if (getTargetMachine().Options.UnsafeFPMath &&
5184 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5185 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5186 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5187 return Result;
5190 ARMCC::CondCodes CondCode, CondCode2;
5191 bool InvalidOnQNaN;
5192 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
5194 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5195 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
5196 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5197 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5198 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5199 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5200 if (CondCode2 != ARMCC::AL) {
5201 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5202 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5203 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5205 return Res;
5208 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5209 SDValue Chain = Op.getOperand(0);
5210 SDValue Table = Op.getOperand(1);
5211 SDValue Index = Op.getOperand(2);
5212 SDLoc dl(Op);
5214 EVT PTy = getPointerTy(DAG.getDataLayout());
5215 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5216 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5217 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5218 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5219 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5220 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5221 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5222 // which does another jump to the destination. This also makes it easier
5223 // to translate it to TBB / TBH later (Thumb2 only).
5224 // FIXME: This might not work if the function is extremely large.
5225 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5226 Addr, Op.getOperand(2), JTI);
5228 if (isPositionIndependent() || Subtarget->isROPI()) {
5229 Addr =
5230 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5231 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5232 Chain = Addr.getValue(1);
5233 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5234 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5235 } else {
5236 Addr =
5237 DAG.getLoad(PTy, dl, Chain, Addr,
5238 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5239 Chain = Addr.getValue(1);
5240 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5244 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5245 EVT VT = Op.getValueType();
5246 SDLoc dl(Op);
5248 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5249 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5250 return Op;
5251 return DAG.UnrollVectorOp(Op.getNode());
5254 const bool HasFullFP16 =
5255 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5257 EVT NewTy;
5258 const EVT OpTy = Op.getOperand(0).getValueType();
5259 if (OpTy == MVT::v4f32)
5260 NewTy = MVT::v4i32;
5261 else if (OpTy == MVT::v4f16 && HasFullFP16)
5262 NewTy = MVT::v4i16;
5263 else if (OpTy == MVT::v8f16 && HasFullFP16)
5264 NewTy = MVT::v8i16;
5265 else
5266 llvm_unreachable("Invalid type for custom lowering!");
5268 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5269 return DAG.UnrollVectorOp(Op.getNode());
5271 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5272 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5275 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5276 EVT VT = Op.getValueType();
5277 if (VT.isVector())
5278 return LowerVectorFP_TO_INT(Op, DAG);
5279 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5280 RTLIB::Libcall LC;
5281 if (Op.getOpcode() == ISD::FP_TO_SINT)
5282 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5283 Op.getValueType());
5284 else
5285 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5286 Op.getValueType());
5287 MakeLibCallOptions CallOptions;
5288 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5289 CallOptions, SDLoc(Op)).first;
5292 return Op;
5295 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5296 EVT VT = Op.getValueType();
5297 SDLoc dl(Op);
5299 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5300 if (VT.getVectorElementType() == MVT::f32)
5301 return Op;
5302 return DAG.UnrollVectorOp(Op.getNode());
5305 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5306 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5307 "Invalid type for custom lowering!");
5309 const bool HasFullFP16 =
5310 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5312 EVT DestVecType;
5313 if (VT == MVT::v4f32)
5314 DestVecType = MVT::v4i32;
5315 else if (VT == MVT::v4f16 && HasFullFP16)
5316 DestVecType = MVT::v4i16;
5317 else if (VT == MVT::v8f16 && HasFullFP16)
5318 DestVecType = MVT::v8i16;
5319 else
5320 return DAG.UnrollVectorOp(Op.getNode());
5322 unsigned CastOpc;
5323 unsigned Opc;
5324 switch (Op.getOpcode()) {
5325 default: llvm_unreachable("Invalid opcode!");
5326 case ISD::SINT_TO_FP:
5327 CastOpc = ISD::SIGN_EXTEND;
5328 Opc = ISD::SINT_TO_FP;
5329 break;
5330 case ISD::UINT_TO_FP:
5331 CastOpc = ISD::ZERO_EXTEND;
5332 Opc = ISD::UINT_TO_FP;
5333 break;
5336 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5337 return DAG.getNode(Opc, dl, VT, Op);
5340 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5341 EVT VT = Op.getValueType();
5342 if (VT.isVector())
5343 return LowerVectorINT_TO_FP(Op, DAG);
5344 if (isUnsupportedFloatingType(VT)) {
5345 RTLIB::Libcall LC;
5346 if (Op.getOpcode() == ISD::SINT_TO_FP)
5347 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5348 Op.getValueType());
5349 else
5350 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5351 Op.getValueType());
5352 MakeLibCallOptions CallOptions;
5353 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5354 CallOptions, SDLoc(Op)).first;
5357 return Op;
5360 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5361 // Implement fcopysign with a fabs and a conditional fneg.
5362 SDValue Tmp0 = Op.getOperand(0);
5363 SDValue Tmp1 = Op.getOperand(1);
5364 SDLoc dl(Op);
5365 EVT VT = Op.getValueType();
5366 EVT SrcVT = Tmp1.getValueType();
5367 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5368 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5369 bool UseNEON = !InGPR && Subtarget->hasNEON();
5371 if (UseNEON) {
5372 // Use VBSL to copy the sign bit.
5373 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5374 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5375 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5376 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5377 if (VT == MVT::f64)
5378 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5379 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5380 DAG.getConstant(32, dl, MVT::i32));
5381 else /*if (VT == MVT::f32)*/
5382 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5383 if (SrcVT == MVT::f32) {
5384 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5385 if (VT == MVT::f64)
5386 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5387 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5388 DAG.getConstant(32, dl, MVT::i32));
5389 } else if (VT == MVT::f32)
5390 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5391 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5392 DAG.getConstant(32, dl, MVT::i32));
5393 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5394 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5396 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5397 dl, MVT::i32);
5398 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5399 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5400 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5402 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5403 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5404 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5405 if (VT == MVT::f32) {
5406 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5407 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5408 DAG.getConstant(0, dl, MVT::i32));
5409 } else {
5410 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5413 return Res;
5416 // Bitcast operand 1 to i32.
5417 if (SrcVT == MVT::f64)
5418 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5419 Tmp1).getValue(1);
5420 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5422 // Or in the signbit with integer operations.
5423 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5424 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5425 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5426 if (VT == MVT::f32) {
5427 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5428 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5429 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5430 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5433 // f64: Or the high part with signbit and then combine two parts.
5434 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5435 Tmp0);
5436 SDValue Lo = Tmp0.getValue(0);
5437 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5438 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5439 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5442 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5443 MachineFunction &MF = DAG.getMachineFunction();
5444 MachineFrameInfo &MFI = MF.getFrameInfo();
5445 MFI.setReturnAddressIsTaken(true);
5447 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5448 return SDValue();
5450 EVT VT = Op.getValueType();
5451 SDLoc dl(Op);
5452 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5453 if (Depth) {
5454 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5455 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5456 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5457 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5458 MachinePointerInfo());
5461 // Return LR, which contains the return address. Mark it an implicit live-in.
5462 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5463 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5466 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5467 const ARMBaseRegisterInfo &ARI =
5468 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5469 MachineFunction &MF = DAG.getMachineFunction();
5470 MachineFrameInfo &MFI = MF.getFrameInfo();
5471 MFI.setFrameAddressIsTaken(true);
5473 EVT VT = Op.getValueType();
5474 SDLoc dl(Op); // FIXME probably not meaningful
5475 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5476 Register FrameReg = ARI.getFrameRegister(MF);
5477 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5478 while (Depth--)
5479 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5480 MachinePointerInfo());
5481 return FrameAddr;
5484 // FIXME? Maybe this could be a TableGen attribute on some registers and
5485 // this table could be generated automatically from RegInfo.
5486 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5487 SelectionDAG &DAG) const {
5488 unsigned Reg = StringSwitch<unsigned>(RegName)
5489 .Case("sp", ARM::SP)
5490 .Default(0);
5491 if (Reg)
5492 return Reg;
5493 report_fatal_error(Twine("Invalid register name \""
5494 + StringRef(RegName) + "\"."));
5497 // Result is 64 bit value so split into two 32 bit values and return as a
5498 // pair of values.
5499 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5500 SelectionDAG &DAG) {
5501 SDLoc DL(N);
5503 // This function is only supposed to be called for i64 type destination.
5504 assert(N->getValueType(0) == MVT::i64
5505 && "ExpandREAD_REGISTER called for non-i64 type result.");
5507 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5508 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5509 N->getOperand(0),
5510 N->getOperand(1));
5512 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5513 Read.getValue(1)));
5514 Results.push_back(Read.getOperand(0));
5517 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5518 /// When \p DstVT, the destination type of \p BC, is on the vector
5519 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5520 /// it might be possible to combine them, such that everything stays on the
5521 /// vector register bank.
5522 /// \p return The node that would replace \p BT, if the combine
5523 /// is possible.
5524 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5525 SelectionDAG &DAG) {
5526 SDValue Op = BC->getOperand(0);
5527 EVT DstVT = BC->getValueType(0);
5529 // The only vector instruction that can produce a scalar (remember,
5530 // since the bitcast was about to be turned into VMOVDRR, the source
5531 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5532 // Moreover, we can do this combine only if there is one use.
5533 // Finally, if the destination type is not a vector, there is not
5534 // much point on forcing everything on the vector bank.
5535 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5536 !Op.hasOneUse())
5537 return SDValue();
5539 // If the index is not constant, we will introduce an additional
5540 // multiply that will stick.
5541 // Give up in that case.
5542 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5543 if (!Index)
5544 return SDValue();
5545 unsigned DstNumElt = DstVT.getVectorNumElements();
5547 // Compute the new index.
5548 const APInt &APIntIndex = Index->getAPIntValue();
5549 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5550 NewIndex *= APIntIndex;
5551 // Check if the new constant index fits into i32.
5552 if (NewIndex.getBitWidth() > 32)
5553 return SDValue();
5555 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5556 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5557 SDLoc dl(Op);
5558 SDValue ExtractSrc = Op.getOperand(0);
5559 EVT VecVT = EVT::getVectorVT(
5560 *DAG.getContext(), DstVT.getScalarType(),
5561 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5562 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5563 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5564 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5567 /// ExpandBITCAST - If the target supports VFP, this function is called to
5568 /// expand a bit convert where either the source or destination type is i64 to
5569 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5570 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5571 /// vectors), since the legalizer won't know what to do with that.
5572 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5573 const ARMSubtarget *Subtarget) {
5574 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5575 SDLoc dl(N);
5576 SDValue Op = N->getOperand(0);
5578 // This function is only supposed to be called for i64 types, either as the
5579 // source or destination of the bit convert.
5580 EVT SrcVT = Op.getValueType();
5581 EVT DstVT = N->getValueType(0);
5582 const bool HasFullFP16 = Subtarget->hasFullFP16();
5584 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5585 // FullFP16: half values are passed in S-registers, and we don't
5586 // need any of the bitcast and moves:
5588 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5589 // t5: i32 = bitcast t2
5590 // t18: f16 = ARMISD::VMOVhr t5
5591 if (Op.getOpcode() != ISD::CopyFromReg ||
5592 Op.getValueType() != MVT::f32)
5593 return SDValue();
5595 auto Move = N->use_begin();
5596 if (Move->getOpcode() != ARMISD::VMOVhr)
5597 return SDValue();
5599 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5600 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5601 DAG.ReplaceAllUsesWith(*Move, &Copy);
5602 return Copy;
5605 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5606 if (!HasFullFP16)
5607 return SDValue();
5608 // SoftFP: read half-precision arguments:
5610 // t2: i32,ch = ...
5611 // t7: i16 = truncate t2 <~~~~ Op
5612 // t8: f16 = bitcast t7 <~~~~ N
5614 if (Op.getOperand(0).getValueType() == MVT::i32)
5615 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5616 MVT::f16, Op.getOperand(0));
5618 return SDValue();
5621 // Half-precision return values
5622 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5623 if (!HasFullFP16)
5624 return SDValue();
5626 // t11: f16 = fadd t8, t10
5627 // t12: i16 = bitcast t11 <~~~ SDNode N
5628 // t13: i32 = zero_extend t12
5629 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5630 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5632 // transform this into:
5634 // t20: i32 = ARMISD::VMOVrh t11
5635 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5637 auto ZeroExtend = N->use_begin();
5638 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5639 ZeroExtend->getValueType(0) != MVT::i32)
5640 return SDValue();
5642 auto Copy = ZeroExtend->use_begin();
5643 if (Copy->getOpcode() == ISD::CopyToReg &&
5644 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5645 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5646 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5647 return Cvt;
5649 return SDValue();
5652 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5653 return SDValue();
5655 // Turn i64->f64 into VMOVDRR.
5656 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5657 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5658 // if we can combine the bitcast with its source.
5659 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5660 return Val;
5662 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5663 DAG.getConstant(0, dl, MVT::i32));
5664 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5665 DAG.getConstant(1, dl, MVT::i32));
5666 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5667 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5670 // Turn f64->i64 into VMOVRRD.
5671 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5672 SDValue Cvt;
5673 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5674 SrcVT.getVectorNumElements() > 1)
5675 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5676 DAG.getVTList(MVT::i32, MVT::i32),
5677 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5678 else
5679 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5680 DAG.getVTList(MVT::i32, MVT::i32), Op);
5681 // Merge the pieces into a single i64 value.
5682 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5685 return SDValue();
5688 /// getZeroVector - Returns a vector of specified type with all zero elements.
5689 /// Zero vectors are used to represent vector negation and in those cases
5690 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5691 /// not support i64 elements, so sometimes the zero vectors will need to be
5692 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5693 /// zero vector.
5694 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5695 assert(VT.isVector() && "Expected a vector type");
5696 // The canonical modified immediate encoding of a zero vector is....0!
5697 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5698 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5699 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5700 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5703 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5704 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5705 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5706 SelectionDAG &DAG) const {
5707 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5708 EVT VT = Op.getValueType();
5709 unsigned VTBits = VT.getSizeInBits();
5710 SDLoc dl(Op);
5711 SDValue ShOpLo = Op.getOperand(0);
5712 SDValue ShOpHi = Op.getOperand(1);
5713 SDValue ShAmt = Op.getOperand(2);
5714 SDValue ARMcc;
5715 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5716 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5718 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5720 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5721 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5722 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5723 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5724 DAG.getConstant(VTBits, dl, MVT::i32));
5725 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5726 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5727 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5728 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5729 ISD::SETGE, ARMcc, DAG, dl);
5730 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5731 ARMcc, CCR, CmpLo);
5733 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5734 SDValue HiBigShift = Opc == ISD::SRA
5735 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5736 DAG.getConstant(VTBits - 1, dl, VT))
5737 : DAG.getConstant(0, dl, VT);
5738 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5739 ISD::SETGE, ARMcc, DAG, dl);
5740 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5741 ARMcc, CCR, CmpHi);
5743 SDValue Ops[2] = { Lo, Hi };
5744 return DAG.getMergeValues(Ops, dl);
5747 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5748 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5749 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5750 SelectionDAG &DAG) const {
5751 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5752 EVT VT = Op.getValueType();
5753 unsigned VTBits = VT.getSizeInBits();
5754 SDLoc dl(Op);
5755 SDValue ShOpLo = Op.getOperand(0);
5756 SDValue ShOpHi = Op.getOperand(1);
5757 SDValue ShAmt = Op.getOperand(2);
5758 SDValue ARMcc;
5759 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5761 assert(Op.getOpcode() == ISD::SHL_PARTS);
5762 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5763 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5764 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5765 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5766 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5768 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5769 DAG.getConstant(VTBits, dl, MVT::i32));
5770 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5771 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5772 ISD::SETGE, ARMcc, DAG, dl);
5773 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5774 ARMcc, CCR, CmpHi);
5776 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5777 ISD::SETGE, ARMcc, DAG, dl);
5778 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5779 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5780 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5782 SDValue Ops[2] = { Lo, Hi };
5783 return DAG.getMergeValues(Ops, dl);
5786 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5787 SelectionDAG &DAG) const {
5788 // The rounding mode is in bits 23:22 of the FPSCR.
5789 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5790 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5791 // so that the shift + and get folded into a bitfield extract.
5792 SDLoc dl(Op);
5793 SDValue Ops[] = { DAG.getEntryNode(),
5794 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5796 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5797 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5798 DAG.getConstant(1U << 22, dl, MVT::i32));
5799 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5800 DAG.getConstant(22, dl, MVT::i32));
5801 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5802 DAG.getConstant(3, dl, MVT::i32));
5805 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5806 const ARMSubtarget *ST) {
5807 SDLoc dl(N);
5808 EVT VT = N->getValueType(0);
5809 if (VT.isVector() && ST->hasNEON()) {
5811 // Compute the least significant set bit: LSB = X & -X
5812 SDValue X = N->getOperand(0);
5813 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5814 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5816 EVT ElemTy = VT.getVectorElementType();
5818 if (ElemTy == MVT::i8) {
5819 // Compute with: cttz(x) = ctpop(lsb - 1)
5820 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5821 DAG.getTargetConstant(1, dl, ElemTy));
5822 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5823 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5826 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5827 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5828 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5829 unsigned NumBits = ElemTy.getSizeInBits();
5830 SDValue WidthMinus1 =
5831 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5832 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5833 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5834 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5837 // Compute with: cttz(x) = ctpop(lsb - 1)
5839 // Compute LSB - 1.
5840 SDValue Bits;
5841 if (ElemTy == MVT::i64) {
5842 // Load constant 0xffff'ffff'ffff'ffff to register.
5843 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5844 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5845 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5846 } else {
5847 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5848 DAG.getTargetConstant(1, dl, ElemTy));
5849 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5851 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5854 if (!ST->hasV6T2Ops())
5855 return SDValue();
5857 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5858 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5861 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5862 const ARMSubtarget *ST) {
5863 EVT VT = N->getValueType(0);
5864 SDLoc DL(N);
5866 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5867 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5868 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5869 "Unexpected type for custom ctpop lowering");
5871 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5872 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5873 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5874 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5876 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5877 unsigned EltSize = 8;
5878 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5879 while (EltSize != VT.getScalarSizeInBits()) {
5880 SmallVector<SDValue, 8> Ops;
5881 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5882 TLI.getPointerTy(DAG.getDataLayout())));
5883 Ops.push_back(Res);
5885 EltSize *= 2;
5886 NumElts /= 2;
5887 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5888 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5891 return Res;
5894 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5895 /// operand of a vector shift operation, where all the elements of the
5896 /// build_vector must have the same constant integer value.
5897 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5898 // Ignore bit_converts.
5899 while (Op.getOpcode() == ISD::BITCAST)
5900 Op = Op.getOperand(0);
5901 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5902 APInt SplatBits, SplatUndef;
5903 unsigned SplatBitSize;
5904 bool HasAnyUndefs;
5905 if (!BVN ||
5906 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5907 ElementBits) ||
5908 SplatBitSize > ElementBits)
5909 return false;
5910 Cnt = SplatBits.getSExtValue();
5911 return true;
5914 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5915 /// operand of a vector shift left operation. That value must be in the range:
5916 /// 0 <= Value < ElementBits for a left shift; or
5917 /// 0 <= Value <= ElementBits for a long left shift.
5918 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5919 assert(VT.isVector() && "vector shift count is not a vector type");
5920 int64_t ElementBits = VT.getScalarSizeInBits();
5921 if (!getVShiftImm(Op, ElementBits, Cnt))
5922 return false;
5923 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5926 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5927 /// operand of a vector shift right operation. For a shift opcode, the value
5928 /// is positive, but for an intrinsic the value count must be negative. The
5929 /// absolute value must be in the range:
5930 /// 1 <= |Value| <= ElementBits for a right shift; or
5931 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5932 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5933 int64_t &Cnt) {
5934 assert(VT.isVector() && "vector shift count is not a vector type");
5935 int64_t ElementBits = VT.getScalarSizeInBits();
5936 if (!getVShiftImm(Op, ElementBits, Cnt))
5937 return false;
5938 if (!isIntrinsic)
5939 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5940 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5941 Cnt = -Cnt;
5942 return true;
5944 return false;
5947 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5948 const ARMSubtarget *ST) {
5949 EVT VT = N->getValueType(0);
5950 SDLoc dl(N);
5951 int64_t Cnt;
5953 if (!VT.isVector())
5954 return SDValue();
5956 // We essentially have two forms here. Shift by an immediate and shift by a
5957 // vector register (there are also shift by a gpr, but that is just handled
5958 // with a tablegen pattern). We cannot easily match shift by an immediate in
5959 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5960 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5961 // signed or unsigned, and a negative shift indicates a shift right).
5962 if (N->getOpcode() == ISD::SHL) {
5963 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5964 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5965 DAG.getConstant(Cnt, dl, MVT::i32));
5966 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
5967 N->getOperand(1));
5970 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
5971 "unexpected vector shift opcode");
5973 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
5974 unsigned VShiftOpc =
5975 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
5976 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
5977 DAG.getConstant(Cnt, dl, MVT::i32));
5980 // Other right shifts we don't have operations for (we use a shift left by a
5981 // negative number).
5982 EVT ShiftVT = N->getOperand(1).getValueType();
5983 SDValue NegatedCount = DAG.getNode(
5984 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
5985 unsigned VShiftOpc =
5986 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
5987 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
5990 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5991 const ARMSubtarget *ST) {
5992 EVT VT = N->getValueType(0);
5993 SDLoc dl(N);
5995 // We can get here for a node like i32 = ISD::SHL i32, i64
5996 if (VT != MVT::i64)
5997 return SDValue();
5999 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6000 N->getOpcode() == ISD::SHL) &&
6001 "Unknown shift to lower!");
6003 unsigned ShOpc = N->getOpcode();
6004 if (ST->hasMVEIntegerOps()) {
6005 SDValue ShAmt = N->getOperand(1);
6006 unsigned ShPartsOpc = ARMISD::LSLL;
6007 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6009 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6010 // then do the default optimisation
6011 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6012 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6013 return SDValue();
6015 // Extract the lower 32 bits of the shift amount if it's not an i32
6016 if (ShAmt->getValueType(0) != MVT::i32)
6017 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6019 if (ShOpc == ISD::SRL) {
6020 if (!Con)
6021 // There is no t2LSRLr instruction so negate and perform an lsll if the
6022 // shift amount is in a register, emulating a right shift.
6023 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6024 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6025 else
6026 // Else generate an lsrl on the immediate shift amount
6027 ShPartsOpc = ARMISD::LSRL;
6028 } else if (ShOpc == ISD::SRA)
6029 ShPartsOpc = ARMISD::ASRL;
6031 // Lower 32 bits of the destination/source
6032 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6033 DAG.getConstant(0, dl, MVT::i32));
6034 // Upper 32 bits of the destination/source
6035 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6036 DAG.getConstant(1, dl, MVT::i32));
6038 // Generate the shift operation as computed above
6039 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6040 ShAmt);
6041 // The upper 32 bits come from the second return value of lsll
6042 Hi = SDValue(Lo.getNode(), 1);
6043 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6046 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6047 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6048 return SDValue();
6050 // If we are in thumb mode, we don't have RRX.
6051 if (ST->isThumb1Only())
6052 return SDValue();
6054 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6055 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6056 DAG.getConstant(0, dl, MVT::i32));
6057 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6058 DAG.getConstant(1, dl, MVT::i32));
6060 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6061 // captures the result into a carry flag.
6062 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6063 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6065 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6066 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6068 // Merge the pieces into a single i64 value.
6069 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6072 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6073 const ARMSubtarget *ST) {
6074 bool Invert = false;
6075 bool Swap = false;
6076 unsigned Opc = ARMCC::AL;
6078 SDValue Op0 = Op.getOperand(0);
6079 SDValue Op1 = Op.getOperand(1);
6080 SDValue CC = Op.getOperand(2);
6081 EVT VT = Op.getValueType();
6082 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6083 SDLoc dl(Op);
6085 EVT CmpVT;
6086 if (ST->hasNEON())
6087 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6088 else {
6089 assert(ST->hasMVEIntegerOps() &&
6090 "No hardware support for integer vector comparison!");
6092 if (Op.getValueType().getVectorElementType() != MVT::i1)
6093 return SDValue();
6095 // Make sure we expand floating point setcc to scalar if we do not have
6096 // mve.fp, so that we can handle them from there.
6097 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6098 return SDValue();
6100 CmpVT = VT;
6103 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6104 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6105 // Special-case integer 64-bit equality comparisons. They aren't legal,
6106 // but they can be lowered with a few vector instructions.
6107 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6108 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6109 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6110 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6111 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6112 DAG.getCondCode(ISD::SETEQ));
6113 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6114 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6115 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6116 if (SetCCOpcode == ISD::SETNE)
6117 Merged = DAG.getNOT(dl, Merged, CmpVT);
6118 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6119 return Merged;
6122 if (CmpVT.getVectorElementType() == MVT::i64)
6123 // 64-bit comparisons are not legal in general.
6124 return SDValue();
6126 if (Op1.getValueType().isFloatingPoint()) {
6127 switch (SetCCOpcode) {
6128 default: llvm_unreachable("Illegal FP comparison");
6129 case ISD::SETUNE:
6130 case ISD::SETNE:
6131 if (ST->hasMVEFloatOps()) {
6132 Opc = ARMCC::NE; break;
6133 } else {
6134 Invert = true; LLVM_FALLTHROUGH;
6136 case ISD::SETOEQ:
6137 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6138 case ISD::SETOLT:
6139 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6140 case ISD::SETOGT:
6141 case ISD::SETGT: Opc = ARMCC::GT; break;
6142 case ISD::SETOLE:
6143 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6144 case ISD::SETOGE:
6145 case ISD::SETGE: Opc = ARMCC::GE; break;
6146 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6147 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6148 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6149 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6150 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6151 case ISD::SETONE: {
6152 // Expand this to (OLT | OGT).
6153 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6154 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6155 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6156 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6157 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6158 if (Invert)
6159 Result = DAG.getNOT(dl, Result, VT);
6160 return Result;
6162 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6163 case ISD::SETO: {
6164 // Expand this to (OLT | OGE).
6165 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6166 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6167 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6168 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6169 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6170 if (Invert)
6171 Result = DAG.getNOT(dl, Result, VT);
6172 return Result;
6175 } else {
6176 // Integer comparisons.
6177 switch (SetCCOpcode) {
6178 default: llvm_unreachable("Illegal integer comparison");
6179 case ISD::SETNE:
6180 if (ST->hasMVEIntegerOps()) {
6181 Opc = ARMCC::NE; break;
6182 } else {
6183 Invert = true; LLVM_FALLTHROUGH;
6185 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6186 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6187 case ISD::SETGT: Opc = ARMCC::GT; break;
6188 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6189 case ISD::SETGE: Opc = ARMCC::GE; break;
6190 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6191 case ISD::SETUGT: Opc = ARMCC::HI; break;
6192 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6193 case ISD::SETUGE: Opc = ARMCC::HS; break;
6196 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6197 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6198 SDValue AndOp;
6199 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6200 AndOp = Op0;
6201 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6202 AndOp = Op1;
6204 // Ignore bitconvert.
6205 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6206 AndOp = AndOp.getOperand(0);
6208 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6209 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6210 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6211 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6212 if (!Invert)
6213 Result = DAG.getNOT(dl, Result, VT);
6214 return Result;
6219 if (Swap)
6220 std::swap(Op0, Op1);
6222 // If one of the operands is a constant vector zero, attempt to fold the
6223 // comparison to a specialized compare-against-zero form.
6224 SDValue SingleOp;
6225 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6226 SingleOp = Op0;
6227 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6228 if (Opc == ARMCC::GE)
6229 Opc = ARMCC::LE;
6230 else if (Opc == ARMCC::GT)
6231 Opc = ARMCC::LT;
6232 SingleOp = Op1;
6235 SDValue Result;
6236 if (SingleOp.getNode()) {
6237 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6238 DAG.getConstant(Opc, dl, MVT::i32));
6239 } else {
6240 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6241 DAG.getConstant(Opc, dl, MVT::i32));
6244 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6246 if (Invert)
6247 Result = DAG.getNOT(dl, Result, VT);
6249 return Result;
6252 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6253 SDValue LHS = Op.getOperand(0);
6254 SDValue RHS = Op.getOperand(1);
6255 SDValue Carry = Op.getOperand(2);
6256 SDValue Cond = Op.getOperand(3);
6257 SDLoc DL(Op);
6259 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6261 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6262 // have to invert the carry first.
6263 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6264 DAG.getConstant(1, DL, MVT::i32), Carry);
6265 // This converts the boolean value carry into the carry flag.
6266 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6268 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6269 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6271 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6272 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6273 SDValue ARMcc = DAG.getConstant(
6274 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6275 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6276 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6277 Cmp.getValue(1), SDValue());
6278 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6279 CCR, Chain.getValue(1));
6282 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6283 /// valid vector constant for a NEON or MVE instruction with a "modified
6284 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6285 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6286 unsigned SplatBitSize, SelectionDAG &DAG,
6287 const SDLoc &dl, EVT &VT, bool is128Bits,
6288 VMOVModImmType type) {
6289 unsigned OpCmode, Imm;
6291 // SplatBitSize is set to the smallest size that splats the vector, so a
6292 // zero vector will always have SplatBitSize == 8. However, NEON modified
6293 // immediate instructions others than VMOV do not support the 8-bit encoding
6294 // of a zero vector, and the default encoding of zero is supposed to be the
6295 // 32-bit version.
6296 if (SplatBits == 0)
6297 SplatBitSize = 32;
6299 switch (SplatBitSize) {
6300 case 8:
6301 if (type != VMOVModImm)
6302 return SDValue();
6303 // Any 1-byte value is OK. Op=0, Cmode=1110.
6304 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6305 OpCmode = 0xe;
6306 Imm = SplatBits;
6307 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6308 break;
6310 case 16:
6311 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6312 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6313 if ((SplatBits & ~0xff) == 0) {
6314 // Value = 0x00nn: Op=x, Cmode=100x.
6315 OpCmode = 0x8;
6316 Imm = SplatBits;
6317 break;
6319 if ((SplatBits & ~0xff00) == 0) {
6320 // Value = 0xnn00: Op=x, Cmode=101x.
6321 OpCmode = 0xa;
6322 Imm = SplatBits >> 8;
6323 break;
6325 return SDValue();
6327 case 32:
6328 // NEON's 32-bit VMOV supports splat values where:
6329 // * only one byte is nonzero, or
6330 // * the least significant byte is 0xff and the second byte is nonzero, or
6331 // * the least significant 2 bytes are 0xff and the third is nonzero.
6332 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6333 if ((SplatBits & ~0xff) == 0) {
6334 // Value = 0x000000nn: Op=x, Cmode=000x.
6335 OpCmode = 0;
6336 Imm = SplatBits;
6337 break;
6339 if ((SplatBits & ~0xff00) == 0) {
6340 // Value = 0x0000nn00: Op=x, Cmode=001x.
6341 OpCmode = 0x2;
6342 Imm = SplatBits >> 8;
6343 break;
6345 if ((SplatBits & ~0xff0000) == 0) {
6346 // Value = 0x00nn0000: Op=x, Cmode=010x.
6347 OpCmode = 0x4;
6348 Imm = SplatBits >> 16;
6349 break;
6351 if ((SplatBits & ~0xff000000) == 0) {
6352 // Value = 0xnn000000: Op=x, Cmode=011x.
6353 OpCmode = 0x6;
6354 Imm = SplatBits >> 24;
6355 break;
6358 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6359 if (type == OtherModImm) return SDValue();
6361 if ((SplatBits & ~0xffff) == 0 &&
6362 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6363 // Value = 0x0000nnff: Op=x, Cmode=1100.
6364 OpCmode = 0xc;
6365 Imm = SplatBits >> 8;
6366 break;
6369 // cmode == 0b1101 is not supported for MVE VMVN
6370 if (type == MVEVMVNModImm)
6371 return SDValue();
6373 if ((SplatBits & ~0xffffff) == 0 &&
6374 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6375 // Value = 0x00nnffff: Op=x, Cmode=1101.
6376 OpCmode = 0xd;
6377 Imm = SplatBits >> 16;
6378 break;
6381 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6382 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6383 // VMOV.I32. A (very) minor optimization would be to replicate the value
6384 // and fall through here to test for a valid 64-bit splat. But, then the
6385 // caller would also need to check and handle the change in size.
6386 return SDValue();
6388 case 64: {
6389 if (type != VMOVModImm)
6390 return SDValue();
6391 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6392 uint64_t BitMask = 0xff;
6393 uint64_t Val = 0;
6394 unsigned ImmMask = 1;
6395 Imm = 0;
6396 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6397 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6398 Val |= BitMask;
6399 Imm |= ImmMask;
6400 } else if ((SplatBits & BitMask) != 0) {
6401 return SDValue();
6403 BitMask <<= 8;
6404 ImmMask <<= 1;
6407 if (DAG.getDataLayout().isBigEndian())
6408 // swap higher and lower 32 bit word
6409 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6411 // Op=1, Cmode=1110.
6412 OpCmode = 0x1e;
6413 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6414 break;
6417 default:
6418 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6421 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6422 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6425 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6426 const ARMSubtarget *ST) const {
6427 EVT VT = Op.getValueType();
6428 bool IsDouble = (VT == MVT::f64);
6429 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6430 const APFloat &FPVal = CFP->getValueAPF();
6432 // Prevent floating-point constants from using literal loads
6433 // when execute-only is enabled.
6434 if (ST->genExecuteOnly()) {
6435 // If we can represent the constant as an immediate, don't lower it
6436 if (isFPImmLegal(FPVal, VT))
6437 return Op;
6438 // Otherwise, construct as integer, and move to float register
6439 APInt INTVal = FPVal.bitcastToAPInt();
6440 SDLoc DL(CFP);
6441 switch (VT.getSimpleVT().SimpleTy) {
6442 default:
6443 llvm_unreachable("Unknown floating point type!");
6444 break;
6445 case MVT::f64: {
6446 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6447 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6448 if (!ST->isLittle())
6449 std::swap(Lo, Hi);
6450 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6452 case MVT::f32:
6453 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6454 DAG.getConstant(INTVal, DL, MVT::i32));
6458 if (!ST->hasVFP3Base())
6459 return SDValue();
6461 // Use the default (constant pool) lowering for double constants when we have
6462 // an SP-only FPU
6463 if (IsDouble && !Subtarget->hasFP64())
6464 return SDValue();
6466 // Try splatting with a VMOV.f32...
6467 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6469 if (ImmVal != -1) {
6470 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6471 // We have code in place to select a valid ConstantFP already, no need to
6472 // do any mangling.
6473 return Op;
6476 // It's a float and we are trying to use NEON operations where
6477 // possible. Lower it to a splat followed by an extract.
6478 SDLoc DL(Op);
6479 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6480 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6481 NewVal);
6482 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6483 DAG.getConstant(0, DL, MVT::i32));
6486 // The rest of our options are NEON only, make sure that's allowed before
6487 // proceeding..
6488 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6489 return SDValue();
6491 EVT VMovVT;
6492 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6494 // It wouldn't really be worth bothering for doubles except for one very
6495 // important value, which does happen to match: 0.0. So make sure we don't do
6496 // anything stupid.
6497 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6498 return SDValue();
6500 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6501 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6502 VMovVT, false, VMOVModImm);
6503 if (NewVal != SDValue()) {
6504 SDLoc DL(Op);
6505 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6506 NewVal);
6507 if (IsDouble)
6508 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6510 // It's a float: cast and extract a vector element.
6511 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6512 VecConstant);
6513 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6514 DAG.getConstant(0, DL, MVT::i32));
6517 // Finally, try a VMVN.i32
6518 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6519 false, VMVNModImm);
6520 if (NewVal != SDValue()) {
6521 SDLoc DL(Op);
6522 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6524 if (IsDouble)
6525 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6527 // It's a float: cast and extract a vector element.
6528 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6529 VecConstant);
6530 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6531 DAG.getConstant(0, DL, MVT::i32));
6534 return SDValue();
6537 // check if an VEXT instruction can handle the shuffle mask when the
6538 // vector sources of the shuffle are the same.
6539 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6540 unsigned NumElts = VT.getVectorNumElements();
6542 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6543 if (M[0] < 0)
6544 return false;
6546 Imm = M[0];
6548 // If this is a VEXT shuffle, the immediate value is the index of the first
6549 // element. The other shuffle indices must be the successive elements after
6550 // the first one.
6551 unsigned ExpectedElt = Imm;
6552 for (unsigned i = 1; i < NumElts; ++i) {
6553 // Increment the expected index. If it wraps around, just follow it
6554 // back to index zero and keep going.
6555 ++ExpectedElt;
6556 if (ExpectedElt == NumElts)
6557 ExpectedElt = 0;
6559 if (M[i] < 0) continue; // ignore UNDEF indices
6560 if (ExpectedElt != static_cast<unsigned>(M[i]))
6561 return false;
6564 return true;
6567 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6568 bool &ReverseVEXT, unsigned &Imm) {
6569 unsigned NumElts = VT.getVectorNumElements();
6570 ReverseVEXT = false;
6572 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6573 if (M[0] < 0)
6574 return false;
6576 Imm = M[0];
6578 // If this is a VEXT shuffle, the immediate value is the index of the first
6579 // element. The other shuffle indices must be the successive elements after
6580 // the first one.
6581 unsigned ExpectedElt = Imm;
6582 for (unsigned i = 1; i < NumElts; ++i) {
6583 // Increment the expected index. If it wraps around, it may still be
6584 // a VEXT but the source vectors must be swapped.
6585 ExpectedElt += 1;
6586 if (ExpectedElt == NumElts * 2) {
6587 ExpectedElt = 0;
6588 ReverseVEXT = true;
6591 if (M[i] < 0) continue; // ignore UNDEF indices
6592 if (ExpectedElt != static_cast<unsigned>(M[i]))
6593 return false;
6596 // Adjust the index value if the source operands will be swapped.
6597 if (ReverseVEXT)
6598 Imm -= NumElts;
6600 return true;
6603 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6604 /// instruction with the specified blocksize. (The order of the elements
6605 /// within each block of the vector is reversed.)
6606 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6607 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6608 "Only possible block sizes for VREV are: 16, 32, 64");
6610 unsigned EltSz = VT.getScalarSizeInBits();
6611 if (EltSz == 64)
6612 return false;
6614 unsigned NumElts = VT.getVectorNumElements();
6615 unsigned BlockElts = M[0] + 1;
6616 // If the first shuffle index is UNDEF, be optimistic.
6617 if (M[0] < 0)
6618 BlockElts = BlockSize / EltSz;
6620 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6621 return false;
6623 for (unsigned i = 0; i < NumElts; ++i) {
6624 if (M[i] < 0) continue; // ignore UNDEF indices
6625 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6626 return false;
6629 return true;
6632 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6633 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6634 // range, then 0 is placed into the resulting vector. So pretty much any mask
6635 // of 8 elements can work here.
6636 return VT == MVT::v8i8 && M.size() == 8;
6639 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6640 unsigned Index) {
6641 if (Mask.size() == Elements * 2)
6642 return Index / Elements;
6643 return Mask[Index] == 0 ? 0 : 1;
6646 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6647 // checking that pairs of elements in the shuffle mask represent the same index
6648 // in each vector, incrementing the expected index by 2 at each step.
6649 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6650 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6651 // v2={e,f,g,h}
6652 // WhichResult gives the offset for each element in the mask based on which
6653 // of the two results it belongs to.
6655 // The transpose can be represented either as:
6656 // result1 = shufflevector v1, v2, result1_shuffle_mask
6657 // result2 = shufflevector v1, v2, result2_shuffle_mask
6658 // where v1/v2 and the shuffle masks have the same number of elements
6659 // (here WhichResult (see below) indicates which result is being checked)
6661 // or as:
6662 // results = shufflevector v1, v2, shuffle_mask
6663 // where both results are returned in one vector and the shuffle mask has twice
6664 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6665 // want to check the low half and high half of the shuffle mask as if it were
6666 // the other case
6667 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6668 unsigned EltSz = VT.getScalarSizeInBits();
6669 if (EltSz == 64)
6670 return false;
6672 unsigned NumElts = VT.getVectorNumElements();
6673 if (M.size() != NumElts && M.size() != NumElts*2)
6674 return false;
6676 // If the mask is twice as long as the input vector then we need to check the
6677 // upper and lower parts of the mask with a matching value for WhichResult
6678 // FIXME: A mask with only even values will be rejected in case the first
6679 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6680 // M[0] is used to determine WhichResult
6681 for (unsigned i = 0; i < M.size(); i += NumElts) {
6682 WhichResult = SelectPairHalf(NumElts, M, i);
6683 for (unsigned j = 0; j < NumElts; j += 2) {
6684 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6685 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6686 return false;
6690 if (M.size() == NumElts*2)
6691 WhichResult = 0;
6693 return true;
6696 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6697 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6698 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6699 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6700 unsigned EltSz = VT.getScalarSizeInBits();
6701 if (EltSz == 64)
6702 return false;
6704 unsigned NumElts = VT.getVectorNumElements();
6705 if (M.size() != NumElts && M.size() != NumElts*2)
6706 return false;
6708 for (unsigned i = 0; i < M.size(); i += NumElts) {
6709 WhichResult = SelectPairHalf(NumElts, M, i);
6710 for (unsigned j = 0; j < NumElts; j += 2) {
6711 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6712 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6713 return false;
6717 if (M.size() == NumElts*2)
6718 WhichResult = 0;
6720 return true;
6723 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6724 // that the mask elements are either all even and in steps of size 2 or all odd
6725 // and in steps of size 2.
6726 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6727 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6728 // v2={e,f,g,h}
6729 // Requires similar checks to that of isVTRNMask with
6730 // respect the how results are returned.
6731 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6732 unsigned EltSz = VT.getScalarSizeInBits();
6733 if (EltSz == 64)
6734 return false;
6736 unsigned NumElts = VT.getVectorNumElements();
6737 if (M.size() != NumElts && M.size() != NumElts*2)
6738 return false;
6740 for (unsigned i = 0; i < M.size(); i += NumElts) {
6741 WhichResult = SelectPairHalf(NumElts, M, i);
6742 for (unsigned j = 0; j < NumElts; ++j) {
6743 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6744 return false;
6748 if (M.size() == NumElts*2)
6749 WhichResult = 0;
6751 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6752 if (VT.is64BitVector() && EltSz == 32)
6753 return false;
6755 return true;
6758 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6759 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6760 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6761 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6762 unsigned EltSz = VT.getScalarSizeInBits();
6763 if (EltSz == 64)
6764 return false;
6766 unsigned NumElts = VT.getVectorNumElements();
6767 if (M.size() != NumElts && M.size() != NumElts*2)
6768 return false;
6770 unsigned Half = NumElts / 2;
6771 for (unsigned i = 0; i < M.size(); i += NumElts) {
6772 WhichResult = SelectPairHalf(NumElts, M, i);
6773 for (unsigned j = 0; j < NumElts; j += Half) {
6774 unsigned Idx = WhichResult;
6775 for (unsigned k = 0; k < Half; ++k) {
6776 int MIdx = M[i + j + k];
6777 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6778 return false;
6779 Idx += 2;
6784 if (M.size() == NumElts*2)
6785 WhichResult = 0;
6787 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6788 if (VT.is64BitVector() && EltSz == 32)
6789 return false;
6791 return true;
6794 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6795 // that pairs of elements of the shufflemask represent the same index in each
6796 // vector incrementing sequentially through the vectors.
6797 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6798 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6799 // v2={e,f,g,h}
6800 // Requires similar checks to that of isVTRNMask with respect the how results
6801 // are returned.
6802 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6803 unsigned EltSz = VT.getScalarSizeInBits();
6804 if (EltSz == 64)
6805 return false;
6807 unsigned NumElts = VT.getVectorNumElements();
6808 if (M.size() != NumElts && M.size() != NumElts*2)
6809 return false;
6811 for (unsigned i = 0; i < M.size(); i += NumElts) {
6812 WhichResult = SelectPairHalf(NumElts, M, i);
6813 unsigned Idx = WhichResult * NumElts / 2;
6814 for (unsigned j = 0; j < NumElts; j += 2) {
6815 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6816 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6817 return false;
6818 Idx += 1;
6822 if (M.size() == NumElts*2)
6823 WhichResult = 0;
6825 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6826 if (VT.is64BitVector() && EltSz == 32)
6827 return false;
6829 return true;
6832 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6833 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6834 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6835 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6836 unsigned EltSz = VT.getScalarSizeInBits();
6837 if (EltSz == 64)
6838 return false;
6840 unsigned NumElts = VT.getVectorNumElements();
6841 if (M.size() != NumElts && M.size() != NumElts*2)
6842 return false;
6844 for (unsigned i = 0; i < M.size(); i += NumElts) {
6845 WhichResult = SelectPairHalf(NumElts, M, i);
6846 unsigned Idx = WhichResult * NumElts / 2;
6847 for (unsigned j = 0; j < NumElts; j += 2) {
6848 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6849 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6850 return false;
6851 Idx += 1;
6855 if (M.size() == NumElts*2)
6856 WhichResult = 0;
6858 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6859 if (VT.is64BitVector() && EltSz == 32)
6860 return false;
6862 return true;
6865 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6866 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6867 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6868 unsigned &WhichResult,
6869 bool &isV_UNDEF) {
6870 isV_UNDEF = false;
6871 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6872 return ARMISD::VTRN;
6873 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6874 return ARMISD::VUZP;
6875 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6876 return ARMISD::VZIP;
6878 isV_UNDEF = true;
6879 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6880 return ARMISD::VTRN;
6881 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6882 return ARMISD::VUZP;
6883 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6884 return ARMISD::VZIP;
6886 return 0;
6889 /// \return true if this is a reverse operation on an vector.
6890 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6891 unsigned NumElts = VT.getVectorNumElements();
6892 // Make sure the mask has the right size.
6893 if (NumElts != M.size())
6894 return false;
6896 // Look for <15, ..., 3, -1, 1, 0>.
6897 for (unsigned i = 0; i != NumElts; ++i)
6898 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6899 return false;
6901 return true;
6904 // If N is an integer constant that can be moved into a register in one
6905 // instruction, return an SDValue of such a constant (will become a MOV
6906 // instruction). Otherwise return null.
6907 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6908 const ARMSubtarget *ST, const SDLoc &dl) {
6909 uint64_t Val;
6910 if (!isa<ConstantSDNode>(N))
6911 return SDValue();
6912 Val = cast<ConstantSDNode>(N)->getZExtValue();
6914 if (ST->isThumb1Only()) {
6915 if (Val <= 255 || ~Val <= 255)
6916 return DAG.getConstant(Val, dl, MVT::i32);
6917 } else {
6918 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6919 return DAG.getConstant(Val, dl, MVT::i32);
6921 return SDValue();
6924 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6925 const ARMSubtarget *ST) {
6926 SDLoc dl(Op);
6927 EVT VT = Op.getValueType();
6929 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6931 unsigned NumElts = VT.getVectorNumElements();
6932 unsigned BoolMask;
6933 unsigned BitsPerBool;
6934 if (NumElts == 4) {
6935 BitsPerBool = 4;
6936 BoolMask = 0xf;
6937 } else if (NumElts == 8) {
6938 BitsPerBool = 2;
6939 BoolMask = 0x3;
6940 } else if (NumElts == 16) {
6941 BitsPerBool = 1;
6942 BoolMask = 0x1;
6943 } else
6944 return SDValue();
6946 // If this is a single value copied into all lanes (a splat), we can just sign
6947 // extend that single value
6948 SDValue FirstOp = Op.getOperand(0);
6949 if (!isa<ConstantSDNode>(FirstOp) &&
6950 std::all_of(std::next(Op->op_begin()), Op->op_end(),
6951 [&FirstOp](SDUse &U) {
6952 return U.get().isUndef() || U.get() == FirstOp;
6953 })) {
6954 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
6955 DAG.getValueType(MVT::i1));
6956 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
6959 // First create base with bits set where known
6960 unsigned Bits32 = 0;
6961 for (unsigned i = 0; i < NumElts; ++i) {
6962 SDValue V = Op.getOperand(i);
6963 if (!isa<ConstantSDNode>(V) && !V.isUndef())
6964 continue;
6965 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
6966 if (BitSet)
6967 Bits32 |= BoolMask << (i * BitsPerBool);
6970 // Add in unknown nodes
6971 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
6972 DAG.getConstant(Bits32, dl, MVT::i32));
6973 for (unsigned i = 0; i < NumElts; ++i) {
6974 SDValue V = Op.getOperand(i);
6975 if (isa<ConstantSDNode>(V) || V.isUndef())
6976 continue;
6977 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
6978 DAG.getConstant(i, dl, MVT::i32));
6981 return Base;
6984 // If this is a case we can't handle, return null and let the default
6985 // expansion code take care of it.
6986 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6987 const ARMSubtarget *ST) const {
6988 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6989 SDLoc dl(Op);
6990 EVT VT = Op.getValueType();
6992 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
6993 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
6995 APInt SplatBits, SplatUndef;
6996 unsigned SplatBitSize;
6997 bool HasAnyUndefs;
6998 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6999 if (SplatUndef.isAllOnesValue())
7000 return DAG.getUNDEF(VT);
7002 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7003 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
7004 // Check if an immediate VMOV works.
7005 EVT VmovVT;
7006 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
7007 SplatUndef.getZExtValue(), SplatBitSize,
7008 DAG, dl, VmovVT, VT.is128BitVector(),
7009 VMOVModImm);
7011 if (Val.getNode()) {
7012 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7013 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7016 // Try an immediate VMVN.
7017 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7018 Val = isVMOVModifiedImm(
7019 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
7020 DAG, dl, VmovVT, VT.is128BitVector(),
7021 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7022 if (Val.getNode()) {
7023 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7024 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7027 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7028 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7029 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7030 if (ImmVal != -1) {
7031 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7032 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7038 // Scan through the operands to see if only one value is used.
7040 // As an optimisation, even if more than one value is used it may be more
7041 // profitable to splat with one value then change some lanes.
7043 // Heuristically we decide to do this if the vector has a "dominant" value,
7044 // defined as splatted to more than half of the lanes.
7045 unsigned NumElts = VT.getVectorNumElements();
7046 bool isOnlyLowElement = true;
7047 bool usesOnlyOneValue = true;
7048 bool hasDominantValue = false;
7049 bool isConstant = true;
7051 // Map of the number of times a particular SDValue appears in the
7052 // element list.
7053 DenseMap<SDValue, unsigned> ValueCounts;
7054 SDValue Value;
7055 for (unsigned i = 0; i < NumElts; ++i) {
7056 SDValue V = Op.getOperand(i);
7057 if (V.isUndef())
7058 continue;
7059 if (i > 0)
7060 isOnlyLowElement = false;
7061 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7062 isConstant = false;
7064 ValueCounts.insert(std::make_pair(V, 0));
7065 unsigned &Count = ValueCounts[V];
7067 // Is this value dominant? (takes up more than half of the lanes)
7068 if (++Count > (NumElts / 2)) {
7069 hasDominantValue = true;
7070 Value = V;
7073 if (ValueCounts.size() != 1)
7074 usesOnlyOneValue = false;
7075 if (!Value.getNode() && !ValueCounts.empty())
7076 Value = ValueCounts.begin()->first;
7078 if (ValueCounts.empty())
7079 return DAG.getUNDEF(VT);
7081 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7082 // Keep going if we are hitting this case.
7083 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7084 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7086 unsigned EltSize = VT.getScalarSizeInBits();
7088 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7089 // i32 and try again.
7090 if (hasDominantValue && EltSize <= 32) {
7091 if (!isConstant) {
7092 SDValue N;
7094 // If we are VDUPing a value that comes directly from a vector, that will
7095 // cause an unnecessary move to and from a GPR, where instead we could
7096 // just use VDUPLANE. We can only do this if the lane being extracted
7097 // is at a constant index, as the VDUP from lane instructions only have
7098 // constant-index forms.
7099 ConstantSDNode *constIndex;
7100 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7101 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7102 // We need to create a new undef vector to use for the VDUPLANE if the
7103 // size of the vector from which we get the value is different than the
7104 // size of the vector that we need to create. We will insert the element
7105 // such that the register coalescer will remove unnecessary copies.
7106 if (VT != Value->getOperand(0).getValueType()) {
7107 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7108 VT.getVectorNumElements();
7109 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7110 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7111 Value, DAG.getConstant(index, dl, MVT::i32)),
7112 DAG.getConstant(index, dl, MVT::i32));
7113 } else
7114 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7115 Value->getOperand(0), Value->getOperand(1));
7116 } else
7117 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7119 if (!usesOnlyOneValue) {
7120 // The dominant value was splatted as 'N', but we now have to insert
7121 // all differing elements.
7122 for (unsigned I = 0; I < NumElts; ++I) {
7123 if (Op.getOperand(I) == Value)
7124 continue;
7125 SmallVector<SDValue, 3> Ops;
7126 Ops.push_back(N);
7127 Ops.push_back(Op.getOperand(I));
7128 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7129 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7132 return N;
7134 if (VT.getVectorElementType().isFloatingPoint()) {
7135 SmallVector<SDValue, 8> Ops;
7136 MVT FVT = VT.getVectorElementType().getSimpleVT();
7137 assert(FVT == MVT::f32 || FVT == MVT::f16);
7138 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7139 for (unsigned i = 0; i < NumElts; ++i)
7140 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7141 Op.getOperand(i)));
7142 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7143 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7144 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7145 if (Val.getNode())
7146 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7148 if (usesOnlyOneValue) {
7149 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7150 if (isConstant && Val.getNode())
7151 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7155 // If all elements are constants and the case above didn't get hit, fall back
7156 // to the default expansion, which will generate a load from the constant
7157 // pool.
7158 if (isConstant)
7159 return SDValue();
7161 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7162 if (NumElts >= 4) {
7163 SDValue shuffle = ReconstructShuffle(Op, DAG);
7164 if (shuffle != SDValue())
7165 return shuffle;
7168 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7169 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7170 // into two 64-bit vectors; we might discover a better way to lower it.
7171 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7172 EVT ExtVT = VT.getVectorElementType();
7173 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7174 SDValue Lower =
7175 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7176 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7177 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7178 SDValue Upper = DAG.getBuildVector(
7179 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7180 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7181 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7182 if (Lower && Upper)
7183 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7186 // Vectors with 32- or 64-bit elements can be built by directly assigning
7187 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7188 // will be legalized.
7189 if (EltSize >= 32) {
7190 // Do the expansion with floating-point types, since that is what the VFP
7191 // registers are defined to use, and since i64 is not legal.
7192 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7193 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7194 SmallVector<SDValue, 8> Ops;
7195 for (unsigned i = 0; i < NumElts; ++i)
7196 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7197 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7198 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7201 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7202 // know the default expansion would otherwise fall back on something even
7203 // worse. For a vector with one or two non-undef values, that's
7204 // scalar_to_vector for the elements followed by a shuffle (provided the
7205 // shuffle is valid for the target) and materialization element by element
7206 // on the stack followed by a load for everything else.
7207 if (!isConstant && !usesOnlyOneValue) {
7208 SDValue Vec = DAG.getUNDEF(VT);
7209 for (unsigned i = 0 ; i < NumElts; ++i) {
7210 SDValue V = Op.getOperand(i);
7211 if (V.isUndef())
7212 continue;
7213 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7214 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7216 return Vec;
7219 return SDValue();
7222 // Gather data to see if the operation can be modelled as a
7223 // shuffle in combination with VEXTs.
7224 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7225 SelectionDAG &DAG) const {
7226 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7227 SDLoc dl(Op);
7228 EVT VT = Op.getValueType();
7229 unsigned NumElts = VT.getVectorNumElements();
7231 struct ShuffleSourceInfo {
7232 SDValue Vec;
7233 unsigned MinElt = std::numeric_limits<unsigned>::max();
7234 unsigned MaxElt = 0;
7236 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7237 // be compatible with the shuffle we intend to construct. As a result
7238 // ShuffleVec will be some sliding window into the original Vec.
7239 SDValue ShuffleVec;
7241 // Code should guarantee that element i in Vec starts at element "WindowBase
7242 // + i * WindowScale in ShuffleVec".
7243 int WindowBase = 0;
7244 int WindowScale = 1;
7246 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7248 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7251 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7252 // node.
7253 SmallVector<ShuffleSourceInfo, 2> Sources;
7254 for (unsigned i = 0; i < NumElts; ++i) {
7255 SDValue V = Op.getOperand(i);
7256 if (V.isUndef())
7257 continue;
7258 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7259 // A shuffle can only come from building a vector from various
7260 // elements of other vectors.
7261 return SDValue();
7262 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7263 // Furthermore, shuffles require a constant mask, whereas extractelts
7264 // accept variable indices.
7265 return SDValue();
7268 // Add this element source to the list if it's not already there.
7269 SDValue SourceVec = V.getOperand(0);
7270 auto Source = llvm::find(Sources, SourceVec);
7271 if (Source == Sources.end())
7272 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7274 // Update the minimum and maximum lane number seen.
7275 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7276 Source->MinElt = std::min(Source->MinElt, EltNo);
7277 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7280 // Currently only do something sane when at most two source vectors
7281 // are involved.
7282 if (Sources.size() > 2)
7283 return SDValue();
7285 // Find out the smallest element size among result and two sources, and use
7286 // it as element size to build the shuffle_vector.
7287 EVT SmallestEltTy = VT.getVectorElementType();
7288 for (auto &Source : Sources) {
7289 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7290 if (SrcEltTy.bitsLT(SmallestEltTy))
7291 SmallestEltTy = SrcEltTy;
7293 unsigned ResMultiplier =
7294 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7295 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7296 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7298 // If the source vector is too wide or too narrow, we may nevertheless be able
7299 // to construct a compatible shuffle either by concatenating it with UNDEF or
7300 // extracting a suitable range of elements.
7301 for (auto &Src : Sources) {
7302 EVT SrcVT = Src.ShuffleVec.getValueType();
7304 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7305 continue;
7307 // This stage of the search produces a source with the same element type as
7308 // the original, but with a total width matching the BUILD_VECTOR output.
7309 EVT EltVT = SrcVT.getVectorElementType();
7310 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7311 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7313 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7314 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7315 return SDValue();
7316 // We can pad out the smaller vector for free, so if it's part of a
7317 // shuffle...
7318 Src.ShuffleVec =
7319 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7320 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7321 continue;
7324 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7325 return SDValue();
7327 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7328 // Span too large for a VEXT to cope
7329 return SDValue();
7332 if (Src.MinElt >= NumSrcElts) {
7333 // The extraction can just take the second half
7334 Src.ShuffleVec =
7335 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7336 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7337 Src.WindowBase = -NumSrcElts;
7338 } else if (Src.MaxElt < NumSrcElts) {
7339 // The extraction can just take the first half
7340 Src.ShuffleVec =
7341 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7342 DAG.getConstant(0, dl, MVT::i32));
7343 } else {
7344 // An actual VEXT is needed
7345 SDValue VEXTSrc1 =
7346 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7347 DAG.getConstant(0, dl, MVT::i32));
7348 SDValue VEXTSrc2 =
7349 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7350 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7352 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7353 VEXTSrc2,
7354 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7355 Src.WindowBase = -Src.MinElt;
7359 // Another possible incompatibility occurs from the vector element types. We
7360 // can fix this by bitcasting the source vectors to the same type we intend
7361 // for the shuffle.
7362 for (auto &Src : Sources) {
7363 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7364 if (SrcEltTy == SmallestEltTy)
7365 continue;
7366 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7367 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7368 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7369 Src.WindowBase *= Src.WindowScale;
7372 // Final sanity check before we try to actually produce a shuffle.
7373 LLVM_DEBUG(for (auto Src
7374 : Sources)
7375 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7377 // The stars all align, our next step is to produce the mask for the shuffle.
7378 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7379 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7380 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7381 SDValue Entry = Op.getOperand(i);
7382 if (Entry.isUndef())
7383 continue;
7385 auto Src = llvm::find(Sources, Entry.getOperand(0));
7386 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7388 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7389 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7390 // segment.
7391 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7392 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7393 VT.getScalarSizeInBits());
7394 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7396 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7397 // starting at the appropriate offset.
7398 int *LaneMask = &Mask[i * ResMultiplier];
7400 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7401 ExtractBase += NumElts * (Src - Sources.begin());
7402 for (int j = 0; j < LanesDefined; ++j)
7403 LaneMask[j] = ExtractBase + j;
7407 // We can't handle more than two sources. This should have already
7408 // been checked before this point.
7409 assert(Sources.size() <= 2 && "Too many sources!");
7411 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7412 for (unsigned i = 0; i < Sources.size(); ++i)
7413 ShuffleOps[i] = Sources[i].ShuffleVec;
7415 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7416 ShuffleOps[1], Mask, DAG);
7417 if (!Shuffle)
7418 return SDValue();
7419 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7422 enum ShuffleOpCodes {
7423 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7424 OP_VREV,
7425 OP_VDUP0,
7426 OP_VDUP1,
7427 OP_VDUP2,
7428 OP_VDUP3,
7429 OP_VEXT1,
7430 OP_VEXT2,
7431 OP_VEXT3,
7432 OP_VUZPL, // VUZP, left result
7433 OP_VUZPR, // VUZP, right result
7434 OP_VZIPL, // VZIP, left result
7435 OP_VZIPR, // VZIP, right result
7436 OP_VTRNL, // VTRN, left result
7437 OP_VTRNR // VTRN, right result
7440 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7441 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7442 switch (OpNum) {
7443 case OP_COPY:
7444 case OP_VREV:
7445 case OP_VDUP0:
7446 case OP_VDUP1:
7447 case OP_VDUP2:
7448 case OP_VDUP3:
7449 return true;
7451 return false;
7454 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7455 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7456 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7457 /// are assumed to be legal.
7458 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7459 if (VT.getVectorNumElements() == 4 &&
7460 (VT.is128BitVector() || VT.is64BitVector())) {
7461 unsigned PFIndexes[4];
7462 for (unsigned i = 0; i != 4; ++i) {
7463 if (M[i] < 0)
7464 PFIndexes[i] = 8;
7465 else
7466 PFIndexes[i] = M[i];
7469 // Compute the index in the perfect shuffle table.
7470 unsigned PFTableIndex =
7471 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7472 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7473 unsigned Cost = (PFEntry >> 30);
7475 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7476 return true;
7479 bool ReverseVEXT, isV_UNDEF;
7480 unsigned Imm, WhichResult;
7482 unsigned EltSize = VT.getScalarSizeInBits();
7483 if (EltSize >= 32 ||
7484 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7485 isVREVMask(M, VT, 64) ||
7486 isVREVMask(M, VT, 32) ||
7487 isVREVMask(M, VT, 16))
7488 return true;
7489 else if (Subtarget->hasNEON() &&
7490 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7491 isVTBLMask(M, VT) ||
7492 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7493 return true;
7494 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7495 isReverseMask(M, VT))
7496 return true;
7497 else
7498 return false;
7501 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7502 /// the specified operations to build the shuffle.
7503 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7504 SDValue RHS, SelectionDAG &DAG,
7505 const SDLoc &dl) {
7506 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7507 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7508 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7510 if (OpNum == OP_COPY) {
7511 if (LHSID == (1*9+2)*9+3) return LHS;
7512 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7513 return RHS;
7516 SDValue OpLHS, OpRHS;
7517 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7518 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7519 EVT VT = OpLHS.getValueType();
7521 switch (OpNum) {
7522 default: llvm_unreachable("Unknown shuffle opcode!");
7523 case OP_VREV:
7524 // VREV divides the vector in half and swaps within the half.
7525 if (VT.getVectorElementType() == MVT::i32 ||
7526 VT.getVectorElementType() == MVT::f32)
7527 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7528 // vrev <4 x i16> -> VREV32
7529 if (VT.getVectorElementType() == MVT::i16)
7530 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7531 // vrev <4 x i8> -> VREV16
7532 assert(VT.getVectorElementType() == MVT::i8);
7533 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7534 case OP_VDUP0:
7535 case OP_VDUP1:
7536 case OP_VDUP2:
7537 case OP_VDUP3:
7538 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7539 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7540 case OP_VEXT1:
7541 case OP_VEXT2:
7542 case OP_VEXT3:
7543 return DAG.getNode(ARMISD::VEXT, dl, VT,
7544 OpLHS, OpRHS,
7545 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7546 case OP_VUZPL:
7547 case OP_VUZPR:
7548 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7549 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7550 case OP_VZIPL:
7551 case OP_VZIPR:
7552 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7553 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7554 case OP_VTRNL:
7555 case OP_VTRNR:
7556 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7557 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7561 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7562 ArrayRef<int> ShuffleMask,
7563 SelectionDAG &DAG) {
7564 // Check to see if we can use the VTBL instruction.
7565 SDValue V1 = Op.getOperand(0);
7566 SDValue V2 = Op.getOperand(1);
7567 SDLoc DL(Op);
7569 SmallVector<SDValue, 8> VTBLMask;
7570 for (ArrayRef<int>::iterator
7571 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7572 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7574 if (V2.getNode()->isUndef())
7575 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7576 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7578 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7579 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7582 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7583 SelectionDAG &DAG) {
7584 SDLoc DL(Op);
7585 SDValue OpLHS = Op.getOperand(0);
7586 EVT VT = OpLHS.getValueType();
7588 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7589 "Expect an v8i16/v16i8 type");
7590 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7591 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7592 // extract the first 8 bytes into the top double word and the last 8 bytes
7593 // into the bottom double word. The v8i16 case is similar.
7594 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7595 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7596 DAG.getConstant(ExtractNum, DL, MVT::i32));
7599 static EVT getVectorTyFromPredicateVector(EVT VT) {
7600 switch (VT.getSimpleVT().SimpleTy) {
7601 case MVT::v4i1:
7602 return MVT::v4i32;
7603 case MVT::v8i1:
7604 return MVT::v8i16;
7605 case MVT::v16i1:
7606 return MVT::v16i8;
7607 default:
7608 llvm_unreachable("Unexpected vector predicate type");
7612 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7613 SelectionDAG &DAG) {
7614 // Converting from boolean predicates to integers involves creating a vector
7615 // of all ones or all zeroes and selecting the lanes based upon the real
7616 // predicate.
7617 SDValue AllOnes =
7618 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7619 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7621 SDValue AllZeroes =
7622 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7623 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7625 // Get full vector type from predicate type
7626 EVT NewVT = getVectorTyFromPredicateVector(VT);
7628 SDValue RecastV1;
7629 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7630 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7631 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7632 // since we know in hardware the sizes are really the same.
7633 if (VT != MVT::v16i1)
7634 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7635 else
7636 RecastV1 = Pred;
7638 // Select either all ones or zeroes depending upon the real predicate bits.
7639 SDValue PredAsVector =
7640 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7642 // Recast our new predicate-as-integer v16i8 vector into something
7643 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7644 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7647 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7648 const ARMSubtarget *ST) {
7649 EVT VT = Op.getValueType();
7650 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7651 ArrayRef<int> ShuffleMask = SVN->getMask();
7653 assert(ST->hasMVEIntegerOps() &&
7654 "No support for vector shuffle of boolean predicates");
7656 SDValue V1 = Op.getOperand(0);
7657 SDLoc dl(Op);
7658 if (isReverseMask(ShuffleMask, VT)) {
7659 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7660 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7661 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7662 DAG.getConstant(16, dl, MVT::i32));
7663 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7666 // Until we can come up with optimised cases for every single vector
7667 // shuffle in existence we have chosen the least painful strategy. This is
7668 // to essentially promote the boolean predicate to a 8-bit integer, where
7669 // each predicate represents a byte. Then we fall back on a normal integer
7670 // vector shuffle and convert the result back into a predicate vector. In
7671 // many cases the generated code might be even better than scalar code
7672 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7673 // fields in a register into 8 other arbitrary 2-bit fields!
7674 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7675 EVT NewVT = PredAsVector.getValueType();
7677 // Do the shuffle!
7678 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7679 DAG.getUNDEF(NewVT), ShuffleMask);
7681 // Now return the result of comparing the shuffled vector with zero,
7682 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7683 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7684 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7687 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7688 const ARMSubtarget *ST) {
7689 SDValue V1 = Op.getOperand(0);
7690 SDValue V2 = Op.getOperand(1);
7691 SDLoc dl(Op);
7692 EVT VT = Op.getValueType();
7693 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7694 unsigned EltSize = VT.getScalarSizeInBits();
7696 if (ST->hasMVEIntegerOps() && EltSize == 1)
7697 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7699 // Convert shuffles that are directly supported on NEON to target-specific
7700 // DAG nodes, instead of keeping them as shuffles and matching them again
7701 // during code selection. This is more efficient and avoids the possibility
7702 // of inconsistencies between legalization and selection.
7703 // FIXME: floating-point vectors should be canonicalized to integer vectors
7704 // of the same time so that they get CSEd properly.
7705 ArrayRef<int> ShuffleMask = SVN->getMask();
7707 if (EltSize <= 32) {
7708 if (SVN->isSplat()) {
7709 int Lane = SVN->getSplatIndex();
7710 // If this is undef splat, generate it via "just" vdup, if possible.
7711 if (Lane == -1) Lane = 0;
7713 // Test if V1 is a SCALAR_TO_VECTOR.
7714 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7715 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7717 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7718 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7719 // reaches it).
7720 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7721 !isa<ConstantSDNode>(V1.getOperand(0))) {
7722 bool IsScalarToVector = true;
7723 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7724 if (!V1.getOperand(i).isUndef()) {
7725 IsScalarToVector = false;
7726 break;
7728 if (IsScalarToVector)
7729 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7731 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7732 DAG.getConstant(Lane, dl, MVT::i32));
7735 bool ReverseVEXT = false;
7736 unsigned Imm = 0;
7737 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7738 if (ReverseVEXT)
7739 std::swap(V1, V2);
7740 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7741 DAG.getConstant(Imm, dl, MVT::i32));
7744 if (isVREVMask(ShuffleMask, VT, 64))
7745 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7746 if (isVREVMask(ShuffleMask, VT, 32))
7747 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7748 if (isVREVMask(ShuffleMask, VT, 16))
7749 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7751 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7752 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7753 DAG.getConstant(Imm, dl, MVT::i32));
7756 // Check for Neon shuffles that modify both input vectors in place.
7757 // If both results are used, i.e., if there are two shuffles with the same
7758 // source operands and with masks corresponding to both results of one of
7759 // these operations, DAG memoization will ensure that a single node is
7760 // used for both shuffles.
7761 unsigned WhichResult = 0;
7762 bool isV_UNDEF = false;
7763 if (ST->hasNEON()) {
7764 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7765 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7766 if (isV_UNDEF)
7767 V2 = V1;
7768 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7769 .getValue(WhichResult);
7773 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7774 // shuffles that produce a result larger than their operands with:
7775 // shuffle(concat(v1, undef), concat(v2, undef))
7776 // ->
7777 // shuffle(concat(v1, v2), undef)
7778 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7780 // This is useful in the general case, but there are special cases where
7781 // native shuffles produce larger results: the two-result ops.
7783 // Look through the concat when lowering them:
7784 // shuffle(concat(v1, v2), undef)
7785 // ->
7786 // concat(VZIP(v1, v2):0, :1)
7788 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7789 SDValue SubV1 = V1->getOperand(0);
7790 SDValue SubV2 = V1->getOperand(1);
7791 EVT SubVT = SubV1.getValueType();
7793 // We expect these to have been canonicalized to -1.
7794 assert(llvm::all_of(ShuffleMask, [&](int i) {
7795 return i < (int)VT.getVectorNumElements();
7796 }) && "Unexpected shuffle index into UNDEF operand!");
7798 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7799 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7800 if (isV_UNDEF)
7801 SubV2 = SubV1;
7802 assert((WhichResult == 0) &&
7803 "In-place shuffle of concat can only have one result!");
7804 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7805 SubV1, SubV2);
7806 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7807 Res.getValue(1));
7812 // If the shuffle is not directly supported and it has 4 elements, use
7813 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7814 unsigned NumElts = VT.getVectorNumElements();
7815 if (NumElts == 4) {
7816 unsigned PFIndexes[4];
7817 for (unsigned i = 0; i != 4; ++i) {
7818 if (ShuffleMask[i] < 0)
7819 PFIndexes[i] = 8;
7820 else
7821 PFIndexes[i] = ShuffleMask[i];
7824 // Compute the index in the perfect shuffle table.
7825 unsigned PFTableIndex =
7826 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7827 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7828 unsigned Cost = (PFEntry >> 30);
7830 if (Cost <= 4) {
7831 if (ST->hasNEON())
7832 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7833 else if (isLegalMVEShuffleOp(PFEntry)) {
7834 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7835 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7836 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7837 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7838 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7839 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7844 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7845 if (EltSize >= 32) {
7846 // Do the expansion with floating-point types, since that is what the VFP
7847 // registers are defined to use, and since i64 is not legal.
7848 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7849 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7850 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7851 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7852 SmallVector<SDValue, 8> Ops;
7853 for (unsigned i = 0; i < NumElts; ++i) {
7854 if (ShuffleMask[i] < 0)
7855 Ops.push_back(DAG.getUNDEF(EltVT));
7856 else
7857 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7858 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7859 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7860 dl, MVT::i32)));
7862 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7863 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7866 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7867 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7869 if (ST->hasNEON() && VT == MVT::v8i8)
7870 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7871 return NewOp;
7873 return SDValue();
7876 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7877 const ARMSubtarget *ST) {
7878 EVT VecVT = Op.getOperand(0).getValueType();
7879 SDLoc dl(Op);
7881 assert(ST->hasMVEIntegerOps() &&
7882 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7884 SDValue Conv =
7885 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7886 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7887 unsigned LaneWidth =
7888 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7889 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7890 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7891 Op.getOperand(1), DAG.getValueType(MVT::i1));
7892 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7893 DAG.getConstant(~Mask, dl, MVT::i32));
7894 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7897 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7898 SelectionDAG &DAG) const {
7899 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7900 SDValue Lane = Op.getOperand(2);
7901 if (!isa<ConstantSDNode>(Lane))
7902 return SDValue();
7904 SDValue Elt = Op.getOperand(1);
7905 EVT EltVT = Elt.getValueType();
7907 if (Subtarget->hasMVEIntegerOps() &&
7908 Op.getValueType().getScalarSizeInBits() == 1)
7909 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7911 if (getTypeAction(*DAG.getContext(), EltVT) ==
7912 TargetLowering::TypePromoteFloat) {
7913 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7914 // but the type system will try to do that if we don't intervene.
7915 // Reinterpret any such vector-element insertion as one with the
7916 // corresponding integer types.
7918 SDLoc dl(Op);
7920 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7921 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7922 TargetLowering::TypePromoteFloat);
7924 SDValue VecIn = Op.getOperand(0);
7925 EVT VecVT = VecIn.getValueType();
7926 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7927 VecVT.getVectorNumElements());
7929 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7930 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7931 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7932 IVecIn, IElt, Lane);
7933 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
7936 return Op;
7939 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7940 const ARMSubtarget *ST) {
7941 EVT VecVT = Op.getOperand(0).getValueType();
7942 SDLoc dl(Op);
7944 assert(ST->hasMVEIntegerOps() &&
7945 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7947 SDValue Conv =
7948 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7949 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7950 unsigned LaneWidth =
7951 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7952 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
7953 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
7954 return Shift;
7957 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
7958 const ARMSubtarget *ST) {
7959 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7960 SDValue Lane = Op.getOperand(1);
7961 if (!isa<ConstantSDNode>(Lane))
7962 return SDValue();
7964 SDValue Vec = Op.getOperand(0);
7965 EVT VT = Vec.getValueType();
7967 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7968 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
7970 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7971 SDLoc dl(Op);
7972 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7975 return Op;
7978 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
7979 const ARMSubtarget *ST) {
7980 SDValue V1 = Op.getOperand(0);
7981 SDValue V2 = Op.getOperand(1);
7982 SDLoc dl(Op);
7983 EVT VT = Op.getValueType();
7984 EVT Op1VT = V1.getValueType();
7985 EVT Op2VT = V2.getValueType();
7986 unsigned NumElts = VT.getVectorNumElements();
7988 assert(Op1VT == Op2VT && "Operand types don't match!");
7989 assert(VT.getScalarSizeInBits() == 1 &&
7990 "Unexpected custom CONCAT_VECTORS lowering");
7991 assert(ST->hasMVEIntegerOps() &&
7992 "CONCAT_VECTORS lowering only supported for MVE");
7994 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7995 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
7997 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
7998 // promoted to v8i16, etc.
8000 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8002 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8003 // to be the right size for the destination. For example, if Op1 is v4i1 then
8004 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8005 // which when promoted is v8i16. That means each i32 element from Op1 needs
8006 // truncating to i16 and inserting in the result.
8007 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8008 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8009 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8010 EVT NewVT = NewV.getValueType();
8011 EVT ConcatVT = ConVec.getValueType();
8012 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8013 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8014 DAG.getIntPtrConstant(i, dl));
8015 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8016 DAG.getConstant(j, dl, MVT::i32));
8018 return ConVec;
8020 unsigned j = 0;
8021 ConVec = ExractInto(NewV1, ConVec, j);
8022 ConVec = ExractInto(NewV2, ConVec, j);
8024 // Now return the result of comparing the subvector with zero,
8025 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8026 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8027 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8030 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8031 const ARMSubtarget *ST) {
8032 EVT VT = Op->getValueType(0);
8033 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8034 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8036 // The only time a CONCAT_VECTORS operation can have legal types is when
8037 // two 64-bit vectors are concatenated to a 128-bit vector.
8038 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8039 "unexpected CONCAT_VECTORS");
8040 SDLoc dl(Op);
8041 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8042 SDValue Op0 = Op.getOperand(0);
8043 SDValue Op1 = Op.getOperand(1);
8044 if (!Op0.isUndef())
8045 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8046 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8047 DAG.getIntPtrConstant(0, dl));
8048 if (!Op1.isUndef())
8049 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8050 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8051 DAG.getIntPtrConstant(1, dl));
8052 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8055 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8056 const ARMSubtarget *ST) {
8057 SDValue V1 = Op.getOperand(0);
8058 SDValue V2 = Op.getOperand(1);
8059 SDLoc dl(Op);
8060 EVT VT = Op.getValueType();
8061 EVT Op1VT = V1.getValueType();
8062 unsigned NumElts = VT.getVectorNumElements();
8063 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8065 assert(VT.getScalarSizeInBits() == 1 &&
8066 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8067 assert(ST->hasMVEIntegerOps() &&
8068 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8070 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8072 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8073 // promoted to v8i16, etc.
8075 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8077 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8078 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8079 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8080 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8081 DAG.getIntPtrConstant(i, dl));
8082 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8083 DAG.getConstant(j, dl, MVT::i32));
8086 // Now return the result of comparing the subvector with zero,
8087 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8088 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8089 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8092 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8093 /// element has been zero/sign-extended, depending on the isSigned parameter,
8094 /// from an integer type half its size.
8095 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8096 bool isSigned) {
8097 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8098 EVT VT = N->getValueType(0);
8099 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8100 SDNode *BVN = N->getOperand(0).getNode();
8101 if (BVN->getValueType(0) != MVT::v4i32 ||
8102 BVN->getOpcode() != ISD::BUILD_VECTOR)
8103 return false;
8104 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8105 unsigned HiElt = 1 - LoElt;
8106 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8107 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8108 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8109 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8110 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8111 return false;
8112 if (isSigned) {
8113 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8114 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8115 return true;
8116 } else {
8117 if (Hi0->isNullValue() && Hi1->isNullValue())
8118 return true;
8120 return false;
8123 if (N->getOpcode() != ISD::BUILD_VECTOR)
8124 return false;
8126 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8127 SDNode *Elt = N->getOperand(i).getNode();
8128 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8129 unsigned EltSize = VT.getScalarSizeInBits();
8130 unsigned HalfSize = EltSize / 2;
8131 if (isSigned) {
8132 if (!isIntN(HalfSize, C->getSExtValue()))
8133 return false;
8134 } else {
8135 if (!isUIntN(HalfSize, C->getZExtValue()))
8136 return false;
8138 continue;
8140 return false;
8143 return true;
8146 /// isSignExtended - Check if a node is a vector value that is sign-extended
8147 /// or a constant BUILD_VECTOR with sign-extended elements.
8148 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8149 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8150 return true;
8151 if (isExtendedBUILD_VECTOR(N, DAG, true))
8152 return true;
8153 return false;
8156 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8157 /// or a constant BUILD_VECTOR with zero-extended elements.
8158 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8159 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8160 return true;
8161 if (isExtendedBUILD_VECTOR(N, DAG, false))
8162 return true;
8163 return false;
8166 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8167 if (OrigVT.getSizeInBits() >= 64)
8168 return OrigVT;
8170 assert(OrigVT.isSimple() && "Expecting a simple value type");
8172 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8173 switch (OrigSimpleTy) {
8174 default: llvm_unreachable("Unexpected Vector Type");
8175 case MVT::v2i8:
8176 case MVT::v2i16:
8177 return MVT::v2i32;
8178 case MVT::v4i8:
8179 return MVT::v4i16;
8183 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8184 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8185 /// We insert the required extension here to get the vector to fill a D register.
8186 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8187 const EVT &OrigTy,
8188 const EVT &ExtTy,
8189 unsigned ExtOpcode) {
8190 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8191 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8192 // 64-bits we need to insert a new extension so that it will be 64-bits.
8193 assert(ExtTy.is128BitVector() && "Unexpected extension size");
8194 if (OrigTy.getSizeInBits() >= 64)
8195 return N;
8197 // Must extend size to at least 64 bits to be used as an operand for VMULL.
8198 EVT NewVT = getExtensionTo64Bits(OrigTy);
8200 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8203 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8204 /// does not do any sign/zero extension. If the original vector is less
8205 /// than 64 bits, an appropriate extension will be added after the load to
8206 /// reach a total size of 64 bits. We have to add the extension separately
8207 /// because ARM does not have a sign/zero extending load for vectors.
8208 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8209 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8211 // The load already has the right type.
8212 if (ExtendedTy == LD->getMemoryVT())
8213 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8214 LD->getBasePtr(), LD->getPointerInfo(),
8215 LD->getAlignment(), LD->getMemOperand()->getFlags());
8217 // We need to create a zextload/sextload. We cannot just create a load
8218 // followed by a zext/zext node because LowerMUL is also run during normal
8219 // operation legalization where we can't create illegal types.
8220 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8221 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8222 LD->getMemoryVT(), LD->getAlignment(),
8223 LD->getMemOperand()->getFlags());
8226 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8227 /// extending load, or BUILD_VECTOR with extended elements, return the
8228 /// unextended value. The unextended vector should be 64 bits so that it can
8229 /// be used as an operand to a VMULL instruction. If the original vector size
8230 /// before extension is less than 64 bits we add a an extension to resize
8231 /// the vector to 64 bits.
8232 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8233 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8234 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8235 N->getOperand(0)->getValueType(0),
8236 N->getValueType(0),
8237 N->getOpcode());
8239 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8240 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8241 "Expected extending load");
8243 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8244 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8245 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8246 SDValue extLoad =
8247 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8248 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8250 return newLoad;
8253 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8254 // have been legalized as a BITCAST from v4i32.
8255 if (N->getOpcode() == ISD::BITCAST) {
8256 SDNode *BVN = N->getOperand(0).getNode();
8257 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8258 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8259 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8260 return DAG.getBuildVector(
8261 MVT::v2i32, SDLoc(N),
8262 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8264 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8265 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8266 EVT VT = N->getValueType(0);
8267 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8268 unsigned NumElts = VT.getVectorNumElements();
8269 MVT TruncVT = MVT::getIntegerVT(EltSize);
8270 SmallVector<SDValue, 8> Ops;
8271 SDLoc dl(N);
8272 for (unsigned i = 0; i != NumElts; ++i) {
8273 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8274 const APInt &CInt = C->getAPIntValue();
8275 // Element types smaller than 32 bits are not legal, so use i32 elements.
8276 // The values are implicitly truncated so sext vs. zext doesn't matter.
8277 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8279 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8282 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8283 unsigned Opcode = N->getOpcode();
8284 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8285 SDNode *N0 = N->getOperand(0).getNode();
8286 SDNode *N1 = N->getOperand(1).getNode();
8287 return N0->hasOneUse() && N1->hasOneUse() &&
8288 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8290 return false;
8293 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8294 unsigned Opcode = N->getOpcode();
8295 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8296 SDNode *N0 = N->getOperand(0).getNode();
8297 SDNode *N1 = N->getOperand(1).getNode();
8298 return N0->hasOneUse() && N1->hasOneUse() &&
8299 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8301 return false;
8304 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8305 // Multiplications are only custom-lowered for 128-bit vectors so that
8306 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8307 EVT VT = Op.getValueType();
8308 assert(VT.is128BitVector() && VT.isInteger() &&
8309 "unexpected type for custom-lowering ISD::MUL");
8310 SDNode *N0 = Op.getOperand(0).getNode();
8311 SDNode *N1 = Op.getOperand(1).getNode();
8312 unsigned NewOpc = 0;
8313 bool isMLA = false;
8314 bool isN0SExt = isSignExtended(N0, DAG);
8315 bool isN1SExt = isSignExtended(N1, DAG);
8316 if (isN0SExt && isN1SExt)
8317 NewOpc = ARMISD::VMULLs;
8318 else {
8319 bool isN0ZExt = isZeroExtended(N0, DAG);
8320 bool isN1ZExt = isZeroExtended(N1, DAG);
8321 if (isN0ZExt && isN1ZExt)
8322 NewOpc = ARMISD::VMULLu;
8323 else if (isN1SExt || isN1ZExt) {
8324 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8325 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8326 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8327 NewOpc = ARMISD::VMULLs;
8328 isMLA = true;
8329 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8330 NewOpc = ARMISD::VMULLu;
8331 isMLA = true;
8332 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8333 std::swap(N0, N1);
8334 NewOpc = ARMISD::VMULLu;
8335 isMLA = true;
8339 if (!NewOpc) {
8340 if (VT == MVT::v2i64)
8341 // Fall through to expand this. It is not legal.
8342 return SDValue();
8343 else
8344 // Other vector multiplications are legal.
8345 return Op;
8349 // Legalize to a VMULL instruction.
8350 SDLoc DL(Op);
8351 SDValue Op0;
8352 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8353 if (!isMLA) {
8354 Op0 = SkipExtensionForVMULL(N0, DAG);
8355 assert(Op0.getValueType().is64BitVector() &&
8356 Op1.getValueType().is64BitVector() &&
8357 "unexpected types for extended operands to VMULL");
8358 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8361 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8362 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8363 // vmull q0, d4, d6
8364 // vmlal q0, d5, d6
8365 // is faster than
8366 // vaddl q0, d4, d5
8367 // vmovl q1, d6
8368 // vmul q0, q0, q1
8369 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8370 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8371 EVT Op1VT = Op1.getValueType();
8372 return DAG.getNode(N0->getOpcode(), DL, VT,
8373 DAG.getNode(NewOpc, DL, VT,
8374 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8375 DAG.getNode(NewOpc, DL, VT,
8376 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8379 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8380 SelectionDAG &DAG) {
8381 // TODO: Should this propagate fast-math-flags?
8383 // Convert to float
8384 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8385 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8386 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8387 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8388 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8389 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8390 // Get reciprocal estimate.
8391 // float4 recip = vrecpeq_f32(yf);
8392 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8393 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8395 // Because char has a smaller range than uchar, we can actually get away
8396 // without any newton steps. This requires that we use a weird bias
8397 // of 0xb000, however (again, this has been exhaustively tested).
8398 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8399 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8400 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8401 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8402 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8403 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8404 // Convert back to short.
8405 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8406 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8407 return X;
8410 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8411 SelectionDAG &DAG) {
8412 // TODO: Should this propagate fast-math-flags?
8414 SDValue N2;
8415 // Convert to float.
8416 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8417 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8418 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8419 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8420 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8421 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8423 // Use reciprocal estimate and one refinement step.
8424 // float4 recip = vrecpeq_f32(yf);
8425 // recip *= vrecpsq_f32(yf, recip);
8426 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8427 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8428 N1);
8429 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8430 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8431 N1, N2);
8432 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8433 // Because short has a smaller range than ushort, we can actually get away
8434 // with only a single newton step. This requires that we use a weird bias
8435 // of 89, however (again, this has been exhaustively tested).
8436 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8437 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8438 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8439 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8440 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8441 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8442 // Convert back to integer and return.
8443 // return vmovn_s32(vcvt_s32_f32(result));
8444 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8445 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8446 return N0;
8449 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8450 const ARMSubtarget *ST) {
8451 EVT VT = Op.getValueType();
8452 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8453 "unexpected type for custom-lowering ISD::SDIV");
8455 SDLoc dl(Op);
8456 SDValue N0 = Op.getOperand(0);
8457 SDValue N1 = Op.getOperand(1);
8458 SDValue N2, N3;
8460 if (VT == MVT::v8i8) {
8461 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8462 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8464 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8465 DAG.getIntPtrConstant(4, dl));
8466 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8467 DAG.getIntPtrConstant(4, dl));
8468 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8469 DAG.getIntPtrConstant(0, dl));
8470 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8471 DAG.getIntPtrConstant(0, dl));
8473 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8474 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8476 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8477 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8479 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8480 return N0;
8482 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8485 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8486 const ARMSubtarget *ST) {
8487 // TODO: Should this propagate fast-math-flags?
8488 EVT VT = Op.getValueType();
8489 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8490 "unexpected type for custom-lowering ISD::UDIV");
8492 SDLoc dl(Op);
8493 SDValue N0 = Op.getOperand(0);
8494 SDValue N1 = Op.getOperand(1);
8495 SDValue N2, N3;
8497 if (VT == MVT::v8i8) {
8498 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8499 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8501 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8502 DAG.getIntPtrConstant(4, dl));
8503 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8504 DAG.getIntPtrConstant(4, dl));
8505 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8506 DAG.getIntPtrConstant(0, dl));
8507 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8508 DAG.getIntPtrConstant(0, dl));
8510 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8511 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8513 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8514 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8516 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8517 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8518 MVT::i32),
8519 N0);
8520 return N0;
8523 // v4i16 sdiv ... Convert to float.
8524 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8525 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8526 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8527 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8528 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8529 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8531 // Use reciprocal estimate and two refinement steps.
8532 // float4 recip = vrecpeq_f32(yf);
8533 // recip *= vrecpsq_f32(yf, recip);
8534 // recip *= vrecpsq_f32(yf, recip);
8535 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8536 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8537 BN1);
8538 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8539 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8540 BN1, N2);
8541 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8542 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8543 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8544 BN1, N2);
8545 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8546 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8547 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8548 // and that it will never cause us to return an answer too large).
8549 // float4 result = as_float4(as_int4(xf*recip) + 2);
8550 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8551 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8552 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8553 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8554 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8555 // Convert back to integer and return.
8556 // return vmovn_u32(vcvt_s32_f32(result));
8557 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8558 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8559 return N0;
8562 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8563 SDNode *N = Op.getNode();
8564 EVT VT = N->getValueType(0);
8565 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8567 SDValue Carry = Op.getOperand(2);
8569 SDLoc DL(Op);
8571 SDValue Result;
8572 if (Op.getOpcode() == ISD::ADDCARRY) {
8573 // This converts the boolean value carry into the carry flag.
8574 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8576 // Do the addition proper using the carry flag we wanted.
8577 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8578 Op.getOperand(1), Carry);
8580 // Now convert the carry flag into a boolean value.
8581 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8582 } else {
8583 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8584 // have to invert the carry first.
8585 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8586 DAG.getConstant(1, DL, MVT::i32), Carry);
8587 // This converts the boolean value carry into the carry flag.
8588 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8590 // Do the subtraction proper using the carry flag we wanted.
8591 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8592 Op.getOperand(1), Carry);
8594 // Now convert the carry flag into a boolean value.
8595 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8596 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8597 // by ISD::SUBCARRY, so compute 1 - C.
8598 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8599 DAG.getConstant(1, DL, MVT::i32), Carry);
8602 // Return both values.
8603 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8606 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8607 assert(Subtarget->isTargetDarwin());
8609 // For iOS, we want to call an alternative entry point: __sincos_stret,
8610 // return values are passed via sret.
8611 SDLoc dl(Op);
8612 SDValue Arg = Op.getOperand(0);
8613 EVT ArgVT = Arg.getValueType();
8614 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8615 auto PtrVT = getPointerTy(DAG.getDataLayout());
8617 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8618 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8620 // Pair of floats / doubles used to pass the result.
8621 Type *RetTy = StructType::get(ArgTy, ArgTy);
8622 auto &DL = DAG.getDataLayout();
8624 ArgListTy Args;
8625 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8626 SDValue SRet;
8627 if (ShouldUseSRet) {
8628 // Create stack object for sret.
8629 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8630 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8631 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8632 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8634 ArgListEntry Entry;
8635 Entry.Node = SRet;
8636 Entry.Ty = RetTy->getPointerTo();
8637 Entry.IsSExt = false;
8638 Entry.IsZExt = false;
8639 Entry.IsSRet = true;
8640 Args.push_back(Entry);
8641 RetTy = Type::getVoidTy(*DAG.getContext());
8644 ArgListEntry Entry;
8645 Entry.Node = Arg;
8646 Entry.Ty = ArgTy;
8647 Entry.IsSExt = false;
8648 Entry.IsZExt = false;
8649 Args.push_back(Entry);
8651 RTLIB::Libcall LC =
8652 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8653 const char *LibcallName = getLibcallName(LC);
8654 CallingConv::ID CC = getLibcallCallingConv(LC);
8655 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8657 TargetLowering::CallLoweringInfo CLI(DAG);
8658 CLI.setDebugLoc(dl)
8659 .setChain(DAG.getEntryNode())
8660 .setCallee(CC, RetTy, Callee, std::move(Args))
8661 .setDiscardResult(ShouldUseSRet);
8662 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8664 if (!ShouldUseSRet)
8665 return CallResult.first;
8667 SDValue LoadSin =
8668 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8670 // Address of cos field.
8671 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8672 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8673 SDValue LoadCos =
8674 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8676 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8677 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8678 LoadSin.getValue(0), LoadCos.getValue(0));
8681 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8682 bool Signed,
8683 SDValue &Chain) const {
8684 EVT VT = Op.getValueType();
8685 assert((VT == MVT::i32 || VT == MVT::i64) &&
8686 "unexpected type for custom lowering DIV");
8687 SDLoc dl(Op);
8689 const auto &DL = DAG.getDataLayout();
8690 const auto &TLI = DAG.getTargetLoweringInfo();
8692 const char *Name = nullptr;
8693 if (Signed)
8694 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8695 else
8696 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8698 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8700 ARMTargetLowering::ArgListTy Args;
8702 for (auto AI : {1, 0}) {
8703 ArgListEntry Arg;
8704 Arg.Node = Op.getOperand(AI);
8705 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8706 Args.push_back(Arg);
8709 CallLoweringInfo CLI(DAG);
8710 CLI.setDebugLoc(dl)
8711 .setChain(Chain)
8712 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8713 ES, std::move(Args));
8715 return LowerCallTo(CLI).first;
8718 // This is a code size optimisation: return the original SDIV node to
8719 // DAGCombiner when we don't want to expand SDIV into a sequence of
8720 // instructions, and an empty node otherwise which will cause the
8721 // SDIV to be expanded in DAGCombine.
8722 SDValue
8723 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8724 SelectionDAG &DAG,
8725 SmallVectorImpl<SDNode *> &Created) const {
8726 // TODO: Support SREM
8727 if (N->getOpcode() != ISD::SDIV)
8728 return SDValue();
8730 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8731 const bool MinSize = ST.hasMinSize();
8732 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8733 : ST.hasDivideInARMMode();
8735 // Don't touch vector types; rewriting this may lead to scalarizing
8736 // the int divs.
8737 if (N->getOperand(0).getValueType().isVector())
8738 return SDValue();
8740 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8741 // hwdiv support for this to be really profitable.
8742 if (!(MinSize && HasDivide))
8743 return SDValue();
8745 // ARM mode is a bit simpler than Thumb: we can handle large power
8746 // of 2 immediates with 1 mov instruction; no further checks required,
8747 // just return the sdiv node.
8748 if (!ST.isThumb())
8749 return SDValue(N, 0);
8751 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8752 // and thus lose the code size benefits of a MOVS that requires only 2.
8753 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8754 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8755 if (Divisor.sgt(128))
8756 return SDValue();
8758 return SDValue(N, 0);
8761 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8762 bool Signed) const {
8763 assert(Op.getValueType() == MVT::i32 &&
8764 "unexpected type for custom lowering DIV");
8765 SDLoc dl(Op);
8767 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8768 DAG.getEntryNode(), Op.getOperand(1));
8770 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8773 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8774 SDLoc DL(N);
8775 SDValue Op = N->getOperand(1);
8776 if (N->getValueType(0) == MVT::i32)
8777 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8778 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8779 DAG.getConstant(0, DL, MVT::i32));
8780 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8781 DAG.getConstant(1, DL, MVT::i32));
8782 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8783 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8786 void ARMTargetLowering::ExpandDIV_Windows(
8787 SDValue Op, SelectionDAG &DAG, bool Signed,
8788 SmallVectorImpl<SDValue> &Results) const {
8789 const auto &DL = DAG.getDataLayout();
8790 const auto &TLI = DAG.getTargetLoweringInfo();
8792 assert(Op.getValueType() == MVT::i64 &&
8793 "unexpected type for custom lowering DIV");
8794 SDLoc dl(Op);
8796 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8798 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8800 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8801 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8802 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8803 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8805 Results.push_back(Lower);
8806 Results.push_back(Upper);
8809 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
8810 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
8811 EVT MemVT = LD->getMemoryVT();
8812 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
8813 "Expected a predicate type!");
8814 assert(MemVT == Op.getValueType());
8815 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
8816 "Expected a non-extending load");
8817 assert(LD->isUnindexed() && "Expected a unindexed load");
8819 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
8820 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
8821 // need to make sure that 8/4 bits are actually loaded into the correct
8822 // place, which means loading the value and then shuffling the values into
8823 // the bottom bits of the predicate.
8824 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
8825 // for BE).
8827 SDLoc dl(Op);
8828 SDValue Load = DAG.getExtLoad(
8829 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
8830 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
8831 LD->getMemOperand());
8832 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
8833 if (MemVT != MVT::v16i1)
8834 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
8835 DAG.getConstant(0, dl, MVT::i32));
8836 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
8839 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
8840 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
8841 EVT MemVT = ST->getMemoryVT();
8842 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
8843 "Expected a predicate type!");
8844 assert(MemVT == ST->getValue().getValueType());
8845 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
8846 assert(ST->isUnindexed() && "Expected a unindexed store");
8848 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
8849 // unset and a scalar store.
8850 SDLoc dl(Op);
8851 SDValue Build = ST->getValue();
8852 if (MemVT != MVT::v16i1) {
8853 SmallVector<SDValue, 16> Ops;
8854 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
8855 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
8856 DAG.getConstant(I, dl, MVT::i32)));
8857 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
8858 Ops.push_back(DAG.getUNDEF(MVT::i32));
8859 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
8861 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
8862 return DAG.getTruncStore(
8863 ST->getChain(), dl, GRP, ST->getBasePtr(),
8864 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
8865 ST->getMemOperand());
8868 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
8869 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
8870 MVT VT = Op.getSimpleValueType();
8871 SDValue Mask = N->getMask();
8872 SDValue PassThru = N->getPassThru();
8873 SDLoc dl(Op);
8875 if (ISD::isBuildVectorAllZeros(PassThru.getNode()) ||
8876 (PassThru->getOpcode() == ARMISD::VMOVIMM &&
8877 isNullConstant(PassThru->getOperand(0))))
8878 return Op;
8880 // MVE Masked loads use zero as the passthru value. Here we convert undef to
8881 // zero too, and other values are lowered to a select.
8882 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
8883 DAG.getTargetConstant(0, dl, MVT::i32));
8884 SDValue NewLoad = DAG.getMaskedLoad(
8885 VT, dl, N->getChain(), N->getBasePtr(), Mask, ZeroVec, N->getMemoryVT(),
8886 N->getMemOperand(), N->getExtensionType(), N->isExpandingLoad());
8887 SDValue Combo = NewLoad;
8888 if (!PassThru.isUndef())
8889 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
8890 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
8893 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8894 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8895 // Acquire/Release load/store is not legal for targets without a dmb or
8896 // equivalent available.
8897 return SDValue();
8899 // Monotonic load/store is legal for all targets.
8900 return Op;
8903 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8904 SmallVectorImpl<SDValue> &Results,
8905 SelectionDAG &DAG,
8906 const ARMSubtarget *Subtarget) {
8907 SDLoc DL(N);
8908 // Under Power Management extensions, the cycle-count is:
8909 // mrc p15, #0, <Rt>, c9, c13, #0
8910 SDValue Ops[] = { N->getOperand(0), // Chain
8911 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8912 DAG.getTargetConstant(15, DL, MVT::i32),
8913 DAG.getTargetConstant(0, DL, MVT::i32),
8914 DAG.getTargetConstant(9, DL, MVT::i32),
8915 DAG.getTargetConstant(13, DL, MVT::i32),
8916 DAG.getTargetConstant(0, DL, MVT::i32)
8919 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8920 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8921 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8922 DAG.getConstant(0, DL, MVT::i32)));
8923 Results.push_back(Cycles32.getValue(1));
8926 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8927 SDLoc dl(V.getNode());
8928 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
8929 SDValue VHi = DAG.getAnyExtOrTrunc(
8930 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
8931 dl, MVT::i32);
8932 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8933 if (isBigEndian)
8934 std::swap (VLo, VHi);
8935 SDValue RegClass =
8936 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
8937 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
8938 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
8939 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
8940 return SDValue(
8941 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
8944 static void ReplaceCMP_SWAP_64Results(SDNode *N,
8945 SmallVectorImpl<SDValue> & Results,
8946 SelectionDAG &DAG) {
8947 assert(N->getValueType(0) == MVT::i64 &&
8948 "AtomicCmpSwap on types less than 64 should be legal");
8949 SDValue Ops[] = {N->getOperand(1),
8950 createGPRPairNode(DAG, N->getOperand(2)),
8951 createGPRPairNode(DAG, N->getOperand(3)),
8952 N->getOperand(0)};
8953 SDNode *CmpSwap = DAG.getMachineNode(
8954 ARM::CMP_SWAP_64, SDLoc(N),
8955 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
8957 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
8958 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8960 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8962 Results.push_back(
8963 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8964 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8965 Results.push_back(
8966 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8967 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8968 Results.push_back(SDValue(CmpSwap, 2));
8971 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8972 SelectionDAG &DAG) {
8973 const auto &TLI = DAG.getTargetLoweringInfo();
8975 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8976 "Custom lowering is MSVCRT specific!");
8978 SDLoc dl(Op);
8979 SDValue Val = Op.getOperand(0);
8980 MVT Ty = Val->getSimpleValueType(0);
8981 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8982 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8983 TLI.getPointerTy(DAG.getDataLayout()));
8985 TargetLowering::ArgListTy Args;
8986 TargetLowering::ArgListEntry Entry;
8988 Entry.Node = Val;
8989 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8990 Entry.IsZExt = true;
8991 Args.push_back(Entry);
8993 Entry.Node = Exponent;
8994 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8995 Entry.IsZExt = true;
8996 Args.push_back(Entry);
8998 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
9000 // In the in-chain to the call is the entry node If we are emitting a
9001 // tailcall, the chain will be mutated if the node has a non-entry input
9002 // chain.
9003 SDValue InChain = DAG.getEntryNode();
9004 SDValue TCChain = InChain;
9006 const Function &F = DAG.getMachineFunction().getFunction();
9007 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
9008 F.getReturnType() == LCRTy;
9009 if (IsTC)
9010 InChain = TCChain;
9012 TargetLowering::CallLoweringInfo CLI(DAG);
9013 CLI.setDebugLoc(dl)
9014 .setChain(InChain)
9015 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
9016 .setTailCall(IsTC);
9017 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
9019 // Return the chain (the DAG root) if it is a tail call
9020 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
9023 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9024 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9025 switch (Op.getOpcode()) {
9026 default: llvm_unreachable("Don't know how to custom lower this!");
9027 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9028 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9029 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9030 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9031 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9032 case ISD::SELECT: return LowerSELECT(Op, DAG);
9033 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
9034 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9035 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
9036 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
9037 case ISD::VASTART: return LowerVASTART(Op, DAG);
9038 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9039 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
9040 case ISD::SINT_TO_FP:
9041 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
9042 case ISD::FP_TO_SINT:
9043 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
9044 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9045 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9046 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9047 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9048 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9049 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9050 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9051 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9052 Subtarget);
9053 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9054 case ISD::SHL:
9055 case ISD::SRL:
9056 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
9057 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
9058 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
9059 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
9060 case ISD::SRL_PARTS:
9061 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
9062 case ISD::CTTZ:
9063 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9064 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9065 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
9066 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
9067 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
9068 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9069 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9070 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9071 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9072 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9073 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9074 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9075 case ISD::MUL: return LowerMUL(Op, DAG);
9076 case ISD::SDIV:
9077 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9078 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9079 return LowerSDIV(Op, DAG, Subtarget);
9080 case ISD::UDIV:
9081 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9082 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9083 return LowerUDIV(Op, DAG, Subtarget);
9084 case ISD::ADDCARRY:
9085 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
9086 case ISD::SADDO:
9087 case ISD::SSUBO:
9088 return LowerSignedALUO(Op, DAG);
9089 case ISD::UADDO:
9090 case ISD::USUBO:
9091 return LowerUnsignedALUO(Op, DAG);
9092 case ISD::LOAD:
9093 return LowerPredicateLoad(Op, DAG);
9094 case ISD::STORE:
9095 return LowerPredicateStore(Op, DAG);
9096 case ISD::MLOAD:
9097 return LowerMLOAD(Op, DAG);
9098 case ISD::ATOMIC_LOAD:
9099 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
9100 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
9101 case ISD::SDIVREM:
9102 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
9103 case ISD::DYNAMIC_STACKALLOC:
9104 if (Subtarget->isTargetWindows())
9105 return LowerDYNAMIC_STACKALLOC(Op, DAG);
9106 llvm_unreachable("Don't know how to custom lower this!");
9107 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9108 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9109 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
9110 case ARMISD::WIN__DBZCHK: return SDValue();
9114 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9115 SelectionDAG &DAG) {
9116 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9117 unsigned Opc = 0;
9118 if (IntNo == Intrinsic::arm_smlald)
9119 Opc = ARMISD::SMLALD;
9120 else if (IntNo == Intrinsic::arm_smlaldx)
9121 Opc = ARMISD::SMLALDX;
9122 else if (IntNo == Intrinsic::arm_smlsld)
9123 Opc = ARMISD::SMLSLD;
9124 else if (IntNo == Intrinsic::arm_smlsldx)
9125 Opc = ARMISD::SMLSLDX;
9126 else
9127 return;
9129 SDLoc dl(N);
9130 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9131 N->getOperand(3),
9132 DAG.getConstant(0, dl, MVT::i32));
9133 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9134 N->getOperand(3),
9135 DAG.getConstant(1, dl, MVT::i32));
9137 SDValue LongMul = DAG.getNode(Opc, dl,
9138 DAG.getVTList(MVT::i32, MVT::i32),
9139 N->getOperand(1), N->getOperand(2),
9140 Lo, Hi);
9141 Results.push_back(LongMul.getValue(0));
9142 Results.push_back(LongMul.getValue(1));
9145 /// ReplaceNodeResults - Replace the results of node with an illegal result
9146 /// type with new values built out of custom code.
9147 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9148 SmallVectorImpl<SDValue> &Results,
9149 SelectionDAG &DAG) const {
9150 SDValue Res;
9151 switch (N->getOpcode()) {
9152 default:
9153 llvm_unreachable("Don't know how to custom expand this!");
9154 case ISD::READ_REGISTER:
9155 ExpandREAD_REGISTER(N, Results, DAG);
9156 break;
9157 case ISD::BITCAST:
9158 Res = ExpandBITCAST(N, DAG, Subtarget);
9159 break;
9160 case ISD::SRL:
9161 case ISD::SRA:
9162 case ISD::SHL:
9163 Res = Expand64BitShift(N, DAG, Subtarget);
9164 break;
9165 case ISD::SREM:
9166 case ISD::UREM:
9167 Res = LowerREM(N, DAG);
9168 break;
9169 case ISD::SDIVREM:
9170 case ISD::UDIVREM:
9171 Res = LowerDivRem(SDValue(N, 0), DAG);
9172 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9173 Results.push_back(Res.getValue(0));
9174 Results.push_back(Res.getValue(1));
9175 return;
9176 case ISD::READCYCLECOUNTER:
9177 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9178 return;
9179 case ISD::UDIV:
9180 case ISD::SDIV:
9181 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9182 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9183 Results);
9184 case ISD::ATOMIC_CMP_SWAP:
9185 ReplaceCMP_SWAP_64Results(N, Results, DAG);
9186 return;
9187 case ISD::INTRINSIC_WO_CHAIN:
9188 return ReplaceLongIntrinsic(N, Results, DAG);
9189 case ISD::ABS:
9190 lowerABS(N, Results, DAG);
9191 return ;
9194 if (Res.getNode())
9195 Results.push_back(Res);
9198 //===----------------------------------------------------------------------===//
9199 // ARM Scheduler Hooks
9200 //===----------------------------------------------------------------------===//
9202 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9203 /// registers the function context.
9204 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9205 MachineBasicBlock *MBB,
9206 MachineBasicBlock *DispatchBB,
9207 int FI) const {
9208 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9209 "ROPI/RWPI not currently supported with SjLj");
9210 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9211 DebugLoc dl = MI.getDebugLoc();
9212 MachineFunction *MF = MBB->getParent();
9213 MachineRegisterInfo *MRI = &MF->getRegInfo();
9214 MachineConstantPool *MCP = MF->getConstantPool();
9215 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9216 const Function &F = MF->getFunction();
9218 bool isThumb = Subtarget->isThumb();
9219 bool isThumb2 = Subtarget->isThumb2();
9221 unsigned PCLabelId = AFI->createPICLabelUId();
9222 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9223 ARMConstantPoolValue *CPV =
9224 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9225 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9227 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9228 : &ARM::GPRRegClass;
9230 // Grab constant pool and fixed stack memory operands.
9231 MachineMemOperand *CPMMO =
9232 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9233 MachineMemOperand::MOLoad, 4, 4);
9235 MachineMemOperand *FIMMOSt =
9236 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9237 MachineMemOperand::MOStore, 4, 4);
9239 // Load the address of the dispatch MBB into the jump buffer.
9240 if (isThumb2) {
9241 // Incoming value: jbuf
9242 // ldr.n r5, LCPI1_1
9243 // orr r5, r5, #1
9244 // add r5, pc
9245 // str r5, [$jbuf, #+4] ; &jbuf[1]
9246 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9247 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9248 .addConstantPoolIndex(CPI)
9249 .addMemOperand(CPMMO)
9250 .add(predOps(ARMCC::AL));
9251 // Set the low bit because of thumb mode.
9252 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9253 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9254 .addReg(NewVReg1, RegState::Kill)
9255 .addImm(0x01)
9256 .add(predOps(ARMCC::AL))
9257 .add(condCodeOp());
9258 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9259 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9260 .addReg(NewVReg2, RegState::Kill)
9261 .addImm(PCLabelId);
9262 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9263 .addReg(NewVReg3, RegState::Kill)
9264 .addFrameIndex(FI)
9265 .addImm(36) // &jbuf[1] :: pc
9266 .addMemOperand(FIMMOSt)
9267 .add(predOps(ARMCC::AL));
9268 } else if (isThumb) {
9269 // Incoming value: jbuf
9270 // ldr.n r1, LCPI1_4
9271 // add r1, pc
9272 // mov r2, #1
9273 // orrs r1, r2
9274 // add r2, $jbuf, #+4 ; &jbuf[1]
9275 // str r1, [r2]
9276 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9277 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9278 .addConstantPoolIndex(CPI)
9279 .addMemOperand(CPMMO)
9280 .add(predOps(ARMCC::AL));
9281 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9282 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9283 .addReg(NewVReg1, RegState::Kill)
9284 .addImm(PCLabelId);
9285 // Set the low bit because of thumb mode.
9286 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9287 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9288 .addReg(ARM::CPSR, RegState::Define)
9289 .addImm(1)
9290 .add(predOps(ARMCC::AL));
9291 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9292 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9293 .addReg(ARM::CPSR, RegState::Define)
9294 .addReg(NewVReg2, RegState::Kill)
9295 .addReg(NewVReg3, RegState::Kill)
9296 .add(predOps(ARMCC::AL));
9297 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9298 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9299 .addFrameIndex(FI)
9300 .addImm(36); // &jbuf[1] :: pc
9301 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9302 .addReg(NewVReg4, RegState::Kill)
9303 .addReg(NewVReg5, RegState::Kill)
9304 .addImm(0)
9305 .addMemOperand(FIMMOSt)
9306 .add(predOps(ARMCC::AL));
9307 } else {
9308 // Incoming value: jbuf
9309 // ldr r1, LCPI1_1
9310 // add r1, pc, r1
9311 // str r1, [$jbuf, #+4] ; &jbuf[1]
9312 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9313 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9314 .addConstantPoolIndex(CPI)
9315 .addImm(0)
9316 .addMemOperand(CPMMO)
9317 .add(predOps(ARMCC::AL));
9318 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9319 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9320 .addReg(NewVReg1, RegState::Kill)
9321 .addImm(PCLabelId)
9322 .add(predOps(ARMCC::AL));
9323 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9324 .addReg(NewVReg2, RegState::Kill)
9325 .addFrameIndex(FI)
9326 .addImm(36) // &jbuf[1] :: pc
9327 .addMemOperand(FIMMOSt)
9328 .add(predOps(ARMCC::AL));
9332 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9333 MachineBasicBlock *MBB) const {
9334 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9335 DebugLoc dl = MI.getDebugLoc();
9336 MachineFunction *MF = MBB->getParent();
9337 MachineRegisterInfo *MRI = &MF->getRegInfo();
9338 MachineFrameInfo &MFI = MF->getFrameInfo();
9339 int FI = MFI.getFunctionContextIndex();
9341 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9342 : &ARM::GPRnopcRegClass;
9344 // Get a mapping of the call site numbers to all of the landing pads they're
9345 // associated with.
9346 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9347 unsigned MaxCSNum = 0;
9348 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9349 ++BB) {
9350 if (!BB->isEHPad()) continue;
9352 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9353 // pad.
9354 for (MachineBasicBlock::iterator
9355 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9356 if (!II->isEHLabel()) continue;
9358 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9359 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9361 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9362 for (SmallVectorImpl<unsigned>::iterator
9363 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9364 CSI != CSE; ++CSI) {
9365 CallSiteNumToLPad[*CSI].push_back(&*BB);
9366 MaxCSNum = std::max(MaxCSNum, *CSI);
9368 break;
9372 // Get an ordered list of the machine basic blocks for the jump table.
9373 std::vector<MachineBasicBlock*> LPadList;
9374 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9375 LPadList.reserve(CallSiteNumToLPad.size());
9376 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9377 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9378 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9379 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9380 LPadList.push_back(*II);
9381 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9385 assert(!LPadList.empty() &&
9386 "No landing pad destinations for the dispatch jump table!");
9388 // Create the jump table and associated information.
9389 MachineJumpTableInfo *JTI =
9390 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9391 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9393 // Create the MBBs for the dispatch code.
9395 // Shove the dispatch's address into the return slot in the function context.
9396 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9397 DispatchBB->setIsEHPad();
9399 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9400 unsigned trap_opcode;
9401 if (Subtarget->isThumb())
9402 trap_opcode = ARM::tTRAP;
9403 else
9404 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9406 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9407 DispatchBB->addSuccessor(TrapBB);
9409 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9410 DispatchBB->addSuccessor(DispContBB);
9412 // Insert and MBBs.
9413 MF->insert(MF->end(), DispatchBB);
9414 MF->insert(MF->end(), DispContBB);
9415 MF->insert(MF->end(), TrapBB);
9417 // Insert code into the entry block that creates and registers the function
9418 // context.
9419 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9421 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9422 MachinePointerInfo::getFixedStack(*MF, FI),
9423 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9425 MachineInstrBuilder MIB;
9426 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9428 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9429 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9431 // Add a register mask with no preserved registers. This results in all
9432 // registers being marked as clobbered. This can't work if the dispatch block
9433 // is in a Thumb1 function and is linked with ARM code which uses the FP
9434 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9435 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9437 bool IsPositionIndependent = isPositionIndependent();
9438 unsigned NumLPads = LPadList.size();
9439 if (Subtarget->isThumb2()) {
9440 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9441 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9442 .addFrameIndex(FI)
9443 .addImm(4)
9444 .addMemOperand(FIMMOLd)
9445 .add(predOps(ARMCC::AL));
9447 if (NumLPads < 256) {
9448 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9449 .addReg(NewVReg1)
9450 .addImm(LPadList.size())
9451 .add(predOps(ARMCC::AL));
9452 } else {
9453 Register VReg1 = MRI->createVirtualRegister(TRC);
9454 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9455 .addImm(NumLPads & 0xFFFF)
9456 .add(predOps(ARMCC::AL));
9458 unsigned VReg2 = VReg1;
9459 if ((NumLPads & 0xFFFF0000) != 0) {
9460 VReg2 = MRI->createVirtualRegister(TRC);
9461 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9462 .addReg(VReg1)
9463 .addImm(NumLPads >> 16)
9464 .add(predOps(ARMCC::AL));
9467 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9468 .addReg(NewVReg1)
9469 .addReg(VReg2)
9470 .add(predOps(ARMCC::AL));
9473 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9474 .addMBB(TrapBB)
9475 .addImm(ARMCC::HI)
9476 .addReg(ARM::CPSR);
9478 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9479 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9480 .addJumpTableIndex(MJTI)
9481 .add(predOps(ARMCC::AL));
9483 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9484 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9485 .addReg(NewVReg3, RegState::Kill)
9486 .addReg(NewVReg1)
9487 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9488 .add(predOps(ARMCC::AL))
9489 .add(condCodeOp());
9491 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9492 .addReg(NewVReg4, RegState::Kill)
9493 .addReg(NewVReg1)
9494 .addJumpTableIndex(MJTI);
9495 } else if (Subtarget->isThumb()) {
9496 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9497 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9498 .addFrameIndex(FI)
9499 .addImm(1)
9500 .addMemOperand(FIMMOLd)
9501 .add(predOps(ARMCC::AL));
9503 if (NumLPads < 256) {
9504 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9505 .addReg(NewVReg1)
9506 .addImm(NumLPads)
9507 .add(predOps(ARMCC::AL));
9508 } else {
9509 MachineConstantPool *ConstantPool = MF->getConstantPool();
9510 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9511 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9513 // MachineConstantPool wants an explicit alignment.
9514 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9515 if (Align == 0)
9516 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9517 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9519 Register VReg1 = MRI->createVirtualRegister(TRC);
9520 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9521 .addReg(VReg1, RegState::Define)
9522 .addConstantPoolIndex(Idx)
9523 .add(predOps(ARMCC::AL));
9524 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9525 .addReg(NewVReg1)
9526 .addReg(VReg1)
9527 .add(predOps(ARMCC::AL));
9530 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9531 .addMBB(TrapBB)
9532 .addImm(ARMCC::HI)
9533 .addReg(ARM::CPSR);
9535 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9536 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9537 .addReg(ARM::CPSR, RegState::Define)
9538 .addReg(NewVReg1)
9539 .addImm(2)
9540 .add(predOps(ARMCC::AL));
9542 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9543 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9544 .addJumpTableIndex(MJTI)
9545 .add(predOps(ARMCC::AL));
9547 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9548 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9549 .addReg(ARM::CPSR, RegState::Define)
9550 .addReg(NewVReg2, RegState::Kill)
9551 .addReg(NewVReg3)
9552 .add(predOps(ARMCC::AL));
9554 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9555 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9557 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9558 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9559 .addReg(NewVReg4, RegState::Kill)
9560 .addImm(0)
9561 .addMemOperand(JTMMOLd)
9562 .add(predOps(ARMCC::AL));
9564 unsigned NewVReg6 = NewVReg5;
9565 if (IsPositionIndependent) {
9566 NewVReg6 = MRI->createVirtualRegister(TRC);
9567 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9568 .addReg(ARM::CPSR, RegState::Define)
9569 .addReg(NewVReg5, RegState::Kill)
9570 .addReg(NewVReg3)
9571 .add(predOps(ARMCC::AL));
9574 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9575 .addReg(NewVReg6, RegState::Kill)
9576 .addJumpTableIndex(MJTI);
9577 } else {
9578 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9579 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9580 .addFrameIndex(FI)
9581 .addImm(4)
9582 .addMemOperand(FIMMOLd)
9583 .add(predOps(ARMCC::AL));
9585 if (NumLPads < 256) {
9586 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9587 .addReg(NewVReg1)
9588 .addImm(NumLPads)
9589 .add(predOps(ARMCC::AL));
9590 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9591 Register VReg1 = MRI->createVirtualRegister(TRC);
9592 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9593 .addImm(NumLPads & 0xFFFF)
9594 .add(predOps(ARMCC::AL));
9596 unsigned VReg2 = VReg1;
9597 if ((NumLPads & 0xFFFF0000) != 0) {
9598 VReg2 = MRI->createVirtualRegister(TRC);
9599 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9600 .addReg(VReg1)
9601 .addImm(NumLPads >> 16)
9602 .add(predOps(ARMCC::AL));
9605 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9606 .addReg(NewVReg1)
9607 .addReg(VReg2)
9608 .add(predOps(ARMCC::AL));
9609 } else {
9610 MachineConstantPool *ConstantPool = MF->getConstantPool();
9611 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9612 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9614 // MachineConstantPool wants an explicit alignment.
9615 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9616 if (Align == 0)
9617 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9618 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9620 Register VReg1 = MRI->createVirtualRegister(TRC);
9621 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9622 .addReg(VReg1, RegState::Define)
9623 .addConstantPoolIndex(Idx)
9624 .addImm(0)
9625 .add(predOps(ARMCC::AL));
9626 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9627 .addReg(NewVReg1)
9628 .addReg(VReg1, RegState::Kill)
9629 .add(predOps(ARMCC::AL));
9632 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9633 .addMBB(TrapBB)
9634 .addImm(ARMCC::HI)
9635 .addReg(ARM::CPSR);
9637 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9638 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9639 .addReg(NewVReg1)
9640 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9641 .add(predOps(ARMCC::AL))
9642 .add(condCodeOp());
9643 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9644 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9645 .addJumpTableIndex(MJTI)
9646 .add(predOps(ARMCC::AL));
9648 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9649 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9650 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9651 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9652 .addReg(NewVReg3, RegState::Kill)
9653 .addReg(NewVReg4)
9654 .addImm(0)
9655 .addMemOperand(JTMMOLd)
9656 .add(predOps(ARMCC::AL));
9658 if (IsPositionIndependent) {
9659 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9660 .addReg(NewVReg5, RegState::Kill)
9661 .addReg(NewVReg4)
9662 .addJumpTableIndex(MJTI);
9663 } else {
9664 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9665 .addReg(NewVReg5, RegState::Kill)
9666 .addJumpTableIndex(MJTI);
9670 // Add the jump table entries as successors to the MBB.
9671 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9672 for (std::vector<MachineBasicBlock*>::iterator
9673 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9674 MachineBasicBlock *CurMBB = *I;
9675 if (SeenMBBs.insert(CurMBB).second)
9676 DispContBB->addSuccessor(CurMBB);
9679 // N.B. the order the invoke BBs are processed in doesn't matter here.
9680 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9681 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9682 for (MachineBasicBlock *BB : InvokeBBs) {
9684 // Remove the landing pad successor from the invoke block and replace it
9685 // with the new dispatch block.
9686 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9687 BB->succ_end());
9688 while (!Successors.empty()) {
9689 MachineBasicBlock *SMBB = Successors.pop_back_val();
9690 if (SMBB->isEHPad()) {
9691 BB->removeSuccessor(SMBB);
9692 MBBLPads.push_back(SMBB);
9696 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9697 BB->normalizeSuccProbs();
9699 // Find the invoke call and mark all of the callee-saved registers as
9700 // 'implicit defined' so that they're spilled. This prevents code from
9701 // moving instructions to before the EH block, where they will never be
9702 // executed.
9703 for (MachineBasicBlock::reverse_iterator
9704 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9705 if (!II->isCall()) continue;
9707 DenseMap<unsigned, bool> DefRegs;
9708 for (MachineInstr::mop_iterator
9709 OI = II->operands_begin(), OE = II->operands_end();
9710 OI != OE; ++OI) {
9711 if (!OI->isReg()) continue;
9712 DefRegs[OI->getReg()] = true;
9715 MachineInstrBuilder MIB(*MF, &*II);
9717 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9718 unsigned Reg = SavedRegs[i];
9719 if (Subtarget->isThumb2() &&
9720 !ARM::tGPRRegClass.contains(Reg) &&
9721 !ARM::hGPRRegClass.contains(Reg))
9722 continue;
9723 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9724 continue;
9725 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9726 continue;
9727 if (!DefRegs[Reg])
9728 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9731 break;
9735 // Mark all former landing pads as non-landing pads. The dispatch is the only
9736 // landing pad now.
9737 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9738 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9739 (*I)->setIsEHPad(false);
9741 // The instruction is gone now.
9742 MI.eraseFromParent();
9745 static
9746 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9747 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9748 E = MBB->succ_end(); I != E; ++I)
9749 if (*I != Succ)
9750 return *I;
9751 llvm_unreachable("Expecting a BB with two successors!");
9754 /// Return the load opcode for a given load size. If load size >= 8,
9755 /// neon opcode will be returned.
9756 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9757 if (LdSize >= 8)
9758 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9759 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9760 if (IsThumb1)
9761 return LdSize == 4 ? ARM::tLDRi
9762 : LdSize == 2 ? ARM::tLDRHi
9763 : LdSize == 1 ? ARM::tLDRBi : 0;
9764 if (IsThumb2)
9765 return LdSize == 4 ? ARM::t2LDR_POST
9766 : LdSize == 2 ? ARM::t2LDRH_POST
9767 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9768 return LdSize == 4 ? ARM::LDR_POST_IMM
9769 : LdSize == 2 ? ARM::LDRH_POST
9770 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9773 /// Return the store opcode for a given store size. If store size >= 8,
9774 /// neon opcode will be returned.
9775 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9776 if (StSize >= 8)
9777 return StSize == 16 ? ARM::VST1q32wb_fixed
9778 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9779 if (IsThumb1)
9780 return StSize == 4 ? ARM::tSTRi
9781 : StSize == 2 ? ARM::tSTRHi
9782 : StSize == 1 ? ARM::tSTRBi : 0;
9783 if (IsThumb2)
9784 return StSize == 4 ? ARM::t2STR_POST
9785 : StSize == 2 ? ARM::t2STRH_POST
9786 : StSize == 1 ? ARM::t2STRB_POST : 0;
9787 return StSize == 4 ? ARM::STR_POST_IMM
9788 : StSize == 2 ? ARM::STRH_POST
9789 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9792 /// Emit a post-increment load operation with given size. The instructions
9793 /// will be added to BB at Pos.
9794 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9795 const TargetInstrInfo *TII, const DebugLoc &dl,
9796 unsigned LdSize, unsigned Data, unsigned AddrIn,
9797 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9798 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9799 assert(LdOpc != 0 && "Should have a load opcode");
9800 if (LdSize >= 8) {
9801 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9802 .addReg(AddrOut, RegState::Define)
9803 .addReg(AddrIn)
9804 .addImm(0)
9805 .add(predOps(ARMCC::AL));
9806 } else if (IsThumb1) {
9807 // load + update AddrIn
9808 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9809 .addReg(AddrIn)
9810 .addImm(0)
9811 .add(predOps(ARMCC::AL));
9812 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9813 .add(t1CondCodeOp())
9814 .addReg(AddrIn)
9815 .addImm(LdSize)
9816 .add(predOps(ARMCC::AL));
9817 } else if (IsThumb2) {
9818 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9819 .addReg(AddrOut, RegState::Define)
9820 .addReg(AddrIn)
9821 .addImm(LdSize)
9822 .add(predOps(ARMCC::AL));
9823 } else { // arm
9824 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9825 .addReg(AddrOut, RegState::Define)
9826 .addReg(AddrIn)
9827 .addReg(0)
9828 .addImm(LdSize)
9829 .add(predOps(ARMCC::AL));
9833 /// Emit a post-increment store operation with given size. The instructions
9834 /// will be added to BB at Pos.
9835 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9836 const TargetInstrInfo *TII, const DebugLoc &dl,
9837 unsigned StSize, unsigned Data, unsigned AddrIn,
9838 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9839 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9840 assert(StOpc != 0 && "Should have a store opcode");
9841 if (StSize >= 8) {
9842 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9843 .addReg(AddrIn)
9844 .addImm(0)
9845 .addReg(Data)
9846 .add(predOps(ARMCC::AL));
9847 } else if (IsThumb1) {
9848 // store + update AddrIn
9849 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9850 .addReg(Data)
9851 .addReg(AddrIn)
9852 .addImm(0)
9853 .add(predOps(ARMCC::AL));
9854 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9855 .add(t1CondCodeOp())
9856 .addReg(AddrIn)
9857 .addImm(StSize)
9858 .add(predOps(ARMCC::AL));
9859 } else if (IsThumb2) {
9860 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9861 .addReg(Data)
9862 .addReg(AddrIn)
9863 .addImm(StSize)
9864 .add(predOps(ARMCC::AL));
9865 } else { // arm
9866 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9867 .addReg(Data)
9868 .addReg(AddrIn)
9869 .addReg(0)
9870 .addImm(StSize)
9871 .add(predOps(ARMCC::AL));
9875 MachineBasicBlock *
9876 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9877 MachineBasicBlock *BB) const {
9878 // This pseudo instruction has 3 operands: dst, src, size
9879 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9880 // Otherwise, we will generate unrolled scalar copies.
9881 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9882 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9883 MachineFunction::iterator It = ++BB->getIterator();
9885 Register dest = MI.getOperand(0).getReg();
9886 Register src = MI.getOperand(1).getReg();
9887 unsigned SizeVal = MI.getOperand(2).getImm();
9888 unsigned Align = MI.getOperand(3).getImm();
9889 DebugLoc dl = MI.getDebugLoc();
9891 MachineFunction *MF = BB->getParent();
9892 MachineRegisterInfo &MRI = MF->getRegInfo();
9893 unsigned UnitSize = 0;
9894 const TargetRegisterClass *TRC = nullptr;
9895 const TargetRegisterClass *VecTRC = nullptr;
9897 bool IsThumb1 = Subtarget->isThumb1Only();
9898 bool IsThumb2 = Subtarget->isThumb2();
9899 bool IsThumb = Subtarget->isThumb();
9901 if (Align & 1) {
9902 UnitSize = 1;
9903 } else if (Align & 2) {
9904 UnitSize = 2;
9905 } else {
9906 // Check whether we can use NEON instructions.
9907 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9908 Subtarget->hasNEON()) {
9909 if ((Align % 16 == 0) && SizeVal >= 16)
9910 UnitSize = 16;
9911 else if ((Align % 8 == 0) && SizeVal >= 8)
9912 UnitSize = 8;
9914 // Can't use NEON instructions.
9915 if (UnitSize == 0)
9916 UnitSize = 4;
9919 // Select the correct opcode and register class for unit size load/store
9920 bool IsNeon = UnitSize >= 8;
9921 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
9922 if (IsNeon)
9923 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
9924 : UnitSize == 8 ? &ARM::DPRRegClass
9925 : nullptr;
9927 unsigned BytesLeft = SizeVal % UnitSize;
9928 unsigned LoopSize = SizeVal - BytesLeft;
9930 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
9931 // Use LDR and STR to copy.
9932 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
9933 // [destOut] = STR_POST(scratch, destIn, UnitSize)
9934 unsigned srcIn = src;
9935 unsigned destIn = dest;
9936 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
9937 Register srcOut = MRI.createVirtualRegister(TRC);
9938 Register destOut = MRI.createVirtualRegister(TRC);
9939 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9940 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
9941 IsThumb1, IsThumb2);
9942 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
9943 IsThumb1, IsThumb2);
9944 srcIn = srcOut;
9945 destIn = destOut;
9948 // Handle the leftover bytes with LDRB and STRB.
9949 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
9950 // [destOut] = STRB_POST(scratch, destIn, 1)
9951 for (unsigned i = 0; i < BytesLeft; i++) {
9952 Register srcOut = MRI.createVirtualRegister(TRC);
9953 Register destOut = MRI.createVirtualRegister(TRC);
9954 Register scratch = MRI.createVirtualRegister(TRC);
9955 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
9956 IsThumb1, IsThumb2);
9957 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
9958 IsThumb1, IsThumb2);
9959 srcIn = srcOut;
9960 destIn = destOut;
9962 MI.eraseFromParent(); // The instruction is gone now.
9963 return BB;
9966 // Expand the pseudo op to a loop.
9967 // thisMBB:
9968 // ...
9969 // movw varEnd, # --> with thumb2
9970 // movt varEnd, #
9971 // ldrcp varEnd, idx --> without thumb2
9972 // fallthrough --> loopMBB
9973 // loopMBB:
9974 // PHI varPhi, varEnd, varLoop
9975 // PHI srcPhi, src, srcLoop
9976 // PHI destPhi, dst, destLoop
9977 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9978 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9979 // subs varLoop, varPhi, #UnitSize
9980 // bne loopMBB
9981 // fallthrough --> exitMBB
9982 // exitMBB:
9983 // epilogue to handle left-over bytes
9984 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9985 // [destOut] = STRB_POST(scratch, destLoop, 1)
9986 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9987 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9988 MF->insert(It, loopMBB);
9989 MF->insert(It, exitMBB);
9991 // Transfer the remainder of BB and its successor edges to exitMBB.
9992 exitMBB->splice(exitMBB->begin(), BB,
9993 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9994 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9996 // Load an immediate to varEnd.
9997 Register varEnd = MRI.createVirtualRegister(TRC);
9998 if (Subtarget->useMovt()) {
9999 unsigned Vtmp = varEnd;
10000 if ((LoopSize & 0xFFFF0000) != 0)
10001 Vtmp = MRI.createVirtualRegister(TRC);
10002 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10003 .addImm(LoopSize & 0xFFFF)
10004 .add(predOps(ARMCC::AL));
10006 if ((LoopSize & 0xFFFF0000) != 0)
10007 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10008 .addReg(Vtmp)
10009 .addImm(LoopSize >> 16)
10010 .add(predOps(ARMCC::AL));
10011 } else {
10012 MachineConstantPool *ConstantPool = MF->getConstantPool();
10013 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10014 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10016 // MachineConstantPool wants an explicit alignment.
10017 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
10018 if (Align == 0)
10019 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
10020 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
10021 MachineMemOperand *CPMMO =
10022 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10023 MachineMemOperand::MOLoad, 4, 4);
10025 if (IsThumb)
10026 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10027 .addReg(varEnd, RegState::Define)
10028 .addConstantPoolIndex(Idx)
10029 .add(predOps(ARMCC::AL))
10030 .addMemOperand(CPMMO);
10031 else
10032 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10033 .addReg(varEnd, RegState::Define)
10034 .addConstantPoolIndex(Idx)
10035 .addImm(0)
10036 .add(predOps(ARMCC::AL))
10037 .addMemOperand(CPMMO);
10039 BB->addSuccessor(loopMBB);
10041 // Generate the loop body:
10042 // varPhi = PHI(varLoop, varEnd)
10043 // srcPhi = PHI(srcLoop, src)
10044 // destPhi = PHI(destLoop, dst)
10045 MachineBasicBlock *entryBB = BB;
10046 BB = loopMBB;
10047 Register varLoop = MRI.createVirtualRegister(TRC);
10048 Register varPhi = MRI.createVirtualRegister(TRC);
10049 Register srcLoop = MRI.createVirtualRegister(TRC);
10050 Register srcPhi = MRI.createVirtualRegister(TRC);
10051 Register destLoop = MRI.createVirtualRegister(TRC);
10052 Register destPhi = MRI.createVirtualRegister(TRC);
10054 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10055 .addReg(varLoop).addMBB(loopMBB)
10056 .addReg(varEnd).addMBB(entryBB);
10057 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10058 .addReg(srcLoop).addMBB(loopMBB)
10059 .addReg(src).addMBB(entryBB);
10060 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10061 .addReg(destLoop).addMBB(loopMBB)
10062 .addReg(dest).addMBB(entryBB);
10064 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10065 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10066 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10067 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10068 IsThumb1, IsThumb2);
10069 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10070 IsThumb1, IsThumb2);
10072 // Decrement loop variable by UnitSize.
10073 if (IsThumb1) {
10074 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10075 .add(t1CondCodeOp())
10076 .addReg(varPhi)
10077 .addImm(UnitSize)
10078 .add(predOps(ARMCC::AL));
10079 } else {
10080 MachineInstrBuilder MIB =
10081 BuildMI(*BB, BB->end(), dl,
10082 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10083 MIB.addReg(varPhi)
10084 .addImm(UnitSize)
10085 .add(predOps(ARMCC::AL))
10086 .add(condCodeOp());
10087 MIB->getOperand(5).setReg(ARM::CPSR);
10088 MIB->getOperand(5).setIsDef(true);
10090 BuildMI(*BB, BB->end(), dl,
10091 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10092 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10094 // loopMBB can loop back to loopMBB or fall through to exitMBB.
10095 BB->addSuccessor(loopMBB);
10096 BB->addSuccessor(exitMBB);
10098 // Add epilogue to handle BytesLeft.
10099 BB = exitMBB;
10100 auto StartOfExit = exitMBB->begin();
10102 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10103 // [destOut] = STRB_POST(scratch, destLoop, 1)
10104 unsigned srcIn = srcLoop;
10105 unsigned destIn = destLoop;
10106 for (unsigned i = 0; i < BytesLeft; i++) {
10107 Register srcOut = MRI.createVirtualRegister(TRC);
10108 Register destOut = MRI.createVirtualRegister(TRC);
10109 Register scratch = MRI.createVirtualRegister(TRC);
10110 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10111 IsThumb1, IsThumb2);
10112 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10113 IsThumb1, IsThumb2);
10114 srcIn = srcOut;
10115 destIn = destOut;
10118 MI.eraseFromParent(); // The instruction is gone now.
10119 return BB;
10122 MachineBasicBlock *
10123 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10124 MachineBasicBlock *MBB) const {
10125 const TargetMachine &TM = getTargetMachine();
10126 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10127 DebugLoc DL = MI.getDebugLoc();
10129 assert(Subtarget->isTargetWindows() &&
10130 "__chkstk is only supported on Windows");
10131 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10133 // __chkstk takes the number of words to allocate on the stack in R4, and
10134 // returns the stack adjustment in number of bytes in R4. This will not
10135 // clober any other registers (other than the obvious lr).
10137 // Although, technically, IP should be considered a register which may be
10138 // clobbered, the call itself will not touch it. Windows on ARM is a pure
10139 // thumb-2 environment, so there is no interworking required. As a result, we
10140 // do not expect a veneer to be emitted by the linker, clobbering IP.
10142 // Each module receives its own copy of __chkstk, so no import thunk is
10143 // required, again, ensuring that IP is not clobbered.
10145 // Finally, although some linkers may theoretically provide a trampoline for
10146 // out of range calls (which is quite common due to a 32M range limitation of
10147 // branches for Thumb), we can generate the long-call version via
10148 // -mcmodel=large, alleviating the need for the trampoline which may clobber
10149 // IP.
10151 switch (TM.getCodeModel()) {
10152 case CodeModel::Tiny:
10153 llvm_unreachable("Tiny code model not available on ARM.");
10154 case CodeModel::Small:
10155 case CodeModel::Medium:
10156 case CodeModel::Kernel:
10157 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10158 .add(predOps(ARMCC::AL))
10159 .addExternalSymbol("__chkstk")
10160 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10161 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10162 .addReg(ARM::R12,
10163 RegState::Implicit | RegState::Define | RegState::Dead)
10164 .addReg(ARM::CPSR,
10165 RegState::Implicit | RegState::Define | RegState::Dead);
10166 break;
10167 case CodeModel::Large: {
10168 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10169 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10171 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10172 .addExternalSymbol("__chkstk");
10173 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10174 .add(predOps(ARMCC::AL))
10175 .addReg(Reg, RegState::Kill)
10176 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10177 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10178 .addReg(ARM::R12,
10179 RegState::Implicit | RegState::Define | RegState::Dead)
10180 .addReg(ARM::CPSR,
10181 RegState::Implicit | RegState::Define | RegState::Dead);
10182 break;
10186 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10187 .addReg(ARM::SP, RegState::Kill)
10188 .addReg(ARM::R4, RegState::Kill)
10189 .setMIFlags(MachineInstr::FrameSetup)
10190 .add(predOps(ARMCC::AL))
10191 .add(condCodeOp());
10193 MI.eraseFromParent();
10194 return MBB;
10197 MachineBasicBlock *
10198 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10199 MachineBasicBlock *MBB) const {
10200 DebugLoc DL = MI.getDebugLoc();
10201 MachineFunction *MF = MBB->getParent();
10202 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10204 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10205 MF->insert(++MBB->getIterator(), ContBB);
10206 ContBB->splice(ContBB->begin(), MBB,
10207 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10208 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10209 MBB->addSuccessor(ContBB);
10211 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10212 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10213 MF->push_back(TrapBB);
10214 MBB->addSuccessor(TrapBB);
10216 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10217 .addReg(MI.getOperand(0).getReg())
10218 .addImm(0)
10219 .add(predOps(ARMCC::AL));
10220 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10221 .addMBB(TrapBB)
10222 .addImm(ARMCC::EQ)
10223 .addReg(ARM::CPSR);
10225 MI.eraseFromParent();
10226 return ContBB;
10229 // The CPSR operand of SelectItr might be missing a kill marker
10230 // because there were multiple uses of CPSR, and ISel didn't know
10231 // which to mark. Figure out whether SelectItr should have had a
10232 // kill marker, and set it if it should. Returns the correct kill
10233 // marker value.
10234 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10235 MachineBasicBlock* BB,
10236 const TargetRegisterInfo* TRI) {
10237 // Scan forward through BB for a use/def of CPSR.
10238 MachineBasicBlock::iterator miI(std::next(SelectItr));
10239 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10240 const MachineInstr& mi = *miI;
10241 if (mi.readsRegister(ARM::CPSR))
10242 return false;
10243 if (mi.definesRegister(ARM::CPSR))
10244 break; // Should have kill-flag - update below.
10247 // If we hit the end of the block, check whether CPSR is live into a
10248 // successor.
10249 if (miI == BB->end()) {
10250 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10251 sEnd = BB->succ_end();
10252 sItr != sEnd; ++sItr) {
10253 MachineBasicBlock* succ = *sItr;
10254 if (succ->isLiveIn(ARM::CPSR))
10255 return false;
10259 // We found a def, or hit the end of the basic block and CPSR wasn't live
10260 // out. SelectMI should have a kill flag on CPSR.
10261 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10262 return true;
10265 MachineBasicBlock *
10266 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10267 MachineBasicBlock *BB) const {
10268 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10269 DebugLoc dl = MI.getDebugLoc();
10270 bool isThumb2 = Subtarget->isThumb2();
10271 switch (MI.getOpcode()) {
10272 default: {
10273 MI.print(errs());
10274 llvm_unreachable("Unexpected instr type to insert");
10277 // Thumb1 post-indexed loads are really just single-register LDMs.
10278 case ARM::tLDR_postidx: {
10279 MachineOperand Def(MI.getOperand(1));
10280 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10281 .add(Def) // Rn_wb
10282 .add(MI.getOperand(2)) // Rn
10283 .add(MI.getOperand(3)) // PredImm
10284 .add(MI.getOperand(4)) // PredReg
10285 .add(MI.getOperand(0)) // Rt
10286 .cloneMemRefs(MI);
10287 MI.eraseFromParent();
10288 return BB;
10291 // The Thumb2 pre-indexed stores have the same MI operands, they just
10292 // define them differently in the .td files from the isel patterns, so
10293 // they need pseudos.
10294 case ARM::t2STR_preidx:
10295 MI.setDesc(TII->get(ARM::t2STR_PRE));
10296 return BB;
10297 case ARM::t2STRB_preidx:
10298 MI.setDesc(TII->get(ARM::t2STRB_PRE));
10299 return BB;
10300 case ARM::t2STRH_preidx:
10301 MI.setDesc(TII->get(ARM::t2STRH_PRE));
10302 return BB;
10304 case ARM::STRi_preidx:
10305 case ARM::STRBi_preidx: {
10306 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10307 : ARM::STRB_PRE_IMM;
10308 // Decode the offset.
10309 unsigned Offset = MI.getOperand(4).getImm();
10310 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10311 Offset = ARM_AM::getAM2Offset(Offset);
10312 if (isSub)
10313 Offset = -Offset;
10315 MachineMemOperand *MMO = *MI.memoperands_begin();
10316 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10317 .add(MI.getOperand(0)) // Rn_wb
10318 .add(MI.getOperand(1)) // Rt
10319 .add(MI.getOperand(2)) // Rn
10320 .addImm(Offset) // offset (skip GPR==zero_reg)
10321 .add(MI.getOperand(5)) // pred
10322 .add(MI.getOperand(6))
10323 .addMemOperand(MMO);
10324 MI.eraseFromParent();
10325 return BB;
10327 case ARM::STRr_preidx:
10328 case ARM::STRBr_preidx:
10329 case ARM::STRH_preidx: {
10330 unsigned NewOpc;
10331 switch (MI.getOpcode()) {
10332 default: llvm_unreachable("unexpected opcode!");
10333 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10334 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10335 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10337 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10338 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10339 MIB.add(MI.getOperand(i));
10340 MI.eraseFromParent();
10341 return BB;
10344 case ARM::tMOVCCr_pseudo: {
10345 // To "insert" a SELECT_CC instruction, we actually have to insert the
10346 // diamond control-flow pattern. The incoming instruction knows the
10347 // destination vreg to set, the condition code register to branch on, the
10348 // true/false values to select between, and a branch opcode to use.
10349 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10350 MachineFunction::iterator It = ++BB->getIterator();
10352 // thisMBB:
10353 // ...
10354 // TrueVal = ...
10355 // cmpTY ccX, r1, r2
10356 // bCC copy1MBB
10357 // fallthrough --> copy0MBB
10358 MachineBasicBlock *thisMBB = BB;
10359 MachineFunction *F = BB->getParent();
10360 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10361 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10362 F->insert(It, copy0MBB);
10363 F->insert(It, sinkMBB);
10365 // Check whether CPSR is live past the tMOVCCr_pseudo.
10366 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10367 if (!MI.killsRegister(ARM::CPSR) &&
10368 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10369 copy0MBB->addLiveIn(ARM::CPSR);
10370 sinkMBB->addLiveIn(ARM::CPSR);
10373 // Transfer the remainder of BB and its successor edges to sinkMBB.
10374 sinkMBB->splice(sinkMBB->begin(), BB,
10375 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10376 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10378 BB->addSuccessor(copy0MBB);
10379 BB->addSuccessor(sinkMBB);
10381 BuildMI(BB, dl, TII->get(ARM::tBcc))
10382 .addMBB(sinkMBB)
10383 .addImm(MI.getOperand(3).getImm())
10384 .addReg(MI.getOperand(4).getReg());
10386 // copy0MBB:
10387 // %FalseValue = ...
10388 // # fallthrough to sinkMBB
10389 BB = copy0MBB;
10391 // Update machine-CFG edges
10392 BB->addSuccessor(sinkMBB);
10394 // sinkMBB:
10395 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10396 // ...
10397 BB = sinkMBB;
10398 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10399 .addReg(MI.getOperand(1).getReg())
10400 .addMBB(copy0MBB)
10401 .addReg(MI.getOperand(2).getReg())
10402 .addMBB(thisMBB);
10404 MI.eraseFromParent(); // The pseudo instruction is gone now.
10405 return BB;
10408 case ARM::BCCi64:
10409 case ARM::BCCZi64: {
10410 // If there is an unconditional branch to the other successor, remove it.
10411 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10413 // Compare both parts that make up the double comparison separately for
10414 // equality.
10415 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10417 Register LHS1 = MI.getOperand(1).getReg();
10418 Register LHS2 = MI.getOperand(2).getReg();
10419 if (RHSisZero) {
10420 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10421 .addReg(LHS1)
10422 .addImm(0)
10423 .add(predOps(ARMCC::AL));
10424 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10425 .addReg(LHS2).addImm(0)
10426 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10427 } else {
10428 Register RHS1 = MI.getOperand(3).getReg();
10429 Register RHS2 = MI.getOperand(4).getReg();
10430 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10431 .addReg(LHS1)
10432 .addReg(RHS1)
10433 .add(predOps(ARMCC::AL));
10434 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10435 .addReg(LHS2).addReg(RHS2)
10436 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10439 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10440 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10441 if (MI.getOperand(0).getImm() == ARMCC::NE)
10442 std::swap(destMBB, exitMBB);
10444 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10445 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10446 if (isThumb2)
10447 BuildMI(BB, dl, TII->get(ARM::t2B))
10448 .addMBB(exitMBB)
10449 .add(predOps(ARMCC::AL));
10450 else
10451 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10453 MI.eraseFromParent(); // The pseudo instruction is gone now.
10454 return BB;
10457 case ARM::Int_eh_sjlj_setjmp:
10458 case ARM::Int_eh_sjlj_setjmp_nofp:
10459 case ARM::tInt_eh_sjlj_setjmp:
10460 case ARM::t2Int_eh_sjlj_setjmp:
10461 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10462 return BB;
10464 case ARM::Int_eh_sjlj_setup_dispatch:
10465 EmitSjLjDispatchBlock(MI, BB);
10466 return BB;
10468 case ARM::ABS:
10469 case ARM::t2ABS: {
10470 // To insert an ABS instruction, we have to insert the
10471 // diamond control-flow pattern. The incoming instruction knows the
10472 // source vreg to test against 0, the destination vreg to set,
10473 // the condition code register to branch on, the
10474 // true/false values to select between, and a branch opcode to use.
10475 // It transforms
10476 // V1 = ABS V0
10477 // into
10478 // V2 = MOVS V0
10479 // BCC (branch to SinkBB if V0 >= 0)
10480 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10481 // SinkBB: V1 = PHI(V2, V3)
10482 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10483 MachineFunction::iterator BBI = ++BB->getIterator();
10484 MachineFunction *Fn = BB->getParent();
10485 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10486 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10487 Fn->insert(BBI, RSBBB);
10488 Fn->insert(BBI, SinkBB);
10490 Register ABSSrcReg = MI.getOperand(1).getReg();
10491 Register ABSDstReg = MI.getOperand(0).getReg();
10492 bool ABSSrcKIll = MI.getOperand(1).isKill();
10493 bool isThumb2 = Subtarget->isThumb2();
10494 MachineRegisterInfo &MRI = Fn->getRegInfo();
10495 // In Thumb mode S must not be specified if source register is the SP or
10496 // PC and if destination register is the SP, so restrict register class
10497 Register NewRsbDstReg = MRI.createVirtualRegister(
10498 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10500 // Transfer the remainder of BB and its successor edges to sinkMBB.
10501 SinkBB->splice(SinkBB->begin(), BB,
10502 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10503 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10505 BB->addSuccessor(RSBBB);
10506 BB->addSuccessor(SinkBB);
10508 // fall through to SinkMBB
10509 RSBBB->addSuccessor(SinkBB);
10511 // insert a cmp at the end of BB
10512 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10513 .addReg(ABSSrcReg)
10514 .addImm(0)
10515 .add(predOps(ARMCC::AL));
10517 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10518 BuildMI(BB, dl,
10519 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10520 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10522 // insert rsbri in RSBBB
10523 // Note: BCC and rsbri will be converted into predicated rsbmi
10524 // by if-conversion pass
10525 BuildMI(*RSBBB, RSBBB->begin(), dl,
10526 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10527 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10528 .addImm(0)
10529 .add(predOps(ARMCC::AL))
10530 .add(condCodeOp());
10532 // insert PHI in SinkBB,
10533 // reuse ABSDstReg to not change uses of ABS instruction
10534 BuildMI(*SinkBB, SinkBB->begin(), dl,
10535 TII->get(ARM::PHI), ABSDstReg)
10536 .addReg(NewRsbDstReg).addMBB(RSBBB)
10537 .addReg(ABSSrcReg).addMBB(BB);
10539 // remove ABS instruction
10540 MI.eraseFromParent();
10542 // return last added BB
10543 return SinkBB;
10545 case ARM::COPY_STRUCT_BYVAL_I32:
10546 ++NumLoopByVals;
10547 return EmitStructByval(MI, BB);
10548 case ARM::WIN__CHKSTK:
10549 return EmitLowered__chkstk(MI, BB);
10550 case ARM::WIN__DBZCHK:
10551 return EmitLowered__dbzchk(MI, BB);
10555 /// Attaches vregs to MEMCPY that it will use as scratch registers
10556 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10557 /// instead of as a custom inserter because we need the use list from the SDNode.
10558 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10559 MachineInstr &MI, const SDNode *Node) {
10560 bool isThumb1 = Subtarget->isThumb1Only();
10562 DebugLoc DL = MI.getDebugLoc();
10563 MachineFunction *MF = MI.getParent()->getParent();
10564 MachineRegisterInfo &MRI = MF->getRegInfo();
10565 MachineInstrBuilder MIB(*MF, MI);
10567 // If the new dst/src is unused mark it as dead.
10568 if (!Node->hasAnyUseOfValue(0)) {
10569 MI.getOperand(0).setIsDead(true);
10571 if (!Node->hasAnyUseOfValue(1)) {
10572 MI.getOperand(1).setIsDead(true);
10575 // The MEMCPY both defines and kills the scratch registers.
10576 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10577 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10578 : &ARM::GPRRegClass);
10579 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10583 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10584 SDNode *Node) const {
10585 if (MI.getOpcode() == ARM::MEMCPY) {
10586 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10587 return;
10590 const MCInstrDesc *MCID = &MI.getDesc();
10591 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10592 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10593 // operand is still set to noreg. If needed, set the optional operand's
10594 // register to CPSR, and remove the redundant implicit def.
10596 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10598 // Rename pseudo opcodes.
10599 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10600 unsigned ccOutIdx;
10601 if (NewOpc) {
10602 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10603 MCID = &TII->get(NewOpc);
10605 assert(MCID->getNumOperands() ==
10606 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10607 && "converted opcode should be the same except for cc_out"
10608 " (and, on Thumb1, pred)");
10610 MI.setDesc(*MCID);
10612 // Add the optional cc_out operand
10613 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10615 // On Thumb1, move all input operands to the end, then add the predicate
10616 if (Subtarget->isThumb1Only()) {
10617 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10618 MI.addOperand(MI.getOperand(1));
10619 MI.RemoveOperand(1);
10622 // Restore the ties
10623 for (unsigned i = MI.getNumOperands(); i--;) {
10624 const MachineOperand& op = MI.getOperand(i);
10625 if (op.isReg() && op.isUse()) {
10626 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10627 if (DefIdx != -1)
10628 MI.tieOperands(DefIdx, i);
10632 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10633 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10634 ccOutIdx = 1;
10635 } else
10636 ccOutIdx = MCID->getNumOperands() - 1;
10637 } else
10638 ccOutIdx = MCID->getNumOperands() - 1;
10640 // Any ARM instruction that sets the 's' bit should specify an optional
10641 // "cc_out" operand in the last operand position.
10642 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10643 assert(!NewOpc && "Optional cc_out operand required");
10644 return;
10646 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10647 // since we already have an optional CPSR def.
10648 bool definesCPSR = false;
10649 bool deadCPSR = false;
10650 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10651 ++i) {
10652 const MachineOperand &MO = MI.getOperand(i);
10653 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10654 definesCPSR = true;
10655 if (MO.isDead())
10656 deadCPSR = true;
10657 MI.RemoveOperand(i);
10658 break;
10661 if (!definesCPSR) {
10662 assert(!NewOpc && "Optional cc_out operand required");
10663 return;
10665 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10666 if (deadCPSR) {
10667 assert(!MI.getOperand(ccOutIdx).getReg() &&
10668 "expect uninitialized optional cc_out operand");
10669 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10670 if (!Subtarget->isThumb1Only())
10671 return;
10674 // If this instruction was defined with an optional CPSR def and its dag node
10675 // had a live implicit CPSR def, then activate the optional CPSR def.
10676 MachineOperand &MO = MI.getOperand(ccOutIdx);
10677 MO.setReg(ARM::CPSR);
10678 MO.setIsDef(true);
10681 //===----------------------------------------------------------------------===//
10682 // ARM Optimization Hooks
10683 //===----------------------------------------------------------------------===//
10685 // Helper function that checks if N is a null or all ones constant.
10686 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10687 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10690 // Return true if N is conditionally 0 or all ones.
10691 // Detects these expressions where cc is an i1 value:
10693 // (select cc 0, y) [AllOnes=0]
10694 // (select cc y, 0) [AllOnes=0]
10695 // (zext cc) [AllOnes=0]
10696 // (sext cc) [AllOnes=0/1]
10697 // (select cc -1, y) [AllOnes=1]
10698 // (select cc y, -1) [AllOnes=1]
10700 // Invert is set when N is the null/all ones constant when CC is false.
10701 // OtherOp is set to the alternative value of N.
10702 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10703 SDValue &CC, bool &Invert,
10704 SDValue &OtherOp,
10705 SelectionDAG &DAG) {
10706 switch (N->getOpcode()) {
10707 default: return false;
10708 case ISD::SELECT: {
10709 CC = N->getOperand(0);
10710 SDValue N1 = N->getOperand(1);
10711 SDValue N2 = N->getOperand(2);
10712 if (isZeroOrAllOnes(N1, AllOnes)) {
10713 Invert = false;
10714 OtherOp = N2;
10715 return true;
10717 if (isZeroOrAllOnes(N2, AllOnes)) {
10718 Invert = true;
10719 OtherOp = N1;
10720 return true;
10722 return false;
10724 case ISD::ZERO_EXTEND:
10725 // (zext cc) can never be the all ones value.
10726 if (AllOnes)
10727 return false;
10728 LLVM_FALLTHROUGH;
10729 case ISD::SIGN_EXTEND: {
10730 SDLoc dl(N);
10731 EVT VT = N->getValueType(0);
10732 CC = N->getOperand(0);
10733 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10734 return false;
10735 Invert = !AllOnes;
10736 if (AllOnes)
10737 // When looking for an AllOnes constant, N is an sext, and the 'other'
10738 // value is 0.
10739 OtherOp = DAG.getConstant(0, dl, VT);
10740 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10741 // When looking for a 0 constant, N can be zext or sext.
10742 OtherOp = DAG.getConstant(1, dl, VT);
10743 else
10744 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10745 VT);
10746 return true;
10751 // Combine a constant select operand into its use:
10753 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10754 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10755 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10756 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10757 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10759 // The transform is rejected if the select doesn't have a constant operand that
10760 // is null, or all ones when AllOnes is set.
10762 // Also recognize sext/zext from i1:
10764 // (add (zext cc), x) -> (select cc (add x, 1), x)
10765 // (add (sext cc), x) -> (select cc (add x, -1), x)
10767 // These transformations eventually create predicated instructions.
10769 // @param N The node to transform.
10770 // @param Slct The N operand that is a select.
10771 // @param OtherOp The other N operand (x above).
10772 // @param DCI Context.
10773 // @param AllOnes Require the select constant to be all ones instead of null.
10774 // @returns The new node, or SDValue() on failure.
10775 static
10776 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10777 TargetLowering::DAGCombinerInfo &DCI,
10778 bool AllOnes = false) {
10779 SelectionDAG &DAG = DCI.DAG;
10780 EVT VT = N->getValueType(0);
10781 SDValue NonConstantVal;
10782 SDValue CCOp;
10783 bool SwapSelectOps;
10784 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10785 NonConstantVal, DAG))
10786 return SDValue();
10788 // Slct is now know to be the desired identity constant when CC is true.
10789 SDValue TrueVal = OtherOp;
10790 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10791 OtherOp, NonConstantVal);
10792 // Unless SwapSelectOps says CC should be false.
10793 if (SwapSelectOps)
10794 std::swap(TrueVal, FalseVal);
10796 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10797 CCOp, TrueVal, FalseVal);
10800 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10801 static
10802 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10803 TargetLowering::DAGCombinerInfo &DCI) {
10804 SDValue N0 = N->getOperand(0);
10805 SDValue N1 = N->getOperand(1);
10806 if (N0.getNode()->hasOneUse())
10807 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10808 return Result;
10809 if (N1.getNode()->hasOneUse())
10810 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10811 return Result;
10812 return SDValue();
10815 static bool IsVUZPShuffleNode(SDNode *N) {
10816 // VUZP shuffle node.
10817 if (N->getOpcode() == ARMISD::VUZP)
10818 return true;
10820 // "VUZP" on i32 is an alias for VTRN.
10821 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10822 return true;
10824 return false;
10827 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10828 TargetLowering::DAGCombinerInfo &DCI,
10829 const ARMSubtarget *Subtarget) {
10830 // Look for ADD(VUZP.0, VUZP.1).
10831 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10832 N0 == N1)
10833 return SDValue();
10835 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10836 if (!N->getValueType(0).is64BitVector())
10837 return SDValue();
10839 // Generate vpadd.
10840 SelectionDAG &DAG = DCI.DAG;
10841 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10842 SDLoc dl(N);
10843 SDNode *Unzip = N0.getNode();
10844 EVT VT = N->getValueType(0);
10846 SmallVector<SDValue, 8> Ops;
10847 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10848 TLI.getPointerTy(DAG.getDataLayout())));
10849 Ops.push_back(Unzip->getOperand(0));
10850 Ops.push_back(Unzip->getOperand(1));
10852 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10855 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10856 TargetLowering::DAGCombinerInfo &DCI,
10857 const ARMSubtarget *Subtarget) {
10858 // Check for two extended operands.
10859 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10860 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10861 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10862 N1.getOpcode() == ISD::ZERO_EXTEND))
10863 return SDValue();
10865 SDValue N00 = N0.getOperand(0);
10866 SDValue N10 = N1.getOperand(0);
10868 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10869 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10870 N00 == N10)
10871 return SDValue();
10873 // We only recognize Q register paddl here; this can't be reached until
10874 // after type legalization.
10875 if (!N00.getValueType().is64BitVector() ||
10876 !N0.getValueType().is128BitVector())
10877 return SDValue();
10879 // Generate vpaddl.
10880 SelectionDAG &DAG = DCI.DAG;
10881 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10882 SDLoc dl(N);
10883 EVT VT = N->getValueType(0);
10885 SmallVector<SDValue, 8> Ops;
10886 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10887 unsigned Opcode;
10888 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10889 Opcode = Intrinsic::arm_neon_vpaddls;
10890 else
10891 Opcode = Intrinsic::arm_neon_vpaddlu;
10892 Ops.push_back(DAG.getConstant(Opcode, dl,
10893 TLI.getPointerTy(DAG.getDataLayout())));
10894 EVT ElemTy = N00.getValueType().getVectorElementType();
10895 unsigned NumElts = VT.getVectorNumElements();
10896 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10897 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10898 N00.getOperand(0), N00.getOperand(1));
10899 Ops.push_back(Concat);
10901 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10904 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10905 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10906 // much easier to match.
10907 static SDValue
10908 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10909 TargetLowering::DAGCombinerInfo &DCI,
10910 const ARMSubtarget *Subtarget) {
10911 // Only perform optimization if after legalize, and if NEON is available. We
10912 // also expected both operands to be BUILD_VECTORs.
10913 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10914 || N0.getOpcode() != ISD::BUILD_VECTOR
10915 || N1.getOpcode() != ISD::BUILD_VECTOR)
10916 return SDValue();
10918 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10919 EVT VT = N->getValueType(0);
10920 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10921 return SDValue();
10923 // Check that the vector operands are of the right form.
10924 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
10925 // operands, where N is the size of the formed vector.
10926 // Each EXTRACT_VECTOR should have the same input vector and odd or even
10927 // index such that we have a pair wise add pattern.
10929 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
10930 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10931 return SDValue();
10932 SDValue Vec = N0->getOperand(0)->getOperand(0);
10933 SDNode *V = Vec.getNode();
10934 unsigned nextIndex = 0;
10936 // For each operands to the ADD which are BUILD_VECTORs,
10937 // check to see if each of their operands are an EXTRACT_VECTOR with
10938 // the same vector and appropriate index.
10939 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
10940 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
10941 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10943 SDValue ExtVec0 = N0->getOperand(i);
10944 SDValue ExtVec1 = N1->getOperand(i);
10946 // First operand is the vector, verify its the same.
10947 if (V != ExtVec0->getOperand(0).getNode() ||
10948 V != ExtVec1->getOperand(0).getNode())
10949 return SDValue();
10951 // Second is the constant, verify its correct.
10952 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
10953 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
10955 // For the constant, we want to see all the even or all the odd.
10956 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
10957 || C1->getZExtValue() != nextIndex+1)
10958 return SDValue();
10960 // Increment index.
10961 nextIndex+=2;
10962 } else
10963 return SDValue();
10966 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
10967 // we're using the entire input vector, otherwise there's a size/legality
10968 // mismatch somewhere.
10969 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10970 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10971 return SDValue();
10973 // Create VPADDL node.
10974 SelectionDAG &DAG = DCI.DAG;
10975 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10977 SDLoc dl(N);
10979 // Build operand list.
10980 SmallVector<SDValue, 8> Ops;
10981 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10982 TLI.getPointerTy(DAG.getDataLayout())));
10984 // Input is the vector.
10985 Ops.push_back(Vec);
10987 // Get widened type and narrowed type.
10988 MVT widenType;
10989 unsigned numElem = VT.getVectorNumElements();
10991 EVT inputLaneType = Vec.getValueType().getVectorElementType();
10992 switch (inputLaneType.getSimpleVT().SimpleTy) {
10993 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10994 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10995 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10996 default:
10997 llvm_unreachable("Invalid vector element type for padd optimization.");
11000 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11001 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11002 return DAG.getNode(ExtOp, dl, VT, tmp);
11005 static SDValue findMUL_LOHI(SDValue V) {
11006 if (V->getOpcode() == ISD::UMUL_LOHI ||
11007 V->getOpcode() == ISD::SMUL_LOHI)
11008 return V;
11009 return SDValue();
11012 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11013 TargetLowering::DAGCombinerInfo &DCI,
11014 const ARMSubtarget *Subtarget) {
11015 if (Subtarget->isThumb()) {
11016 if (!Subtarget->hasDSP())
11017 return SDValue();
11018 } else if (!Subtarget->hasV5TEOps())
11019 return SDValue();
11021 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11022 // accumulates the product into a 64-bit value. The 16-bit values will
11023 // be sign extended somehow or SRA'd into 32-bit values
11024 // (addc (adde (mul 16bit, 16bit), lo), hi)
11025 SDValue Mul = AddcNode->getOperand(0);
11026 SDValue Lo = AddcNode->getOperand(1);
11027 if (Mul.getOpcode() != ISD::MUL) {
11028 Lo = AddcNode->getOperand(0);
11029 Mul = AddcNode->getOperand(1);
11030 if (Mul.getOpcode() != ISD::MUL)
11031 return SDValue();
11034 SDValue SRA = AddeNode->getOperand(0);
11035 SDValue Hi = AddeNode->getOperand(1);
11036 if (SRA.getOpcode() != ISD::SRA) {
11037 SRA = AddeNode->getOperand(1);
11038 Hi = AddeNode->getOperand(0);
11039 if (SRA.getOpcode() != ISD::SRA)
11040 return SDValue();
11042 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11043 if (Const->getZExtValue() != 31)
11044 return SDValue();
11045 } else
11046 return SDValue();
11048 if (SRA.getOperand(0) != Mul)
11049 return SDValue();
11051 SelectionDAG &DAG = DCI.DAG;
11052 SDLoc dl(AddcNode);
11053 unsigned Opcode = 0;
11054 SDValue Op0;
11055 SDValue Op1;
11057 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11058 Opcode = ARMISD::SMLALBB;
11059 Op0 = Mul.getOperand(0);
11060 Op1 = Mul.getOperand(1);
11061 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11062 Opcode = ARMISD::SMLALBT;
11063 Op0 = Mul.getOperand(0);
11064 Op1 = Mul.getOperand(1).getOperand(0);
11065 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11066 Opcode = ARMISD::SMLALTB;
11067 Op0 = Mul.getOperand(0).getOperand(0);
11068 Op1 = Mul.getOperand(1);
11069 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11070 Opcode = ARMISD::SMLALTT;
11071 Op0 = Mul->getOperand(0).getOperand(0);
11072 Op1 = Mul->getOperand(1).getOperand(0);
11075 if (!Op0 || !Op1)
11076 return SDValue();
11078 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11079 Op0, Op1, Lo, Hi);
11080 // Replace the ADDs' nodes uses by the MLA node's values.
11081 SDValue HiMLALResult(SMLAL.getNode(), 1);
11082 SDValue LoMLALResult(SMLAL.getNode(), 0);
11084 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11085 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11087 // Return original node to notify the driver to stop replacing.
11088 SDValue resNode(AddcNode, 0);
11089 return resNode;
11092 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11093 TargetLowering::DAGCombinerInfo &DCI,
11094 const ARMSubtarget *Subtarget) {
11095 // Look for multiply add opportunities.
11096 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11097 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11098 // a glue link from the first add to the second add.
11099 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11100 // a S/UMLAL instruction.
11101 // UMUL_LOHI
11102 // / :lo \ :hi
11103 // V \ [no multiline comment]
11104 // loAdd -> ADDC |
11105 // \ :carry /
11106 // V V
11107 // ADDE <- hiAdd
11109 // In the special case where only the higher part of a signed result is used
11110 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11111 // a constant with the exact value of 0x80000000, we recognize we are dealing
11112 // with a "rounded multiply and add" (or subtract) and transform it into
11113 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11115 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11116 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11117 "Expect an ADDE or SUBE");
11119 assert(AddeSubeNode->getNumOperands() == 3 &&
11120 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11121 "ADDE node has the wrong inputs");
11123 // Check that we are chained to the right ADDC or SUBC node.
11124 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11125 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11126 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11127 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11128 AddcSubcNode->getOpcode() != ARMISD::SUBC))
11129 return SDValue();
11131 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11132 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11134 // Check if the two operands are from the same mul_lohi node.
11135 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11136 return SDValue();
11138 assert(AddcSubcNode->getNumValues() == 2 &&
11139 AddcSubcNode->getValueType(0) == MVT::i32 &&
11140 "Expect ADDC with two result values. First: i32");
11142 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11143 // maybe a SMLAL which multiplies two 16-bit values.
11144 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11145 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11146 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11147 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11148 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11149 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11151 // Check for the triangle shape.
11152 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11153 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11155 // Make sure that the ADDE/SUBE operands are not coming from the same node.
11156 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11157 return SDValue();
11159 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11160 bool IsLeftOperandMUL = false;
11161 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11162 if (MULOp == SDValue())
11163 MULOp = findMUL_LOHI(AddeSubeOp1);
11164 else
11165 IsLeftOperandMUL = true;
11166 if (MULOp == SDValue())
11167 return SDValue();
11169 // Figure out the right opcode.
11170 unsigned Opc = MULOp->getOpcode();
11171 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11173 // Figure out the high and low input values to the MLAL node.
11174 SDValue *HiAddSub = nullptr;
11175 SDValue *LoMul = nullptr;
11176 SDValue *LowAddSub = nullptr;
11178 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11179 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11180 return SDValue();
11182 if (IsLeftOperandMUL)
11183 HiAddSub = &AddeSubeOp1;
11184 else
11185 HiAddSub = &AddeSubeOp0;
11187 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11188 // whose low result is fed to the ADDC/SUBC we are checking.
11190 if (AddcSubcOp0 == MULOp.getValue(0)) {
11191 LoMul = &AddcSubcOp0;
11192 LowAddSub = &AddcSubcOp1;
11194 if (AddcSubcOp1 == MULOp.getValue(0)) {
11195 LoMul = &AddcSubcOp1;
11196 LowAddSub = &AddcSubcOp0;
11199 if (!LoMul)
11200 return SDValue();
11202 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11203 // the replacement below will create a cycle.
11204 if (AddcSubcNode == HiAddSub->getNode() ||
11205 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11206 return SDValue();
11208 // Create the merged node.
11209 SelectionDAG &DAG = DCI.DAG;
11211 // Start building operand list.
11212 SmallVector<SDValue, 8> Ops;
11213 Ops.push_back(LoMul->getOperand(0));
11214 Ops.push_back(LoMul->getOperand(1));
11216 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
11217 // the case, we must be doing signed multiplication and only use the higher
11218 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11219 // addition or subtraction with the value of 0x800000.
11220 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11221 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11222 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11223 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11224 0x80000000) {
11225 Ops.push_back(*HiAddSub);
11226 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11227 FinalOpc = ARMISD::SMMLSR;
11228 } else {
11229 FinalOpc = ARMISD::SMMLAR;
11231 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11232 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11234 return SDValue(AddeSubeNode, 0);
11235 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11236 // SMMLS is generated during instruction selection and the rest of this
11237 // function can not handle the case where AddcSubcNode is a SUBC.
11238 return SDValue();
11240 // Finish building the operand list for {U/S}MLAL
11241 Ops.push_back(*LowAddSub);
11242 Ops.push_back(*HiAddSub);
11244 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11245 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11247 // Replace the ADDs' nodes uses by the MLA node's values.
11248 SDValue HiMLALResult(MLALNode.getNode(), 1);
11249 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11251 SDValue LoMLALResult(MLALNode.getNode(), 0);
11252 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11254 // Return original node to notify the driver to stop replacing.
11255 return SDValue(AddeSubeNode, 0);
11258 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11259 TargetLowering::DAGCombinerInfo &DCI,
11260 const ARMSubtarget *Subtarget) {
11261 // UMAAL is similar to UMLAL except that it adds two unsigned values.
11262 // While trying to combine for the other MLAL nodes, first search for the
11263 // chance to use UMAAL. Check if Addc uses a node which has already
11264 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11265 // as the addend, and it's handled in PerformUMLALCombine.
11267 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11268 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11270 // Check that we have a glued ADDC node.
11271 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11272 if (AddcNode->getOpcode() != ARMISD::ADDC)
11273 return SDValue();
11275 // Find the converted UMAAL or quit if it doesn't exist.
11276 SDNode *UmlalNode = nullptr;
11277 SDValue AddHi;
11278 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11279 UmlalNode = AddcNode->getOperand(0).getNode();
11280 AddHi = AddcNode->getOperand(1);
11281 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11282 UmlalNode = AddcNode->getOperand(1).getNode();
11283 AddHi = AddcNode->getOperand(0);
11284 } else {
11285 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11288 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11289 // the ADDC as well as Zero.
11290 if (!isNullConstant(UmlalNode->getOperand(3)))
11291 return SDValue();
11293 if ((isNullConstant(AddeNode->getOperand(0)) &&
11294 AddeNode->getOperand(1).getNode() == UmlalNode) ||
11295 (AddeNode->getOperand(0).getNode() == UmlalNode &&
11296 isNullConstant(AddeNode->getOperand(1)))) {
11297 SelectionDAG &DAG = DCI.DAG;
11298 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11299 UmlalNode->getOperand(2), AddHi };
11300 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11301 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11303 // Replace the ADDs' nodes uses by the UMAAL node's values.
11304 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11305 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11307 // Return original node to notify the driver to stop replacing.
11308 return SDValue(AddeNode, 0);
11310 return SDValue();
11313 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11314 const ARMSubtarget *Subtarget) {
11315 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11316 return SDValue();
11318 // Check that we have a pair of ADDC and ADDE as operands.
11319 // Both addends of the ADDE must be zero.
11320 SDNode* AddcNode = N->getOperand(2).getNode();
11321 SDNode* AddeNode = N->getOperand(3).getNode();
11322 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11323 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11324 isNullConstant(AddeNode->getOperand(0)) &&
11325 isNullConstant(AddeNode->getOperand(1)) &&
11326 (AddeNode->getOperand(2).getNode() == AddcNode))
11327 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11328 DAG.getVTList(MVT::i32, MVT::i32),
11329 {N->getOperand(0), N->getOperand(1),
11330 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11331 else
11332 return SDValue();
11335 static SDValue PerformAddcSubcCombine(SDNode *N,
11336 TargetLowering::DAGCombinerInfo &DCI,
11337 const ARMSubtarget *Subtarget) {
11338 SelectionDAG &DAG(DCI.DAG);
11340 if (N->getOpcode() == ARMISD::SUBC) {
11341 // (SUBC (ADDE 0, 0, C), 1) -> C
11342 SDValue LHS = N->getOperand(0);
11343 SDValue RHS = N->getOperand(1);
11344 if (LHS->getOpcode() == ARMISD::ADDE &&
11345 isNullConstant(LHS->getOperand(0)) &&
11346 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11347 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11351 if (Subtarget->isThumb1Only()) {
11352 SDValue RHS = N->getOperand(1);
11353 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11354 int32_t imm = C->getSExtValue();
11355 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11356 SDLoc DL(N);
11357 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11358 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11359 : ARMISD::ADDC;
11360 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11365 return SDValue();
11368 static SDValue PerformAddeSubeCombine(SDNode *N,
11369 TargetLowering::DAGCombinerInfo &DCI,
11370 const ARMSubtarget *Subtarget) {
11371 if (Subtarget->isThumb1Only()) {
11372 SelectionDAG &DAG = DCI.DAG;
11373 SDValue RHS = N->getOperand(1);
11374 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11375 int64_t imm = C->getSExtValue();
11376 if (imm < 0) {
11377 SDLoc DL(N);
11379 // The with-carry-in form matches bitwise not instead of the negation.
11380 // Effectively, the inverse interpretation of the carry flag already
11381 // accounts for part of the negation.
11382 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11384 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11385 : ARMISD::ADDE;
11386 return DAG.getNode(Opcode, DL, N->getVTList(),
11387 N->getOperand(0), RHS, N->getOperand(2));
11390 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11391 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11393 return SDValue();
11396 static SDValue PerformABSCombine(SDNode *N,
11397 TargetLowering::DAGCombinerInfo &DCI,
11398 const ARMSubtarget *Subtarget) {
11399 SDValue res;
11400 SelectionDAG &DAG = DCI.DAG;
11401 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11403 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11404 return SDValue();
11406 if (!TLI.expandABS(N, res, DAG))
11407 return SDValue();
11409 return res;
11412 /// PerformADDECombine - Target-specific dag combine transform from
11413 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11414 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11415 static SDValue PerformADDECombine(SDNode *N,
11416 TargetLowering::DAGCombinerInfo &DCI,
11417 const ARMSubtarget *Subtarget) {
11418 // Only ARM and Thumb2 support UMLAL/SMLAL.
11419 if (Subtarget->isThumb1Only())
11420 return PerformAddeSubeCombine(N, DCI, Subtarget);
11422 // Only perform the checks after legalize when the pattern is available.
11423 if (DCI.isBeforeLegalize()) return SDValue();
11425 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11428 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11429 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11430 /// called with the default operands, and if that fails, with commuted
11431 /// operands.
11432 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11433 TargetLowering::DAGCombinerInfo &DCI,
11434 const ARMSubtarget *Subtarget){
11435 // Attempt to create vpadd for this add.
11436 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11437 return Result;
11439 // Attempt to create vpaddl for this add.
11440 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11441 return Result;
11442 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11443 Subtarget))
11444 return Result;
11446 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11447 if (N0.getNode()->hasOneUse())
11448 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11449 return Result;
11450 return SDValue();
11453 bool
11454 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11455 CombineLevel Level) const {
11456 if (Level == BeforeLegalizeTypes)
11457 return true;
11459 if (N->getOpcode() != ISD::SHL)
11460 return true;
11462 if (Subtarget->isThumb1Only()) {
11463 // Avoid making expensive immediates by commuting shifts. (This logic
11464 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11465 // for free.)
11466 if (N->getOpcode() != ISD::SHL)
11467 return true;
11468 SDValue N1 = N->getOperand(0);
11469 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11470 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11471 return true;
11472 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11473 if (Const->getAPIntValue().ult(256))
11474 return false;
11475 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11476 Const->getAPIntValue().sgt(-256))
11477 return false;
11479 return true;
11482 // Turn off commute-with-shift transform after legalization, so it doesn't
11483 // conflict with PerformSHLSimplify. (We could try to detect when
11484 // PerformSHLSimplify would trigger more precisely, but it isn't
11485 // really necessary.)
11486 return false;
11489 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11490 const SDNode *N, CombineLevel Level) const {
11491 if (!Subtarget->isThumb1Only())
11492 return true;
11494 if (Level == BeforeLegalizeTypes)
11495 return true;
11497 return false;
11500 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11501 if (!Subtarget->hasNEON()) {
11502 if (Subtarget->isThumb1Only())
11503 return VT.getScalarSizeInBits() <= 32;
11504 return true;
11506 return VT.isScalarInteger();
11509 static SDValue PerformSHLSimplify(SDNode *N,
11510 TargetLowering::DAGCombinerInfo &DCI,
11511 const ARMSubtarget *ST) {
11512 // Allow the generic combiner to identify potential bswaps.
11513 if (DCI.isBeforeLegalize())
11514 return SDValue();
11516 // DAG combiner will fold:
11517 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11518 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11519 // Other code patterns that can be also be modified have the following form:
11520 // b + ((a << 1) | 510)
11521 // b + ((a << 1) & 510)
11522 // b + ((a << 1) ^ 510)
11523 // b + ((a << 1) + 510)
11525 // Many instructions can perform the shift for free, but it requires both
11526 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11527 // instruction will needed. So, unfold back to the original pattern if:
11528 // - if c1 and c2 are small enough that they don't require mov imms.
11529 // - the user(s) of the node can perform an shl
11531 // No shifted operands for 16-bit instructions.
11532 if (ST->isThumb() && ST->isThumb1Only())
11533 return SDValue();
11535 // Check that all the users could perform the shl themselves.
11536 for (auto U : N->uses()) {
11537 switch(U->getOpcode()) {
11538 default:
11539 return SDValue();
11540 case ISD::SUB:
11541 case ISD::ADD:
11542 case ISD::AND:
11543 case ISD::OR:
11544 case ISD::XOR:
11545 case ISD::SETCC:
11546 case ARMISD::CMP:
11547 // Check that the user isn't already using a constant because there
11548 // aren't any instructions that support an immediate operand and a
11549 // shifted operand.
11550 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11551 isa<ConstantSDNode>(U->getOperand(1)))
11552 return SDValue();
11554 // Check that it's not already using a shift.
11555 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11556 U->getOperand(1).getOpcode() == ISD::SHL)
11557 return SDValue();
11558 break;
11562 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11563 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11564 return SDValue();
11566 if (N->getOperand(0).getOpcode() != ISD::SHL)
11567 return SDValue();
11569 SDValue SHL = N->getOperand(0);
11571 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11572 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11573 if (!C1ShlC2 || !C2)
11574 return SDValue();
11576 APInt C2Int = C2->getAPIntValue();
11577 APInt C1Int = C1ShlC2->getAPIntValue();
11579 // Check that performing a lshr will not lose any information.
11580 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11581 C2Int.getBitWidth() - C2->getZExtValue());
11582 if ((C1Int & Mask) != C1Int)
11583 return SDValue();
11585 // Shift the first constant.
11586 C1Int.lshrInPlace(C2Int);
11588 // The immediates are encoded as an 8-bit value that can be rotated.
11589 auto LargeImm = [](const APInt &Imm) {
11590 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11591 return Imm.getBitWidth() - Zeros > 8;
11594 if (LargeImm(C1Int) || LargeImm(C2Int))
11595 return SDValue();
11597 SelectionDAG &DAG = DCI.DAG;
11598 SDLoc dl(N);
11599 SDValue X = SHL.getOperand(0);
11600 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11601 DAG.getConstant(C1Int, dl, MVT::i32));
11602 // Shift left to compensate for the lshr of C1Int.
11603 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11605 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11606 SHL.dump(); N->dump());
11607 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11608 return Res;
11612 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11614 static SDValue PerformADDCombine(SDNode *N,
11615 TargetLowering::DAGCombinerInfo &DCI,
11616 const ARMSubtarget *Subtarget) {
11617 SDValue N0 = N->getOperand(0);
11618 SDValue N1 = N->getOperand(1);
11620 // Only works one way, because it needs an immediate operand.
11621 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11622 return Result;
11624 // First try with the default operand order.
11625 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11626 return Result;
11628 // If that didn't work, try again with the operands commuted.
11629 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11632 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11634 static SDValue PerformSUBCombine(SDNode *N,
11635 TargetLowering::DAGCombinerInfo &DCI) {
11636 SDValue N0 = N->getOperand(0);
11637 SDValue N1 = N->getOperand(1);
11639 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11640 if (N1.getNode()->hasOneUse())
11641 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11642 return Result;
11644 return SDValue();
11647 /// PerformVMULCombine
11648 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11649 /// special multiplier accumulator forwarding.
11650 /// vmul d3, d0, d2
11651 /// vmla d3, d1, d2
11652 /// is faster than
11653 /// vadd d3, d0, d1
11654 /// vmul d3, d3, d2
11655 // However, for (A + B) * (A + B),
11656 // vadd d2, d0, d1
11657 // vmul d3, d0, d2
11658 // vmla d3, d1, d2
11659 // is slower than
11660 // vadd d2, d0, d1
11661 // vmul d3, d2, d2
11662 static SDValue PerformVMULCombine(SDNode *N,
11663 TargetLowering::DAGCombinerInfo &DCI,
11664 const ARMSubtarget *Subtarget) {
11665 if (!Subtarget->hasVMLxForwarding())
11666 return SDValue();
11668 SelectionDAG &DAG = DCI.DAG;
11669 SDValue N0 = N->getOperand(0);
11670 SDValue N1 = N->getOperand(1);
11671 unsigned Opcode = N0.getOpcode();
11672 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11673 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11674 Opcode = N1.getOpcode();
11675 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11676 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11677 return SDValue();
11678 std::swap(N0, N1);
11681 if (N0 == N1)
11682 return SDValue();
11684 EVT VT = N->getValueType(0);
11685 SDLoc DL(N);
11686 SDValue N00 = N0->getOperand(0);
11687 SDValue N01 = N0->getOperand(1);
11688 return DAG.getNode(Opcode, DL, VT,
11689 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11690 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11693 static SDValue PerformMULCombine(SDNode *N,
11694 TargetLowering::DAGCombinerInfo &DCI,
11695 const ARMSubtarget *Subtarget) {
11696 SelectionDAG &DAG = DCI.DAG;
11698 if (Subtarget->isThumb1Only())
11699 return SDValue();
11701 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11702 return SDValue();
11704 EVT VT = N->getValueType(0);
11705 if (VT.is64BitVector() || VT.is128BitVector())
11706 return PerformVMULCombine(N, DCI, Subtarget);
11707 if (VT != MVT::i32)
11708 return SDValue();
11710 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11711 if (!C)
11712 return SDValue();
11714 int64_t MulAmt = C->getSExtValue();
11715 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11717 ShiftAmt = ShiftAmt & (32 - 1);
11718 SDValue V = N->getOperand(0);
11719 SDLoc DL(N);
11721 SDValue Res;
11722 MulAmt >>= ShiftAmt;
11724 if (MulAmt >= 0) {
11725 if (isPowerOf2_32(MulAmt - 1)) {
11726 // (mul x, 2^N + 1) => (add (shl x, N), x)
11727 Res = DAG.getNode(ISD::ADD, DL, VT,
11729 DAG.getNode(ISD::SHL, DL, VT,
11731 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11732 MVT::i32)));
11733 } else if (isPowerOf2_32(MulAmt + 1)) {
11734 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11735 Res = DAG.getNode(ISD::SUB, DL, VT,
11736 DAG.getNode(ISD::SHL, DL, VT,
11738 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11739 MVT::i32)),
11741 } else
11742 return SDValue();
11743 } else {
11744 uint64_t MulAmtAbs = -MulAmt;
11745 if (isPowerOf2_32(MulAmtAbs + 1)) {
11746 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11747 Res = DAG.getNode(ISD::SUB, DL, VT,
11749 DAG.getNode(ISD::SHL, DL, VT,
11751 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11752 MVT::i32)));
11753 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11754 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11755 Res = DAG.getNode(ISD::ADD, DL, VT,
11757 DAG.getNode(ISD::SHL, DL, VT,
11759 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11760 MVT::i32)));
11761 Res = DAG.getNode(ISD::SUB, DL, VT,
11762 DAG.getConstant(0, DL, MVT::i32), Res);
11763 } else
11764 return SDValue();
11767 if (ShiftAmt != 0)
11768 Res = DAG.getNode(ISD::SHL, DL, VT,
11769 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11771 // Do not add new nodes to DAG combiner worklist.
11772 DCI.CombineTo(N, Res, false);
11773 return SDValue();
11776 static SDValue CombineANDShift(SDNode *N,
11777 TargetLowering::DAGCombinerInfo &DCI,
11778 const ARMSubtarget *Subtarget) {
11779 // Allow DAGCombine to pattern-match before we touch the canonical form.
11780 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11781 return SDValue();
11783 if (N->getValueType(0) != MVT::i32)
11784 return SDValue();
11786 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11787 if (!N1C)
11788 return SDValue();
11790 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11791 // Don't transform uxtb/uxth.
11792 if (C1 == 255 || C1 == 65535)
11793 return SDValue();
11795 SDNode *N0 = N->getOperand(0).getNode();
11796 if (!N0->hasOneUse())
11797 return SDValue();
11799 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11800 return SDValue();
11802 bool LeftShift = N0->getOpcode() == ISD::SHL;
11804 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11805 if (!N01C)
11806 return SDValue();
11808 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11809 if (!C2 || C2 >= 32)
11810 return SDValue();
11812 // Clear irrelevant bits in the mask.
11813 if (LeftShift)
11814 C1 &= (-1U << C2);
11815 else
11816 C1 &= (-1U >> C2);
11818 SelectionDAG &DAG = DCI.DAG;
11819 SDLoc DL(N);
11821 // We have a pattern of the form "(and (shl x, c2) c1)" or
11822 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11823 // transform to a pair of shifts, to save materializing c1.
11825 // First pattern: right shift, then mask off leading bits.
11826 // FIXME: Use demanded bits?
11827 if (!LeftShift && isMask_32(C1)) {
11828 uint32_t C3 = countLeadingZeros(C1);
11829 if (C2 < C3) {
11830 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11831 DAG.getConstant(C3 - C2, DL, MVT::i32));
11832 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11833 DAG.getConstant(C3, DL, MVT::i32));
11837 // First pattern, reversed: left shift, then mask off trailing bits.
11838 if (LeftShift && isMask_32(~C1)) {
11839 uint32_t C3 = countTrailingZeros(C1);
11840 if (C2 < C3) {
11841 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11842 DAG.getConstant(C3 - C2, DL, MVT::i32));
11843 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11844 DAG.getConstant(C3, DL, MVT::i32));
11848 // Second pattern: left shift, then mask off leading bits.
11849 // FIXME: Use demanded bits?
11850 if (LeftShift && isShiftedMask_32(C1)) {
11851 uint32_t Trailing = countTrailingZeros(C1);
11852 uint32_t C3 = countLeadingZeros(C1);
11853 if (Trailing == C2 && C2 + C3 < 32) {
11854 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11855 DAG.getConstant(C2 + C3, DL, MVT::i32));
11856 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11857 DAG.getConstant(C3, DL, MVT::i32));
11861 // Second pattern, reversed: right shift, then mask off trailing bits.
11862 // FIXME: Handle other patterns of known/demanded bits.
11863 if (!LeftShift && isShiftedMask_32(C1)) {
11864 uint32_t Leading = countLeadingZeros(C1);
11865 uint32_t C3 = countTrailingZeros(C1);
11866 if (Leading == C2 && C2 + C3 < 32) {
11867 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11868 DAG.getConstant(C2 + C3, DL, MVT::i32));
11869 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11870 DAG.getConstant(C3, DL, MVT::i32));
11874 // FIXME: Transform "(and (shl x, c2) c1)" ->
11875 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11876 // c1.
11877 return SDValue();
11880 static SDValue PerformANDCombine(SDNode *N,
11881 TargetLowering::DAGCombinerInfo &DCI,
11882 const ARMSubtarget *Subtarget) {
11883 // Attempt to use immediate-form VBIC
11884 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11885 SDLoc dl(N);
11886 EVT VT = N->getValueType(0);
11887 SelectionDAG &DAG = DCI.DAG;
11889 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11890 return SDValue();
11892 APInt SplatBits, SplatUndef;
11893 unsigned SplatBitSize;
11894 bool HasAnyUndefs;
11895 if (BVN && Subtarget->hasNEON() &&
11896 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11897 if (SplatBitSize <= 64) {
11898 EVT VbicVT;
11899 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11900 SplatUndef.getZExtValue(), SplatBitSize,
11901 DAG, dl, VbicVT, VT.is128BitVector(),
11902 OtherModImm);
11903 if (Val.getNode()) {
11904 SDValue Input =
11905 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11906 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11907 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11912 if (!Subtarget->isThumb1Only()) {
11913 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11914 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11915 return Result;
11917 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11918 return Result;
11921 if (Subtarget->isThumb1Only())
11922 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
11923 return Result;
11925 return SDValue();
11928 // Try combining OR nodes to SMULWB, SMULWT.
11929 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
11930 TargetLowering::DAGCombinerInfo &DCI,
11931 const ARMSubtarget *Subtarget) {
11932 if (!Subtarget->hasV6Ops() ||
11933 (Subtarget->isThumb() &&
11934 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
11935 return SDValue();
11937 SDValue SRL = OR->getOperand(0);
11938 SDValue SHL = OR->getOperand(1);
11940 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
11941 SRL = OR->getOperand(1);
11942 SHL = OR->getOperand(0);
11944 if (!isSRL16(SRL) || !isSHL16(SHL))
11945 return SDValue();
11947 // The first operands to the shifts need to be the two results from the
11948 // same smul_lohi node.
11949 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
11950 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
11951 return SDValue();
11953 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
11954 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
11955 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
11956 return SDValue();
11958 // Now we have:
11959 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
11960 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
11961 // For SMUWB the 16-bit value will signed extended somehow.
11962 // For SMULWT only the SRA is required.
11963 // Check both sides of SMUL_LOHI
11964 SDValue OpS16 = SMULLOHI->getOperand(0);
11965 SDValue OpS32 = SMULLOHI->getOperand(1);
11967 SelectionDAG &DAG = DCI.DAG;
11968 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
11969 OpS16 = OpS32;
11970 OpS32 = SMULLOHI->getOperand(0);
11973 SDLoc dl(OR);
11974 unsigned Opcode = 0;
11975 if (isS16(OpS16, DAG))
11976 Opcode = ARMISD::SMULWB;
11977 else if (isSRA16(OpS16)) {
11978 Opcode = ARMISD::SMULWT;
11979 OpS16 = OpS16->getOperand(0);
11981 else
11982 return SDValue();
11984 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11985 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11986 return SDValue(OR, 0);
11989 static SDValue PerformORCombineToBFI(SDNode *N,
11990 TargetLowering::DAGCombinerInfo &DCI,
11991 const ARMSubtarget *Subtarget) {
11992 // BFI is only available on V6T2+
11993 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11994 return SDValue();
11996 EVT VT = N->getValueType(0);
11997 SDValue N0 = N->getOperand(0);
11998 SDValue N1 = N->getOperand(1);
11999 SelectionDAG &DAG = DCI.DAG;
12000 SDLoc DL(N);
12001 // 1) or (and A, mask), val => ARMbfi A, val, mask
12002 // iff (val & mask) == val
12004 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12005 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
12006 // && mask == ~mask2
12007 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
12008 // && ~mask == mask2
12009 // (i.e., copy a bitfield value into another bitfield of the same width)
12011 if (VT != MVT::i32)
12012 return SDValue();
12014 SDValue N00 = N0.getOperand(0);
12016 // The value and the mask need to be constants so we can verify this is
12017 // actually a bitfield set. If the mask is 0xffff, we can do better
12018 // via a movt instruction, so don't use BFI in that case.
12019 SDValue MaskOp = N0.getOperand(1);
12020 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
12021 if (!MaskC)
12022 return SDValue();
12023 unsigned Mask = MaskC->getZExtValue();
12024 if (Mask == 0xffff)
12025 return SDValue();
12026 SDValue Res;
12027 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
12028 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12029 if (N1C) {
12030 unsigned Val = N1C->getZExtValue();
12031 if ((Val & ~Mask) != Val)
12032 return SDValue();
12034 if (ARM::isBitFieldInvertedMask(Mask)) {
12035 Val >>= countTrailingZeros(~Mask);
12037 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
12038 DAG.getConstant(Val, DL, MVT::i32),
12039 DAG.getConstant(Mask, DL, MVT::i32));
12041 DCI.CombineTo(N, Res, false);
12042 // Return value from the original node to inform the combiner than N is
12043 // now dead.
12044 return SDValue(N, 0);
12046 } else if (N1.getOpcode() == ISD::AND) {
12047 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12048 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12049 if (!N11C)
12050 return SDValue();
12051 unsigned Mask2 = N11C->getZExtValue();
12053 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
12054 // as is to match.
12055 if (ARM::isBitFieldInvertedMask(Mask) &&
12056 (Mask == ~Mask2)) {
12057 // The pack halfword instruction works better for masks that fit it,
12058 // so use that when it's available.
12059 if (Subtarget->hasDSP() &&
12060 (Mask == 0xffff || Mask == 0xffff0000))
12061 return SDValue();
12062 // 2a
12063 unsigned amt = countTrailingZeros(Mask2);
12064 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
12065 DAG.getConstant(amt, DL, MVT::i32));
12066 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
12067 DAG.getConstant(Mask, DL, MVT::i32));
12068 DCI.CombineTo(N, Res, false);
12069 // Return value from the original node to inform the combiner than N is
12070 // now dead.
12071 return SDValue(N, 0);
12072 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
12073 (~Mask == Mask2)) {
12074 // The pack halfword instruction works better for masks that fit it,
12075 // so use that when it's available.
12076 if (Subtarget->hasDSP() &&
12077 (Mask2 == 0xffff || Mask2 == 0xffff0000))
12078 return SDValue();
12079 // 2b
12080 unsigned lsb = countTrailingZeros(Mask);
12081 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
12082 DAG.getConstant(lsb, DL, MVT::i32));
12083 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
12084 DAG.getConstant(Mask2, DL, MVT::i32));
12085 DCI.CombineTo(N, Res, false);
12086 // Return value from the original node to inform the combiner than N is
12087 // now dead.
12088 return SDValue(N, 0);
12092 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
12093 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
12094 ARM::isBitFieldInvertedMask(~Mask)) {
12095 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
12096 // where lsb(mask) == #shamt and masked bits of B are known zero.
12097 SDValue ShAmt = N00.getOperand(1);
12098 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
12099 unsigned LSB = countTrailingZeros(Mask);
12100 if (ShAmtC != LSB)
12101 return SDValue();
12103 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
12104 DAG.getConstant(~Mask, DL, MVT::i32));
12106 DCI.CombineTo(N, Res, false);
12107 // Return value from the original node to inform the combiner than N is
12108 // now dead.
12109 return SDValue(N, 0);
12112 return SDValue();
12115 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12116 switch (CC) {
12117 case ARMCC::EQ:
12118 case ARMCC::NE:
12119 case ARMCC::LE:
12120 case ARMCC::GT:
12121 case ARMCC::GE:
12122 case ARMCC::LT:
12123 return true;
12124 case ARMCC::HS:
12125 case ARMCC::HI:
12126 return !IsFloat;
12127 default:
12128 return false;
12132 static SDValue PerformORCombine_i1(SDNode *N,
12133 TargetLowering::DAGCombinerInfo &DCI,
12134 const ARMSubtarget *Subtarget) {
12135 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12136 // together with predicates
12137 EVT VT = N->getValueType(0);
12138 SDValue N0 = N->getOperand(0);
12139 SDValue N1 = N->getOperand(1);
12141 ARMCC::CondCodes CondCode0 = ARMCC::AL;
12142 ARMCC::CondCodes CondCode1 = ARMCC::AL;
12143 if (N0->getOpcode() == ARMISD::VCMP)
12144 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
12145 ->getZExtValue();
12146 else if (N0->getOpcode() == ARMISD::VCMPZ)
12147 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
12148 ->getZExtValue();
12149 if (N1->getOpcode() == ARMISD::VCMP)
12150 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
12151 ->getZExtValue();
12152 else if (N1->getOpcode() == ARMISD::VCMPZ)
12153 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
12154 ->getZExtValue();
12156 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
12157 return SDValue();
12159 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
12160 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
12162 if (!isValidMVECond(Opposite0,
12163 N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
12164 !isValidMVECond(Opposite1,
12165 N1->getOperand(0)->getValueType(0).isFloatingPoint()))
12166 return SDValue();
12168 SmallVector<SDValue, 4> Ops0;
12169 Ops0.push_back(N0->getOperand(0));
12170 if (N0->getOpcode() == ARMISD::VCMP)
12171 Ops0.push_back(N0->getOperand(1));
12172 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12173 SmallVector<SDValue, 4> Ops1;
12174 Ops1.push_back(N1->getOperand(0));
12175 if (N1->getOpcode() == ARMISD::VCMP)
12176 Ops1.push_back(N1->getOperand(1));
12177 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12179 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12180 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12181 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12182 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12183 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12186 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12187 static SDValue PerformORCombine(SDNode *N,
12188 TargetLowering::DAGCombinerInfo &DCI,
12189 const ARMSubtarget *Subtarget) {
12190 // Attempt to use immediate-form VORR
12191 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12192 SDLoc dl(N);
12193 EVT VT = N->getValueType(0);
12194 SelectionDAG &DAG = DCI.DAG;
12196 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12197 return SDValue();
12199 APInt SplatBits, SplatUndef;
12200 unsigned SplatBitSize;
12201 bool HasAnyUndefs;
12202 if (BVN && Subtarget->hasNEON() &&
12203 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12204 if (SplatBitSize <= 64) {
12205 EVT VorrVT;
12206 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
12207 SplatUndef.getZExtValue(), SplatBitSize,
12208 DAG, dl, VorrVT, VT.is128BitVector(),
12209 OtherModImm);
12210 if (Val.getNode()) {
12211 SDValue Input =
12212 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12213 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12214 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12219 if (!Subtarget->isThumb1Only()) {
12220 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12221 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12222 return Result;
12223 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12224 return Result;
12227 SDValue N0 = N->getOperand(0);
12228 SDValue N1 = N->getOperand(1);
12230 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12231 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12232 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12234 // The code below optimizes (or (and X, Y), Z).
12235 // The AND operand needs to have a single user to make these optimizations
12236 // profitable.
12237 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12238 return SDValue();
12240 APInt SplatUndef;
12241 unsigned SplatBitSize;
12242 bool HasAnyUndefs;
12244 APInt SplatBits0, SplatBits1;
12245 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12246 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12247 // Ensure that the second operand of both ands are constants
12248 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12249 HasAnyUndefs) && !HasAnyUndefs) {
12250 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12251 HasAnyUndefs) && !HasAnyUndefs) {
12252 // Ensure that the bit width of the constants are the same and that
12253 // the splat arguments are logical inverses as per the pattern we
12254 // are trying to simplify.
12255 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12256 SplatBits0 == ~SplatBits1) {
12257 // Canonicalize the vector type to make instruction selection
12258 // simpler.
12259 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12260 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12261 N0->getOperand(1),
12262 N0->getOperand(0),
12263 N1->getOperand(0));
12264 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12270 if (Subtarget->hasMVEIntegerOps() &&
12271 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12272 return PerformORCombine_i1(N, DCI, Subtarget);
12274 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12275 // reasonable.
12276 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12277 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12278 return Res;
12281 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12282 return Result;
12284 return SDValue();
12287 static SDValue PerformXORCombine(SDNode *N,
12288 TargetLowering::DAGCombinerInfo &DCI,
12289 const ARMSubtarget *Subtarget) {
12290 EVT VT = N->getValueType(0);
12291 SelectionDAG &DAG = DCI.DAG;
12293 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12294 return SDValue();
12296 if (!Subtarget->isThumb1Only()) {
12297 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12298 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12299 return Result;
12301 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12302 return Result;
12305 return SDValue();
12308 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12309 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12310 // their position in "to" (Rd).
12311 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12312 assert(N->getOpcode() == ARMISD::BFI);
12314 SDValue From = N->getOperand(1);
12315 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12316 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12318 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12319 // #C in the base of the SHR.
12320 if (From->getOpcode() == ISD::SRL &&
12321 isa<ConstantSDNode>(From->getOperand(1))) {
12322 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12323 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12324 FromMask <<= Shift.getLimitedValue(31);
12325 From = From->getOperand(0);
12328 return From;
12331 // If A and B contain one contiguous set of bits, does A | B == A . B?
12333 // Neither A nor B must be zero.
12334 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12335 unsigned LastActiveBitInA = A.countTrailingZeros();
12336 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12337 return LastActiveBitInA - 1 == FirstActiveBitInB;
12340 static SDValue FindBFIToCombineWith(SDNode *N) {
12341 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12342 // if one exists.
12343 APInt ToMask, FromMask;
12344 SDValue From = ParseBFI(N, ToMask, FromMask);
12345 SDValue To = N->getOperand(0);
12347 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12348 // aren't compatible, but not if they set the same bit in their destination as
12349 // we do (or that of any BFI we're going to combine with).
12350 SDValue V = To;
12351 APInt CombinedToMask = ToMask;
12352 while (V.getOpcode() == ARMISD::BFI) {
12353 APInt NewToMask, NewFromMask;
12354 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12355 if (NewFrom != From) {
12356 // This BFI has a different base. Keep going.
12357 CombinedToMask |= NewToMask;
12358 V = V.getOperand(0);
12359 continue;
12362 // Do the written bits conflict with any we've seen so far?
12363 if ((NewToMask & CombinedToMask).getBoolValue())
12364 // Conflicting bits - bail out because going further is unsafe.
12365 return SDValue();
12367 // Are the new bits contiguous when combined with the old bits?
12368 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12369 BitsProperlyConcatenate(FromMask, NewFromMask))
12370 return V;
12371 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12372 BitsProperlyConcatenate(NewFromMask, FromMask))
12373 return V;
12375 // We've seen a write to some bits, so track it.
12376 CombinedToMask |= NewToMask;
12377 // Keep going...
12378 V = V.getOperand(0);
12381 return SDValue();
12384 static SDValue PerformBFICombine(SDNode *N,
12385 TargetLowering::DAGCombinerInfo &DCI) {
12386 SDValue N1 = N->getOperand(1);
12387 if (N1.getOpcode() == ISD::AND) {
12388 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12389 // the bits being cleared by the AND are not demanded by the BFI.
12390 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12391 if (!N11C)
12392 return SDValue();
12393 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12394 unsigned LSB = countTrailingZeros(~InvMask);
12395 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12396 assert(Width <
12397 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12398 "undefined behavior");
12399 unsigned Mask = (1u << Width) - 1;
12400 unsigned Mask2 = N11C->getZExtValue();
12401 if ((Mask & (~Mask2)) == 0)
12402 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12403 N->getOperand(0), N1.getOperand(0),
12404 N->getOperand(2));
12405 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12406 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12407 // Keep track of any consecutive bits set that all come from the same base
12408 // value. We can combine these together into a single BFI.
12409 SDValue CombineBFI = FindBFIToCombineWith(N);
12410 if (CombineBFI == SDValue())
12411 return SDValue();
12413 // We've found a BFI.
12414 APInt ToMask1, FromMask1;
12415 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12417 APInt ToMask2, FromMask2;
12418 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12419 assert(From1 == From2);
12420 (void)From2;
12422 // First, unlink CombineBFI.
12423 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12424 // Then create a new BFI, combining the two together.
12425 APInt NewFromMask = FromMask1 | FromMask2;
12426 APInt NewToMask = ToMask1 | ToMask2;
12428 EVT VT = N->getValueType(0);
12429 SDLoc dl(N);
12431 if (NewFromMask[0] == 0)
12432 From1 = DCI.DAG.getNode(
12433 ISD::SRL, dl, VT, From1,
12434 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12435 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12436 DCI.DAG.getConstant(~NewToMask, dl, VT));
12438 return SDValue();
12441 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12442 /// ARMISD::VMOVRRD.
12443 static SDValue PerformVMOVRRDCombine(SDNode *N,
12444 TargetLowering::DAGCombinerInfo &DCI,
12445 const ARMSubtarget *Subtarget) {
12446 // vmovrrd(vmovdrr x, y) -> x,y
12447 SDValue InDouble = N->getOperand(0);
12448 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12449 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12451 // vmovrrd(load f64) -> (load i32), (load i32)
12452 SDNode *InNode = InDouble.getNode();
12453 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12454 InNode->getValueType(0) == MVT::f64 &&
12455 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12456 !cast<LoadSDNode>(InNode)->isVolatile()) {
12457 // TODO: Should this be done for non-FrameIndex operands?
12458 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12460 SelectionDAG &DAG = DCI.DAG;
12461 SDLoc DL(LD);
12462 SDValue BasePtr = LD->getBasePtr();
12463 SDValue NewLD1 =
12464 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12465 LD->getAlignment(), LD->getMemOperand()->getFlags());
12467 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12468 DAG.getConstant(4, DL, MVT::i32));
12470 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12471 LD->getPointerInfo().getWithOffset(4),
12472 std::min(4U, LD->getAlignment()),
12473 LD->getMemOperand()->getFlags());
12475 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12476 if (DCI.DAG.getDataLayout().isBigEndian())
12477 std::swap (NewLD1, NewLD2);
12478 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12479 return Result;
12482 return SDValue();
12485 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12486 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12487 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12488 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12489 SDValue Op0 = N->getOperand(0);
12490 SDValue Op1 = N->getOperand(1);
12491 if (Op0.getOpcode() == ISD::BITCAST)
12492 Op0 = Op0.getOperand(0);
12493 if (Op1.getOpcode() == ISD::BITCAST)
12494 Op1 = Op1.getOperand(0);
12495 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12496 Op0.getNode() == Op1.getNode() &&
12497 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12498 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12499 N->getValueType(0), Op0.getOperand(0));
12500 return SDValue();
12503 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12504 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12505 /// i64 vector to have f64 elements, since the value can then be loaded
12506 /// directly into a VFP register.
12507 static bool hasNormalLoadOperand(SDNode *N) {
12508 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12509 for (unsigned i = 0; i < NumElts; ++i) {
12510 SDNode *Elt = N->getOperand(i).getNode();
12511 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12512 return true;
12514 return false;
12517 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12518 /// ISD::BUILD_VECTOR.
12519 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12520 TargetLowering::DAGCombinerInfo &DCI,
12521 const ARMSubtarget *Subtarget) {
12522 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12523 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12524 // into a pair of GPRs, which is fine when the value is used as a scalar,
12525 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12526 SelectionDAG &DAG = DCI.DAG;
12527 if (N->getNumOperands() == 2)
12528 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12529 return RV;
12531 // Load i64 elements as f64 values so that type legalization does not split
12532 // them up into i32 values.
12533 EVT VT = N->getValueType(0);
12534 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12535 return SDValue();
12536 SDLoc dl(N);
12537 SmallVector<SDValue, 8> Ops;
12538 unsigned NumElts = VT.getVectorNumElements();
12539 for (unsigned i = 0; i < NumElts; ++i) {
12540 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12541 Ops.push_back(V);
12542 // Make the DAGCombiner fold the bitcast.
12543 DCI.AddToWorklist(V.getNode());
12545 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12546 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12547 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12550 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12551 static SDValue
12552 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12553 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12554 // At that time, we may have inserted bitcasts from integer to float.
12555 // If these bitcasts have survived DAGCombine, change the lowering of this
12556 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12557 // force to use floating point types.
12559 // Make sure we can change the type of the vector.
12560 // This is possible iff:
12561 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12562 // 1.1. Vector is used only once.
12563 // 1.2. Use is a bit convert to an integer type.
12564 // 2. The size of its operands are 32-bits (64-bits are not legal).
12565 EVT VT = N->getValueType(0);
12566 EVT EltVT = VT.getVectorElementType();
12568 // Check 1.1. and 2.
12569 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12570 return SDValue();
12572 // By construction, the input type must be float.
12573 assert(EltVT == MVT::f32 && "Unexpected type!");
12575 // Check 1.2.
12576 SDNode *Use = *N->use_begin();
12577 if (Use->getOpcode() != ISD::BITCAST ||
12578 Use->getValueType(0).isFloatingPoint())
12579 return SDValue();
12581 // Check profitability.
12582 // Model is, if more than half of the relevant operands are bitcast from
12583 // i32, turn the build_vector into a sequence of insert_vector_elt.
12584 // Relevant operands are everything that is not statically
12585 // (i.e., at compile time) bitcasted.
12586 unsigned NumOfBitCastedElts = 0;
12587 unsigned NumElts = VT.getVectorNumElements();
12588 unsigned NumOfRelevantElts = NumElts;
12589 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12590 SDValue Elt = N->getOperand(Idx);
12591 if (Elt->getOpcode() == ISD::BITCAST) {
12592 // Assume only bit cast to i32 will go away.
12593 if (Elt->getOperand(0).getValueType() == MVT::i32)
12594 ++NumOfBitCastedElts;
12595 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12596 // Constants are statically casted, thus do not count them as
12597 // relevant operands.
12598 --NumOfRelevantElts;
12601 // Check if more than half of the elements require a non-free bitcast.
12602 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12603 return SDValue();
12605 SelectionDAG &DAG = DCI.DAG;
12606 // Create the new vector type.
12607 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12608 // Check if the type is legal.
12609 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12610 if (!TLI.isTypeLegal(VecVT))
12611 return SDValue();
12613 // Combine:
12614 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12615 // => BITCAST INSERT_VECTOR_ELT
12616 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12617 // (BITCAST EN), N.
12618 SDValue Vec = DAG.getUNDEF(VecVT);
12619 SDLoc dl(N);
12620 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12621 SDValue V = N->getOperand(Idx);
12622 if (V.isUndef())
12623 continue;
12624 if (V.getOpcode() == ISD::BITCAST &&
12625 V->getOperand(0).getValueType() == MVT::i32)
12626 // Fold obvious case.
12627 V = V.getOperand(0);
12628 else {
12629 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12630 // Make the DAGCombiner fold the bitcasts.
12631 DCI.AddToWorklist(V.getNode());
12633 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12634 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12636 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12637 // Make the DAGCombiner fold the bitcasts.
12638 DCI.AddToWorklist(Vec.getNode());
12639 return Vec;
12642 static SDValue
12643 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12644 EVT VT = N->getValueType(0);
12645 SDValue Op = N->getOperand(0);
12646 SDLoc dl(N);
12648 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
12649 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
12650 // If the valuetypes are the same, we can remove the cast entirely.
12651 if (Op->getOperand(0).getValueType() == VT)
12652 return Op->getOperand(0);
12653 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl,
12654 Op->getOperand(0).getValueType(), Op->getOperand(0));
12657 return SDValue();
12660 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12661 /// ISD::INSERT_VECTOR_ELT.
12662 static SDValue PerformInsertEltCombine(SDNode *N,
12663 TargetLowering::DAGCombinerInfo &DCI) {
12664 // Bitcast an i64 load inserted into a vector to f64.
12665 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12666 EVT VT = N->getValueType(0);
12667 SDNode *Elt = N->getOperand(1).getNode();
12668 if (VT.getVectorElementType() != MVT::i64 ||
12669 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12670 return SDValue();
12672 SelectionDAG &DAG = DCI.DAG;
12673 SDLoc dl(N);
12674 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12675 VT.getVectorNumElements());
12676 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12677 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12678 // Make the DAGCombiner fold the bitcasts.
12679 DCI.AddToWorklist(Vec.getNode());
12680 DCI.AddToWorklist(V.getNode());
12681 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12682 Vec, V, N->getOperand(2));
12683 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12686 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12687 /// ISD::VECTOR_SHUFFLE.
12688 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12689 // The LLVM shufflevector instruction does not require the shuffle mask
12690 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12691 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12692 // operands do not match the mask length, they are extended by concatenating
12693 // them with undef vectors. That is probably the right thing for other
12694 // targets, but for NEON it is better to concatenate two double-register
12695 // size vector operands into a single quad-register size vector. Do that
12696 // transformation here:
12697 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12698 // shuffle(concat(v1, v2), undef)
12699 SDValue Op0 = N->getOperand(0);
12700 SDValue Op1 = N->getOperand(1);
12701 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12702 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12703 Op0.getNumOperands() != 2 ||
12704 Op1.getNumOperands() != 2)
12705 return SDValue();
12706 SDValue Concat0Op1 = Op0.getOperand(1);
12707 SDValue Concat1Op1 = Op1.getOperand(1);
12708 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12709 return SDValue();
12710 // Skip the transformation if any of the types are illegal.
12711 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12712 EVT VT = N->getValueType(0);
12713 if (!TLI.isTypeLegal(VT) ||
12714 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12715 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12716 return SDValue();
12718 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12719 Op0.getOperand(0), Op1.getOperand(0));
12720 // Translate the shuffle mask.
12721 SmallVector<int, 16> NewMask;
12722 unsigned NumElts = VT.getVectorNumElements();
12723 unsigned HalfElts = NumElts/2;
12724 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12725 for (unsigned n = 0; n < NumElts; ++n) {
12726 int MaskElt = SVN->getMaskElt(n);
12727 int NewElt = -1;
12728 if (MaskElt < (int)HalfElts)
12729 NewElt = MaskElt;
12730 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12731 NewElt = HalfElts + MaskElt - NumElts;
12732 NewMask.push_back(NewElt);
12734 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12735 DAG.getUNDEF(VT), NewMask);
12738 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12739 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12740 /// base address updates.
12741 /// For generic load/stores, the memory type is assumed to be a vector.
12742 /// The caller is assumed to have checked legality.
12743 static SDValue CombineBaseUpdate(SDNode *N,
12744 TargetLowering::DAGCombinerInfo &DCI) {
12745 SelectionDAG &DAG = DCI.DAG;
12746 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12747 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12748 const bool isStore = N->getOpcode() == ISD::STORE;
12749 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12750 SDValue Addr = N->getOperand(AddrOpIdx);
12751 MemSDNode *MemN = cast<MemSDNode>(N);
12752 SDLoc dl(N);
12754 // Search for a use of the address operand that is an increment.
12755 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12756 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12757 SDNode *User = *UI;
12758 if (User->getOpcode() != ISD::ADD ||
12759 UI.getUse().getResNo() != Addr.getResNo())
12760 continue;
12762 // Check that the add is independent of the load/store. Otherwise, folding
12763 // it would create a cycle. We can avoid searching through Addr as it's a
12764 // predecessor to both.
12765 SmallPtrSet<const SDNode *, 32> Visited;
12766 SmallVector<const SDNode *, 16> Worklist;
12767 Visited.insert(Addr.getNode());
12768 Worklist.push_back(N);
12769 Worklist.push_back(User);
12770 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12771 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12772 continue;
12774 // Find the new opcode for the updating load/store.
12775 bool isLoadOp = true;
12776 bool isLaneOp = false;
12777 unsigned NewOpc = 0;
12778 unsigned NumVecs = 0;
12779 if (isIntrinsic) {
12780 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12781 switch (IntNo) {
12782 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12783 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12784 NumVecs = 1; break;
12785 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12786 NumVecs = 2; break;
12787 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12788 NumVecs = 3; break;
12789 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12790 NumVecs = 4; break;
12791 case Intrinsic::arm_neon_vld2dup:
12792 case Intrinsic::arm_neon_vld3dup:
12793 case Intrinsic::arm_neon_vld4dup:
12794 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12795 // combining base updates for such intrinsics.
12796 continue;
12797 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12798 NumVecs = 2; isLaneOp = true; break;
12799 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12800 NumVecs = 3; isLaneOp = true; break;
12801 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12802 NumVecs = 4; isLaneOp = true; break;
12803 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12804 NumVecs = 1; isLoadOp = false; break;
12805 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12806 NumVecs = 2; isLoadOp = false; break;
12807 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12808 NumVecs = 3; isLoadOp = false; break;
12809 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12810 NumVecs = 4; isLoadOp = false; break;
12811 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12812 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12813 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12814 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12815 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12816 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12818 } else {
12819 isLaneOp = true;
12820 switch (N->getOpcode()) {
12821 default: llvm_unreachable("unexpected opcode for Neon base update");
12822 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12823 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12824 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12825 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12826 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12827 NumVecs = 1; isLaneOp = false; break;
12828 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12829 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12833 // Find the size of memory referenced by the load/store.
12834 EVT VecTy;
12835 if (isLoadOp) {
12836 VecTy = N->getValueType(0);
12837 } else if (isIntrinsic) {
12838 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12839 } else {
12840 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12841 VecTy = N->getOperand(1).getValueType();
12844 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12845 if (isLaneOp)
12846 NumBytes /= VecTy.getVectorNumElements();
12848 // If the increment is a constant, it must match the memory ref size.
12849 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12850 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12851 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12852 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12853 // separate instructions that make it harder to use a non-constant update.
12854 continue;
12857 // OK, we found an ADD we can fold into the base update.
12858 // Now, create a _UPD node, taking care of not breaking alignment.
12860 EVT AlignedVecTy = VecTy;
12861 unsigned Alignment = MemN->getAlignment();
12863 // If this is a less-than-standard-aligned load/store, change the type to
12864 // match the standard alignment.
12865 // The alignment is overlooked when selecting _UPD variants; and it's
12866 // easier to introduce bitcasts here than fix that.
12867 // There are 3 ways to get to this base-update combine:
12868 // - intrinsics: they are assumed to be properly aligned (to the standard
12869 // alignment of the memory type), so we don't need to do anything.
12870 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12871 // intrinsics, so, likewise, there's nothing to do.
12872 // - generic load/store instructions: the alignment is specified as an
12873 // explicit operand, rather than implicitly as the standard alignment
12874 // of the memory type (like the intrisics). We need to change the
12875 // memory type to match the explicit alignment. That way, we don't
12876 // generate non-standard-aligned ARMISD::VLDx nodes.
12877 if (isa<LSBaseSDNode>(N)) {
12878 if (Alignment == 0)
12879 Alignment = 1;
12880 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12881 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12882 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12883 assert(!isLaneOp && "Unexpected generic load/store lane.");
12884 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12885 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12887 // Don't set an explicit alignment on regular load/stores that we want
12888 // to transform to VLD/VST 1_UPD nodes.
12889 // This matches the behavior of regular load/stores, which only get an
12890 // explicit alignment if the MMO alignment is larger than the standard
12891 // alignment of the memory type.
12892 // Intrinsics, however, always get an explicit alignment, set to the
12893 // alignment of the MMO.
12894 Alignment = 1;
12897 // Create the new updating load/store node.
12898 // First, create an SDVTList for the new updating node's results.
12899 EVT Tys[6];
12900 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12901 unsigned n;
12902 for (n = 0; n < NumResultVecs; ++n)
12903 Tys[n] = AlignedVecTy;
12904 Tys[n++] = MVT::i32;
12905 Tys[n] = MVT::Other;
12906 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12908 // Then, gather the new node's operands.
12909 SmallVector<SDValue, 8> Ops;
12910 Ops.push_back(N->getOperand(0)); // incoming chain
12911 Ops.push_back(N->getOperand(AddrOpIdx));
12912 Ops.push_back(Inc);
12914 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12915 // Try to match the intrinsic's signature
12916 Ops.push_back(StN->getValue());
12917 } else {
12918 // Loads (and of course intrinsics) match the intrinsics' signature,
12919 // so just add all but the alignment operand.
12920 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12921 Ops.push_back(N->getOperand(i));
12924 // For all node types, the alignment operand is always the last one.
12925 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
12927 // If this is a non-standard-aligned STORE, the penultimate operand is the
12928 // stored value. Bitcast it to the aligned type.
12929 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
12930 SDValue &StVal = Ops[Ops.size()-2];
12931 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
12934 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
12935 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
12936 MemN->getMemOperand());
12938 // Update the uses.
12939 SmallVector<SDValue, 5> NewResults;
12940 for (unsigned i = 0; i < NumResultVecs; ++i)
12941 NewResults.push_back(SDValue(UpdN.getNode(), i));
12943 // If this is an non-standard-aligned LOAD, the first result is the loaded
12944 // value. Bitcast it to the expected result type.
12945 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
12946 SDValue &LdVal = NewResults[0];
12947 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
12950 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
12951 DCI.CombineTo(N, NewResults);
12952 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12954 break;
12956 return SDValue();
12959 static SDValue PerformVLDCombine(SDNode *N,
12960 TargetLowering::DAGCombinerInfo &DCI) {
12961 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12962 return SDValue();
12964 return CombineBaseUpdate(N, DCI);
12967 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
12968 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
12969 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
12970 /// return true.
12971 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12972 SelectionDAG &DAG = DCI.DAG;
12973 EVT VT = N->getValueType(0);
12974 // vldN-dup instructions only support 64-bit vectors for N > 1.
12975 if (!VT.is64BitVector())
12976 return false;
12978 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
12979 SDNode *VLD = N->getOperand(0).getNode();
12980 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
12981 return false;
12982 unsigned NumVecs = 0;
12983 unsigned NewOpc = 0;
12984 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
12985 if (IntNo == Intrinsic::arm_neon_vld2lane) {
12986 NumVecs = 2;
12987 NewOpc = ARMISD::VLD2DUP;
12988 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
12989 NumVecs = 3;
12990 NewOpc = ARMISD::VLD3DUP;
12991 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
12992 NumVecs = 4;
12993 NewOpc = ARMISD::VLD4DUP;
12994 } else {
12995 return false;
12998 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
12999 // numbers match the load.
13000 unsigned VLDLaneNo =
13001 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
13002 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13003 UI != UE; ++UI) {
13004 // Ignore uses of the chain result.
13005 if (UI.getUse().getResNo() == NumVecs)
13006 continue;
13007 SDNode *User = *UI;
13008 if (User->getOpcode() != ARMISD::VDUPLANE ||
13009 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
13010 return false;
13013 // Create the vldN-dup node.
13014 EVT Tys[5];
13015 unsigned n;
13016 for (n = 0; n < NumVecs; ++n)
13017 Tys[n] = VT;
13018 Tys[n] = MVT::Other;
13019 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
13020 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
13021 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
13022 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
13023 Ops, VLDMemInt->getMemoryVT(),
13024 VLDMemInt->getMemOperand());
13026 // Update the uses.
13027 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13028 UI != UE; ++UI) {
13029 unsigned ResNo = UI.getUse().getResNo();
13030 // Ignore uses of the chain result.
13031 if (ResNo == NumVecs)
13032 continue;
13033 SDNode *User = *UI;
13034 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
13037 // Now the vldN-lane intrinsic is dead except for its chain result.
13038 // Update uses of the chain.
13039 std::vector<SDValue> VLDDupResults;
13040 for (unsigned n = 0; n < NumVecs; ++n)
13041 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
13042 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
13043 DCI.CombineTo(VLD, VLDDupResults);
13045 return true;
13048 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
13049 /// ARMISD::VDUPLANE.
13050 static SDValue PerformVDUPLANECombine(SDNode *N,
13051 TargetLowering::DAGCombinerInfo &DCI) {
13052 SDValue Op = N->getOperand(0);
13054 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
13055 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
13056 if (CombineVLDDUP(N, DCI))
13057 return SDValue(N, 0);
13059 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
13060 // redundant. Ignore bit_converts for now; element sizes are checked below.
13061 while (Op.getOpcode() == ISD::BITCAST)
13062 Op = Op.getOperand(0);
13063 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
13064 return SDValue();
13066 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
13067 unsigned EltSize = Op.getScalarValueSizeInBits();
13068 // The canonical VMOV for a zero vector uses a 32-bit element size.
13069 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13070 unsigned EltBits;
13071 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
13072 EltSize = 8;
13073 EVT VT = N->getValueType(0);
13074 if (EltSize > VT.getScalarSizeInBits())
13075 return SDValue();
13077 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
13080 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
13081 static SDValue PerformVDUPCombine(SDNode *N,
13082 TargetLowering::DAGCombinerInfo &DCI,
13083 const ARMSubtarget *Subtarget) {
13084 SelectionDAG &DAG = DCI.DAG;
13085 SDValue Op = N->getOperand(0);
13087 if (!Subtarget->hasNEON())
13088 return SDValue();
13090 // Match VDUP(LOAD) -> VLD1DUP.
13091 // We match this pattern here rather than waiting for isel because the
13092 // transform is only legal for unindexed loads.
13093 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
13094 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
13095 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
13096 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
13097 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
13098 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
13099 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
13100 Ops, LD->getMemoryVT(),
13101 LD->getMemOperand());
13102 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
13103 return VLDDup;
13106 return SDValue();
13109 static SDValue PerformLOADCombine(SDNode *N,
13110 TargetLowering::DAGCombinerInfo &DCI) {
13111 EVT VT = N->getValueType(0);
13113 // If this is a legal vector load, try to combine it into a VLD1_UPD.
13114 if (ISD::isNormalLoad(N) && VT.isVector() &&
13115 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13116 return CombineBaseUpdate(N, DCI);
13118 return SDValue();
13121 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
13122 // pack all of the elements in one place. Next, store to memory in fewer
13123 // chunks.
13124 SDValue PerformTruncatingStoreCombine(StoreSDNode *St, SelectionDAG &DAG) {
13125 SDValue StVal = St->getValue();
13126 EVT VT = StVal.getValueType();
13127 if (!St->isTruncatingStore() || !VT.isVector())
13128 return SDValue();
13129 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13130 EVT StVT = St->getMemoryVT();
13131 unsigned NumElems = VT.getVectorNumElements();
13132 assert(StVT != VT && "Cannot truncate to the same type");
13133 unsigned FromEltSz = VT.getScalarSizeInBits();
13134 unsigned ToEltSz = StVT.getScalarSizeInBits();
13136 // From, To sizes and ElemCount must be pow of two
13137 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
13138 return SDValue();
13140 // We are going to use the original vector elt for storing.
13141 // Accumulated smaller vector elements must be a multiple of the store size.
13142 if (0 != (NumElems * FromEltSz) % ToEltSz)
13143 return SDValue();
13145 unsigned SizeRatio = FromEltSz / ToEltSz;
13146 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13148 // Create a type on which we perform the shuffle.
13149 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13150 NumElems * SizeRatio);
13151 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13153 SDLoc DL(St);
13154 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13155 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13156 for (unsigned i = 0; i < NumElems; ++i)
13157 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
13158 : i * SizeRatio;
13160 // Can't shuffle using an illegal type.
13161 if (!TLI.isTypeLegal(WideVecVT))
13162 return SDValue();
13164 SDValue Shuff = DAG.getVectorShuffle(
13165 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
13166 // At this point all of the data is stored at the bottom of the
13167 // register. We now need to save it to mem.
13169 // Find the largest store unit
13170 MVT StoreType = MVT::i8;
13171 for (MVT Tp : MVT::integer_valuetypes()) {
13172 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13173 StoreType = Tp;
13175 // Didn't find a legal store type.
13176 if (!TLI.isTypeLegal(StoreType))
13177 return SDValue();
13179 // Bitcast the original vector into a vector of store-size units
13180 EVT StoreVecVT =
13181 EVT::getVectorVT(*DAG.getContext(), StoreType,
13182 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
13183 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13184 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13185 SmallVector<SDValue, 8> Chains;
13186 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13187 TLI.getPointerTy(DAG.getDataLayout()));
13188 SDValue BasePtr = St->getBasePtr();
13190 // Perform one or more big stores into memory.
13191 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
13192 for (unsigned I = 0; I < E; I++) {
13193 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
13194 ShuffWide, DAG.getIntPtrConstant(I, DL));
13195 SDValue Ch =
13196 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
13197 St->getAlignment(), St->getMemOperand()->getFlags());
13198 BasePtr =
13199 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
13200 Chains.push_back(Ch);
13202 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13205 // Try taking a single vector store from an truncate (which would otherwise turn
13206 // into an expensive buildvector) and splitting it into a series of narrowing
13207 // stores.
13208 SDValue PerformSplittingToNarrowingStores(StoreSDNode *St, SelectionDAG &DAG) {
13209 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
13210 return SDValue();
13211 SDValue Trunc = St->getValue();
13212 if (Trunc->getOpcode() != ISD::TRUNCATE)
13213 return SDValue();
13214 EVT FromVT = Trunc->getOperand(0).getValueType();
13215 EVT ToVT = Trunc.getValueType();
13216 if (!ToVT.isVector())
13217 return SDValue();
13218 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
13219 EVT ToEltVT = ToVT.getVectorElementType();
13220 EVT FromEltVT = FromVT.getVectorElementType();
13222 unsigned NumElements = 0;
13223 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
13224 NumElements = 4;
13225 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
13226 NumElements = 8;
13227 if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements ||
13228 FromVT.getVectorNumElements() % NumElements != 0)
13229 return SDValue();
13231 SDLoc DL(St);
13232 // Details about the old store
13233 SDValue Ch = St->getChain();
13234 SDValue BasePtr = St->getBasePtr();
13235 unsigned Alignment = St->getOriginalAlignment();
13236 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
13237 AAMDNodes AAInfo = St->getAAInfo();
13239 EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements);
13240 EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements);
13242 SmallVector<SDValue, 4> Stores;
13243 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
13244 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
13245 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
13247 SDValue Extract =
13248 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
13249 DAG.getConstant(i * NumElements, DL, MVT::i32));
13250 SDValue Store = DAG.getTruncStore(
13251 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
13252 NewToVT, Alignment, MMOFlags, AAInfo);
13253 Stores.push_back(Store);
13255 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
13258 /// PerformSTORECombine - Target-specific dag combine xforms for
13259 /// ISD::STORE.
13260 static SDValue PerformSTORECombine(SDNode *N,
13261 TargetLowering::DAGCombinerInfo &DCI,
13262 const ARMSubtarget *Subtarget) {
13263 StoreSDNode *St = cast<StoreSDNode>(N);
13264 if (St->isVolatile())
13265 return SDValue();
13266 SDValue StVal = St->getValue();
13267 EVT VT = StVal.getValueType();
13269 if (Subtarget->hasNEON())
13270 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
13271 return Store;
13273 if (Subtarget->hasMVEIntegerOps())
13274 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
13275 return NewToken;
13277 if (!ISD::isNormalStore(St))
13278 return SDValue();
13280 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
13281 // ARM stores of arguments in the same cache line.
13282 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
13283 StVal.getNode()->hasOneUse()) {
13284 SelectionDAG &DAG = DCI.DAG;
13285 bool isBigEndian = DAG.getDataLayout().isBigEndian();
13286 SDLoc DL(St);
13287 SDValue BasePtr = St->getBasePtr();
13288 SDValue NewST1 = DAG.getStore(
13289 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
13290 BasePtr, St->getPointerInfo(), St->getAlignment(),
13291 St->getMemOperand()->getFlags());
13293 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13294 DAG.getConstant(4, DL, MVT::i32));
13295 return DAG.getStore(NewST1.getValue(0), DL,
13296 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
13297 OffsetPtr, St->getPointerInfo(),
13298 std::min(4U, St->getAlignment() / 2),
13299 St->getMemOperand()->getFlags());
13302 if (StVal.getValueType() == MVT::i64 &&
13303 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13305 // Bitcast an i64 store extracted from a vector to f64.
13306 // Otherwise, the i64 value will be legalized to a pair of i32 values.
13307 SelectionDAG &DAG = DCI.DAG;
13308 SDLoc dl(StVal);
13309 SDValue IntVec = StVal.getOperand(0);
13310 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13311 IntVec.getValueType().getVectorNumElements());
13312 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
13313 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13314 Vec, StVal.getOperand(1));
13315 dl = SDLoc(N);
13316 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
13317 // Make the DAGCombiner fold the bitcasts.
13318 DCI.AddToWorklist(Vec.getNode());
13319 DCI.AddToWorklist(ExtElt.getNode());
13320 DCI.AddToWorklist(V.getNode());
13321 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
13322 St->getPointerInfo(), St->getAlignment(),
13323 St->getMemOperand()->getFlags(), St->getAAInfo());
13326 // If this is a legal vector store, try to combine it into a VST1_UPD.
13327 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
13328 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13329 return CombineBaseUpdate(N, DCI);
13331 return SDValue();
13334 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
13335 /// can replace combinations of VMUL and VCVT (floating-point to integer)
13336 /// when the VMUL has a constant operand that is a power of 2.
13338 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13339 /// vmul.f32 d16, d17, d16
13340 /// vcvt.s32.f32 d16, d16
13341 /// becomes:
13342 /// vcvt.s32.f32 d16, d16, #3
13343 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
13344 const ARMSubtarget *Subtarget) {
13345 if (!Subtarget->hasNEON())
13346 return SDValue();
13348 SDValue Op = N->getOperand(0);
13349 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13350 Op.getOpcode() != ISD::FMUL)
13351 return SDValue();
13353 SDValue ConstVec = Op->getOperand(1);
13354 if (!isa<BuildVectorSDNode>(ConstVec))
13355 return SDValue();
13357 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13358 uint32_t FloatBits = FloatTy.getSizeInBits();
13359 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13360 uint32_t IntBits = IntTy.getSizeInBits();
13361 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13362 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13363 // These instructions only exist converting from f32 to i32. We can handle
13364 // smaller integers by generating an extra truncate, but larger ones would
13365 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13366 // these intructions only support v2i32/v4i32 types.
13367 return SDValue();
13370 BitVector UndefElements;
13371 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13372 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13373 if (C == -1 || C == 0 || C > 32)
13374 return SDValue();
13376 SDLoc dl(N);
13377 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
13378 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
13379 Intrinsic::arm_neon_vcvtfp2fxu;
13380 SDValue FixConv = DAG.getNode(
13381 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13382 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
13383 DAG.getConstant(C, dl, MVT::i32));
13385 if (IntBits < FloatBits)
13386 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
13388 return FixConv;
13391 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13392 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13393 /// when the VDIV has a constant operand that is a power of 2.
13395 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13396 /// vcvt.f32.s32 d16, d16
13397 /// vdiv.f32 d16, d17, d16
13398 /// becomes:
13399 /// vcvt.f32.s32 d16, d16, #3
13400 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13401 const ARMSubtarget *Subtarget) {
13402 if (!Subtarget->hasNEON())
13403 return SDValue();
13405 SDValue Op = N->getOperand(0);
13406 unsigned OpOpcode = Op.getNode()->getOpcode();
13407 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13408 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13409 return SDValue();
13411 SDValue ConstVec = N->getOperand(1);
13412 if (!isa<BuildVectorSDNode>(ConstVec))
13413 return SDValue();
13415 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13416 uint32_t FloatBits = FloatTy.getSizeInBits();
13417 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13418 uint32_t IntBits = IntTy.getSizeInBits();
13419 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13420 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13421 // These instructions only exist converting from i32 to f32. We can handle
13422 // smaller integers by generating an extra extend, but larger ones would
13423 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13424 // these intructions only support v2i32/v4i32 types.
13425 return SDValue();
13428 BitVector UndefElements;
13429 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13430 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13431 if (C == -1 || C == 0 || C > 32)
13432 return SDValue();
13434 SDLoc dl(N);
13435 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13436 SDValue ConvInput = Op.getOperand(0);
13437 if (IntBits < FloatBits)
13438 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13439 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13440 ConvInput);
13442 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13443 Intrinsic::arm_neon_vcvtfxu2fp;
13444 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13445 Op.getValueType(),
13446 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13447 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13450 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13451 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13452 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13453 switch (IntNo) {
13454 default:
13455 // Don't do anything for most intrinsics.
13456 break;
13458 // Vector shifts: check for immediate versions and lower them.
13459 // Note: This is done during DAG combining instead of DAG legalizing because
13460 // the build_vectors for 64-bit vector element shift counts are generally
13461 // not legal, and it is hard to see their values after they get legalized to
13462 // loads from a constant pool.
13463 case Intrinsic::arm_neon_vshifts:
13464 case Intrinsic::arm_neon_vshiftu:
13465 case Intrinsic::arm_neon_vrshifts:
13466 case Intrinsic::arm_neon_vrshiftu:
13467 case Intrinsic::arm_neon_vrshiftn:
13468 case Intrinsic::arm_neon_vqshifts:
13469 case Intrinsic::arm_neon_vqshiftu:
13470 case Intrinsic::arm_neon_vqshiftsu:
13471 case Intrinsic::arm_neon_vqshiftns:
13472 case Intrinsic::arm_neon_vqshiftnu:
13473 case Intrinsic::arm_neon_vqshiftnsu:
13474 case Intrinsic::arm_neon_vqrshiftns:
13475 case Intrinsic::arm_neon_vqrshiftnu:
13476 case Intrinsic::arm_neon_vqrshiftnsu: {
13477 EVT VT = N->getOperand(1).getValueType();
13478 int64_t Cnt;
13479 unsigned VShiftOpc = 0;
13481 switch (IntNo) {
13482 case Intrinsic::arm_neon_vshifts:
13483 case Intrinsic::arm_neon_vshiftu:
13484 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13485 VShiftOpc = ARMISD::VSHLIMM;
13486 break;
13488 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13489 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13490 : ARMISD::VSHRuIMM);
13491 break;
13493 return SDValue();
13495 case Intrinsic::arm_neon_vrshifts:
13496 case Intrinsic::arm_neon_vrshiftu:
13497 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13498 break;
13499 return SDValue();
13501 case Intrinsic::arm_neon_vqshifts:
13502 case Intrinsic::arm_neon_vqshiftu:
13503 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13504 break;
13505 return SDValue();
13507 case Intrinsic::arm_neon_vqshiftsu:
13508 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13509 break;
13510 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13512 case Intrinsic::arm_neon_vrshiftn:
13513 case Intrinsic::arm_neon_vqshiftns:
13514 case Intrinsic::arm_neon_vqshiftnu:
13515 case Intrinsic::arm_neon_vqshiftnsu:
13516 case Intrinsic::arm_neon_vqrshiftns:
13517 case Intrinsic::arm_neon_vqrshiftnu:
13518 case Intrinsic::arm_neon_vqrshiftnsu:
13519 // Narrowing shifts require an immediate right shift.
13520 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13521 break;
13522 llvm_unreachable("invalid shift count for narrowing vector shift "
13523 "intrinsic");
13525 default:
13526 llvm_unreachable("unhandled vector shift");
13529 switch (IntNo) {
13530 case Intrinsic::arm_neon_vshifts:
13531 case Intrinsic::arm_neon_vshiftu:
13532 // Opcode already set above.
13533 break;
13534 case Intrinsic::arm_neon_vrshifts:
13535 VShiftOpc = ARMISD::VRSHRsIMM;
13536 break;
13537 case Intrinsic::arm_neon_vrshiftu:
13538 VShiftOpc = ARMISD::VRSHRuIMM;
13539 break;
13540 case Intrinsic::arm_neon_vrshiftn:
13541 VShiftOpc = ARMISD::VRSHRNIMM;
13542 break;
13543 case Intrinsic::arm_neon_vqshifts:
13544 VShiftOpc = ARMISD::VQSHLsIMM;
13545 break;
13546 case Intrinsic::arm_neon_vqshiftu:
13547 VShiftOpc = ARMISD::VQSHLuIMM;
13548 break;
13549 case Intrinsic::arm_neon_vqshiftsu:
13550 VShiftOpc = ARMISD::VQSHLsuIMM;
13551 break;
13552 case Intrinsic::arm_neon_vqshiftns:
13553 VShiftOpc = ARMISD::VQSHRNsIMM;
13554 break;
13555 case Intrinsic::arm_neon_vqshiftnu:
13556 VShiftOpc = ARMISD::VQSHRNuIMM;
13557 break;
13558 case Intrinsic::arm_neon_vqshiftnsu:
13559 VShiftOpc = ARMISD::VQSHRNsuIMM;
13560 break;
13561 case Intrinsic::arm_neon_vqrshiftns:
13562 VShiftOpc = ARMISD::VQRSHRNsIMM;
13563 break;
13564 case Intrinsic::arm_neon_vqrshiftnu:
13565 VShiftOpc = ARMISD::VQRSHRNuIMM;
13566 break;
13567 case Intrinsic::arm_neon_vqrshiftnsu:
13568 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13569 break;
13572 SDLoc dl(N);
13573 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13574 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13577 case Intrinsic::arm_neon_vshiftins: {
13578 EVT VT = N->getOperand(1).getValueType();
13579 int64_t Cnt;
13580 unsigned VShiftOpc = 0;
13582 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13583 VShiftOpc = ARMISD::VSLIIMM;
13584 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13585 VShiftOpc = ARMISD::VSRIIMM;
13586 else {
13587 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13590 SDLoc dl(N);
13591 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13592 N->getOperand(1), N->getOperand(2),
13593 DAG.getConstant(Cnt, dl, MVT::i32));
13596 case Intrinsic::arm_neon_vqrshifts:
13597 case Intrinsic::arm_neon_vqrshiftu:
13598 // No immediate versions of these to check for.
13599 break;
13602 return SDValue();
13605 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13606 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13607 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13608 /// vector element shift counts are generally not legal, and it is hard to see
13609 /// their values after they get legalized to loads from a constant pool.
13610 static SDValue PerformShiftCombine(SDNode *N,
13611 TargetLowering::DAGCombinerInfo &DCI,
13612 const ARMSubtarget *ST) {
13613 SelectionDAG &DAG = DCI.DAG;
13614 EVT VT = N->getValueType(0);
13615 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13616 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13617 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13618 SDValue N1 = N->getOperand(1);
13619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13620 SDValue N0 = N->getOperand(0);
13621 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13622 DAG.MaskedValueIsZero(N0.getOperand(0),
13623 APInt::getHighBitsSet(32, 16)))
13624 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13628 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13629 N->getOperand(0)->getOpcode() == ISD::AND &&
13630 N->getOperand(0)->hasOneUse()) {
13631 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13632 return SDValue();
13633 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13634 // usually show up because instcombine prefers to canonicalize it to
13635 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13636 // out of GEP lowering in some cases.
13637 SDValue N0 = N->getOperand(0);
13638 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13639 if (!ShiftAmtNode)
13640 return SDValue();
13641 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13642 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13643 if (!AndMaskNode)
13644 return SDValue();
13645 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13646 // Don't transform uxtb/uxth.
13647 if (AndMask == 255 || AndMask == 65535)
13648 return SDValue();
13649 if (isMask_32(AndMask)) {
13650 uint32_t MaskedBits = countLeadingZeros(AndMask);
13651 if (MaskedBits > ShiftAmt) {
13652 SDLoc DL(N);
13653 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13654 DAG.getConstant(MaskedBits, DL, MVT::i32));
13655 return DAG.getNode(
13656 ISD::SRL, DL, MVT::i32, SHL,
13657 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13662 // Nothing to be done for scalar shifts.
13663 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13664 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13665 return SDValue();
13666 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13667 return SDValue();
13669 int64_t Cnt;
13671 switch (N->getOpcode()) {
13672 default: llvm_unreachable("unexpected shift opcode");
13674 case ISD::SHL:
13675 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13676 SDLoc dl(N);
13677 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13678 DAG.getConstant(Cnt, dl, MVT::i32));
13680 break;
13682 case ISD::SRA:
13683 case ISD::SRL:
13684 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13685 unsigned VShiftOpc =
13686 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13687 SDLoc dl(N);
13688 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13689 DAG.getConstant(Cnt, dl, MVT::i32));
13692 return SDValue();
13695 // Look for a sign/zero extend of a larger than legal load. This can be split
13696 // into two extending loads, which are simpler to deal with than an arbitrary
13697 // sign extend.
13698 SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
13699 SDValue N0 = N->getOperand(0);
13700 if (N0.getOpcode() != ISD::LOAD)
13701 return SDValue();
13702 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
13703 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
13704 LD->getExtensionType() != ISD::NON_EXTLOAD)
13705 return SDValue();
13706 EVT FromVT = LD->getValueType(0);
13707 EVT ToVT = N->getValueType(0);
13708 if (!ToVT.isVector())
13709 return SDValue();
13710 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
13711 EVT ToEltVT = ToVT.getVectorElementType();
13712 EVT FromEltVT = FromVT.getVectorElementType();
13714 unsigned NumElements = 0;
13715 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
13716 NumElements = 4;
13717 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
13718 NumElements = 8;
13719 if (NumElements == 0 ||
13720 FromVT.getVectorNumElements() == NumElements ||
13721 FromVT.getVectorNumElements() % NumElements != 0 ||
13722 !isPowerOf2_32(NumElements))
13723 return SDValue();
13725 SDLoc DL(LD);
13726 // Details about the old load
13727 SDValue Ch = LD->getChain();
13728 SDValue BasePtr = LD->getBasePtr();
13729 unsigned Alignment = LD->getOriginalAlignment();
13730 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
13731 AAMDNodes AAInfo = LD->getAAInfo();
13733 ISD::LoadExtType NewExtType =
13734 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
13735 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
13736 EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext());
13737 EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
13738 unsigned NewOffset = NewFromVT.getSizeInBits() / 8;
13739 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
13741 // Split the load in half, each side of which is extended separately. This
13742 // is good enough, as legalisation will take it from there. They are either
13743 // already legal or they will be split further into something that is
13744 // legal.
13745 SDValue NewLoad1 =
13746 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset,
13747 LD->getPointerInfo(), NewFromVT, Alignment, MMOFlags, AAInfo);
13748 SDValue NewLoad2 =
13749 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
13750 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
13751 Alignment, MMOFlags, AAInfo);
13753 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13754 SDValue(NewLoad1.getNode(), 1),
13755 SDValue(NewLoad2.getNode(), 1));
13756 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
13757 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2);
13760 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13761 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13762 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13763 const ARMSubtarget *ST) {
13764 SDValue N0 = N->getOperand(0);
13766 // Check for sign- and zero-extensions of vector extract operations of 8-
13767 // and 16-bit vector elements. NEON supports these directly. They are
13768 // handled during DAG combining because type legalization will promote them
13769 // to 32-bit types and it is messy to recognize the operations after that.
13770 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13771 SDValue Vec = N0.getOperand(0);
13772 SDValue Lane = N0.getOperand(1);
13773 EVT VT = N->getValueType(0);
13774 EVT EltVT = N0.getValueType();
13775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13777 if (VT == MVT::i32 &&
13778 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13779 TLI.isTypeLegal(Vec.getValueType()) &&
13780 isa<ConstantSDNode>(Lane)) {
13782 unsigned Opc = 0;
13783 switch (N->getOpcode()) {
13784 default: llvm_unreachable("unexpected opcode");
13785 case ISD::SIGN_EXTEND:
13786 Opc = ARMISD::VGETLANEs;
13787 break;
13788 case ISD::ZERO_EXTEND:
13789 case ISD::ANY_EXTEND:
13790 Opc = ARMISD::VGETLANEu;
13791 break;
13793 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13797 if (ST->hasMVEIntegerOps())
13798 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
13799 return NewLoad;
13801 return SDValue();
13804 static const APInt *isPowerOf2Constant(SDValue V) {
13805 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13806 if (!C)
13807 return nullptr;
13808 const APInt *CV = &C->getAPIntValue();
13809 return CV->isPowerOf2() ? CV : nullptr;
13812 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13813 // If we have a CMOV, OR and AND combination such as:
13814 // if (x & CN)
13815 // y |= CM;
13817 // And:
13818 // * CN is a single bit;
13819 // * All bits covered by CM are known zero in y
13821 // Then we can convert this into a sequence of BFI instructions. This will
13822 // always be a win if CM is a single bit, will always be no worse than the
13823 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13824 // three bits (due to the extra IT instruction).
13826 SDValue Op0 = CMOV->getOperand(0);
13827 SDValue Op1 = CMOV->getOperand(1);
13828 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13829 auto CC = CCNode->getAPIntValue().getLimitedValue();
13830 SDValue CmpZ = CMOV->getOperand(4);
13832 // The compare must be against zero.
13833 if (!isNullConstant(CmpZ->getOperand(1)))
13834 return SDValue();
13836 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13837 SDValue And = CmpZ->getOperand(0);
13838 if (And->getOpcode() != ISD::AND)
13839 return SDValue();
13840 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13841 if (!AndC)
13842 return SDValue();
13843 SDValue X = And->getOperand(0);
13845 if (CC == ARMCC::EQ) {
13846 // We're performing an "equal to zero" compare. Swap the operands so we
13847 // canonicalize on a "not equal to zero" compare.
13848 std::swap(Op0, Op1);
13849 } else {
13850 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13853 if (Op1->getOpcode() != ISD::OR)
13854 return SDValue();
13856 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13857 if (!OrC)
13858 return SDValue();
13859 SDValue Y = Op1->getOperand(0);
13861 if (Op0 != Y)
13862 return SDValue();
13864 // Now, is it profitable to continue?
13865 APInt OrCI = OrC->getAPIntValue();
13866 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13867 if (OrCI.countPopulation() > Heuristic)
13868 return SDValue();
13870 // Lastly, can we determine that the bits defined by OrCI
13871 // are zero in Y?
13872 KnownBits Known = DAG.computeKnownBits(Y);
13873 if ((OrCI & Known.Zero) != OrCI)
13874 return SDValue();
13876 // OK, we can do the combine.
13877 SDValue V = Y;
13878 SDLoc dl(X);
13879 EVT VT = X.getValueType();
13880 unsigned BitInX = AndC->logBase2();
13882 if (BitInX != 0) {
13883 // We must shift X first.
13884 X = DAG.getNode(ISD::SRL, dl, VT, X,
13885 DAG.getConstant(BitInX, dl, VT));
13888 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13889 BitInY < NumActiveBits; ++BitInY) {
13890 if (OrCI[BitInY] == 0)
13891 continue;
13892 APInt Mask(VT.getSizeInBits(), 0);
13893 Mask.setBit(BitInY);
13894 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13895 // Confusingly, the operand is an *inverted* mask.
13896 DAG.getConstant(~Mask, dl, VT));
13899 return V;
13902 // Given N, the value controlling the conditional branch, search for the loop
13903 // intrinsic, returning it, along with how the value is used. We need to handle
13904 // patterns such as the following:
13905 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13906 // (brcond (setcc (loop.decrement), 0, eq), exit)
13907 // (brcond (setcc (loop.decrement), 0, ne), header)
13908 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13909 bool &Negate) {
13910 switch (N->getOpcode()) {
13911 default:
13912 break;
13913 case ISD::XOR: {
13914 if (!isa<ConstantSDNode>(N.getOperand(1)))
13915 return SDValue();
13916 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13917 return SDValue();
13918 Negate = !Negate;
13919 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
13921 case ISD::SETCC: {
13922 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
13923 if (!Const)
13924 return SDValue();
13925 if (Const->isNullValue())
13926 Imm = 0;
13927 else if (Const->isOne())
13928 Imm = 1;
13929 else
13930 return SDValue();
13931 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
13932 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
13934 case ISD::INTRINSIC_W_CHAIN: {
13935 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
13936 if (IntOp != Intrinsic::test_set_loop_iterations &&
13937 IntOp != Intrinsic::loop_decrement_reg)
13938 return SDValue();
13939 return N;
13942 return SDValue();
13945 static SDValue PerformHWLoopCombine(SDNode *N,
13946 TargetLowering::DAGCombinerInfo &DCI,
13947 const ARMSubtarget *ST) {
13949 // The hwloop intrinsics that we're interested are used for control-flow,
13950 // either for entering or exiting the loop:
13951 // - test.set.loop.iterations will test whether its operand is zero. If it
13952 // is zero, the proceeding branch should not enter the loop.
13953 // - loop.decrement.reg also tests whether its operand is zero. If it is
13954 // zero, the proceeding branch should not branch back to the beginning of
13955 // the loop.
13956 // So here, we need to check that how the brcond is using the result of each
13957 // of the intrinsics to ensure that we're branching to the right place at the
13958 // right time.
13960 ISD::CondCode CC;
13961 SDValue Cond;
13962 int Imm = 1;
13963 bool Negate = false;
13964 SDValue Chain = N->getOperand(0);
13965 SDValue Dest;
13967 if (N->getOpcode() == ISD::BRCOND) {
13968 CC = ISD::SETEQ;
13969 Cond = N->getOperand(1);
13970 Dest = N->getOperand(2);
13971 } else {
13972 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
13973 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13974 Cond = N->getOperand(2);
13975 Dest = N->getOperand(4);
13976 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
13977 if (!Const->isOne() && !Const->isNullValue())
13978 return SDValue();
13979 Imm = Const->getZExtValue();
13980 } else
13981 return SDValue();
13984 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
13985 if (!Int)
13986 return SDValue();
13988 if (Negate)
13989 CC = ISD::getSetCCInverse(CC, true);
13991 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
13992 return (CC == ISD::SETEQ && Imm == 0) ||
13993 (CC == ISD::SETNE && Imm == 1) ||
13994 (CC == ISD::SETLT && Imm == 1) ||
13995 (CC == ISD::SETULT && Imm == 1);
13998 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
13999 return (CC == ISD::SETEQ && Imm == 1) ||
14000 (CC == ISD::SETNE && Imm == 0) ||
14001 (CC == ISD::SETGT && Imm == 0) ||
14002 (CC == ISD::SETUGT && Imm == 0) ||
14003 (CC == ISD::SETGE && Imm == 1) ||
14004 (CC == ISD::SETUGE && Imm == 1);
14007 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
14008 "unsupported condition");
14010 SDLoc dl(Int);
14011 SelectionDAG &DAG = DCI.DAG;
14012 SDValue Elements = Int.getOperand(2);
14013 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
14014 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
14015 && "expected single br user");
14016 SDNode *Br = *N->use_begin();
14017 SDValue OtherTarget = Br->getOperand(1);
14019 // Update the unconditional branch to branch to the given Dest.
14020 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
14021 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
14022 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
14023 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
14026 if (IntOp == Intrinsic::test_set_loop_iterations) {
14027 SDValue Res;
14028 // We expect this 'instruction' to branch when the counter is zero.
14029 if (IsTrueIfZero(CC, Imm)) {
14030 SDValue Ops[] = { Chain, Elements, Dest };
14031 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14032 } else {
14033 // The logic is the reverse of what we need for WLS, so find the other
14034 // basic block target: the target of the proceeding br.
14035 UpdateUncondBr(Br, Dest, DAG);
14037 SDValue Ops[] = { Chain, Elements, OtherTarget };
14038 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14040 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
14041 return Res;
14042 } else {
14043 SDValue Size = DAG.getTargetConstant(
14044 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
14045 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
14046 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
14047 DAG.getVTList(MVT::i32, MVT::Other), Args);
14048 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
14050 // We expect this instruction to branch when the count is not zero.
14051 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
14053 // Update the unconditional branch to target the loop preheader if we've
14054 // found the condition has been reversed.
14055 if (Target == OtherTarget)
14056 UpdateUncondBr(Br, Dest, DAG);
14058 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14059 SDValue(LoopDec.getNode(), 1), Chain);
14061 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
14062 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
14064 return SDValue();
14067 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
14068 SDValue
14069 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
14070 SDValue Cmp = N->getOperand(4);
14071 if (Cmp.getOpcode() != ARMISD::CMPZ)
14072 // Only looking at NE cases.
14073 return SDValue();
14075 EVT VT = N->getValueType(0);
14076 SDLoc dl(N);
14077 SDValue LHS = Cmp.getOperand(0);
14078 SDValue RHS = Cmp.getOperand(1);
14079 SDValue Chain = N->getOperand(0);
14080 SDValue BB = N->getOperand(1);
14081 SDValue ARMcc = N->getOperand(2);
14082 ARMCC::CondCodes CC =
14083 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
14085 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
14086 // -> (brcond Chain BB CC CPSR Cmp)
14087 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
14088 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
14089 LHS->getOperand(0)->hasOneUse()) {
14090 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
14091 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
14092 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14093 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
14094 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
14095 (LHS01C && LHS01C->getZExtValue() == 1) &&
14096 (LHS1C && LHS1C->getZExtValue() == 1) &&
14097 (RHSC && RHSC->getZExtValue() == 0)) {
14098 return DAG.getNode(
14099 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
14100 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
14104 return SDValue();
14107 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
14108 SDValue
14109 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
14110 SDValue Cmp = N->getOperand(4);
14111 if (Cmp.getOpcode() != ARMISD::CMPZ)
14112 // Only looking at EQ and NE cases.
14113 return SDValue();
14115 EVT VT = N->getValueType(0);
14116 SDLoc dl(N);
14117 SDValue LHS = Cmp.getOperand(0);
14118 SDValue RHS = Cmp.getOperand(1);
14119 SDValue FalseVal = N->getOperand(0);
14120 SDValue TrueVal = N->getOperand(1);
14121 SDValue ARMcc = N->getOperand(2);
14122 ARMCC::CondCodes CC =
14123 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
14125 // BFI is only available on V6T2+.
14126 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
14127 SDValue R = PerformCMOVToBFICombine(N, DAG);
14128 if (R)
14129 return R;
14132 // Simplify
14133 // mov r1, r0
14134 // cmp r1, x
14135 // mov r0, y
14136 // moveq r0, x
14137 // to
14138 // cmp r0, x
14139 // movne r0, y
14141 // mov r1, r0
14142 // cmp r1, x
14143 // mov r0, x
14144 // movne r0, y
14145 // to
14146 // cmp r0, x
14147 // movne r0, y
14148 /// FIXME: Turn this into a target neutral optimization?
14149 SDValue Res;
14150 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
14151 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
14152 N->getOperand(3), Cmp);
14153 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
14154 SDValue ARMcc;
14155 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
14156 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
14157 N->getOperand(3), NewCmp);
14160 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
14161 // -> (cmov F T CC CPSR Cmp)
14162 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
14163 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
14164 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14165 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
14166 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
14167 (LHS1C && LHS1C->getZExtValue() == 1) &&
14168 (RHSC && RHSC->getZExtValue() == 0)) {
14169 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
14170 LHS->getOperand(2), LHS->getOperand(3),
14171 LHS->getOperand(4));
14175 if (!VT.isInteger())
14176 return SDValue();
14178 // Materialize a boolean comparison for integers so we can avoid branching.
14179 if (isNullConstant(FalseVal)) {
14180 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
14181 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
14182 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
14183 // right 5 bits will make that 32 be 1, otherwise it will be 0.
14184 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
14185 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
14186 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
14187 DAG.getConstant(5, dl, MVT::i32));
14188 } else {
14189 // CMOV 0, 1, ==, (CMPZ x, y) ->
14190 // (ADDCARRY (SUB x, y), t:0, t:1)
14191 // where t = (SUBCARRY 0, (SUB x, y), 0)
14193 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
14194 // x != y. In other words, a carry C == 1 when x == y, C == 0
14195 // otherwise.
14196 // The final ADDCARRY computes
14197 // x - y + (0 - (x - y)) + C == C
14198 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
14199 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14200 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
14201 // ISD::SUBCARRY returns a borrow but we want the carry here
14202 // actually.
14203 SDValue Carry =
14204 DAG.getNode(ISD::SUB, dl, MVT::i32,
14205 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
14206 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
14208 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
14209 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
14210 // This seems pointless but will allow us to combine it further below.
14211 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14212 SDValue Sub =
14213 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14214 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14215 Sub.getValue(1), SDValue());
14216 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
14217 N->getOperand(3), CPSRGlue.getValue(1));
14218 FalseVal = Sub;
14220 } else if (isNullConstant(TrueVal)) {
14221 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
14222 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
14223 // This seems pointless but will allow us to combine it further below
14224 // Note that we change == for != as this is the dual for the case above.
14225 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14226 SDValue Sub =
14227 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14228 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14229 Sub.getValue(1), SDValue());
14230 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
14231 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
14232 N->getOperand(3), CPSRGlue.getValue(1));
14233 FalseVal = Sub;
14237 // On Thumb1, the DAG above may be further combined if z is a power of 2
14238 // (z == 2 ^ K).
14239 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
14240 // t1 = (USUBO (SUB x, y), 1)
14241 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
14242 // Result = if K != 0 then (SHL t2:0, K) else t2:0
14244 // This also handles the special case of comparing against zero; it's
14245 // essentially, the same pattern, except there's no SUBS:
14246 // CMOV x, z, !=, (CMPZ x, 0) ->
14247 // t1 = (USUBO x, 1)
14248 // t2 = (SUBCARRY x, t1:0, t1:1)
14249 // Result = if K != 0 then (SHL t2:0, K) else t2:0
14250 const APInt *TrueConst;
14251 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
14252 ((FalseVal.getOpcode() == ARMISD::SUBS &&
14253 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
14254 (FalseVal == LHS && isNullConstant(RHS))) &&
14255 (TrueConst = isPowerOf2Constant(TrueVal))) {
14256 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14257 unsigned ShiftAmount = TrueConst->logBase2();
14258 if (ShiftAmount)
14259 TrueVal = DAG.getConstant(1, dl, VT);
14260 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
14261 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
14263 if (ShiftAmount)
14264 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
14265 DAG.getConstant(ShiftAmount, dl, MVT::i32));
14268 if (Res.getNode()) {
14269 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
14270 // Capture demanded bits information that would be otherwise lost.
14271 if (Known.Zero == 0xfffffffe)
14272 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14273 DAG.getValueType(MVT::i1));
14274 else if (Known.Zero == 0xffffff00)
14275 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14276 DAG.getValueType(MVT::i8));
14277 else if (Known.Zero == 0xffff0000)
14278 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14279 DAG.getValueType(MVT::i16));
14282 return Res;
14285 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
14286 DAGCombinerInfo &DCI) const {
14287 switch (N->getOpcode()) {
14288 default: break;
14289 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
14290 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
14291 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
14292 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
14293 case ISD::SUB: return PerformSUBCombine(N, DCI);
14294 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
14295 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
14296 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
14297 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
14298 case ISD::BRCOND:
14299 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
14300 case ARMISD::ADDC:
14301 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
14302 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
14303 case ARMISD::BFI: return PerformBFICombine(N, DCI);
14304 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
14305 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
14306 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
14307 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
14308 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
14309 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
14310 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
14311 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
14312 case ISD::FP_TO_SINT:
14313 case ISD::FP_TO_UINT:
14314 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
14315 case ISD::FDIV:
14316 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
14317 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
14318 case ISD::SHL:
14319 case ISD::SRA:
14320 case ISD::SRL:
14321 return PerformShiftCombine(N, DCI, Subtarget);
14322 case ISD::SIGN_EXTEND:
14323 case ISD::ZERO_EXTEND:
14324 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
14325 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
14326 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
14327 case ISD::LOAD: return PerformLOADCombine(N, DCI);
14328 case ARMISD::VLD1DUP:
14329 case ARMISD::VLD2DUP:
14330 case ARMISD::VLD3DUP:
14331 case ARMISD::VLD4DUP:
14332 return PerformVLDCombine(N, DCI);
14333 case ARMISD::BUILD_VECTOR:
14334 return PerformARMBUILD_VECTORCombine(N, DCI);
14335 case ARMISD::PREDICATE_CAST:
14336 return PerformPREDICATE_CASTCombine(N, DCI);
14337 case ARMISD::SMULWB: {
14338 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14339 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14340 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14341 return SDValue();
14342 break;
14344 case ARMISD::SMULWT: {
14345 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14346 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14347 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14348 return SDValue();
14349 break;
14351 case ARMISD::SMLALBB: {
14352 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14353 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14354 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14355 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14356 return SDValue();
14357 break;
14359 case ARMISD::SMLALBT: {
14360 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
14361 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14362 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
14363 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14364 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
14365 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
14366 return SDValue();
14367 break;
14369 case ARMISD::SMLALTB: {
14370 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
14371 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14372 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
14373 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14374 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
14375 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
14376 return SDValue();
14377 break;
14379 case ARMISD::SMLALTT: {
14380 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14381 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14382 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14383 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14384 return SDValue();
14385 break;
14387 case ISD::INTRINSIC_VOID:
14388 case ISD::INTRINSIC_W_CHAIN:
14389 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14390 case Intrinsic::arm_neon_vld1:
14391 case Intrinsic::arm_neon_vld1x2:
14392 case Intrinsic::arm_neon_vld1x3:
14393 case Intrinsic::arm_neon_vld1x4:
14394 case Intrinsic::arm_neon_vld2:
14395 case Intrinsic::arm_neon_vld3:
14396 case Intrinsic::arm_neon_vld4:
14397 case Intrinsic::arm_neon_vld2lane:
14398 case Intrinsic::arm_neon_vld3lane:
14399 case Intrinsic::arm_neon_vld4lane:
14400 case Intrinsic::arm_neon_vld2dup:
14401 case Intrinsic::arm_neon_vld3dup:
14402 case Intrinsic::arm_neon_vld4dup:
14403 case Intrinsic::arm_neon_vst1:
14404 case Intrinsic::arm_neon_vst1x2:
14405 case Intrinsic::arm_neon_vst1x3:
14406 case Intrinsic::arm_neon_vst1x4:
14407 case Intrinsic::arm_neon_vst2:
14408 case Intrinsic::arm_neon_vst3:
14409 case Intrinsic::arm_neon_vst4:
14410 case Intrinsic::arm_neon_vst2lane:
14411 case Intrinsic::arm_neon_vst3lane:
14412 case Intrinsic::arm_neon_vst4lane:
14413 return PerformVLDCombine(N, DCI);
14414 default: break;
14416 break;
14418 return SDValue();
14421 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
14422 EVT VT) const {
14423 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
14426 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
14427 unsigned Alignment,
14428 MachineMemOperand::Flags,
14429 bool *Fast) const {
14430 // Depends what it gets converted into if the type is weird.
14431 if (!VT.isSimple())
14432 return false;
14434 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
14435 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
14436 auto Ty = VT.getSimpleVT().SimpleTy;
14438 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
14439 // Unaligned access can use (for example) LRDB, LRDH, LDR
14440 if (AllowsUnaligned) {
14441 if (Fast)
14442 *Fast = Subtarget->hasV7Ops();
14443 return true;
14447 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
14448 // For any little-endian targets with neon, we can support unaligned ld/st
14449 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
14450 // A big-endian target may also explicitly support unaligned accesses
14451 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
14452 if (Fast)
14453 *Fast = true;
14454 return true;
14458 if (!Subtarget->hasMVEIntegerOps())
14459 return false;
14461 // These are for predicates
14462 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14463 if (Fast)
14464 *Fast = true;
14465 return true;
14468 // These are for truncated stores/narrowing loads. They are fine so long as
14469 // the alignment is at least the size of the item being loaded
14470 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
14471 Alignment >= VT.getScalarSizeInBits() / 8) {
14472 if (Fast)
14473 *Fast = true;
14474 return true;
14477 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
14478 // VSTRW.U32 all store the vector register in exactly the same format, and
14479 // differ only in the range of their immediate offset field and the required
14480 // alignment. So there is always a store that can be used, regardless of
14481 // actual type.
14483 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
14484 // VREV64.8) pair and get the same effect. This will likely be better than
14485 // aligning the vector through the stack.
14486 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
14487 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
14488 Ty == MVT::v2f64) {
14489 if (Fast)
14490 *Fast = true;
14491 return true;
14494 return false;
14497 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14498 unsigned AlignCheck) {
14499 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14500 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14503 EVT ARMTargetLowering::getOptimalMemOpType(
14504 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14505 bool ZeroMemset, bool MemcpyStrSrc,
14506 const AttributeList &FuncAttributes) const {
14507 // See if we can use NEON instructions for this...
14508 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14509 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14510 bool Fast;
14511 if (Size >= 16 &&
14512 (memOpAlign(SrcAlign, DstAlign, 16) ||
14513 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14514 MachineMemOperand::MONone, &Fast) &&
14515 Fast))) {
14516 return MVT::v2f64;
14517 } else if (Size >= 8 &&
14518 (memOpAlign(SrcAlign, DstAlign, 8) ||
14519 (allowsMisalignedMemoryAccesses(
14520 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14521 Fast))) {
14522 return MVT::f64;
14526 // Let the target-independent logic figure it out.
14527 return MVT::Other;
14530 // 64-bit integers are split into their high and low parts and held in two
14531 // different registers, so the trunc is free since the low register can just
14532 // be used.
14533 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14534 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14535 return false;
14536 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14537 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14538 return (SrcBits == 64 && DestBits == 32);
14541 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14542 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14543 !DstVT.isInteger())
14544 return false;
14545 unsigned SrcBits = SrcVT.getSizeInBits();
14546 unsigned DestBits = DstVT.getSizeInBits();
14547 return (SrcBits == 64 && DestBits == 32);
14550 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14551 if (Val.getOpcode() != ISD::LOAD)
14552 return false;
14554 EVT VT1 = Val.getValueType();
14555 if (!VT1.isSimple() || !VT1.isInteger() ||
14556 !VT2.isSimple() || !VT2.isInteger())
14557 return false;
14559 switch (VT1.getSimpleVT().SimpleTy) {
14560 default: break;
14561 case MVT::i1:
14562 case MVT::i8:
14563 case MVT::i16:
14564 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14565 return true;
14568 return false;
14571 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14572 if (!VT.isSimple())
14573 return false;
14575 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14576 // negate values directly (fneg is free). So, we don't want to let the DAG
14577 // combiner rewrite fneg into xors and some other instructions. For f16 and
14578 // FullFP16 argument passing, some bitcast nodes may be introduced,
14579 // triggering this DAG combine rewrite, so we are avoiding that with this.
14580 switch (VT.getSimpleVT().SimpleTy) {
14581 default: break;
14582 case MVT::f16:
14583 return Subtarget->hasFullFP16();
14586 return false;
14589 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14590 /// of the vector elements.
14591 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14592 auto areExtDoubled = [](Instruction *Ext) {
14593 return Ext->getType()->getScalarSizeInBits() ==
14594 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14597 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14598 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14599 !areExtDoubled(cast<Instruction>(Ext1)) ||
14600 !areExtDoubled(cast<Instruction>(Ext2)))
14601 return false;
14603 return true;
14606 /// Check if sinking \p I's operands to I's basic block is profitable, because
14607 /// the operands can be folded into a target instruction, e.g.
14608 /// sext/zext can be folded into vsubl.
14609 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14610 SmallVectorImpl<Use *> &Ops) const {
14611 if (!I->getType()->isVectorTy())
14612 return false;
14614 if (Subtarget->hasNEON()) {
14615 switch (I->getOpcode()) {
14616 case Instruction::Sub:
14617 case Instruction::Add: {
14618 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14619 return false;
14620 Ops.push_back(&I->getOperandUse(0));
14621 Ops.push_back(&I->getOperandUse(1));
14622 return true;
14624 default:
14625 return false;
14629 if (!Subtarget->hasMVEIntegerOps())
14630 return false;
14632 auto IsSinker = [](Instruction *I, int Operand) {
14633 switch (I->getOpcode()) {
14634 case Instruction::Add:
14635 case Instruction::Mul:
14636 return true;
14637 case Instruction::Sub:
14638 return Operand == 1;
14639 default:
14640 return false;
14644 int Op = 0;
14645 if (!isa<ShuffleVectorInst>(I->getOperand(Op)))
14646 Op = 1;
14647 if (!IsSinker(I, Op))
14648 return false;
14649 if (!match(I->getOperand(Op),
14650 m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()),
14651 m_Undef(), m_Zero()))) {
14652 return false;
14654 Instruction *Shuffle = cast<Instruction>(I->getOperand(Op));
14655 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
14656 // and vector registers
14657 for (Use &U : Shuffle->uses()) {
14658 Instruction *Insn = cast<Instruction>(U.getUser());
14659 if (!IsSinker(Insn, U.getOperandNo()))
14660 return false;
14662 Ops.push_back(&Shuffle->getOperandUse(0));
14663 Ops.push_back(&I->getOperandUse(Op));
14664 return true;
14667 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14668 EVT VT = ExtVal.getValueType();
14670 if (!isTypeLegal(VT))
14671 return false;
14673 // Don't create a loadext if we can fold the extension into a wide/long
14674 // instruction.
14675 // If there's more than one user instruction, the loadext is desirable no
14676 // matter what. There can be two uses by the same instruction.
14677 if (ExtVal->use_empty() ||
14678 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14679 return true;
14681 SDNode *U = *ExtVal->use_begin();
14682 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14683 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14684 return false;
14686 return true;
14689 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14690 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14691 return false;
14693 if (!isTypeLegal(EVT::getEVT(Ty1)))
14694 return false;
14696 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14698 // Assuming the caller doesn't have a zeroext or signext return parameter,
14699 // truncation all the way down to i1 is valid.
14700 return true;
14703 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14704 const AddrMode &AM, Type *Ty,
14705 unsigned AS) const {
14706 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14707 if (Subtarget->hasFPAO())
14708 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14709 return 0;
14711 return -1;
14714 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14715 if (V < 0)
14716 return false;
14718 unsigned Scale = 1;
14719 switch (VT.getSimpleVT().SimpleTy) {
14720 case MVT::i1:
14721 case MVT::i8:
14722 // Scale == 1;
14723 break;
14724 case MVT::i16:
14725 // Scale == 2;
14726 Scale = 2;
14727 break;
14728 default:
14729 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14730 // Scale == 4;
14731 Scale = 4;
14732 break;
14735 if ((V & (Scale - 1)) != 0)
14736 return false;
14737 return isUInt<5>(V / Scale);
14740 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14741 const ARMSubtarget *Subtarget) {
14742 if (!VT.isInteger() && !VT.isFloatingPoint())
14743 return false;
14744 if (VT.isVector() && Subtarget->hasNEON())
14745 return false;
14746 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14747 !Subtarget->hasMVEFloatOps())
14748 return false;
14750 bool IsNeg = false;
14751 if (V < 0) {
14752 IsNeg = true;
14753 V = -V;
14756 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14758 // MVE: size * imm7
14759 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14760 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14761 case MVT::i32:
14762 case MVT::f32:
14763 return isShiftedUInt<7,2>(V);
14764 case MVT::i16:
14765 case MVT::f16:
14766 return isShiftedUInt<7,1>(V);
14767 case MVT::i8:
14768 return isUInt<7>(V);
14769 default:
14770 return false;
14774 // half VLDR: 2 * imm8
14775 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14776 return isShiftedUInt<8, 1>(V);
14777 // VLDR and LDRD: 4 * imm8
14778 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14779 return isShiftedUInt<8, 2>(V);
14781 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14782 // + imm12 or - imm8
14783 if (IsNeg)
14784 return isUInt<8>(V);
14785 return isUInt<12>(V);
14788 return false;
14791 /// isLegalAddressImmediate - Return true if the integer value can be used
14792 /// as the offset of the target addressing mode for load / store of the
14793 /// given type.
14794 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14795 const ARMSubtarget *Subtarget) {
14796 if (V == 0)
14797 return true;
14799 if (!VT.isSimple())
14800 return false;
14802 if (Subtarget->isThumb1Only())
14803 return isLegalT1AddressImmediate(V, VT);
14804 else if (Subtarget->isThumb2())
14805 return isLegalT2AddressImmediate(V, VT, Subtarget);
14807 // ARM mode.
14808 if (V < 0)
14809 V = - V;
14810 switch (VT.getSimpleVT().SimpleTy) {
14811 default: return false;
14812 case MVT::i1:
14813 case MVT::i8:
14814 case MVT::i32:
14815 // +- imm12
14816 return isUInt<12>(V);
14817 case MVT::i16:
14818 // +- imm8
14819 return isUInt<8>(V);
14820 case MVT::f32:
14821 case MVT::f64:
14822 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14823 return false;
14824 return isShiftedUInt<8, 2>(V);
14828 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14829 EVT VT) const {
14830 int Scale = AM.Scale;
14831 if (Scale < 0)
14832 return false;
14834 switch (VT.getSimpleVT().SimpleTy) {
14835 default: return false;
14836 case MVT::i1:
14837 case MVT::i8:
14838 case MVT::i16:
14839 case MVT::i32:
14840 if (Scale == 1)
14841 return true;
14842 // r + r << imm
14843 Scale = Scale & ~1;
14844 return Scale == 2 || Scale == 4 || Scale == 8;
14845 case MVT::i64:
14846 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14847 // version in Thumb mode.
14848 // r + r
14849 if (Scale == 1)
14850 return true;
14851 // r * 2 (this can be lowered to r + r).
14852 if (!AM.HasBaseReg && Scale == 2)
14853 return true;
14854 return false;
14855 case MVT::isVoid:
14856 // Note, we allow "void" uses (basically, uses that aren't loads or
14857 // stores), because arm allows folding a scale into many arithmetic
14858 // operations. This should be made more precise and revisited later.
14860 // Allow r << imm, but the imm has to be a multiple of two.
14861 if (Scale & 1) return false;
14862 return isPowerOf2_32(Scale);
14866 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14867 EVT VT) const {
14868 const int Scale = AM.Scale;
14870 // Negative scales are not supported in Thumb1.
14871 if (Scale < 0)
14872 return false;
14874 // Thumb1 addressing modes do not support register scaling excepting the
14875 // following cases:
14876 // 1. Scale == 1 means no scaling.
14877 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14878 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14881 /// isLegalAddressingMode - Return true if the addressing mode represented
14882 /// by AM is legal for this target, for a load/store of the specified type.
14883 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14884 const AddrMode &AM, Type *Ty,
14885 unsigned AS, Instruction *I) const {
14886 EVT VT = getValueType(DL, Ty, true);
14887 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14888 return false;
14890 // Can never fold addr of global into load/store.
14891 if (AM.BaseGV)
14892 return false;
14894 switch (AM.Scale) {
14895 case 0: // no scale reg, must be "r+i" or "r", or "i".
14896 break;
14897 default:
14898 // ARM doesn't support any R+R*scale+imm addr modes.
14899 if (AM.BaseOffs)
14900 return false;
14902 if (!VT.isSimple())
14903 return false;
14905 if (Subtarget->isThumb1Only())
14906 return isLegalT1ScaledAddressingMode(AM, VT);
14908 if (Subtarget->isThumb2())
14909 return isLegalT2ScaledAddressingMode(AM, VT);
14911 int Scale = AM.Scale;
14912 switch (VT.getSimpleVT().SimpleTy) {
14913 default: return false;
14914 case MVT::i1:
14915 case MVT::i8:
14916 case MVT::i32:
14917 if (Scale < 0) Scale = -Scale;
14918 if (Scale == 1)
14919 return true;
14920 // r + r << imm
14921 return isPowerOf2_32(Scale & ~1);
14922 case MVT::i16:
14923 case MVT::i64:
14924 // r +/- r
14925 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
14926 return true;
14927 // r * 2 (this can be lowered to r + r).
14928 if (!AM.HasBaseReg && Scale == 2)
14929 return true;
14930 return false;
14932 case MVT::isVoid:
14933 // Note, we allow "void" uses (basically, uses that aren't loads or
14934 // stores), because arm allows folding a scale into many arithmetic
14935 // operations. This should be made more precise and revisited later.
14937 // Allow r << imm, but the imm has to be a multiple of two.
14938 if (Scale & 1) return false;
14939 return isPowerOf2_32(Scale);
14942 return true;
14945 /// isLegalICmpImmediate - Return true if the specified immediate is legal
14946 /// icmp immediate, that is the target has icmp instructions which can compare
14947 /// a register against the immediate without having to materialize the
14948 /// immediate into a register.
14949 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14950 // Thumb2 and ARM modes can use cmn for negative immediates.
14951 if (!Subtarget->isThumb())
14952 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
14953 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
14954 if (Subtarget->isThumb2())
14955 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
14956 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
14957 // Thumb1 doesn't have cmn, and only 8-bit immediates.
14958 return Imm >= 0 && Imm <= 255;
14961 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
14962 /// *or sub* immediate, that is the target has add or sub instructions which can
14963 /// add a register with the immediate without having to materialize the
14964 /// immediate into a register.
14965 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14966 // Same encoding for add/sub, just flip the sign.
14967 int64_t AbsImm = std::abs(Imm);
14968 if (!Subtarget->isThumb())
14969 return ARM_AM::getSOImmVal(AbsImm) != -1;
14970 if (Subtarget->isThumb2())
14971 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
14972 // Thumb1 only has 8-bit unsigned immediate.
14973 return AbsImm >= 0 && AbsImm <= 255;
14976 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
14977 bool isSEXTLoad, SDValue &Base,
14978 SDValue &Offset, bool &isInc,
14979 SelectionDAG &DAG) {
14980 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14981 return false;
14983 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
14984 // AddressingMode 3
14985 Base = Ptr->getOperand(0);
14986 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14987 int RHSC = (int)RHS->getZExtValue();
14988 if (RHSC < 0 && RHSC > -256) {
14989 assert(Ptr->getOpcode() == ISD::ADD);
14990 isInc = false;
14991 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14992 return true;
14995 isInc = (Ptr->getOpcode() == ISD::ADD);
14996 Offset = Ptr->getOperand(1);
14997 return true;
14998 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
14999 // AddressingMode 2
15000 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15001 int RHSC = (int)RHS->getZExtValue();
15002 if (RHSC < 0 && RHSC > -0x1000) {
15003 assert(Ptr->getOpcode() == ISD::ADD);
15004 isInc = false;
15005 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15006 Base = Ptr->getOperand(0);
15007 return true;
15011 if (Ptr->getOpcode() == ISD::ADD) {
15012 isInc = true;
15013 ARM_AM::ShiftOpc ShOpcVal=
15014 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
15015 if (ShOpcVal != ARM_AM::no_shift) {
15016 Base = Ptr->getOperand(1);
15017 Offset = Ptr->getOperand(0);
15018 } else {
15019 Base = Ptr->getOperand(0);
15020 Offset = Ptr->getOperand(1);
15022 return true;
15025 isInc = (Ptr->getOpcode() == ISD::ADD);
15026 Base = Ptr->getOperand(0);
15027 Offset = Ptr->getOperand(1);
15028 return true;
15031 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
15032 return false;
15035 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
15036 bool isSEXTLoad, SDValue &Base,
15037 SDValue &Offset, bool &isInc,
15038 SelectionDAG &DAG) {
15039 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15040 return false;
15042 Base = Ptr->getOperand(0);
15043 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15044 int RHSC = (int)RHS->getZExtValue();
15045 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
15046 assert(Ptr->getOpcode() == ISD::ADD);
15047 isInc = false;
15048 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15049 return true;
15050 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
15051 isInc = Ptr->getOpcode() == ISD::ADD;
15052 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
15053 return true;
15057 return false;
15060 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
15061 bool isSEXTLoad, bool isLE, SDValue &Base,
15062 SDValue &Offset, bool &isInc,
15063 SelectionDAG &DAG) {
15064 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15065 return false;
15066 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
15067 return false;
15069 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
15070 int RHSC = (int)RHS->getZExtValue();
15072 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
15073 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
15074 assert(Ptr->getOpcode() == ISD::ADD);
15075 isInc = false;
15076 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15077 return true;
15078 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
15079 isInc = Ptr->getOpcode() == ISD::ADD;
15080 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
15081 return true;
15083 return false;
15086 // Try to find a matching instruction based on s/zext, Alignment, Offset and
15087 // (in BE) type.
15088 Base = Ptr->getOperand(0);
15089 if (VT == MVT::v4i16) {
15090 if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
15091 return true;
15092 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
15093 if (IsInRange(RHSC, 0x80, 1))
15094 return true;
15095 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) &&
15096 IsInRange(RHSC, 0x80, 4))
15097 return true;
15098 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) &&
15099 IsInRange(RHSC, 0x80, 2))
15100 return true;
15101 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
15102 return true;
15103 return false;
15106 /// getPreIndexedAddressParts - returns true by value, base pointer and
15107 /// offset pointer and addressing mode by reference if the node's address
15108 /// can be legally represented as pre-indexed load / store address.
15109 bool
15110 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
15111 SDValue &Offset,
15112 ISD::MemIndexedMode &AM,
15113 SelectionDAG &DAG) const {
15114 if (Subtarget->isThumb1Only())
15115 return false;
15117 EVT VT;
15118 SDValue Ptr;
15119 unsigned Align;
15120 bool isSEXTLoad = false;
15121 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15122 Ptr = LD->getBasePtr();
15123 VT = LD->getMemoryVT();
15124 Align = LD->getAlignment();
15125 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15126 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15127 Ptr = ST->getBasePtr();
15128 VT = ST->getMemoryVT();
15129 Align = ST->getAlignment();
15130 } else
15131 return false;
15133 bool isInc;
15134 bool isLegal = false;
15135 if (VT.isVector())
15136 isLegal = Subtarget->hasMVEIntegerOps() &&
15137 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
15138 Subtarget->isLittle(), Base, Offset,
15139 isInc, DAG);
15140 else {
15141 if (Subtarget->isThumb2())
15142 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
15143 Offset, isInc, DAG);
15144 else
15145 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
15146 Offset, isInc, DAG);
15148 if (!isLegal)
15149 return false;
15151 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
15152 return true;
15155 /// getPostIndexedAddressParts - returns true by value, base pointer and
15156 /// offset pointer and addressing mode by reference if this node can be
15157 /// combined with a load / store to form a post-indexed load / store.
15158 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
15159 SDValue &Base,
15160 SDValue &Offset,
15161 ISD::MemIndexedMode &AM,
15162 SelectionDAG &DAG) const {
15163 EVT VT;
15164 SDValue Ptr;
15165 unsigned Align;
15166 bool isSEXTLoad = false, isNonExt;
15167 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15168 VT = LD->getMemoryVT();
15169 Ptr = LD->getBasePtr();
15170 Align = LD->getAlignment();
15171 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15172 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
15173 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15174 VT = ST->getMemoryVT();
15175 Ptr = ST->getBasePtr();
15176 Align = ST->getAlignment();
15177 isNonExt = !ST->isTruncatingStore();
15178 } else
15179 return false;
15181 if (Subtarget->isThumb1Only()) {
15182 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
15183 // must be non-extending/truncating, i32, with an offset of 4.
15184 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
15185 if (Op->getOpcode() != ISD::ADD || !isNonExt)
15186 return false;
15187 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15188 if (!RHS || RHS->getZExtValue() != 4)
15189 return false;
15191 Offset = Op->getOperand(1);
15192 Base = Op->getOperand(0);
15193 AM = ISD::POST_INC;
15194 return true;
15197 bool isInc;
15198 bool isLegal = false;
15199 if (VT.isVector())
15200 isLegal = Subtarget->hasMVEIntegerOps() &&
15201 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad,
15202 Subtarget->isLittle(), Base, Offset,
15203 isInc, DAG);
15204 else {
15205 if (Subtarget->isThumb2())
15206 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15207 isInc, DAG);
15208 else
15209 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15210 isInc, DAG);
15212 if (!isLegal)
15213 return false;
15215 if (Ptr != Base) {
15216 // Swap base ptr and offset to catch more post-index load / store when
15217 // it's legal. In Thumb2 mode, offset must be an immediate.
15218 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
15219 !Subtarget->isThumb2())
15220 std::swap(Base, Offset);
15222 // Post-indexed load / store update the base pointer.
15223 if (Ptr != Base)
15224 return false;
15227 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
15228 return true;
15231 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15232 KnownBits &Known,
15233 const APInt &DemandedElts,
15234 const SelectionDAG &DAG,
15235 unsigned Depth) const {
15236 unsigned BitWidth = Known.getBitWidth();
15237 Known.resetAll();
15238 switch (Op.getOpcode()) {
15239 default: break;
15240 case ARMISD::ADDC:
15241 case ARMISD::ADDE:
15242 case ARMISD::SUBC:
15243 case ARMISD::SUBE:
15244 // Special cases when we convert a carry to a boolean.
15245 if (Op.getResNo() == 0) {
15246 SDValue LHS = Op.getOperand(0);
15247 SDValue RHS = Op.getOperand(1);
15248 // (ADDE 0, 0, C) will give us a single bit.
15249 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
15250 isNullConstant(RHS)) {
15251 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15252 return;
15255 break;
15256 case ARMISD::CMOV: {
15257 // Bits are known zero/one if known on the LHS and RHS.
15258 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
15259 if (Known.isUnknown())
15260 return;
15262 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
15263 Known.Zero &= KnownRHS.Zero;
15264 Known.One &= KnownRHS.One;
15265 return;
15267 case ISD::INTRINSIC_W_CHAIN: {
15268 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
15269 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
15270 switch (IntID) {
15271 default: return;
15272 case Intrinsic::arm_ldaex:
15273 case Intrinsic::arm_ldrex: {
15274 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
15275 unsigned MemBits = VT.getScalarSizeInBits();
15276 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
15277 return;
15281 case ARMISD::BFI: {
15282 // Conservatively, we can recurse down the first operand
15283 // and just mask out all affected bits.
15284 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
15286 // The operand to BFI is already a mask suitable for removing the bits it
15287 // sets.
15288 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
15289 const APInt &Mask = CI->getAPIntValue();
15290 Known.Zero &= Mask;
15291 Known.One &= Mask;
15292 return;
15294 case ARMISD::VGETLANEs:
15295 case ARMISD::VGETLANEu: {
15296 const SDValue &SrcSV = Op.getOperand(0);
15297 EVT VecVT = SrcSV.getValueType();
15298 assert(VecVT.isVector() && "VGETLANE expected a vector type");
15299 const unsigned NumSrcElts = VecVT.getVectorNumElements();
15300 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
15301 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
15302 "VGETLANE index out of bounds");
15303 unsigned Idx = Pos->getZExtValue();
15304 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
15305 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
15307 EVT VT = Op.getValueType();
15308 const unsigned DstSz = VT.getScalarSizeInBits();
15309 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
15310 (void)SrcSz;
15311 assert(SrcSz == Known.getBitWidth());
15312 assert(DstSz > SrcSz);
15313 if (Op.getOpcode() == ARMISD::VGETLANEs)
15314 Known = Known.sext(DstSz);
15315 else {
15316 Known = Known.zext(DstSz, true /* extended bits are known zero */);
15318 assert(DstSz == Known.getBitWidth());
15319 break;
15324 bool
15325 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
15326 const APInt &DemandedAPInt,
15327 TargetLoweringOpt &TLO) const {
15328 // Delay optimization, so we don't have to deal with illegal types, or block
15329 // optimizations.
15330 if (!TLO.LegalOps)
15331 return false;
15333 // Only optimize AND for now.
15334 if (Op.getOpcode() != ISD::AND)
15335 return false;
15337 EVT VT = Op.getValueType();
15339 // Ignore vectors.
15340 if (VT.isVector())
15341 return false;
15343 assert(VT == MVT::i32 && "Unexpected integer type");
15345 // Make sure the RHS really is a constant.
15346 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15347 if (!C)
15348 return false;
15350 unsigned Mask = C->getZExtValue();
15352 unsigned Demanded = DemandedAPInt.getZExtValue();
15353 unsigned ShrunkMask = Mask & Demanded;
15354 unsigned ExpandedMask = Mask | ~Demanded;
15356 // If the mask is all zeros, let the target-independent code replace the
15357 // result with zero.
15358 if (ShrunkMask == 0)
15359 return false;
15361 // If the mask is all ones, erase the AND. (Currently, the target-independent
15362 // code won't do this, so we have to do it explicitly to avoid an infinite
15363 // loop in obscure cases.)
15364 if (ExpandedMask == ~0U)
15365 return TLO.CombineTo(Op, Op.getOperand(0));
15367 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
15368 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
15370 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
15371 if (NewMask == Mask)
15372 return true;
15373 SDLoc DL(Op);
15374 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
15375 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
15376 return TLO.CombineTo(Op, NewOp);
15379 // Prefer uxtb mask.
15380 if (IsLegalMask(0xFF))
15381 return UseMask(0xFF);
15383 // Prefer uxth mask.
15384 if (IsLegalMask(0xFFFF))
15385 return UseMask(0xFFFF);
15387 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
15388 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15389 if (ShrunkMask < 256)
15390 return UseMask(ShrunkMask);
15392 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
15393 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15394 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
15395 return UseMask(ExpandedMask);
15397 // Potential improvements:
15399 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
15400 // We could try to prefer Thumb1 immediates which can be lowered to a
15401 // two-instruction sequence.
15402 // We could try to recognize more legal ARM/Thumb2 immediates here.
15404 return false;
15408 //===----------------------------------------------------------------------===//
15409 // ARM Inline Assembly Support
15410 //===----------------------------------------------------------------------===//
15412 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
15413 // Looking for "rev" which is V6+.
15414 if (!Subtarget->hasV6Ops())
15415 return false;
15417 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15418 std::string AsmStr = IA->getAsmString();
15419 SmallVector<StringRef, 4> AsmPieces;
15420 SplitString(AsmStr, AsmPieces, ";\n");
15422 switch (AsmPieces.size()) {
15423 default: return false;
15424 case 1:
15425 AsmStr = AsmPieces[0];
15426 AsmPieces.clear();
15427 SplitString(AsmStr, AsmPieces, " \t,");
15429 // rev $0, $1
15430 if (AsmPieces.size() == 3 &&
15431 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
15432 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
15433 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15434 if (Ty && Ty->getBitWidth() == 32)
15435 return IntrinsicLowering::LowerToByteSwap(CI);
15437 break;
15440 return false;
15443 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
15444 // At this point, we have to lower this constraint to something else, so we
15445 // lower it to an "r" or "w". However, by doing this we will force the result
15446 // to be in register, while the X constraint is much more permissive.
15448 // Although we are correct (we are free to emit anything, without
15449 // constraints), we might break use cases that would expect us to be more
15450 // efficient and emit something else.
15451 if (!Subtarget->hasVFP2Base())
15452 return "r";
15453 if (ConstraintVT.isFloatingPoint())
15454 return "w";
15455 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
15456 (ConstraintVT.getSizeInBits() == 64 ||
15457 ConstraintVT.getSizeInBits() == 128))
15458 return "w";
15460 return "r";
15463 /// getConstraintType - Given a constraint letter, return the type of
15464 /// constraint it is for this target.
15465 ARMTargetLowering::ConstraintType
15466 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
15467 unsigned S = Constraint.size();
15468 if (S == 1) {
15469 switch (Constraint[0]) {
15470 default: break;
15471 case 'l': return C_RegisterClass;
15472 case 'w': return C_RegisterClass;
15473 case 'h': return C_RegisterClass;
15474 case 'x': return C_RegisterClass;
15475 case 't': return C_RegisterClass;
15476 case 'j': return C_Immediate; // Constant for movw.
15477 // An address with a single base register. Due to the way we
15478 // currently handle addresses it is the same as an 'r' memory constraint.
15479 case 'Q': return C_Memory;
15481 } else if (S == 2) {
15482 switch (Constraint[0]) {
15483 default: break;
15484 case 'T': return C_RegisterClass;
15485 // All 'U+' constraints are addresses.
15486 case 'U': return C_Memory;
15489 return TargetLowering::getConstraintType(Constraint);
15492 /// Examine constraint type and operand type and determine a weight value.
15493 /// This object must already have been set up with the operand type
15494 /// and the current alternative constraint selected.
15495 TargetLowering::ConstraintWeight
15496 ARMTargetLowering::getSingleConstraintMatchWeight(
15497 AsmOperandInfo &info, const char *constraint) const {
15498 ConstraintWeight weight = CW_Invalid;
15499 Value *CallOperandVal = info.CallOperandVal;
15500 // If we don't have a value, we can't do a match,
15501 // but allow it at the lowest weight.
15502 if (!CallOperandVal)
15503 return CW_Default;
15504 Type *type = CallOperandVal->getType();
15505 // Look at the constraint type.
15506 switch (*constraint) {
15507 default:
15508 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15509 break;
15510 case 'l':
15511 if (type->isIntegerTy()) {
15512 if (Subtarget->isThumb())
15513 weight = CW_SpecificReg;
15514 else
15515 weight = CW_Register;
15517 break;
15518 case 'w':
15519 if (type->isFloatingPointTy())
15520 weight = CW_Register;
15521 break;
15523 return weight;
15526 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
15528 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
15529 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
15530 switch (Constraint.size()) {
15531 case 1:
15532 // GCC ARM Constraint Letters
15533 switch (Constraint[0]) {
15534 case 'l': // Low regs or general regs.
15535 if (Subtarget->isThumb())
15536 return RCPair(0U, &ARM::tGPRRegClass);
15537 return RCPair(0U, &ARM::GPRRegClass);
15538 case 'h': // High regs or no regs.
15539 if (Subtarget->isThumb())
15540 return RCPair(0U, &ARM::hGPRRegClass);
15541 break;
15542 case 'r':
15543 if (Subtarget->isThumb1Only())
15544 return RCPair(0U, &ARM::tGPRRegClass);
15545 return RCPair(0U, &ARM::GPRRegClass);
15546 case 'w':
15547 if (VT == MVT::Other)
15548 break;
15549 if (VT == MVT::f32)
15550 return RCPair(0U, &ARM::SPRRegClass);
15551 if (VT.getSizeInBits() == 64)
15552 return RCPair(0U, &ARM::DPRRegClass);
15553 if (VT.getSizeInBits() == 128)
15554 return RCPair(0U, &ARM::QPRRegClass);
15555 break;
15556 case 'x':
15557 if (VT == MVT::Other)
15558 break;
15559 if (VT == MVT::f32)
15560 return RCPair(0U, &ARM::SPR_8RegClass);
15561 if (VT.getSizeInBits() == 64)
15562 return RCPair(0U, &ARM::DPR_8RegClass);
15563 if (VT.getSizeInBits() == 128)
15564 return RCPair(0U, &ARM::QPR_8RegClass);
15565 break;
15566 case 't':
15567 if (VT == MVT::Other)
15568 break;
15569 if (VT == MVT::f32 || VT == MVT::i32)
15570 return RCPair(0U, &ARM::SPRRegClass);
15571 if (VT.getSizeInBits() == 64)
15572 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15573 if (VT.getSizeInBits() == 128)
15574 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15575 break;
15577 break;
15579 case 2:
15580 if (Constraint[0] == 'T') {
15581 switch (Constraint[1]) {
15582 default:
15583 break;
15584 case 'e':
15585 return RCPair(0U, &ARM::tGPREvenRegClass);
15586 case 'o':
15587 return RCPair(0U, &ARM::tGPROddRegClass);
15590 break;
15592 default:
15593 break;
15596 if (StringRef("{cc}").equals_lower(Constraint))
15597 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15599 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15602 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15603 /// vector. If it is invalid, don't add anything to Ops.
15604 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15605 std::string &Constraint,
15606 std::vector<SDValue>&Ops,
15607 SelectionDAG &DAG) const {
15608 SDValue Result;
15610 // Currently only support length 1 constraints.
15611 if (Constraint.length() != 1) return;
15613 char ConstraintLetter = Constraint[0];
15614 switch (ConstraintLetter) {
15615 default: break;
15616 case 'j':
15617 case 'I': case 'J': case 'K': case 'L':
15618 case 'M': case 'N': case 'O':
15619 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15620 if (!C)
15621 return;
15623 int64_t CVal64 = C->getSExtValue();
15624 int CVal = (int) CVal64;
15625 // None of these constraints allow values larger than 32 bits. Check
15626 // that the value fits in an int.
15627 if (CVal != CVal64)
15628 return;
15630 switch (ConstraintLetter) {
15631 case 'j':
15632 // Constant suitable for movw, must be between 0 and
15633 // 65535.
15634 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
15635 if (CVal >= 0 && CVal <= 65535)
15636 break;
15637 return;
15638 case 'I':
15639 if (Subtarget->isThumb1Only()) {
15640 // This must be a constant between 0 and 255, for ADD
15641 // immediates.
15642 if (CVal >= 0 && CVal <= 255)
15643 break;
15644 } else if (Subtarget->isThumb2()) {
15645 // A constant that can be used as an immediate value in a
15646 // data-processing instruction.
15647 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15648 break;
15649 } else {
15650 // A constant that can be used as an immediate value in a
15651 // data-processing instruction.
15652 if (ARM_AM::getSOImmVal(CVal) != -1)
15653 break;
15655 return;
15657 case 'J':
15658 if (Subtarget->isThumb1Only()) {
15659 // This must be a constant between -255 and -1, for negated ADD
15660 // immediates. This can be used in GCC with an "n" modifier that
15661 // prints the negated value, for use with SUB instructions. It is
15662 // not useful otherwise but is implemented for compatibility.
15663 if (CVal >= -255 && CVal <= -1)
15664 break;
15665 } else {
15666 // This must be a constant between -4095 and 4095. It is not clear
15667 // what this constraint is intended for. Implemented for
15668 // compatibility with GCC.
15669 if (CVal >= -4095 && CVal <= 4095)
15670 break;
15672 return;
15674 case 'K':
15675 if (Subtarget->isThumb1Only()) {
15676 // A 32-bit value where only one byte has a nonzero value. Exclude
15677 // zero to match GCC. This constraint is used by GCC internally for
15678 // constants that can be loaded with a move/shift combination.
15679 // It is not useful otherwise but is implemented for compatibility.
15680 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15681 break;
15682 } else if (Subtarget->isThumb2()) {
15683 // A constant whose bitwise inverse can be used as an immediate
15684 // value in a data-processing instruction. This can be used in GCC
15685 // with a "B" modifier that prints the inverted value, for use with
15686 // BIC and MVN instructions. It is not useful otherwise but is
15687 // implemented for compatibility.
15688 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15689 break;
15690 } else {
15691 // A constant whose bitwise inverse can be used as an immediate
15692 // value in a data-processing instruction. This can be used in GCC
15693 // with a "B" modifier that prints the inverted value, for use with
15694 // BIC and MVN instructions. It is not useful otherwise but is
15695 // implemented for compatibility.
15696 if (ARM_AM::getSOImmVal(~CVal) != -1)
15697 break;
15699 return;
15701 case 'L':
15702 if (Subtarget->isThumb1Only()) {
15703 // This must be a constant between -7 and 7,
15704 // for 3-operand ADD/SUB immediate instructions.
15705 if (CVal >= -7 && CVal < 7)
15706 break;
15707 } else if (Subtarget->isThumb2()) {
15708 // A constant whose negation can be used as an immediate value in a
15709 // data-processing instruction. This can be used in GCC with an "n"
15710 // modifier that prints the negated value, for use with SUB
15711 // instructions. It is not useful otherwise but is implemented for
15712 // compatibility.
15713 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15714 break;
15715 } else {
15716 // A constant whose negation can be used as an immediate value in a
15717 // data-processing instruction. This can be used in GCC with an "n"
15718 // modifier that prints the negated value, for use with SUB
15719 // instructions. It is not useful otherwise but is implemented for
15720 // compatibility.
15721 if (ARM_AM::getSOImmVal(-CVal) != -1)
15722 break;
15724 return;
15726 case 'M':
15727 if (Subtarget->isThumb1Only()) {
15728 // This must be a multiple of 4 between 0 and 1020, for
15729 // ADD sp + immediate.
15730 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15731 break;
15732 } else {
15733 // A power of two or a constant between 0 and 32. This is used in
15734 // GCC for the shift amount on shifted register operands, but it is
15735 // useful in general for any shift amounts.
15736 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15737 break;
15739 return;
15741 case 'N':
15742 if (Subtarget->isThumb1Only()) {
15743 // This must be a constant between 0 and 31, for shift amounts.
15744 if (CVal >= 0 && CVal <= 31)
15745 break;
15747 return;
15749 case 'O':
15750 if (Subtarget->isThumb1Only()) {
15751 // This must be a multiple of 4 between -508 and 508, for
15752 // ADD/SUB sp = sp + immediate.
15753 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15754 break;
15756 return;
15758 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15759 break;
15762 if (Result.getNode()) {
15763 Ops.push_back(Result);
15764 return;
15766 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15769 static RTLIB::Libcall getDivRemLibcall(
15770 const SDNode *N, MVT::SimpleValueType SVT) {
15771 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15772 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15773 "Unhandled Opcode in getDivRemLibcall");
15774 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15775 N->getOpcode() == ISD::SREM;
15776 RTLIB::Libcall LC;
15777 switch (SVT) {
15778 default: llvm_unreachable("Unexpected request for libcall!");
15779 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15780 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15781 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15782 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15784 return LC;
15787 static TargetLowering::ArgListTy getDivRemArgList(
15788 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15789 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15790 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15791 "Unhandled Opcode in getDivRemArgList");
15792 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15793 N->getOpcode() == ISD::SREM;
15794 TargetLowering::ArgListTy Args;
15795 TargetLowering::ArgListEntry Entry;
15796 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15797 EVT ArgVT = N->getOperand(i).getValueType();
15798 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15799 Entry.Node = N->getOperand(i);
15800 Entry.Ty = ArgTy;
15801 Entry.IsSExt = isSigned;
15802 Entry.IsZExt = !isSigned;
15803 Args.push_back(Entry);
15805 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15806 std::swap(Args[0], Args[1]);
15807 return Args;
15810 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15811 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15812 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15813 Subtarget->isTargetWindows()) &&
15814 "Register-based DivRem lowering only");
15815 unsigned Opcode = Op->getOpcode();
15816 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15817 "Invalid opcode for Div/Rem lowering");
15818 bool isSigned = (Opcode == ISD::SDIVREM);
15819 EVT VT = Op->getValueType(0);
15820 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15821 SDLoc dl(Op);
15823 // If the target has hardware divide, use divide + multiply + subtract:
15824 // div = a / b
15825 // rem = a - b * div
15826 // return {div, rem}
15827 // This should be lowered into UDIV/SDIV + MLS later on.
15828 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15829 : Subtarget->hasDivideInARMMode();
15830 if (hasDivide && Op->getValueType(0).isSimple() &&
15831 Op->getSimpleValueType(0) == MVT::i32) {
15832 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15833 const SDValue Dividend = Op->getOperand(0);
15834 const SDValue Divisor = Op->getOperand(1);
15835 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15836 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15837 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15839 SDValue Values[2] = {Div, Rem};
15840 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15843 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15844 VT.getSimpleVT().SimpleTy);
15845 SDValue InChain = DAG.getEntryNode();
15847 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15848 DAG.getContext(),
15849 Subtarget);
15851 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15852 getPointerTy(DAG.getDataLayout()));
15854 Type *RetTy = StructType::get(Ty, Ty);
15856 if (Subtarget->isTargetWindows())
15857 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15859 TargetLowering::CallLoweringInfo CLI(DAG);
15860 CLI.setDebugLoc(dl).setChain(InChain)
15861 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15862 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15864 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15865 return CallInfo.first;
15868 // Lowers REM using divmod helpers
15869 // see RTABI section 4.2/4.3
15870 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15871 // Build return types (div and rem)
15872 std::vector<Type*> RetTyParams;
15873 Type *RetTyElement;
15875 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15876 default: llvm_unreachable("Unexpected request for libcall!");
15877 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15878 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15879 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15880 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15883 RetTyParams.push_back(RetTyElement);
15884 RetTyParams.push_back(RetTyElement);
15885 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15886 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15888 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15889 SimpleTy);
15890 SDValue InChain = DAG.getEntryNode();
15891 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15892 Subtarget);
15893 bool isSigned = N->getOpcode() == ISD::SREM;
15894 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15895 getPointerTy(DAG.getDataLayout()));
15897 if (Subtarget->isTargetWindows())
15898 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15900 // Lower call
15901 CallLoweringInfo CLI(DAG);
15902 CLI.setChain(InChain)
15903 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
15904 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
15905 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
15907 // Return second (rem) result operand (first contains div)
15908 SDNode *ResNode = CallResult.first.getNode();
15909 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
15910 return ResNode->getOperand(1);
15913 SDValue
15914 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
15915 assert(Subtarget->isTargetWindows() && "unsupported target platform");
15916 SDLoc DL(Op);
15918 // Get the inputs.
15919 SDValue Chain = Op.getOperand(0);
15920 SDValue Size = Op.getOperand(1);
15922 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
15923 "no-stack-arg-probe")) {
15924 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15925 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15926 Chain = SP.getValue(1);
15927 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
15928 if (Align)
15929 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
15930 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
15931 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
15932 SDValue Ops[2] = { SP, Chain };
15933 return DAG.getMergeValues(Ops, DL);
15936 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
15937 DAG.getConstant(2, DL, MVT::i32));
15939 SDValue Flag;
15940 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
15941 Flag = Chain.getValue(1);
15943 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15944 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
15946 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15947 Chain = NewSP.getValue(1);
15949 SDValue Ops[2] = { NewSP, Chain };
15950 return DAG.getMergeValues(Ops, DL);
15953 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
15954 SDValue SrcVal = Op.getOperand(0);
15955 const unsigned DstSz = Op.getValueType().getSizeInBits();
15956 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
15957 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
15958 "Unexpected type for custom-lowering FP_EXTEND");
15960 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15961 "With both FP DP and 16, any FP conversion is legal!");
15963 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
15964 "With FP16, 16 to 32 conversion is legal!");
15966 // Either we are converting from 16 -> 64, without FP16 and/or
15967 // FP.double-precision or without Armv8-fp. So we must do it in two
15968 // steps.
15969 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
15970 // without FP16. So we must do a function call.
15971 SDLoc Loc(Op);
15972 RTLIB::Libcall LC;
15973 MakeLibCallOptions CallOptions;
15974 if (SrcSz == 16) {
15975 // Instruction from 16 -> 32
15976 if (Subtarget->hasFP16())
15977 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
15978 // Lib call from 16 -> 32
15979 else {
15980 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
15981 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15982 "Unexpected type for custom-lowering FP_EXTEND");
15983 SrcVal =
15984 makeLibCall(DAG, LC, MVT::f32, SrcVal, CallOptions, Loc).first;
15988 if (DstSz != 64)
15989 return SrcVal;
15990 // For sure now SrcVal is 32 bits
15991 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
15992 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
15994 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
15995 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15996 "Unexpected type for custom-lowering FP_EXTEND");
15997 return makeLibCall(DAG, LC, MVT::f64, SrcVal, CallOptions, Loc).first;
16000 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
16001 SDValue SrcVal = Op.getOperand(0);
16002 EVT SrcVT = SrcVal.getValueType();
16003 EVT DstVT = Op.getValueType();
16004 const unsigned DstSz = Op.getValueType().getSizeInBits();
16005 const unsigned SrcSz = SrcVT.getSizeInBits();
16006 (void)DstSz;
16007 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
16008 "Unexpected type for custom-lowering FP_ROUND");
16010 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
16011 "With both FP DP and 16, any FP conversion is legal!");
16013 SDLoc Loc(Op);
16015 // Instruction from 32 -> 16 if hasFP16 is valid
16016 if (SrcSz == 32 && Subtarget->hasFP16())
16017 return Op;
16019 // Lib call from 32 -> 16 / 64 -> [32, 16]
16020 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
16021 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
16022 "Unexpected type for custom-lowering FP_ROUND");
16023 MakeLibCallOptions CallOptions;
16024 return makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, Loc).first;
16027 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
16028 SelectionDAG &DAG) const {
16029 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
16030 MVT HalfT = MVT::i32;
16031 SDLoc dl(N);
16032 SDValue Hi, Lo, Tmp;
16034 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
16035 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
16036 return ;
16038 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
16039 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
16041 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
16042 DAG.getConstant(0, dl, HalfT));
16043 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
16044 DAG.getConstant(1, dl, HalfT));
16046 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
16047 DAG.getConstant(OpTypeBits - 1, dl,
16048 getShiftAmountTy(HalfT, DAG.getDataLayout())));
16049 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
16050 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
16051 SDValue(Lo.getNode(), 1));
16052 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
16053 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
16055 Results.push_back(Lo);
16056 Results.push_back(Hi);
16059 bool
16060 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16061 // The ARM target isn't yet aware of offsets.
16062 return false;
16065 bool ARM::isBitFieldInvertedMask(unsigned v) {
16066 if (v == 0xffffffff)
16067 return false;
16069 // there can be 1's on either or both "outsides", all the "inside"
16070 // bits must be 0's
16071 return isShiftedMask_32(~v);
16074 /// isFPImmLegal - Returns true if the target can instruction select the
16075 /// specified FP immediate natively. If false, the legalizer will
16076 /// materialize the FP immediate as a load from a constant pool.
16077 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16078 bool ForCodeSize) const {
16079 if (!Subtarget->hasVFP3Base())
16080 return false;
16081 if (VT == MVT::f16 && Subtarget->hasFullFP16())
16082 return ARM_AM::getFP16Imm(Imm) != -1;
16083 if (VT == MVT::f32)
16084 return ARM_AM::getFP32Imm(Imm) != -1;
16085 if (VT == MVT::f64 && Subtarget->hasFP64())
16086 return ARM_AM::getFP64Imm(Imm) != -1;
16087 return false;
16090 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
16091 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
16092 /// specified in the intrinsic calls.
16093 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16094 const CallInst &I,
16095 MachineFunction &MF,
16096 unsigned Intrinsic) const {
16097 switch (Intrinsic) {
16098 case Intrinsic::arm_neon_vld1:
16099 case Intrinsic::arm_neon_vld2:
16100 case Intrinsic::arm_neon_vld3:
16101 case Intrinsic::arm_neon_vld4:
16102 case Intrinsic::arm_neon_vld2lane:
16103 case Intrinsic::arm_neon_vld3lane:
16104 case Intrinsic::arm_neon_vld4lane:
16105 case Intrinsic::arm_neon_vld2dup:
16106 case Intrinsic::arm_neon_vld3dup:
16107 case Intrinsic::arm_neon_vld4dup: {
16108 Info.opc = ISD::INTRINSIC_W_CHAIN;
16109 // Conservatively set memVT to the entire set of vectors loaded.
16110 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16111 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
16112 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16113 Info.ptrVal = I.getArgOperand(0);
16114 Info.offset = 0;
16115 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
16116 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
16117 // volatile loads with NEON intrinsics not supported
16118 Info.flags = MachineMemOperand::MOLoad;
16119 return true;
16121 case Intrinsic::arm_neon_vld1x2:
16122 case Intrinsic::arm_neon_vld1x3:
16123 case Intrinsic::arm_neon_vld1x4: {
16124 Info.opc = ISD::INTRINSIC_W_CHAIN;
16125 // Conservatively set memVT to the entire set of vectors loaded.
16126 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16127 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
16128 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16129 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
16130 Info.offset = 0;
16131 Info.align.reset();
16132 // volatile loads with NEON intrinsics not supported
16133 Info.flags = MachineMemOperand::MOLoad;
16134 return true;
16136 case Intrinsic::arm_neon_vst1:
16137 case Intrinsic::arm_neon_vst2:
16138 case Intrinsic::arm_neon_vst3:
16139 case Intrinsic::arm_neon_vst4:
16140 case Intrinsic::arm_neon_vst2lane:
16141 case Intrinsic::arm_neon_vst3lane:
16142 case Intrinsic::arm_neon_vst4lane: {
16143 Info.opc = ISD::INTRINSIC_VOID;
16144 // Conservatively set memVT to the entire set of vectors stored.
16145 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16146 unsigned NumElts = 0;
16147 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
16148 Type *ArgTy = I.getArgOperand(ArgI)->getType();
16149 if (!ArgTy->isVectorTy())
16150 break;
16151 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
16153 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16154 Info.ptrVal = I.getArgOperand(0);
16155 Info.offset = 0;
16156 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
16157 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
16158 // volatile stores with NEON intrinsics not supported
16159 Info.flags = MachineMemOperand::MOStore;
16160 return true;
16162 case Intrinsic::arm_neon_vst1x2:
16163 case Intrinsic::arm_neon_vst1x3:
16164 case Intrinsic::arm_neon_vst1x4: {
16165 Info.opc = ISD::INTRINSIC_VOID;
16166 // Conservatively set memVT to the entire set of vectors stored.
16167 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16168 unsigned NumElts = 0;
16169 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
16170 Type *ArgTy = I.getArgOperand(ArgI)->getType();
16171 if (!ArgTy->isVectorTy())
16172 break;
16173 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
16175 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16176 Info.ptrVal = I.getArgOperand(0);
16177 Info.offset = 0;
16178 Info.align.reset();
16179 // volatile stores with NEON intrinsics not supported
16180 Info.flags = MachineMemOperand::MOStore;
16181 return true;
16183 case Intrinsic::arm_ldaex:
16184 case Intrinsic::arm_ldrex: {
16185 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16186 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
16187 Info.opc = ISD::INTRINSIC_W_CHAIN;
16188 Info.memVT = MVT::getVT(PtrTy->getElementType());
16189 Info.ptrVal = I.getArgOperand(0);
16190 Info.offset = 0;
16191 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
16192 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16193 return true;
16195 case Intrinsic::arm_stlex:
16196 case Intrinsic::arm_strex: {
16197 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16198 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
16199 Info.opc = ISD::INTRINSIC_W_CHAIN;
16200 Info.memVT = MVT::getVT(PtrTy->getElementType());
16201 Info.ptrVal = I.getArgOperand(1);
16202 Info.offset = 0;
16203 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
16204 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16205 return true;
16207 case Intrinsic::arm_stlexd:
16208 case Intrinsic::arm_strexd:
16209 Info.opc = ISD::INTRINSIC_W_CHAIN;
16210 Info.memVT = MVT::i64;
16211 Info.ptrVal = I.getArgOperand(2);
16212 Info.offset = 0;
16213 Info.align = Align(8);
16214 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16215 return true;
16217 case Intrinsic::arm_ldaexd:
16218 case Intrinsic::arm_ldrexd:
16219 Info.opc = ISD::INTRINSIC_W_CHAIN;
16220 Info.memVT = MVT::i64;
16221 Info.ptrVal = I.getArgOperand(0);
16222 Info.offset = 0;
16223 Info.align = Align(8);
16224 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16225 return true;
16227 default:
16228 break;
16231 return false;
16234 /// Returns true if it is beneficial to convert a load of a constant
16235 /// to just the constant itself.
16236 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16237 Type *Ty) const {
16238 assert(Ty->isIntegerTy());
16240 unsigned Bits = Ty->getPrimitiveSizeInBits();
16241 if (Bits == 0 || Bits > 32)
16242 return false;
16243 return true;
16246 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
16247 unsigned Index) const {
16248 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
16249 return false;
16251 return (Index == 0 || Index == ResVT.getVectorNumElements());
16254 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
16255 ARM_MB::MemBOpt Domain) const {
16256 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16258 // First, if the target has no DMB, see what fallback we can use.
16259 if (!Subtarget->hasDataBarrier()) {
16260 // Some ARMv6 cpus can support data barriers with an mcr instruction.
16261 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
16262 // here.
16263 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
16264 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
16265 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
16266 Builder.getInt32(0), Builder.getInt32(7),
16267 Builder.getInt32(10), Builder.getInt32(5)};
16268 return Builder.CreateCall(MCR, args);
16269 } else {
16270 // Instead of using barriers, atomic accesses on these subtargets use
16271 // libcalls.
16272 llvm_unreachable("makeDMB on a target so old that it has no barriers");
16274 } else {
16275 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
16276 // Only a full system barrier exists in the M-class architectures.
16277 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
16278 Constant *CDomain = Builder.getInt32(Domain);
16279 return Builder.CreateCall(DMB, CDomain);
16283 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
16284 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
16285 Instruction *Inst,
16286 AtomicOrdering Ord) const {
16287 switch (Ord) {
16288 case AtomicOrdering::NotAtomic:
16289 case AtomicOrdering::Unordered:
16290 llvm_unreachable("Invalid fence: unordered/non-atomic");
16291 case AtomicOrdering::Monotonic:
16292 case AtomicOrdering::Acquire:
16293 return nullptr; // Nothing to do
16294 case AtomicOrdering::SequentiallyConsistent:
16295 if (!Inst->hasAtomicStore())
16296 return nullptr; // Nothing to do
16297 LLVM_FALLTHROUGH;
16298 case AtomicOrdering::Release:
16299 case AtomicOrdering::AcquireRelease:
16300 if (Subtarget->preferISHSTBarriers())
16301 return makeDMB(Builder, ARM_MB::ISHST);
16302 // FIXME: add a comment with a link to documentation justifying this.
16303 else
16304 return makeDMB(Builder, ARM_MB::ISH);
16306 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
16309 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
16310 Instruction *Inst,
16311 AtomicOrdering Ord) const {
16312 switch (Ord) {
16313 case AtomicOrdering::NotAtomic:
16314 case AtomicOrdering::Unordered:
16315 llvm_unreachable("Invalid fence: unordered/not-atomic");
16316 case AtomicOrdering::Monotonic:
16317 case AtomicOrdering::Release:
16318 return nullptr; // Nothing to do
16319 case AtomicOrdering::Acquire:
16320 case AtomicOrdering::AcquireRelease:
16321 case AtomicOrdering::SequentiallyConsistent:
16322 return makeDMB(Builder, ARM_MB::ISH);
16324 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
16327 // Loads and stores less than 64-bits are already atomic; ones above that
16328 // are doomed anyway, so defer to the default libcall and blame the OS when
16329 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16330 // anything for those.
16331 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16332 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
16333 return (Size == 64) && !Subtarget->isMClass();
16336 // Loads and stores less than 64-bits are already atomic; ones above that
16337 // are doomed anyway, so defer to the default libcall and blame the OS when
16338 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16339 // anything for those.
16340 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
16341 // guarantee, see DDI0406C ARM architecture reference manual,
16342 // sections A8.8.72-74 LDRD)
16343 TargetLowering::AtomicExpansionKind
16344 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16345 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
16346 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
16347 : AtomicExpansionKind::None;
16350 // For the real atomic operations, we have ldrex/strex up to 32 bits,
16351 // and up to 64 bits on the non-M profiles
16352 TargetLowering::AtomicExpansionKind
16353 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16354 if (AI->isFloatingPointOperation())
16355 return AtomicExpansionKind::CmpXChg;
16357 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
16358 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16359 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
16360 ? AtomicExpansionKind::LLSC
16361 : AtomicExpansionKind::None;
16364 TargetLowering::AtomicExpansionKind
16365 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
16366 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16367 // implement cmpxchg without spilling. If the address being exchanged is also
16368 // on the stack and close enough to the spill slot, this can lead to a
16369 // situation where the monitor always gets cleared and the atomic operation
16370 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16371 bool HasAtomicCmpXchg =
16372 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16373 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
16374 return AtomicExpansionKind::LLSC;
16375 return AtomicExpansionKind::None;
16378 bool ARMTargetLowering::shouldInsertFencesForAtomic(
16379 const Instruction *I) const {
16380 return InsertFencesForAtomic;
16383 // This has so far only been implemented for MachO.
16384 bool ARMTargetLowering::useLoadStackGuardNode() const {
16385 return Subtarget->isTargetMachO();
16388 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
16389 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16390 return TargetLowering::insertSSPDeclarations(M);
16392 // MSVC CRT has a global variable holding security cookie.
16393 M.getOrInsertGlobal("__security_cookie",
16394 Type::getInt8PtrTy(M.getContext()));
16396 // MSVC CRT has a function to validate security cookie.
16397 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16398 "__security_check_cookie", Type::getVoidTy(M.getContext()),
16399 Type::getInt8PtrTy(M.getContext()));
16400 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
16401 F->addAttribute(1, Attribute::AttrKind::InReg);
16404 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
16405 // MSVC CRT has a global variable holding security cookie.
16406 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16407 return M.getGlobalVariable("__security_cookie");
16408 return TargetLowering::getSDagStackGuard(M);
16411 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
16412 // MSVC CRT has a function to validate security cookie.
16413 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16414 return M.getFunction("__security_check_cookie");
16415 return TargetLowering::getSSPStackGuardCheck(M);
16418 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
16419 unsigned &Cost) const {
16420 // If we do not have NEON, vector types are not natively supported.
16421 if (!Subtarget->hasNEON())
16422 return false;
16424 // Floating point values and vector values map to the same register file.
16425 // Therefore, although we could do a store extract of a vector type, this is
16426 // better to leave at float as we have more freedom in the addressing mode for
16427 // those.
16428 if (VectorTy->isFPOrFPVectorTy())
16429 return false;
16431 // If the index is unknown at compile time, this is very expensive to lower
16432 // and it is not possible to combine the store with the extract.
16433 if (!isa<ConstantInt>(Idx))
16434 return false;
16436 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
16437 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
16438 // We can do a store + vector extract on any vector that fits perfectly in a D
16439 // or Q register.
16440 if (BitWidth == 64 || BitWidth == 128) {
16441 Cost = 0;
16442 return true;
16444 return false;
16447 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
16448 return Subtarget->hasV6T2Ops();
16451 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
16452 return Subtarget->hasV6T2Ops();
16455 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
16456 return !Subtarget->hasMinSize();
16459 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16460 AtomicOrdering Ord) const {
16461 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16462 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16463 bool IsAcquire = isAcquireOrStronger(Ord);
16465 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
16466 // intrinsic must return {i32, i32} and we have to recombine them into a
16467 // single i64 here.
16468 if (ValTy->getPrimitiveSizeInBits() == 64) {
16469 Intrinsic::ID Int =
16470 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
16471 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
16473 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16474 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
16476 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16477 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16478 if (!Subtarget->isLittle())
16479 std::swap (Lo, Hi);
16480 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16481 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16482 return Builder.CreateOr(
16483 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
16486 Type *Tys[] = { Addr->getType() };
16487 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
16488 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
16490 return Builder.CreateTruncOrBitCast(
16491 Builder.CreateCall(Ldrex, Addr),
16492 cast<PointerType>(Addr->getType())->getElementType());
16495 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16496 IRBuilder<> &Builder) const {
16497 if (!Subtarget->hasV7Ops())
16498 return;
16499 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16500 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
16503 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
16504 Value *Addr,
16505 AtomicOrdering Ord) const {
16506 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16507 bool IsRelease = isReleaseOrStronger(Ord);
16509 // Since the intrinsics must have legal type, the i64 intrinsics take two
16510 // parameters: "i32, i32". We must marshal Val into the appropriate form
16511 // before the call.
16512 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
16513 Intrinsic::ID Int =
16514 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
16515 Function *Strex = Intrinsic::getDeclaration(M, Int);
16516 Type *Int32Ty = Type::getInt32Ty(M->getContext());
16518 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
16519 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
16520 if (!Subtarget->isLittle())
16521 std::swap(Lo, Hi);
16522 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16523 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
16526 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
16527 Type *Tys[] = { Addr->getType() };
16528 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
16530 return Builder.CreateCall(
16531 Strex, {Builder.CreateZExtOrBitCast(
16532 Val, Strex->getFunctionType()->getParamType(0)),
16533 Addr});
16537 bool ARMTargetLowering::alignLoopsWithOptSize() const {
16538 return Subtarget->isMClass();
16541 /// A helper function for determining the number of interleaved accesses we
16542 /// will generate when lowering accesses of the given type.
16543 unsigned
16544 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
16545 const DataLayout &DL) const {
16546 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
16549 bool ARMTargetLowering::isLegalInterleavedAccessType(
16550 VectorType *VecTy, const DataLayout &DL) const {
16552 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16553 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16555 // Ensure the vector doesn't have f16 elements. Even though we could do an
16556 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16557 // f32.
16558 if (VecTy->getElementType()->isHalfTy())
16559 return false;
16561 // Ensure the number of vector elements is greater than 1.
16562 if (VecTy->getNumElements() < 2)
16563 return false;
16565 // Ensure the element type is legal.
16566 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16567 return false;
16569 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16570 // 128 will be split into multiple interleaved accesses.
16571 return VecSize == 64 || VecSize % 128 == 0;
16574 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
16575 if (Subtarget->hasNEON())
16576 return 4;
16577 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
16580 /// Lower an interleaved load into a vldN intrinsic.
16582 /// E.g. Lower an interleaved load (Factor = 2):
16583 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16584 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16585 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16587 /// Into:
16588 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16589 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16590 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16591 bool ARMTargetLowering::lowerInterleavedLoad(
16592 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16593 ArrayRef<unsigned> Indices, unsigned Factor) const {
16594 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16595 "Invalid interleave factor");
16596 assert(!Shuffles.empty() && "Empty shufflevector input");
16597 assert(Shuffles.size() == Indices.size() &&
16598 "Unmatched number of shufflevectors and indices");
16600 VectorType *VecTy = Shuffles[0]->getType();
16601 Type *EltTy = VecTy->getVectorElementType();
16603 const DataLayout &DL = LI->getModule()->getDataLayout();
16605 // Skip if we do not have NEON and skip illegal vector types. We can
16606 // "legalize" wide vector types into multiple interleaved accesses as long as
16607 // the vector types are divisible by 128.
16608 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16609 return false;
16611 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16613 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16614 // load integer vectors first and then convert to pointer vectors.
16615 if (EltTy->isPointerTy())
16616 VecTy =
16617 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16619 IRBuilder<> Builder(LI);
16621 // The base address of the load.
16622 Value *BaseAddr = LI->getPointerOperand();
16624 if (NumLoads > 1) {
16625 // If we're going to generate more than one load, reset the sub-vector type
16626 // to something legal.
16627 VecTy = VectorType::get(VecTy->getVectorElementType(),
16628 VecTy->getVectorNumElements() / NumLoads);
16630 // We will compute the pointer operand of each load from the original base
16631 // address using GEPs. Cast the base address to a pointer to the scalar
16632 // element type.
16633 BaseAddr = Builder.CreateBitCast(
16634 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16635 LI->getPointerAddressSpace()));
16638 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16640 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16641 Type *Tys[] = {VecTy, Int8Ptr};
16642 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16643 Intrinsic::arm_neon_vld3,
16644 Intrinsic::arm_neon_vld4};
16645 Function *VldnFunc =
16646 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16648 // Holds sub-vectors extracted from the load intrinsic return values. The
16649 // sub-vectors are associated with the shufflevector instructions they will
16650 // replace.
16651 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16653 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16654 // If we're generating more than one load, compute the base address of
16655 // subsequent loads as an offset from the previous.
16656 if (LoadCount > 0)
16657 BaseAddr =
16658 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16659 VecTy->getVectorNumElements() * Factor);
16661 SmallVector<Value *, 2> Ops;
16662 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16663 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16665 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16667 // Replace uses of each shufflevector with the corresponding vector loaded
16668 // by ldN.
16669 for (unsigned i = 0; i < Shuffles.size(); i++) {
16670 ShuffleVectorInst *SV = Shuffles[i];
16671 unsigned Index = Indices[i];
16673 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16675 // Convert the integer vector to pointer vector if the element is pointer.
16676 if (EltTy->isPointerTy())
16677 SubVec = Builder.CreateIntToPtr(
16678 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16679 VecTy->getVectorNumElements()));
16681 SubVecs[SV].push_back(SubVec);
16685 // Replace uses of the shufflevector instructions with the sub-vectors
16686 // returned by the load intrinsic. If a shufflevector instruction is
16687 // associated with more than one sub-vector, those sub-vectors will be
16688 // concatenated into a single wide vector.
16689 for (ShuffleVectorInst *SVI : Shuffles) {
16690 auto &SubVec = SubVecs[SVI];
16691 auto *WideVec =
16692 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16693 SVI->replaceAllUsesWith(WideVec);
16696 return true;
16699 /// Lower an interleaved store into a vstN intrinsic.
16701 /// E.g. Lower an interleaved store (Factor = 3):
16702 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16703 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16704 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16706 /// Into:
16707 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16708 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16709 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16710 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16712 /// Note that the new shufflevectors will be removed and we'll only generate one
16713 /// vst3 instruction in CodeGen.
16715 /// Example for a more general valid mask (Factor 3). Lower:
16716 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16717 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16718 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16720 /// Into:
16721 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16722 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16723 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16724 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16725 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16726 ShuffleVectorInst *SVI,
16727 unsigned Factor) const {
16728 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16729 "Invalid interleave factor");
16731 VectorType *VecTy = SVI->getType();
16732 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16733 "Invalid interleaved store");
16735 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16736 Type *EltTy = VecTy->getVectorElementType();
16737 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16739 const DataLayout &DL = SI->getModule()->getDataLayout();
16741 // Skip if we do not have NEON and skip illegal vector types. We can
16742 // "legalize" wide vector types into multiple interleaved accesses as long as
16743 // the vector types are divisible by 128.
16744 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16745 return false;
16747 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16749 Value *Op0 = SVI->getOperand(0);
16750 Value *Op1 = SVI->getOperand(1);
16751 IRBuilder<> Builder(SI);
16753 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16754 // vectors to integer vectors.
16755 if (EltTy->isPointerTy()) {
16756 Type *IntTy = DL.getIntPtrType(EltTy);
16758 // Convert to the corresponding integer vector.
16759 Type *IntVecTy =
16760 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16761 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16762 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16764 SubVecTy = VectorType::get(IntTy, LaneLen);
16767 // The base address of the store.
16768 Value *BaseAddr = SI->getPointerOperand();
16770 if (NumStores > 1) {
16771 // If we're going to generate more than one store, reset the lane length
16772 // and sub-vector type to something legal.
16773 LaneLen /= NumStores;
16774 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16776 // We will compute the pointer operand of each store from the original base
16777 // address using GEPs. Cast the base address to a pointer to the scalar
16778 // element type.
16779 BaseAddr = Builder.CreateBitCast(
16780 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16781 SI->getPointerAddressSpace()));
16784 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16786 auto Mask = SVI->getShuffleMask();
16788 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16789 Type *Tys[] = {Int8Ptr, SubVecTy};
16790 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16791 Intrinsic::arm_neon_vst3,
16792 Intrinsic::arm_neon_vst4};
16794 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16795 // If we generating more than one store, we compute the base address of
16796 // subsequent stores as an offset from the previous.
16797 if (StoreCount > 0)
16798 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16799 BaseAddr, LaneLen * Factor);
16801 SmallVector<Value *, 6> Ops;
16802 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16804 Function *VstNFunc =
16805 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16807 // Split the shufflevector operands into sub vectors for the new vstN call.
16808 for (unsigned i = 0; i < Factor; i++) {
16809 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16810 if (Mask[IdxI] >= 0) {
16811 Ops.push_back(Builder.CreateShuffleVector(
16812 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16813 } else {
16814 unsigned StartMask = 0;
16815 for (unsigned j = 1; j < LaneLen; j++) {
16816 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16817 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16818 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16819 break;
16822 // Note: If all elements in a chunk are undefs, StartMask=0!
16823 // Note: Filling undef gaps with random elements is ok, since
16824 // those elements were being written anyway (with undefs).
16825 // In the case of all undefs we're defaulting to using elems from 0
16826 // Note: StartMask cannot be negative, it's checked in
16827 // isReInterleaveMask
16828 Ops.push_back(Builder.CreateShuffleVector(
16829 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16833 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16834 Builder.CreateCall(VstNFunc, Ops);
16836 return true;
16839 enum HABaseType {
16840 HA_UNKNOWN = 0,
16841 HA_FLOAT,
16842 HA_DOUBLE,
16843 HA_VECT64,
16844 HA_VECT128
16847 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16848 uint64_t &Members) {
16849 if (auto *ST = dyn_cast<StructType>(Ty)) {
16850 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16851 uint64_t SubMembers = 0;
16852 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16853 return false;
16854 Members += SubMembers;
16856 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16857 uint64_t SubMembers = 0;
16858 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16859 return false;
16860 Members += SubMembers * AT->getNumElements();
16861 } else if (Ty->isFloatTy()) {
16862 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16863 return false;
16864 Members = 1;
16865 Base = HA_FLOAT;
16866 } else if (Ty->isDoubleTy()) {
16867 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16868 return false;
16869 Members = 1;
16870 Base = HA_DOUBLE;
16871 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16872 Members = 1;
16873 switch (Base) {
16874 case HA_FLOAT:
16875 case HA_DOUBLE:
16876 return false;
16877 case HA_VECT64:
16878 return VT->getBitWidth() == 64;
16879 case HA_VECT128:
16880 return VT->getBitWidth() == 128;
16881 case HA_UNKNOWN:
16882 switch (VT->getBitWidth()) {
16883 case 64:
16884 Base = HA_VECT64;
16885 return true;
16886 case 128:
16887 Base = HA_VECT128;
16888 return true;
16889 default:
16890 return false;
16895 return (Members > 0 && Members <= 4);
16898 /// Return the correct alignment for the current calling convention.
16899 unsigned
16900 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16901 DataLayout DL) const {
16902 if (!ArgTy->isVectorTy())
16903 return DL.getABITypeAlignment(ArgTy);
16905 // Avoid over-aligning vector parameters. It would require realigning the
16906 // stack and waste space for no real benefit.
16907 return std::min(DL.getABITypeAlignment(ArgTy),
16908 (unsigned)DL.getStackAlignment().value());
16911 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
16912 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
16913 /// passing according to AAPCS rules.
16914 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
16915 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
16916 if (getEffectiveCallingConv(CallConv, isVarArg) !=
16917 CallingConv::ARM_AAPCS_VFP)
16918 return false;
16920 HABaseType Base = HA_UNKNOWN;
16921 uint64_t Members = 0;
16922 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
16923 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
16925 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
16926 return IsHA || IsIntArray;
16929 unsigned ARMTargetLowering::getExceptionPointerRegister(
16930 const Constant *PersonalityFn) const {
16931 // Platforms which do not use SjLj EH may return values in these registers
16932 // via the personality function.
16933 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
16936 unsigned ARMTargetLowering::getExceptionSelectorRegister(
16937 const Constant *PersonalityFn) const {
16938 // Platforms which do not use SjLj EH may return values in these registers
16939 // via the personality function.
16940 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
16943 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
16944 // Update IsSplitCSR in ARMFunctionInfo.
16945 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
16946 AFI->setIsSplitCSR(true);
16949 void ARMTargetLowering::insertCopiesSplitCSR(
16950 MachineBasicBlock *Entry,
16951 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
16952 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
16953 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
16954 if (!IStart)
16955 return;
16957 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
16958 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
16959 MachineBasicBlock::iterator MBBI = Entry->begin();
16960 for (const MCPhysReg *I = IStart; *I; ++I) {
16961 const TargetRegisterClass *RC = nullptr;
16962 if (ARM::GPRRegClass.contains(*I))
16963 RC = &ARM::GPRRegClass;
16964 else if (ARM::DPRRegClass.contains(*I))
16965 RC = &ARM::DPRRegClass;
16966 else
16967 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
16969 Register NewVR = MRI->createVirtualRegister(RC);
16970 // Create copy from CSR to a virtual register.
16971 // FIXME: this currently does not emit CFI pseudo-instructions, it works
16972 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
16973 // nounwind. If we want to generalize this later, we may need to emit
16974 // CFI pseudo-instructions.
16975 assert(Entry->getParent()->getFunction().hasFnAttribute(
16976 Attribute::NoUnwind) &&
16977 "Function should be nounwind in insertCopiesSplitCSR!");
16978 Entry->addLiveIn(*I);
16979 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
16980 .addReg(*I);
16982 // Insert the copy-back instructions right before the terminator.
16983 for (auto *Exit : Exits)
16984 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
16985 TII->get(TargetOpcode::COPY), *I)
16986 .addReg(NewVR);
16990 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
16991 MF.getFrameInfo().computeMaxCallFrameSize(MF);
16992 TargetLoweringBase::finalizeLowering(MF);