[X86][BMI] Pull out schedule classes from bmi_andn<> and bmi_bls<>
[llvm-core.git] / lib / Target / ARM / ARMISelLowering.cpp
blobdb26feb57010390f9826579706123e3314500e45
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);
268 setOperationAction(ISD::SADDSAT, VT, Legal);
269 setOperationAction(ISD::UADDSAT, VT, Legal);
270 setOperationAction(ISD::SSUBSAT, VT, Legal);
271 setOperationAction(ISD::USUBSAT, VT, Legal);
273 // No native support for these.
274 setOperationAction(ISD::UDIV, VT, Expand);
275 setOperationAction(ISD::SDIV, VT, Expand);
276 setOperationAction(ISD::UREM, VT, Expand);
277 setOperationAction(ISD::SREM, VT, Expand);
278 setOperationAction(ISD::CTPOP, VT, Expand);
280 // Vector reductions
281 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
282 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
283 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
284 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
285 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
287 if (!HasMVEFP) {
288 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
289 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
290 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
291 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
294 // Pre and Post inc are supported on loads and stores
295 for (unsigned im = (unsigned)ISD::PRE_INC;
296 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
297 setIndexedLoadAction(im, VT, Legal);
298 setIndexedStoreAction(im, VT, Legal);
302 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
303 for (auto VT : FloatTypes) {
304 addRegisterClass(VT, &ARM::MQPRRegClass);
305 if (!HasMVEFP)
306 setAllExpand(VT);
308 // These are legal or custom whether we have MVE.fp or not
309 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
310 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
311 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
312 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
313 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
314 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
315 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
316 setOperationAction(ISD::SETCC, VT, Custom);
317 setOperationAction(ISD::MLOAD, VT, Custom);
318 setOperationAction(ISD::MSTORE, VT, Legal);
320 // Pre and Post inc are supported on loads and stores
321 for (unsigned im = (unsigned)ISD::PRE_INC;
322 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
323 setIndexedLoadAction(im, VT, Legal);
324 setIndexedStoreAction(im, VT, Legal);
327 if (HasMVEFP) {
328 setOperationAction(ISD::FMINNUM, VT, Legal);
329 setOperationAction(ISD::FMAXNUM, VT, Legal);
330 setOperationAction(ISD::FROUND, VT, Legal);
332 // No native support for these.
333 setOperationAction(ISD::FDIV, VT, Expand);
334 setOperationAction(ISD::FREM, VT, Expand);
335 setOperationAction(ISD::FSQRT, VT, Expand);
336 setOperationAction(ISD::FSIN, VT, Expand);
337 setOperationAction(ISD::FCOS, VT, Expand);
338 setOperationAction(ISD::FPOW, VT, Expand);
339 setOperationAction(ISD::FLOG, VT, Expand);
340 setOperationAction(ISD::FLOG2, VT, Expand);
341 setOperationAction(ISD::FLOG10, VT, Expand);
342 setOperationAction(ISD::FEXP, VT, Expand);
343 setOperationAction(ISD::FEXP2, VT, Expand);
344 setOperationAction(ISD::FNEARBYINT, VT, Expand);
348 // We 'support' these types up to bitcast/load/store level, regardless of
349 // MVE integer-only / float support. Only doing FP data processing on the FP
350 // vector types is inhibited at integer-only level.
351 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
352 for (auto VT : LongTypes) {
353 addRegisterClass(VT, &ARM::MQPRRegClass);
354 setAllExpand(VT);
355 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
356 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
357 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
359 // We can do bitwise operations on v2i64 vectors
360 setOperationAction(ISD::AND, MVT::v2i64, Legal);
361 setOperationAction(ISD::OR, MVT::v2i64, Legal);
362 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
364 // It is legal to extload from v4i8 to v4i16 or v4i32.
365 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
366 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
367 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
369 // Some truncating stores are legal too.
370 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
371 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
372 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
374 // Pre and Post inc on these are legal, given the correct extends
375 for (unsigned im = (unsigned)ISD::PRE_INC;
376 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
377 setIndexedLoadAction(im, MVT::v8i8, Legal);
378 setIndexedStoreAction(im, MVT::v8i8, Legal);
379 setIndexedLoadAction(im, MVT::v4i8, Legal);
380 setIndexedStoreAction(im, MVT::v4i8, Legal);
381 setIndexedLoadAction(im, MVT::v4i16, Legal);
382 setIndexedStoreAction(im, MVT::v4i16, Legal);
385 // Predicate types
386 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
387 for (auto VT : pTypes) {
388 addRegisterClass(VT, &ARM::VCCRRegClass);
389 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
390 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
391 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
392 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
393 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
395 setOperationAction(ISD::SETCC, VT, Custom);
396 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
397 setOperationAction(ISD::LOAD, VT, Custom);
398 setOperationAction(ISD::STORE, VT, Custom);
402 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
403 const ARMSubtarget &STI)
404 : TargetLowering(TM), Subtarget(&STI) {
405 RegInfo = Subtarget->getRegisterInfo();
406 Itins = Subtarget->getInstrItineraryData();
408 setBooleanContents(ZeroOrOneBooleanContent);
409 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
411 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
412 !Subtarget->isTargetWatchOS()) {
413 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
414 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
415 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
416 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
417 : CallingConv::ARM_AAPCS);
420 if (Subtarget->isTargetMachO()) {
421 // Uses VFP for Thumb libfuncs if available.
422 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
423 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
424 static const struct {
425 const RTLIB::Libcall Op;
426 const char * const Name;
427 const ISD::CondCode Cond;
428 } LibraryCalls[] = {
429 // Single-precision floating-point arithmetic.
430 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
431 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
432 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
433 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
435 // Double-precision floating-point arithmetic.
436 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
437 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
438 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
439 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
441 // Single-precision comparisons.
442 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
443 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
444 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
445 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
446 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
447 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
448 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
449 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
451 // Double-precision comparisons.
452 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
453 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
454 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
455 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
456 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
457 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
458 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
459 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
461 // Floating-point to integer conversions.
462 // i64 conversions are done via library routines even when generating VFP
463 // instructions, so use the same ones.
464 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
465 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
466 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
467 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
469 // Conversions between floating types.
470 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
471 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
473 // Integer to floating-point conversions.
474 // i64 conversions are done via library routines even when generating VFP
475 // instructions, so use the same ones.
476 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
477 // e.g., __floatunsidf vs. __floatunssidfvfp.
478 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
479 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
480 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
481 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
484 for (const auto &LC : LibraryCalls) {
485 setLibcallName(LC.Op, LC.Name);
486 if (LC.Cond != ISD::SETCC_INVALID)
487 setCmpLibcallCC(LC.Op, LC.Cond);
492 // These libcalls are not available in 32-bit.
493 setLibcallName(RTLIB::SHL_I128, nullptr);
494 setLibcallName(RTLIB::SRL_I128, nullptr);
495 setLibcallName(RTLIB::SRA_I128, nullptr);
497 // RTLIB
498 if (Subtarget->isAAPCS_ABI() &&
499 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
500 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
501 static const struct {
502 const RTLIB::Libcall Op;
503 const char * const Name;
504 const CallingConv::ID CC;
505 const ISD::CondCode Cond;
506 } LibraryCalls[] = {
507 // Double-precision floating-point arithmetic helper functions
508 // RTABI chapter 4.1.2, Table 2
509 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
511 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
512 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
514 // Double-precision floating-point comparison helper functions
515 // RTABI chapter 4.1.2, Table 3
516 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
517 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
518 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
519 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
520 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
521 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
522 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
523 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
525 // Single-precision floating-point arithmetic helper functions
526 // RTABI chapter 4.1.2, Table 4
527 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
530 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
532 // Single-precision floating-point comparison helper functions
533 // RTABI chapter 4.1.2, Table 5
534 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
535 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
536 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
537 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
538 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
539 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
540 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
541 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
543 // Floating-point to integer conversions.
544 // RTABI chapter 4.1.2, Table 6
545 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
546 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
547 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
548 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
549 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
550 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
552 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
554 // Conversions between floating types.
555 // RTABI chapter 4.1.2, Table 7
556 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
557 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
558 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
560 // Integer to floating-point conversions.
561 // RTABI chapter 4.1.2, Table 8
562 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
563 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
564 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
571 // Long long helper functions
572 // RTABI chapter 4.2, Table 9
573 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
574 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
575 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
576 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
578 // Integer division functions
579 // RTABI chapter 4.3.1
580 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
581 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
582 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
583 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
584 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
585 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
586 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
587 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
590 for (const auto &LC : LibraryCalls) {
591 setLibcallName(LC.Op, LC.Name);
592 setLibcallCallingConv(LC.Op, LC.CC);
593 if (LC.Cond != ISD::SETCC_INVALID)
594 setCmpLibcallCC(LC.Op, LC.Cond);
597 // EABI dependent RTLIB
598 if (TM.Options.EABIVersion == EABI::EABI4 ||
599 TM.Options.EABIVersion == EABI::EABI5) {
600 static const struct {
601 const RTLIB::Libcall Op;
602 const char *const Name;
603 const CallingConv::ID CC;
604 const ISD::CondCode Cond;
605 } MemOpsLibraryCalls[] = {
606 // Memory operations
607 // RTABI chapter 4.3.4
608 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
609 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
610 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
613 for (const auto &LC : MemOpsLibraryCalls) {
614 setLibcallName(LC.Op, LC.Name);
615 setLibcallCallingConv(LC.Op, LC.CC);
616 if (LC.Cond != ISD::SETCC_INVALID)
617 setCmpLibcallCC(LC.Op, LC.Cond);
622 if (Subtarget->isTargetWindows()) {
623 static const struct {
624 const RTLIB::Libcall Op;
625 const char * const Name;
626 const CallingConv::ID CC;
627 } LibraryCalls[] = {
628 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
629 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
630 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
631 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
632 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
633 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
634 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
635 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
638 for (const auto &LC : LibraryCalls) {
639 setLibcallName(LC.Op, LC.Name);
640 setLibcallCallingConv(LC.Op, LC.CC);
644 // Use divmod compiler-rt calls for iOS 5.0 and later.
645 if (Subtarget->isTargetMachO() &&
646 !(Subtarget->isTargetIOS() &&
647 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
648 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
649 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
652 // The half <-> float conversion functions are always soft-float on
653 // non-watchos platforms, but are needed for some targets which use a
654 // hard-float calling convention by default.
655 if (!Subtarget->isTargetWatchABI()) {
656 if (Subtarget->isAAPCS_ABI()) {
657 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
658 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
659 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
660 } else {
661 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
662 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
663 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
667 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
668 // a __gnu_ prefix (which is the default).
669 if (Subtarget->isTargetAEABI()) {
670 static const struct {
671 const RTLIB::Libcall Op;
672 const char * const Name;
673 const CallingConv::ID CC;
674 } LibraryCalls[] = {
675 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
676 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
677 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
680 for (const auto &LC : LibraryCalls) {
681 setLibcallName(LC.Op, LC.Name);
682 setLibcallCallingConv(LC.Op, LC.CC);
686 if (Subtarget->isThumb1Only())
687 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
688 else
689 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
691 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
692 Subtarget->hasFPRegs()) {
693 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
694 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
695 if (!Subtarget->hasVFP2Base())
696 setAllExpand(MVT::f32);
697 if (!Subtarget->hasFP64())
698 setAllExpand(MVT::f64);
701 if (Subtarget->hasFullFP16()) {
702 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
703 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
704 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
705 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
707 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
708 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
711 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
712 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
713 setTruncStoreAction(VT, InnerVT, Expand);
714 addAllExtLoads(VT, InnerVT, Expand);
717 setOperationAction(ISD::MULHS, VT, Expand);
718 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
719 setOperationAction(ISD::MULHU, VT, Expand);
720 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
722 setOperationAction(ISD::BSWAP, VT, Expand);
725 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
726 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
728 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
729 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
731 if (Subtarget->hasMVEIntegerOps())
732 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
734 // Combine low-overhead loop intrinsics so that we can lower i1 types.
735 if (Subtarget->hasLOB()) {
736 setTargetDAGCombine(ISD::BRCOND);
737 setTargetDAGCombine(ISD::BR_CC);
740 if (Subtarget->hasNEON()) {
741 addDRTypeForNEON(MVT::v2f32);
742 addDRTypeForNEON(MVT::v8i8);
743 addDRTypeForNEON(MVT::v4i16);
744 addDRTypeForNEON(MVT::v2i32);
745 addDRTypeForNEON(MVT::v1i64);
747 addQRTypeForNEON(MVT::v4f32);
748 addQRTypeForNEON(MVT::v2f64);
749 addQRTypeForNEON(MVT::v16i8);
750 addQRTypeForNEON(MVT::v8i16);
751 addQRTypeForNEON(MVT::v4i32);
752 addQRTypeForNEON(MVT::v2i64);
754 if (Subtarget->hasFullFP16()) {
755 addQRTypeForNEON(MVT::v8f16);
756 addDRTypeForNEON(MVT::v4f16);
760 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
761 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
762 // none of Neon, MVE or VFP supports any arithmetic operations on it.
763 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
764 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
765 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
766 // FIXME: Code duplication: FDIV and FREM are expanded always, see
767 // ARMTargetLowering::addTypeForNEON method for details.
768 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
769 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
770 // FIXME: Create unittest.
771 // In another words, find a way when "copysign" appears in DAG with vector
772 // operands.
773 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
774 // FIXME: Code duplication: SETCC has custom operation action, see
775 // ARMTargetLowering::addTypeForNEON method for details.
776 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
777 // FIXME: Create unittest for FNEG and for FABS.
778 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
779 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
780 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
781 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
782 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
783 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
784 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
785 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
786 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
787 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
788 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
789 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
790 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
791 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
792 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
793 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
794 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
795 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
798 if (Subtarget->hasNEON()) {
799 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
800 // supported for v4f32.
801 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
802 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
803 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
804 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
805 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
806 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
807 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
808 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
809 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
810 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
811 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
812 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
813 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
814 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
816 // Mark v2f32 intrinsics.
817 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
818 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
819 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
820 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
821 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
822 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
823 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
824 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
825 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
826 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
827 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
828 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
829 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
830 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
832 // Neon does not support some operations on v1i64 and v2i64 types.
833 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
834 // Custom handling for some quad-vector types to detect VMULL.
835 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
836 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
837 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
838 // Custom handling for some vector types to avoid expensive expansions
839 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
840 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
841 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
842 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
843 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
844 // a destination type that is wider than the source, and nor does
845 // it have a FP_TO_[SU]INT instruction with a narrower destination than
846 // source.
847 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
848 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
849 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
850 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
851 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
852 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
853 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
854 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
856 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
857 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
859 // NEON does not have single instruction CTPOP for vectors with element
860 // types wider than 8-bits. However, custom lowering can leverage the
861 // v8i8/v16i8 vcnt instruction.
862 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
863 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
864 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
865 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
866 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
867 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
869 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
870 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
872 // NEON does not have single instruction CTTZ for vectors.
873 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
874 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
875 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
876 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
878 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
879 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
880 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
881 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
883 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
884 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
885 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
886 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
888 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
889 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
890 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
891 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
893 // NEON only has FMA instructions as of VFP4.
894 if (!Subtarget->hasVFP4Base()) {
895 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
896 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
899 setTargetDAGCombine(ISD::INTRINSIC_VOID);
900 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
901 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
902 setTargetDAGCombine(ISD::SHL);
903 setTargetDAGCombine(ISD::SRL);
904 setTargetDAGCombine(ISD::SRA);
905 setTargetDAGCombine(ISD::FP_TO_SINT);
906 setTargetDAGCombine(ISD::FP_TO_UINT);
907 setTargetDAGCombine(ISD::FDIV);
908 setTargetDAGCombine(ISD::LOAD);
910 // It is legal to extload from v4i8 to v4i16 or v4i32.
911 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
912 MVT::v2i32}) {
913 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
914 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
915 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
916 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
921 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
922 setTargetDAGCombine(ISD::BUILD_VECTOR);
923 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
924 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
925 setTargetDAGCombine(ISD::STORE);
926 setTargetDAGCombine(ISD::SIGN_EXTEND);
927 setTargetDAGCombine(ISD::ZERO_EXTEND);
928 setTargetDAGCombine(ISD::ANY_EXTEND);
931 if (!Subtarget->hasFP64()) {
932 // When targeting a floating-point unit with only single-precision
933 // operations, f64 is legal for the few double-precision instructions which
934 // are present However, no double-precision operations other than moves,
935 // loads and stores are provided by the hardware.
936 setOperationAction(ISD::FADD, MVT::f64, Expand);
937 setOperationAction(ISD::FSUB, MVT::f64, Expand);
938 setOperationAction(ISD::FMUL, MVT::f64, Expand);
939 setOperationAction(ISD::FMA, MVT::f64, Expand);
940 setOperationAction(ISD::FDIV, MVT::f64, Expand);
941 setOperationAction(ISD::FREM, MVT::f64, Expand);
942 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
943 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
944 setOperationAction(ISD::FNEG, MVT::f64, Expand);
945 setOperationAction(ISD::FABS, MVT::f64, Expand);
946 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
947 setOperationAction(ISD::FSIN, MVT::f64, Expand);
948 setOperationAction(ISD::FCOS, MVT::f64, Expand);
949 setOperationAction(ISD::FPOW, MVT::f64, Expand);
950 setOperationAction(ISD::FLOG, MVT::f64, Expand);
951 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
952 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
953 setOperationAction(ISD::FEXP, MVT::f64, Expand);
954 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
955 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
956 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
957 setOperationAction(ISD::FRINT, MVT::f64, Expand);
958 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
959 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
960 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
961 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
962 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
963 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
964 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
965 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
966 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
969 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
970 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
971 if (Subtarget->hasFullFP16())
972 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
975 if (!Subtarget->hasFP16())
976 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
978 if (!Subtarget->hasFP64())
979 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
981 computeRegisterProperties(Subtarget->getRegisterInfo());
983 // ARM does not have floating-point extending loads.
984 for (MVT VT : MVT::fp_valuetypes()) {
985 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
986 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
989 // ... or truncating stores
990 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
991 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
992 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
994 // ARM does not have i1 sign extending load.
995 for (MVT VT : MVT::integer_valuetypes())
996 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
998 // ARM supports all 4 flavors of integer indexed load / store.
999 if (!Subtarget->isThumb1Only()) {
1000 for (unsigned im = (unsigned)ISD::PRE_INC;
1001 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1002 setIndexedLoadAction(im, MVT::i1, Legal);
1003 setIndexedLoadAction(im, MVT::i8, Legal);
1004 setIndexedLoadAction(im, MVT::i16, Legal);
1005 setIndexedLoadAction(im, MVT::i32, Legal);
1006 setIndexedStoreAction(im, MVT::i1, Legal);
1007 setIndexedStoreAction(im, MVT::i8, Legal);
1008 setIndexedStoreAction(im, MVT::i16, Legal);
1009 setIndexedStoreAction(im, MVT::i32, Legal);
1011 } else {
1012 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1013 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1014 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1017 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1018 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1019 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1020 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1022 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1023 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1024 if (Subtarget->hasDSP()) {
1025 setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1026 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1027 setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1028 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1030 if (Subtarget->hasBaseDSP()) {
1031 setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1032 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1035 // i64 operation support.
1036 setOperationAction(ISD::MUL, MVT::i64, Expand);
1037 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1038 if (Subtarget->isThumb1Only()) {
1039 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1040 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1042 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1043 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1044 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1046 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1047 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1048 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1049 setOperationAction(ISD::SRL, MVT::i64, Custom);
1050 setOperationAction(ISD::SRA, MVT::i64, Custom);
1051 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1052 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1054 // MVE lowers 64 bit shifts to lsll and lsrl
1055 // assuming that ISD::SRL and SRA of i64 are already marked custom
1056 if (Subtarget->hasMVEIntegerOps())
1057 setOperationAction(ISD::SHL, MVT::i64, Custom);
1059 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1060 if (Subtarget->isThumb1Only()) {
1061 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1062 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1063 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1066 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1067 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1069 // ARM does not have ROTL.
1070 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1071 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1072 setOperationAction(ISD::ROTL, VT, Expand);
1073 setOperationAction(ISD::ROTR, VT, Expand);
1075 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1076 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1077 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1078 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1079 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1082 // @llvm.readcyclecounter requires the Performance Monitors extension.
1083 // Default to the 0 expansion on unsupported platforms.
1084 // FIXME: Technically there are older ARM CPUs that have
1085 // implementation-specific ways of obtaining this information.
1086 if (Subtarget->hasPerfMon())
1087 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1089 // Only ARMv6 has BSWAP.
1090 if (!Subtarget->hasV6Ops())
1091 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1093 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1094 : Subtarget->hasDivideInARMMode();
1095 if (!hasDivide) {
1096 // These are expanded into libcalls if the cpu doesn't have HW divider.
1097 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1098 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1101 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1102 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1103 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1105 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1106 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1109 setOperationAction(ISD::SREM, MVT::i32, Expand);
1110 setOperationAction(ISD::UREM, MVT::i32, Expand);
1112 // Register based DivRem for AEABI (RTABI 4.2)
1113 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1114 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1115 Subtarget->isTargetWindows()) {
1116 setOperationAction(ISD::SREM, MVT::i64, Custom);
1117 setOperationAction(ISD::UREM, MVT::i64, Custom);
1118 HasStandaloneRem = false;
1120 if (Subtarget->isTargetWindows()) {
1121 const struct {
1122 const RTLIB::Libcall Op;
1123 const char * const Name;
1124 const CallingConv::ID CC;
1125 } LibraryCalls[] = {
1126 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1127 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1128 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1129 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1131 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1132 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1133 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1134 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1137 for (const auto &LC : LibraryCalls) {
1138 setLibcallName(LC.Op, LC.Name);
1139 setLibcallCallingConv(LC.Op, LC.CC);
1141 } else {
1142 const struct {
1143 const RTLIB::Libcall Op;
1144 const char * const Name;
1145 const CallingConv::ID CC;
1146 } LibraryCalls[] = {
1147 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1148 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1149 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1150 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1152 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1153 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1154 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1155 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1158 for (const auto &LC : LibraryCalls) {
1159 setLibcallName(LC.Op, LC.Name);
1160 setLibcallCallingConv(LC.Op, LC.CC);
1164 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1165 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1166 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1167 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1168 } else {
1169 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1170 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1173 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
1174 for (auto &VT : {MVT::f32, MVT::f64})
1175 setOperationAction(ISD::FPOWI, VT, Custom);
1177 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1178 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1179 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1180 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1182 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1183 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1185 // Use the default implementation.
1186 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1187 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1188 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1189 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1190 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1191 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1193 if (Subtarget->isTargetWindows())
1194 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1195 else
1196 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1198 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1199 // the default expansion.
1200 InsertFencesForAtomic = false;
1201 if (Subtarget->hasAnyDataBarrier() &&
1202 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1203 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1204 // to ldrex/strex loops already.
1205 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1206 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1207 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1209 // On v8, we have particularly efficient implementations of atomic fences
1210 // if they can be combined with nearby atomic loads and stores.
1211 if (!Subtarget->hasAcquireRelease() ||
1212 getTargetMachine().getOptLevel() == 0) {
1213 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1214 InsertFencesForAtomic = true;
1216 } else {
1217 // If there's anything we can use as a barrier, go through custom lowering
1218 // for ATOMIC_FENCE.
1219 // If target has DMB in thumb, Fences can be inserted.
1220 if (Subtarget->hasDataBarrier())
1221 InsertFencesForAtomic = true;
1223 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1224 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1226 // Set them all for expansion, which will force libcalls.
1227 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1228 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1229 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1230 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1231 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1232 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1233 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1234 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1235 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1236 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1237 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1238 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1239 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1240 // Unordered/Monotonic case.
1241 if (!InsertFencesForAtomic) {
1242 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1243 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1247 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1249 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1250 if (!Subtarget->hasV6Ops()) {
1251 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1252 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1254 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1256 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1257 !Subtarget->isThumb1Only()) {
1258 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1259 // iff target supports vfp2.
1260 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1261 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1264 // We want to custom lower some of our intrinsics.
1265 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1266 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1267 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1268 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1269 if (Subtarget->useSjLjEH())
1270 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1272 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1273 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1274 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1275 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1276 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1277 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1278 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1279 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1280 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1281 if (Subtarget->hasFullFP16()) {
1282 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1283 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1284 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1287 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1289 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1290 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1291 if (Subtarget->hasFullFP16())
1292 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1293 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1294 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1295 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1297 // We don't support sin/cos/fmod/copysign/pow
1298 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1299 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1300 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1301 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1302 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1303 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1304 setOperationAction(ISD::FREM, MVT::f64, Expand);
1305 setOperationAction(ISD::FREM, MVT::f32, Expand);
1306 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1307 !Subtarget->isThumb1Only()) {
1308 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1309 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1311 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1312 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1314 if (!Subtarget->hasVFP4Base()) {
1315 setOperationAction(ISD::FMA, MVT::f64, Expand);
1316 setOperationAction(ISD::FMA, MVT::f32, Expand);
1319 // Various VFP goodness
1320 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1321 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1322 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1323 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1324 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1327 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1328 if (!Subtarget->hasFP16()) {
1329 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1330 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1334 // Use __sincos_stret if available.
1335 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1336 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1337 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1338 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1341 // FP-ARMv8 implements a lot of rounding-like FP operations.
1342 if (Subtarget->hasFPARMv8Base()) {
1343 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1344 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1345 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1346 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1347 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1348 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1349 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1350 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1351 if (Subtarget->hasNEON()) {
1352 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1353 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1354 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1355 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1358 if (Subtarget->hasFP64()) {
1359 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1360 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1361 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1362 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1363 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1364 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1365 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1366 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1370 // FP16 often need to be promoted to call lib functions
1371 if (Subtarget->hasFullFP16()) {
1372 setOperationAction(ISD::FREM, MVT::f16, Promote);
1373 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1374 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1375 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1376 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1377 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1378 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1379 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1380 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1381 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1382 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1383 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1385 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1388 if (Subtarget->hasNEON()) {
1389 // vmin and vmax aren't available in a scalar form, so we use
1390 // a NEON instruction with an undef lane instead.
1391 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1392 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1393 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1394 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1395 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1396 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1397 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1398 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1400 if (Subtarget->hasFullFP16()) {
1401 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1402 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1403 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1404 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1406 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1407 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1408 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1409 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1413 // We have target-specific dag combine patterns for the following nodes:
1414 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1415 setTargetDAGCombine(ISD::ADD);
1416 setTargetDAGCombine(ISD::SUB);
1417 setTargetDAGCombine(ISD::MUL);
1418 setTargetDAGCombine(ISD::AND);
1419 setTargetDAGCombine(ISD::OR);
1420 setTargetDAGCombine(ISD::XOR);
1422 if (Subtarget->hasV6Ops())
1423 setTargetDAGCombine(ISD::SRL);
1424 if (Subtarget->isThumb1Only())
1425 setTargetDAGCombine(ISD::SHL);
1427 setStackPointerRegisterToSaveRestore(ARM::SP);
1429 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1430 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1431 setSchedulingPreference(Sched::RegPressure);
1432 else
1433 setSchedulingPreference(Sched::Hybrid);
1435 //// temporary - rewrite interface to use type
1436 MaxStoresPerMemset = 8;
1437 MaxStoresPerMemsetOptSize = 4;
1438 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1439 MaxStoresPerMemcpyOptSize = 2;
1440 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1441 MaxStoresPerMemmoveOptSize = 2;
1443 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1444 // are at least 4 bytes aligned.
1445 setMinStackArgumentAlignment(Align(4));
1447 // Prefer likely predicted branches to selects on out-of-order cores.
1448 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1450 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1452 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1454 if (Subtarget->isThumb() || Subtarget->isThumb2())
1455 setTargetDAGCombine(ISD::ABS);
1458 bool ARMTargetLowering::useSoftFloat() const {
1459 return Subtarget->useSoftFloat();
1462 // FIXME: It might make sense to define the representative register class as the
1463 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1464 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1465 // SPR's representative would be DPR_VFP2. This should work well if register
1466 // pressure tracking were modified such that a register use would increment the
1467 // pressure of the register class's representative and all of it's super
1468 // classes' representatives transitively. We have not implemented this because
1469 // of the difficulty prior to coalescing of modeling operand register classes
1470 // due to the common occurrence of cross class copies and subregister insertions
1471 // and extractions.
1472 std::pair<const TargetRegisterClass *, uint8_t>
1473 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1474 MVT VT) const {
1475 const TargetRegisterClass *RRC = nullptr;
1476 uint8_t Cost = 1;
1477 switch (VT.SimpleTy) {
1478 default:
1479 return TargetLowering::findRepresentativeClass(TRI, VT);
1480 // Use DPR as representative register class for all floating point
1481 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1482 // the cost is 1 for both f32 and f64.
1483 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1484 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1485 RRC = &ARM::DPRRegClass;
1486 // When NEON is used for SP, only half of the register file is available
1487 // because operations that define both SP and DP results will be constrained
1488 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1489 // coalescing by double-counting the SP regs. See the FIXME above.
1490 if (Subtarget->useNEONForSinglePrecisionFP())
1491 Cost = 2;
1492 break;
1493 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1494 case MVT::v4f32: case MVT::v2f64:
1495 RRC = &ARM::DPRRegClass;
1496 Cost = 2;
1497 break;
1498 case MVT::v4i64:
1499 RRC = &ARM::DPRRegClass;
1500 Cost = 4;
1501 break;
1502 case MVT::v8i64:
1503 RRC = &ARM::DPRRegClass;
1504 Cost = 8;
1505 break;
1507 return std::make_pair(RRC, Cost);
1510 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1511 switch ((ARMISD::NodeType)Opcode) {
1512 case ARMISD::FIRST_NUMBER: break;
1513 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1514 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1515 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1516 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1517 case ARMISD::CALL: return "ARMISD::CALL";
1518 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1519 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1520 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1521 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1522 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1523 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1524 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1525 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1526 case ARMISD::CMP: return "ARMISD::CMP";
1527 case ARMISD::CMN: return "ARMISD::CMN";
1528 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1529 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1530 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1531 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1532 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1534 case ARMISD::CMOV: return "ARMISD::CMOV";
1535 case ARMISD::SUBS: return "ARMISD::SUBS";
1537 case ARMISD::SSAT: return "ARMISD::SSAT";
1538 case ARMISD::USAT: return "ARMISD::USAT";
1540 case ARMISD::ASRL: return "ARMISD::ASRL";
1541 case ARMISD::LSRL: return "ARMISD::LSRL";
1542 case ARMISD::LSLL: return "ARMISD::LSLL";
1544 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1545 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1546 case ARMISD::RRX: return "ARMISD::RRX";
1548 case ARMISD::ADDC: return "ARMISD::ADDC";
1549 case ARMISD::ADDE: return "ARMISD::ADDE";
1550 case ARMISD::SUBC: return "ARMISD::SUBC";
1551 case ARMISD::SUBE: return "ARMISD::SUBE";
1552 case ARMISD::LSLS: return "ARMISD::LSLS";
1554 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1555 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1556 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1557 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1558 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1560 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1561 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1562 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1564 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1566 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1568 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1570 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1572 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1574 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1575 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1577 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1578 case ARMISD::VCMP: return "ARMISD::VCMP";
1579 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1580 case ARMISD::VTST: return "ARMISD::VTST";
1582 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1583 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1584 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1585 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1586 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1587 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1588 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1589 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1590 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1591 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1592 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1593 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1594 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1595 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1596 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1597 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1598 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1599 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1600 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1601 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1602 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1603 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1604 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1605 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1606 case ARMISD::VDUP: return "ARMISD::VDUP";
1607 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1608 case ARMISD::VEXT: return "ARMISD::VEXT";
1609 case ARMISD::VREV64: return "ARMISD::VREV64";
1610 case ARMISD::VREV32: return "ARMISD::VREV32";
1611 case ARMISD::VREV16: return "ARMISD::VREV16";
1612 case ARMISD::VZIP: return "ARMISD::VZIP";
1613 case ARMISD::VUZP: return "ARMISD::VUZP";
1614 case ARMISD::VTRN: return "ARMISD::VTRN";
1615 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1616 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1617 case ARMISD::VMOVN: return "ARMISD::VMOVN";
1618 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1619 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1620 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1621 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1622 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1623 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1624 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1625 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1626 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1627 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1628 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1629 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1630 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1631 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1632 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1633 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1634 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1635 case ARMISD::QADD16b: return "ARMISD::QADD16b";
1636 case ARMISD::QSUB16b: return "ARMISD::QSUB16b";
1637 case ARMISD::QADD8b: return "ARMISD::QADD8b";
1638 case ARMISD::QSUB8b: return "ARMISD::QSUB8b";
1639 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1640 case ARMISD::BFI: return "ARMISD::BFI";
1641 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1642 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1643 case ARMISD::VBSL: return "ARMISD::VBSL";
1644 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1645 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1646 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1647 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1648 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1649 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1650 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1651 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1652 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1653 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1654 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1655 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1656 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1657 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1658 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1659 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1660 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1661 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1662 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1663 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1664 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1665 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1666 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1667 case ARMISD::WLS: return "ARMISD::WLS";
1668 case ARMISD::LE: return "ARMISD::LE";
1669 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1670 case ARMISD::CSINV: return "ARMISD::CSINV";
1671 case ARMISD::CSNEG: return "ARMISD::CSNEG";
1672 case ARMISD::CSINC: return "ARMISD::CSINC";
1674 return nullptr;
1677 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1678 EVT VT) const {
1679 if (!VT.isVector())
1680 return getPointerTy(DL);
1682 // MVE has a predicate register.
1683 if (Subtarget->hasMVEIntegerOps() &&
1684 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1685 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1686 return VT.changeVectorElementTypeToInteger();
1689 /// getRegClassFor - Return the register class that should be used for the
1690 /// specified value type.
1691 const TargetRegisterClass *
1692 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1693 (void)isDivergent;
1694 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1695 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1696 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1697 // MVE Q registers.
1698 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1699 if (VT == MVT::v4i64)
1700 return &ARM::QQPRRegClass;
1701 if (VT == MVT::v8i64)
1702 return &ARM::QQQQPRRegClass;
1704 return TargetLowering::getRegClassFor(VT);
1707 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1708 // source/dest is aligned and the copy size is large enough. We therefore want
1709 // to align such objects passed to memory intrinsics.
1710 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1711 unsigned &PrefAlign) const {
1712 if (!isa<MemIntrinsic>(CI))
1713 return false;
1714 MinSize = 8;
1715 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1716 // cycle faster than 4-byte aligned LDM.
1717 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1718 return true;
1721 // Create a fast isel object.
1722 FastISel *
1723 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1724 const TargetLibraryInfo *libInfo) const {
1725 return ARM::createFastISel(funcInfo, libInfo);
1728 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1729 unsigned NumVals = N->getNumValues();
1730 if (!NumVals)
1731 return Sched::RegPressure;
1733 for (unsigned i = 0; i != NumVals; ++i) {
1734 EVT VT = N->getValueType(i);
1735 if (VT == MVT::Glue || VT == MVT::Other)
1736 continue;
1737 if (VT.isFloatingPoint() || VT.isVector())
1738 return Sched::ILP;
1741 if (!N->isMachineOpcode())
1742 return Sched::RegPressure;
1744 // Load are scheduled for latency even if there instruction itinerary
1745 // is not available.
1746 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1747 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1749 if (MCID.getNumDefs() == 0)
1750 return Sched::RegPressure;
1751 if (!Itins->isEmpty() &&
1752 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1753 return Sched::ILP;
1755 return Sched::RegPressure;
1758 //===----------------------------------------------------------------------===//
1759 // Lowering Code
1760 //===----------------------------------------------------------------------===//
1762 static bool isSRL16(const SDValue &Op) {
1763 if (Op.getOpcode() != ISD::SRL)
1764 return false;
1765 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1766 return Const->getZExtValue() == 16;
1767 return false;
1770 static bool isSRA16(const SDValue &Op) {
1771 if (Op.getOpcode() != ISD::SRA)
1772 return false;
1773 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1774 return Const->getZExtValue() == 16;
1775 return false;
1778 static bool isSHL16(const SDValue &Op) {
1779 if (Op.getOpcode() != ISD::SHL)
1780 return false;
1781 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1782 return Const->getZExtValue() == 16;
1783 return false;
1786 // Check for a signed 16-bit value. We special case SRA because it makes it
1787 // more simple when also looking for SRAs that aren't sign extending a
1788 // smaller value. Without the check, we'd need to take extra care with
1789 // checking order for some operations.
1790 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1791 if (isSRA16(Op))
1792 return isSHL16(Op.getOperand(0));
1793 return DAG.ComputeNumSignBits(Op) == 17;
1796 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1797 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1798 switch (CC) {
1799 default: llvm_unreachable("Unknown condition code!");
1800 case ISD::SETNE: return ARMCC::NE;
1801 case ISD::SETEQ: return ARMCC::EQ;
1802 case ISD::SETGT: return ARMCC::GT;
1803 case ISD::SETGE: return ARMCC::GE;
1804 case ISD::SETLT: return ARMCC::LT;
1805 case ISD::SETLE: return ARMCC::LE;
1806 case ISD::SETUGT: return ARMCC::HI;
1807 case ISD::SETUGE: return ARMCC::HS;
1808 case ISD::SETULT: return ARMCC::LO;
1809 case ISD::SETULE: return ARMCC::LS;
1813 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1814 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1815 ARMCC::CondCodes &CondCode2) {
1816 CondCode2 = ARMCC::AL;
1817 switch (CC) {
1818 default: llvm_unreachable("Unknown FP condition!");
1819 case ISD::SETEQ:
1820 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1821 case ISD::SETGT:
1822 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1823 case ISD::SETGE:
1824 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1825 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1826 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1827 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1828 case ISD::SETO: CondCode = ARMCC::VC; break;
1829 case ISD::SETUO: CondCode = ARMCC::VS; break;
1830 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1831 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1832 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1833 case ISD::SETLT:
1834 case ISD::SETULT: CondCode = ARMCC::LT; break;
1835 case ISD::SETLE:
1836 case ISD::SETULE: CondCode = ARMCC::LE; break;
1837 case ISD::SETNE:
1838 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1842 //===----------------------------------------------------------------------===//
1843 // Calling Convention Implementation
1844 //===----------------------------------------------------------------------===//
1846 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1847 /// account presence of floating point hardware and calling convention
1848 /// limitations, such as support for variadic functions.
1849 CallingConv::ID
1850 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1851 bool isVarArg) const {
1852 switch (CC) {
1853 default:
1854 report_fatal_error("Unsupported calling convention");
1855 case CallingConv::ARM_AAPCS:
1856 case CallingConv::ARM_APCS:
1857 case CallingConv::GHC:
1858 return CC;
1859 case CallingConv::PreserveMost:
1860 return CallingConv::PreserveMost;
1861 case CallingConv::ARM_AAPCS_VFP:
1862 case CallingConv::Swift:
1863 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1864 case CallingConv::C:
1865 if (!Subtarget->isAAPCS_ABI())
1866 return CallingConv::ARM_APCS;
1867 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1868 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1869 !isVarArg)
1870 return CallingConv::ARM_AAPCS_VFP;
1871 else
1872 return CallingConv::ARM_AAPCS;
1873 case CallingConv::Fast:
1874 case CallingConv::CXX_FAST_TLS:
1875 if (!Subtarget->isAAPCS_ABI()) {
1876 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1877 return CallingConv::Fast;
1878 return CallingConv::ARM_APCS;
1879 } else if (Subtarget->hasVFP2Base() &&
1880 !Subtarget->isThumb1Only() && !isVarArg)
1881 return CallingConv::ARM_AAPCS_VFP;
1882 else
1883 return CallingConv::ARM_AAPCS;
1887 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1888 bool isVarArg) const {
1889 return CCAssignFnForNode(CC, false, isVarArg);
1892 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1893 bool isVarArg) const {
1894 return CCAssignFnForNode(CC, true, isVarArg);
1897 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1898 /// CallingConvention.
1899 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1900 bool Return,
1901 bool isVarArg) const {
1902 switch (getEffectiveCallingConv(CC, isVarArg)) {
1903 default:
1904 report_fatal_error("Unsupported calling convention");
1905 case CallingConv::ARM_APCS:
1906 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1907 case CallingConv::ARM_AAPCS:
1908 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1909 case CallingConv::ARM_AAPCS_VFP:
1910 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1911 case CallingConv::Fast:
1912 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1913 case CallingConv::GHC:
1914 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1915 case CallingConv::PreserveMost:
1916 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1920 /// LowerCallResult - Lower the result values of a call into the
1921 /// appropriate copies out of appropriate physical registers.
1922 SDValue ARMTargetLowering::LowerCallResult(
1923 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1924 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1925 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1926 SDValue ThisVal) const {
1927 // Assign locations to each value returned by this call.
1928 SmallVector<CCValAssign, 16> RVLocs;
1929 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1930 *DAG.getContext());
1931 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1933 // Copy all of the result registers out of their specified physreg.
1934 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1935 CCValAssign VA = RVLocs[i];
1937 // Pass 'this' value directly from the argument to return value, to avoid
1938 // reg unit interference
1939 if (i == 0 && isThisReturn) {
1940 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1941 "unexpected return calling convention register assignment");
1942 InVals.push_back(ThisVal);
1943 continue;
1946 SDValue Val;
1947 if (VA.needsCustom()) {
1948 // Handle f64 or half of a v2f64.
1949 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1950 InFlag);
1951 Chain = Lo.getValue(1);
1952 InFlag = Lo.getValue(2);
1953 VA = RVLocs[++i]; // skip ahead to next loc
1954 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1955 InFlag);
1956 Chain = Hi.getValue(1);
1957 InFlag = Hi.getValue(2);
1958 if (!Subtarget->isLittle())
1959 std::swap (Lo, Hi);
1960 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1962 if (VA.getLocVT() == MVT::v2f64) {
1963 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1964 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1965 DAG.getConstant(0, dl, MVT::i32));
1967 VA = RVLocs[++i]; // skip ahead to next loc
1968 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1969 Chain = Lo.getValue(1);
1970 InFlag = Lo.getValue(2);
1971 VA = RVLocs[++i]; // skip ahead to next loc
1972 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1973 Chain = Hi.getValue(1);
1974 InFlag = Hi.getValue(2);
1975 if (!Subtarget->isLittle())
1976 std::swap (Lo, Hi);
1977 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1978 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1979 DAG.getConstant(1, dl, MVT::i32));
1981 } else {
1982 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1983 InFlag);
1984 Chain = Val.getValue(1);
1985 InFlag = Val.getValue(2);
1988 switch (VA.getLocInfo()) {
1989 default: llvm_unreachable("Unknown loc info!");
1990 case CCValAssign::Full: break;
1991 case CCValAssign::BCvt:
1992 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1993 break;
1996 InVals.push_back(Val);
1999 return Chain;
2002 /// LowerMemOpCallTo - Store the argument to the stack.
2003 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2004 SDValue Arg, const SDLoc &dl,
2005 SelectionDAG &DAG,
2006 const CCValAssign &VA,
2007 ISD::ArgFlagsTy Flags) const {
2008 unsigned LocMemOffset = VA.getLocMemOffset();
2009 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2010 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2011 StackPtr, PtrOff);
2012 return DAG.getStore(
2013 Chain, dl, Arg, PtrOff,
2014 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2017 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2018 SDValue Chain, SDValue &Arg,
2019 RegsToPassVector &RegsToPass,
2020 CCValAssign &VA, CCValAssign &NextVA,
2021 SDValue &StackPtr,
2022 SmallVectorImpl<SDValue> &MemOpChains,
2023 ISD::ArgFlagsTy Flags) const {
2024 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2025 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2026 unsigned id = Subtarget->isLittle() ? 0 : 1;
2027 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2029 if (NextVA.isRegLoc())
2030 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2031 else {
2032 assert(NextVA.isMemLoc());
2033 if (!StackPtr.getNode())
2034 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2035 getPointerTy(DAG.getDataLayout()));
2037 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2038 dl, DAG, NextVA,
2039 Flags));
2043 /// LowerCall - Lowering a call into a callseq_start <-
2044 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2045 /// nodes.
2046 SDValue
2047 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2048 SmallVectorImpl<SDValue> &InVals) const {
2049 SelectionDAG &DAG = CLI.DAG;
2050 SDLoc &dl = CLI.DL;
2051 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2052 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2053 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2054 SDValue Chain = CLI.Chain;
2055 SDValue Callee = CLI.Callee;
2056 bool &isTailCall = CLI.IsTailCall;
2057 CallingConv::ID CallConv = CLI.CallConv;
2058 bool doesNotRet = CLI.DoesNotReturn;
2059 bool isVarArg = CLI.IsVarArg;
2061 MachineFunction &MF = DAG.getMachineFunction();
2062 MachineFunction::CallSiteInfo CSInfo;
2063 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2064 bool isThisReturn = false;
2065 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2066 bool PreferIndirect = false;
2068 // Disable tail calls if they're not supported.
2069 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2070 isTailCall = false;
2072 if (isa<GlobalAddressSDNode>(Callee)) {
2073 // If we're optimizing for minimum size and the function is called three or
2074 // more times in this block, we can improve codesize by calling indirectly
2075 // as BLXr has a 16-bit encoding.
2076 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2077 if (CLI.CS) {
2078 auto *BB = CLI.CS.getParent();
2079 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2080 count_if(GV->users(), [&BB](const User *U) {
2081 return isa<Instruction>(U) &&
2082 cast<Instruction>(U)->getParent() == BB;
2083 }) > 2;
2086 if (isTailCall) {
2087 // Check if it's really possible to do a tail call.
2088 isTailCall = IsEligibleForTailCallOptimization(
2089 Callee, CallConv, isVarArg, isStructRet,
2090 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2091 PreferIndirect);
2092 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2093 report_fatal_error("failed to perform tail call elimination on a call "
2094 "site marked musttail");
2095 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2096 // detected sibcalls.
2097 if (isTailCall)
2098 ++NumTailCalls;
2101 // Analyze operands of the call, assigning locations to each operand.
2102 SmallVector<CCValAssign, 16> ArgLocs;
2103 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2104 *DAG.getContext());
2105 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2107 // Get a count of how many bytes are to be pushed on the stack.
2108 unsigned NumBytes = CCInfo.getNextStackOffset();
2110 if (isTailCall) {
2111 // For tail calls, memory operands are available in our caller's stack.
2112 NumBytes = 0;
2113 } else {
2114 // Adjust the stack pointer for the new arguments...
2115 // These operations are automatically eliminated by the prolog/epilog pass
2116 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2119 SDValue StackPtr =
2120 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2122 RegsToPassVector RegsToPass;
2123 SmallVector<SDValue, 8> MemOpChains;
2125 // Walk the register/memloc assignments, inserting copies/loads. In the case
2126 // of tail call optimization, arguments are handled later.
2127 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2128 i != e;
2129 ++i, ++realArgIdx) {
2130 CCValAssign &VA = ArgLocs[i];
2131 SDValue Arg = OutVals[realArgIdx];
2132 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2133 bool isByVal = Flags.isByVal();
2135 // Promote the value if needed.
2136 switch (VA.getLocInfo()) {
2137 default: llvm_unreachable("Unknown loc info!");
2138 case CCValAssign::Full: break;
2139 case CCValAssign::SExt:
2140 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2141 break;
2142 case CCValAssign::ZExt:
2143 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2144 break;
2145 case CCValAssign::AExt:
2146 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2147 break;
2148 case CCValAssign::BCvt:
2149 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2150 break;
2153 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2154 if (VA.needsCustom()) {
2155 if (VA.getLocVT() == MVT::v2f64) {
2156 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2157 DAG.getConstant(0, dl, MVT::i32));
2158 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2159 DAG.getConstant(1, dl, MVT::i32));
2161 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2162 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2164 VA = ArgLocs[++i]; // skip ahead to next loc
2165 if (VA.isRegLoc()) {
2166 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2167 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2168 } else {
2169 assert(VA.isMemLoc());
2171 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2172 dl, DAG, VA, Flags));
2174 } else {
2175 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2176 StackPtr, MemOpChains, Flags);
2178 } else if (VA.isRegLoc()) {
2179 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2180 Outs[0].VT == MVT::i32) {
2181 assert(VA.getLocVT() == MVT::i32 &&
2182 "unexpected calling convention register assignment");
2183 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2184 "unexpected use of 'returned'");
2185 isThisReturn = true;
2187 const TargetOptions &Options = DAG.getTarget().Options;
2188 if (Options.EnableDebugEntryValues)
2189 CSInfo.emplace_back(VA.getLocReg(), i);
2190 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2191 } else if (isByVal) {
2192 assert(VA.isMemLoc());
2193 unsigned offset = 0;
2195 // True if this byval aggregate will be split between registers
2196 // and memory.
2197 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2198 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2200 if (CurByValIdx < ByValArgsCount) {
2202 unsigned RegBegin, RegEnd;
2203 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2205 EVT PtrVT =
2206 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2207 unsigned int i, j;
2208 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2209 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2210 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2211 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2212 MachinePointerInfo(),
2213 DAG.InferPtrAlignment(AddArg));
2214 MemOpChains.push_back(Load.getValue(1));
2215 RegsToPass.push_back(std::make_pair(j, Load));
2218 // If parameter size outsides register area, "offset" value
2219 // helps us to calculate stack slot for remained part properly.
2220 offset = RegEnd - RegBegin;
2222 CCInfo.nextInRegsParam();
2225 if (Flags.getByValSize() > 4*offset) {
2226 auto PtrVT = getPointerTy(DAG.getDataLayout());
2227 unsigned LocMemOffset = VA.getLocMemOffset();
2228 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2229 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2230 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2231 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2232 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2233 MVT::i32);
2234 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2235 MVT::i32);
2237 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2238 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2239 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2240 Ops));
2242 } else if (!isTailCall) {
2243 assert(VA.isMemLoc());
2245 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2246 dl, DAG, VA, Flags));
2250 if (!MemOpChains.empty())
2251 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2253 // Build a sequence of copy-to-reg nodes chained together with token chain
2254 // and flag operands which copy the outgoing args into the appropriate regs.
2255 SDValue InFlag;
2256 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2257 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2258 RegsToPass[i].second, InFlag);
2259 InFlag = Chain.getValue(1);
2262 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2263 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2264 // node so that legalize doesn't hack it.
2265 bool isDirect = false;
2267 const TargetMachine &TM = getTargetMachine();
2268 const Module *Mod = MF.getFunction().getParent();
2269 const GlobalValue *GV = nullptr;
2270 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2271 GV = G->getGlobal();
2272 bool isStub =
2273 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2275 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2276 bool isLocalARMFunc = false;
2277 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2278 auto PtrVt = getPointerTy(DAG.getDataLayout());
2280 if (Subtarget->genLongCalls()) {
2281 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2282 "long-calls codegen is not position independent!");
2283 // Handle a global address or an external symbol. If it's not one of
2284 // those, the target's already in a register, so we don't need to do
2285 // anything extra.
2286 if (isa<GlobalAddressSDNode>(Callee)) {
2287 // Create a constant pool entry for the callee address
2288 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2289 ARMConstantPoolValue *CPV =
2290 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2292 // Get the address of the callee into a register
2293 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2294 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2295 Callee = DAG.getLoad(
2296 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2297 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2298 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2299 const char *Sym = S->getSymbol();
2301 // Create a constant pool entry for the callee address
2302 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2303 ARMConstantPoolValue *CPV =
2304 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2305 ARMPCLabelIndex, 0);
2306 // Get the address of the callee into a register
2307 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2308 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2309 Callee = DAG.getLoad(
2310 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2311 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2313 } else if (isa<GlobalAddressSDNode>(Callee)) {
2314 if (!PreferIndirect) {
2315 isDirect = true;
2316 bool isDef = GV->isStrongDefinitionForLinker();
2318 // ARM call to a local ARM function is predicable.
2319 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2320 // tBX takes a register source operand.
2321 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2322 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2323 Callee = DAG.getNode(
2324 ARMISD::WrapperPIC, dl, PtrVt,
2325 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2326 Callee = DAG.getLoad(
2327 PtrVt, dl, DAG.getEntryNode(), Callee,
2328 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2329 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2330 MachineMemOperand::MOInvariant);
2331 } else if (Subtarget->isTargetCOFF()) {
2332 assert(Subtarget->isTargetWindows() &&
2333 "Windows is the only supported COFF target");
2334 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2335 ? ARMII::MO_DLLIMPORT
2336 : ARMII::MO_NO_FLAG;
2337 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2338 TargetFlags);
2339 if (GV->hasDLLImportStorageClass())
2340 Callee =
2341 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2342 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2343 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2344 } else {
2345 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2348 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2349 isDirect = true;
2350 // tBX takes a register source operand.
2351 const char *Sym = S->getSymbol();
2352 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2353 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2354 ARMConstantPoolValue *CPV =
2355 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2356 ARMPCLabelIndex, 4);
2357 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2358 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2359 Callee = DAG.getLoad(
2360 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2361 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2362 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2363 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2364 } else {
2365 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2369 // FIXME: handle tail calls differently.
2370 unsigned CallOpc;
2371 if (Subtarget->isThumb()) {
2372 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2373 CallOpc = ARMISD::CALL_NOLINK;
2374 else
2375 CallOpc = ARMISD::CALL;
2376 } else {
2377 if (!isDirect && !Subtarget->hasV5TOps())
2378 CallOpc = ARMISD::CALL_NOLINK;
2379 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2380 // Emit regular call when code size is the priority
2381 !Subtarget->hasMinSize())
2382 // "mov lr, pc; b _foo" to avoid confusing the RSP
2383 CallOpc = ARMISD::CALL_NOLINK;
2384 else
2385 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2388 std::vector<SDValue> Ops;
2389 Ops.push_back(Chain);
2390 Ops.push_back(Callee);
2392 // Add argument registers to the end of the list so that they are known live
2393 // into the call.
2394 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2395 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2396 RegsToPass[i].second.getValueType()));
2398 // Add a register mask operand representing the call-preserved registers.
2399 if (!isTailCall) {
2400 const uint32_t *Mask;
2401 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2402 if (isThisReturn) {
2403 // For 'this' returns, use the R0-preserving mask if applicable
2404 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2405 if (!Mask) {
2406 // Set isThisReturn to false if the calling convention is not one that
2407 // allows 'returned' to be modeled in this way, so LowerCallResult does
2408 // not try to pass 'this' straight through
2409 isThisReturn = false;
2410 Mask = ARI->getCallPreservedMask(MF, CallConv);
2412 } else
2413 Mask = ARI->getCallPreservedMask(MF, CallConv);
2415 assert(Mask && "Missing call preserved mask for calling convention");
2416 Ops.push_back(DAG.getRegisterMask(Mask));
2419 if (InFlag.getNode())
2420 Ops.push_back(InFlag);
2422 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2423 if (isTailCall) {
2424 MF.getFrameInfo().setHasTailCall();
2425 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2426 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2427 return Ret;
2430 // Returns a chain and a flag for retval copy to use.
2431 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2432 InFlag = Chain.getValue(1);
2433 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2435 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2436 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2437 if (!Ins.empty())
2438 InFlag = Chain.getValue(1);
2440 // Handle result values, copying them out of physregs into vregs that we
2441 // return.
2442 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2443 InVals, isThisReturn,
2444 isThisReturn ? OutVals[0] : SDValue());
2447 /// HandleByVal - Every parameter *after* a byval parameter is passed
2448 /// on the stack. Remember the next parameter register to allocate,
2449 /// and then confiscate the rest of the parameter registers to insure
2450 /// this.
2451 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2452 unsigned Align) const {
2453 // Byval (as with any stack) slots are always at least 4 byte aligned.
2454 Align = std::max(Align, 4U);
2456 unsigned Reg = State->AllocateReg(GPRArgRegs);
2457 if (!Reg)
2458 return;
2460 unsigned AlignInRegs = Align / 4;
2461 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2462 for (unsigned i = 0; i < Waste; ++i)
2463 Reg = State->AllocateReg(GPRArgRegs);
2465 if (!Reg)
2466 return;
2468 unsigned Excess = 4 * (ARM::R4 - Reg);
2470 // Special case when NSAA != SP and parameter size greater than size of
2471 // all remained GPR regs. In that case we can't split parameter, we must
2472 // send it to stack. We also must set NCRN to R4, so waste all
2473 // remained registers.
2474 const unsigned NSAAOffset = State->getNextStackOffset();
2475 if (NSAAOffset != 0 && Size > Excess) {
2476 while (State->AllocateReg(GPRArgRegs))
2478 return;
2481 // First register for byval parameter is the first register that wasn't
2482 // allocated before this method call, so it would be "reg".
2483 // If parameter is small enough to be saved in range [reg, r4), then
2484 // the end (first after last) register would be reg + param-size-in-regs,
2485 // else parameter would be splitted between registers and stack,
2486 // end register would be r4 in this case.
2487 unsigned ByValRegBegin = Reg;
2488 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2489 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2490 // Note, first register is allocated in the beginning of function already,
2491 // allocate remained amount of registers we need.
2492 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2493 State->AllocateReg(GPRArgRegs);
2494 // A byval parameter that is split between registers and memory needs its
2495 // size truncated here.
2496 // In the case where the entire structure fits in registers, we set the
2497 // size in memory to zero.
2498 Size = std::max<int>(Size - Excess, 0);
2501 /// MatchingStackOffset - Return true if the given stack call argument is
2502 /// already available in the same position (relatively) of the caller's
2503 /// incoming argument stack.
2504 static
2505 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2506 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2507 const TargetInstrInfo *TII) {
2508 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2509 int FI = std::numeric_limits<int>::max();
2510 if (Arg.getOpcode() == ISD::CopyFromReg) {
2511 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2512 if (!Register::isVirtualRegister(VR))
2513 return false;
2514 MachineInstr *Def = MRI->getVRegDef(VR);
2515 if (!Def)
2516 return false;
2517 if (!Flags.isByVal()) {
2518 if (!TII->isLoadFromStackSlot(*Def, FI))
2519 return false;
2520 } else {
2521 return false;
2523 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2524 if (Flags.isByVal())
2525 // ByVal argument is passed in as a pointer but it's now being
2526 // dereferenced. e.g.
2527 // define @foo(%struct.X* %A) {
2528 // tail call @bar(%struct.X* byval %A)
2529 // }
2530 return false;
2531 SDValue Ptr = Ld->getBasePtr();
2532 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2533 if (!FINode)
2534 return false;
2535 FI = FINode->getIndex();
2536 } else
2537 return false;
2539 assert(FI != std::numeric_limits<int>::max());
2540 if (!MFI.isFixedObjectIndex(FI))
2541 return false;
2542 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2545 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2546 /// for tail call optimization. Targets which want to do tail call
2547 /// optimization should implement this function.
2548 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2549 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2550 bool isCalleeStructRet, bool isCallerStructRet,
2551 const SmallVectorImpl<ISD::OutputArg> &Outs,
2552 const SmallVectorImpl<SDValue> &OutVals,
2553 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2554 const bool isIndirect) const {
2555 MachineFunction &MF = DAG.getMachineFunction();
2556 const Function &CallerF = MF.getFunction();
2557 CallingConv::ID CallerCC = CallerF.getCallingConv();
2559 assert(Subtarget->supportsTailCall());
2561 // Indirect tail calls cannot be optimized for Thumb1 if the args
2562 // to the call take up r0-r3. The reason is that there are no legal registers
2563 // left to hold the pointer to the function to be called.
2564 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2565 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2566 return false;
2568 // Look for obvious safe cases to perform tail call optimization that do not
2569 // require ABI changes. This is what gcc calls sibcall.
2571 // Exception-handling functions need a special set of instructions to indicate
2572 // a return to the hardware. Tail-calling another function would probably
2573 // break this.
2574 if (CallerF.hasFnAttribute("interrupt"))
2575 return false;
2577 // Also avoid sibcall optimization if either caller or callee uses struct
2578 // return semantics.
2579 if (isCalleeStructRet || isCallerStructRet)
2580 return false;
2582 // Externally-defined functions with weak linkage should not be
2583 // tail-called on ARM when the OS does not support dynamic
2584 // pre-emption of symbols, as the AAELF spec requires normal calls
2585 // to undefined weak functions to be replaced with a NOP or jump to the
2586 // next instruction. The behaviour of branch instructions in this
2587 // situation (as used for tail calls) is implementation-defined, so we
2588 // cannot rely on the linker replacing the tail call with a return.
2589 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2590 const GlobalValue *GV = G->getGlobal();
2591 const Triple &TT = getTargetMachine().getTargetTriple();
2592 if (GV->hasExternalWeakLinkage() &&
2593 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2594 return false;
2597 // Check that the call results are passed in the same way.
2598 LLVMContext &C = *DAG.getContext();
2599 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2600 CCAssignFnForReturn(CalleeCC, isVarArg),
2601 CCAssignFnForReturn(CallerCC, isVarArg)))
2602 return false;
2603 // The callee has to preserve all registers the caller needs to preserve.
2604 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2605 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2606 if (CalleeCC != CallerCC) {
2607 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2608 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2609 return false;
2612 // If Caller's vararg or byval argument has been split between registers and
2613 // stack, do not perform tail call, since part of the argument is in caller's
2614 // local frame.
2615 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2616 if (AFI_Caller->getArgRegsSaveSize())
2617 return false;
2619 // If the callee takes no arguments then go on to check the results of the
2620 // call.
2621 if (!Outs.empty()) {
2622 // Check if stack adjustment is needed. For now, do not do this if any
2623 // argument is passed on the stack.
2624 SmallVector<CCValAssign, 16> ArgLocs;
2625 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2626 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2627 if (CCInfo.getNextStackOffset()) {
2628 // Check if the arguments are already laid out in the right way as
2629 // the caller's fixed stack objects.
2630 MachineFrameInfo &MFI = MF.getFrameInfo();
2631 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2632 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2633 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2634 i != e;
2635 ++i, ++realArgIdx) {
2636 CCValAssign &VA = ArgLocs[i];
2637 EVT RegVT = VA.getLocVT();
2638 SDValue Arg = OutVals[realArgIdx];
2639 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2640 if (VA.getLocInfo() == CCValAssign::Indirect)
2641 return false;
2642 if (VA.needsCustom()) {
2643 // f64 and vector types are split into multiple registers or
2644 // register/stack-slot combinations. The types will not match
2645 // the registers; give up on memory f64 refs until we figure
2646 // out what to do about this.
2647 if (!VA.isRegLoc())
2648 return false;
2649 if (!ArgLocs[++i].isRegLoc())
2650 return false;
2651 if (RegVT == MVT::v2f64) {
2652 if (!ArgLocs[++i].isRegLoc())
2653 return false;
2654 if (!ArgLocs[++i].isRegLoc())
2655 return false;
2657 } else if (!VA.isRegLoc()) {
2658 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2659 MFI, MRI, TII))
2660 return false;
2665 const MachineRegisterInfo &MRI = MF.getRegInfo();
2666 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2667 return false;
2670 return true;
2673 bool
2674 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2675 MachineFunction &MF, bool isVarArg,
2676 const SmallVectorImpl<ISD::OutputArg> &Outs,
2677 LLVMContext &Context) const {
2678 SmallVector<CCValAssign, 16> RVLocs;
2679 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2680 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2683 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2684 const SDLoc &DL, SelectionDAG &DAG) {
2685 const MachineFunction &MF = DAG.getMachineFunction();
2686 const Function &F = MF.getFunction();
2688 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2690 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2691 // version of the "preferred return address". These offsets affect the return
2692 // instruction if this is a return from PL1 without hypervisor extensions.
2693 // IRQ/FIQ: +4 "subs pc, lr, #4"
2694 // SWI: 0 "subs pc, lr, #0"
2695 // ABORT: +4 "subs pc, lr, #4"
2696 // UNDEF: +4/+2 "subs pc, lr, #0"
2697 // UNDEF varies depending on where the exception came from ARM or Thumb
2698 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2700 int64_t LROffset;
2701 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2702 IntKind == "ABORT")
2703 LROffset = 4;
2704 else if (IntKind == "SWI" || IntKind == "UNDEF")
2705 LROffset = 0;
2706 else
2707 report_fatal_error("Unsupported interrupt attribute. If present, value "
2708 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2710 RetOps.insert(RetOps.begin() + 1,
2711 DAG.getConstant(LROffset, DL, MVT::i32, false));
2713 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2716 SDValue
2717 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2718 bool isVarArg,
2719 const SmallVectorImpl<ISD::OutputArg> &Outs,
2720 const SmallVectorImpl<SDValue> &OutVals,
2721 const SDLoc &dl, SelectionDAG &DAG) const {
2722 // CCValAssign - represent the assignment of the return value to a location.
2723 SmallVector<CCValAssign, 16> RVLocs;
2725 // CCState - Info about the registers and stack slots.
2726 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2727 *DAG.getContext());
2729 // Analyze outgoing return values.
2730 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2732 SDValue Flag;
2733 SmallVector<SDValue, 4> RetOps;
2734 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2735 bool isLittleEndian = Subtarget->isLittle();
2737 MachineFunction &MF = DAG.getMachineFunction();
2738 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2739 AFI->setReturnRegsCount(RVLocs.size());
2741 // Copy the result values into the output registers.
2742 for (unsigned i = 0, realRVLocIdx = 0;
2743 i != RVLocs.size();
2744 ++i, ++realRVLocIdx) {
2745 CCValAssign &VA = RVLocs[i];
2746 assert(VA.isRegLoc() && "Can only return in registers!");
2748 SDValue Arg = OutVals[realRVLocIdx];
2749 bool ReturnF16 = false;
2751 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2752 // Half-precision return values can be returned like this:
2754 // t11 f16 = fadd ...
2755 // t12: i16 = bitcast t11
2756 // t13: i32 = zero_extend t12
2757 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2759 // to avoid code generation for bitcasts, we simply set Arg to the node
2760 // that produces the f16 value, t11 in this case.
2762 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2763 SDValue ZE = Arg.getOperand(0);
2764 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2765 SDValue BC = ZE.getOperand(0);
2766 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2767 Arg = BC.getOperand(0);
2768 ReturnF16 = true;
2774 switch (VA.getLocInfo()) {
2775 default: llvm_unreachable("Unknown loc info!");
2776 case CCValAssign::Full: break;
2777 case CCValAssign::BCvt:
2778 if (!ReturnF16)
2779 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2780 break;
2783 if (VA.needsCustom()) {
2784 if (VA.getLocVT() == MVT::v2f64) {
2785 // Extract the first half and return it in two registers.
2786 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2787 DAG.getConstant(0, dl, MVT::i32));
2788 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2789 DAG.getVTList(MVT::i32, MVT::i32), Half);
2791 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2792 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2793 Flag);
2794 Flag = Chain.getValue(1);
2795 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2796 VA = RVLocs[++i]; // skip ahead to next loc
2797 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2798 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2799 Flag);
2800 Flag = Chain.getValue(1);
2801 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2802 VA = RVLocs[++i]; // skip ahead to next loc
2804 // Extract the 2nd half and fall through to handle it as an f64 value.
2805 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2806 DAG.getConstant(1, dl, MVT::i32));
2808 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2809 // available.
2810 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2811 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2812 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2813 fmrrd.getValue(isLittleEndian ? 0 : 1),
2814 Flag);
2815 Flag = Chain.getValue(1);
2816 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2817 VA = RVLocs[++i]; // skip ahead to next loc
2818 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2819 fmrrd.getValue(isLittleEndian ? 1 : 0),
2820 Flag);
2821 } else
2822 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2824 // Guarantee that all emitted copies are
2825 // stuck together, avoiding something bad.
2826 Flag = Chain.getValue(1);
2827 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2828 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2830 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2831 const MCPhysReg *I =
2832 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2833 if (I) {
2834 for (; *I; ++I) {
2835 if (ARM::GPRRegClass.contains(*I))
2836 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2837 else if (ARM::DPRRegClass.contains(*I))
2838 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2839 else
2840 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2844 // Update chain and glue.
2845 RetOps[0] = Chain;
2846 if (Flag.getNode())
2847 RetOps.push_back(Flag);
2849 // CPUs which aren't M-class use a special sequence to return from
2850 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2851 // though we use "subs pc, lr, #N").
2853 // M-class CPUs actually use a normal return sequence with a special
2854 // (hardware-provided) value in LR, so the normal code path works.
2855 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2856 !Subtarget->isMClass()) {
2857 if (Subtarget->isThumb1Only())
2858 report_fatal_error("interrupt attribute is not supported in Thumb1");
2859 return LowerInterruptReturn(RetOps, dl, DAG);
2862 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2865 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2866 if (N->getNumValues() != 1)
2867 return false;
2868 if (!N->hasNUsesOfValue(1, 0))
2869 return false;
2871 SDValue TCChain = Chain;
2872 SDNode *Copy = *N->use_begin();
2873 if (Copy->getOpcode() == ISD::CopyToReg) {
2874 // If the copy has a glue operand, we conservatively assume it isn't safe to
2875 // perform a tail call.
2876 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2877 return false;
2878 TCChain = Copy->getOperand(0);
2879 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2880 SDNode *VMov = Copy;
2881 // f64 returned in a pair of GPRs.
2882 SmallPtrSet<SDNode*, 2> Copies;
2883 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2884 UI != UE; ++UI) {
2885 if (UI->getOpcode() != ISD::CopyToReg)
2886 return false;
2887 Copies.insert(*UI);
2889 if (Copies.size() > 2)
2890 return false;
2892 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2893 UI != UE; ++UI) {
2894 SDValue UseChain = UI->getOperand(0);
2895 if (Copies.count(UseChain.getNode()))
2896 // Second CopyToReg
2897 Copy = *UI;
2898 else {
2899 // We are at the top of this chain.
2900 // If the copy has a glue operand, we conservatively assume it
2901 // isn't safe to perform a tail call.
2902 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2903 return false;
2904 // First CopyToReg
2905 TCChain = UseChain;
2908 } else if (Copy->getOpcode() == ISD::BITCAST) {
2909 // f32 returned in a single GPR.
2910 if (!Copy->hasOneUse())
2911 return false;
2912 Copy = *Copy->use_begin();
2913 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2914 return false;
2915 // If the copy has a glue operand, we conservatively assume it isn't safe to
2916 // perform a tail call.
2917 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2918 return false;
2919 TCChain = Copy->getOperand(0);
2920 } else {
2921 return false;
2924 bool HasRet = false;
2925 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2926 UI != UE; ++UI) {
2927 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2928 UI->getOpcode() != ARMISD::INTRET_FLAG)
2929 return false;
2930 HasRet = true;
2933 if (!HasRet)
2934 return false;
2936 Chain = TCChain;
2937 return true;
2940 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2941 if (!Subtarget->supportsTailCall())
2942 return false;
2944 auto Attr =
2945 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2946 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2947 return false;
2949 return true;
2952 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2953 // and pass the lower and high parts through.
2954 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2955 SDLoc DL(Op);
2956 SDValue WriteValue = Op->getOperand(2);
2958 // This function is only supposed to be called for i64 type argument.
2959 assert(WriteValue.getValueType() == MVT::i64
2960 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2962 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2963 DAG.getConstant(0, DL, MVT::i32));
2964 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2965 DAG.getConstant(1, DL, MVT::i32));
2966 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2967 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2970 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2971 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2972 // one of the above mentioned nodes. It has to be wrapped because otherwise
2973 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2974 // be used to form addressing mode. These wrapped nodes will be selected
2975 // into MOVi.
2976 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2977 SelectionDAG &DAG) const {
2978 EVT PtrVT = Op.getValueType();
2979 // FIXME there is no actual debug info here
2980 SDLoc dl(Op);
2981 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2982 SDValue Res;
2984 // When generating execute-only code Constant Pools must be promoted to the
2985 // global data section. It's a bit ugly that we can't share them across basic
2986 // blocks, but this way we guarantee that execute-only behaves correct with
2987 // position-independent addressing modes.
2988 if (Subtarget->genExecuteOnly()) {
2989 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2990 auto T = const_cast<Type*>(CP->getType());
2991 auto C = const_cast<Constant*>(CP->getConstVal());
2992 auto M = const_cast<Module*>(DAG.getMachineFunction().
2993 getFunction().getParent());
2994 auto GV = new GlobalVariable(
2995 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2996 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2997 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2998 Twine(AFI->createPICLabelUId())
3000 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3001 dl, PtrVT);
3002 return LowerGlobalAddress(GA, DAG);
3005 if (CP->isMachineConstantPoolEntry())
3006 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
3007 CP->getAlignment());
3008 else
3009 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
3010 CP->getAlignment());
3011 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3014 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3015 return MachineJumpTableInfo::EK_Inline;
3018 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3019 SelectionDAG &DAG) const {
3020 MachineFunction &MF = DAG.getMachineFunction();
3021 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3022 unsigned ARMPCLabelIndex = 0;
3023 SDLoc DL(Op);
3024 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3025 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3026 SDValue CPAddr;
3027 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3028 if (!IsPositionIndependent) {
3029 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3030 } else {
3031 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3032 ARMPCLabelIndex = AFI->createPICLabelUId();
3033 ARMConstantPoolValue *CPV =
3034 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3035 ARMCP::CPBlockAddress, PCAdj);
3036 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3038 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3039 SDValue Result = DAG.getLoad(
3040 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3041 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3042 if (!IsPositionIndependent)
3043 return Result;
3044 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3045 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3048 /// Convert a TLS address reference into the correct sequence of loads
3049 /// and calls to compute the variable's address for Darwin, and return an
3050 /// SDValue containing the final node.
3052 /// Darwin only has one TLS scheme which must be capable of dealing with the
3053 /// fully general situation, in the worst case. This means:
3054 /// + "extern __thread" declaration.
3055 /// + Defined in a possibly unknown dynamic library.
3057 /// The general system is that each __thread variable has a [3 x i32] descriptor
3058 /// which contains information used by the runtime to calculate the address. The
3059 /// only part of this the compiler needs to know about is the first word, which
3060 /// contains a function pointer that must be called with the address of the
3061 /// entire descriptor in "r0".
3063 /// Since this descriptor may be in a different unit, in general access must
3064 /// proceed along the usual ARM rules. A common sequence to produce is:
3066 /// movw rT1, :lower16:_var$non_lazy_ptr
3067 /// movt rT1, :upper16:_var$non_lazy_ptr
3068 /// ldr r0, [rT1]
3069 /// ldr rT2, [r0]
3070 /// blx rT2
3071 /// [...address now in r0...]
3072 SDValue
3073 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3074 SelectionDAG &DAG) const {
3075 assert(Subtarget->isTargetDarwin() &&
3076 "This function expects a Darwin target");
3077 SDLoc DL(Op);
3079 // First step is to get the address of the actua global symbol. This is where
3080 // the TLS descriptor lives.
3081 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3083 // The first entry in the descriptor is a function pointer that we must call
3084 // to obtain the address of the variable.
3085 SDValue Chain = DAG.getEntryNode();
3086 SDValue FuncTLVGet = DAG.getLoad(
3087 MVT::i32, DL, Chain, DescAddr,
3088 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3089 /* Alignment = */ 4,
3090 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3091 MachineMemOperand::MOInvariant);
3092 Chain = FuncTLVGet.getValue(1);
3094 MachineFunction &F = DAG.getMachineFunction();
3095 MachineFrameInfo &MFI = F.getFrameInfo();
3096 MFI.setAdjustsStack(true);
3098 // TLS calls preserve all registers except those that absolutely must be
3099 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3100 // silly).
3101 auto TRI =
3102 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3103 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3104 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3106 // Finally, we can make the call. This is just a degenerate version of a
3107 // normal AArch64 call node: r0 takes the address of the descriptor, and
3108 // returns the address of the variable in this thread.
3109 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3110 Chain =
3111 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3112 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3113 DAG.getRegisterMask(Mask), Chain.getValue(1));
3114 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3117 SDValue
3118 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3119 SelectionDAG &DAG) const {
3120 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3122 SDValue Chain = DAG.getEntryNode();
3123 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3124 SDLoc DL(Op);
3126 // Load the current TEB (thread environment block)
3127 SDValue Ops[] = {Chain,
3128 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3129 DAG.getTargetConstant(15, DL, MVT::i32),
3130 DAG.getTargetConstant(0, DL, MVT::i32),
3131 DAG.getTargetConstant(13, DL, MVT::i32),
3132 DAG.getTargetConstant(0, DL, MVT::i32),
3133 DAG.getTargetConstant(2, DL, MVT::i32)};
3134 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3135 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3137 SDValue TEB = CurrentTEB.getValue(0);
3138 Chain = CurrentTEB.getValue(1);
3140 // Load the ThreadLocalStoragePointer from the TEB
3141 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3142 SDValue TLSArray =
3143 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3144 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3146 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3147 // offset into the TLSArray.
3149 // Load the TLS index from the C runtime
3150 SDValue TLSIndex =
3151 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3152 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3153 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3155 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3156 DAG.getConstant(2, DL, MVT::i32));
3157 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3158 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3159 MachinePointerInfo());
3161 // Get the offset of the start of the .tls section (section base)
3162 const auto *GA = cast<GlobalAddressSDNode>(Op);
3163 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3164 SDValue Offset = DAG.getLoad(
3165 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3166 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3167 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3169 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3172 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3173 SDValue
3174 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3175 SelectionDAG &DAG) const {
3176 SDLoc dl(GA);
3177 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3178 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3179 MachineFunction &MF = DAG.getMachineFunction();
3180 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3181 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3182 ARMConstantPoolValue *CPV =
3183 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3184 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3185 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3186 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3187 Argument = DAG.getLoad(
3188 PtrVT, dl, DAG.getEntryNode(), Argument,
3189 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3190 SDValue Chain = Argument.getValue(1);
3192 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3193 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3195 // call __tls_get_addr.
3196 ArgListTy Args;
3197 ArgListEntry Entry;
3198 Entry.Node = Argument;
3199 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3200 Args.push_back(Entry);
3202 // FIXME: is there useful debug info available here?
3203 TargetLowering::CallLoweringInfo CLI(DAG);
3204 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3205 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3206 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3208 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3209 return CallResult.first;
3212 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3213 // "local exec" model.
3214 SDValue
3215 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3216 SelectionDAG &DAG,
3217 TLSModel::Model model) const {
3218 const GlobalValue *GV = GA->getGlobal();
3219 SDLoc dl(GA);
3220 SDValue Offset;
3221 SDValue Chain = DAG.getEntryNode();
3222 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3223 // Get the Thread Pointer
3224 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3226 if (model == TLSModel::InitialExec) {
3227 MachineFunction &MF = DAG.getMachineFunction();
3228 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3229 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3230 // Initial exec model.
3231 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3232 ARMConstantPoolValue *CPV =
3233 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3234 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3235 true);
3236 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3237 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3238 Offset = DAG.getLoad(
3239 PtrVT, dl, Chain, Offset,
3240 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3241 Chain = Offset.getValue(1);
3243 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3244 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3246 Offset = DAG.getLoad(
3247 PtrVT, dl, Chain, Offset,
3248 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3249 } else {
3250 // local exec model
3251 assert(model == TLSModel::LocalExec);
3252 ARMConstantPoolValue *CPV =
3253 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3254 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3255 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3256 Offset = DAG.getLoad(
3257 PtrVT, dl, Chain, Offset,
3258 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3261 // The address of the thread local variable is the add of the thread
3262 // pointer with the offset of the variable.
3263 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3266 SDValue
3267 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3268 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3269 if (DAG.getTarget().useEmulatedTLS())
3270 return LowerToTLSEmulatedModel(GA, DAG);
3272 if (Subtarget->isTargetDarwin())
3273 return LowerGlobalTLSAddressDarwin(Op, DAG);
3275 if (Subtarget->isTargetWindows())
3276 return LowerGlobalTLSAddressWindows(Op, DAG);
3278 // TODO: implement the "local dynamic" model
3279 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3280 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3282 switch (model) {
3283 case TLSModel::GeneralDynamic:
3284 case TLSModel::LocalDynamic:
3285 return LowerToTLSGeneralDynamicModel(GA, DAG);
3286 case TLSModel::InitialExec:
3287 case TLSModel::LocalExec:
3288 return LowerToTLSExecModels(GA, DAG, model);
3290 llvm_unreachable("bogus TLS model");
3293 /// Return true if all users of V are within function F, looking through
3294 /// ConstantExprs.
3295 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3296 SmallVector<const User*,4> Worklist;
3297 for (auto *U : V->users())
3298 Worklist.push_back(U);
3299 while (!Worklist.empty()) {
3300 auto *U = Worklist.pop_back_val();
3301 if (isa<ConstantExpr>(U)) {
3302 for (auto *UU : U->users())
3303 Worklist.push_back(UU);
3304 continue;
3307 auto *I = dyn_cast<Instruction>(U);
3308 if (!I || I->getParent()->getParent() != F)
3309 return false;
3311 return true;
3314 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3315 const GlobalValue *GV, SelectionDAG &DAG,
3316 EVT PtrVT, const SDLoc &dl) {
3317 // If we're creating a pool entry for a constant global with unnamed address,
3318 // and the global is small enough, we can emit it inline into the constant pool
3319 // to save ourselves an indirection.
3321 // This is a win if the constant is only used in one function (so it doesn't
3322 // need to be duplicated) or duplicating the constant wouldn't increase code
3323 // size (implying the constant is no larger than 4 bytes).
3324 const Function &F = DAG.getMachineFunction().getFunction();
3326 // We rely on this decision to inline being idemopotent and unrelated to the
3327 // use-site. We know that if we inline a variable at one use site, we'll
3328 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3329 // doesn't know about this optimization, so bail out if it's enabled else
3330 // we could decide to inline here (and thus never emit the GV) but require
3331 // the GV from fast-isel generated code.
3332 if (!EnableConstpoolPromotion ||
3333 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3334 return SDValue();
3336 auto *GVar = dyn_cast<GlobalVariable>(GV);
3337 if (!GVar || !GVar->hasInitializer() ||
3338 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3339 !GVar->hasLocalLinkage())
3340 return SDValue();
3342 // If we inline a value that contains relocations, we move the relocations
3343 // from .data to .text. This is not allowed in position-independent code.
3344 auto *Init = GVar->getInitializer();
3345 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3346 Init->needsRelocation())
3347 return SDValue();
3349 // The constant islands pass can only really deal with alignment requests
3350 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3351 // any type wanting greater alignment requirements than 4 bytes. We also
3352 // can only promote constants that are multiples of 4 bytes in size or
3353 // are paddable to a multiple of 4. Currently we only try and pad constants
3354 // that are strings for simplicity.
3355 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3356 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3357 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3358 unsigned RequiredPadding = 4 - (Size % 4);
3359 bool PaddingPossible =
3360 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3361 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3362 Size == 0)
3363 return SDValue();
3365 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3366 MachineFunction &MF = DAG.getMachineFunction();
3367 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3369 // We can't bloat the constant pool too much, else the ConstantIslands pass
3370 // may fail to converge. If we haven't promoted this global yet (it may have
3371 // multiple uses), and promoting it would increase the constant pool size (Sz
3372 // > 4), ensure we have space to do so up to MaxTotal.
3373 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3374 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3375 ConstpoolPromotionMaxTotal)
3376 return SDValue();
3378 // This is only valid if all users are in a single function; we can't clone
3379 // the constant in general. The LLVM IR unnamed_addr allows merging
3380 // constants, but not cloning them.
3382 // We could potentially allow cloning if we could prove all uses of the
3383 // constant in the current function don't care about the address, like
3384 // printf format strings. But that isn't implemented for now.
3385 if (!allUsersAreInFunction(GVar, &F))
3386 return SDValue();
3388 // We're going to inline this global. Pad it out if needed.
3389 if (RequiredPadding != 4) {
3390 StringRef S = CDAInit->getAsString();
3392 SmallVector<uint8_t,16> V(S.size());
3393 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3394 while (RequiredPadding--)
3395 V.push_back(0);
3396 Init = ConstantDataArray::get(*DAG.getContext(), V);
3399 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3400 SDValue CPAddr =
3401 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3402 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3403 AFI->markGlobalAsPromotedToConstantPool(GVar);
3404 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3405 PaddedSize - 4);
3407 ++NumConstpoolPromoted;
3408 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3411 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3412 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3413 if (!(GV = GA->getBaseObject()))
3414 return false;
3415 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3416 return V->isConstant();
3417 return isa<Function>(GV);
3420 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3421 SelectionDAG &DAG) const {
3422 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3423 default: llvm_unreachable("unknown object format");
3424 case Triple::COFF:
3425 return LowerGlobalAddressWindows(Op, DAG);
3426 case Triple::ELF:
3427 return LowerGlobalAddressELF(Op, DAG);
3428 case Triple::MachO:
3429 return LowerGlobalAddressDarwin(Op, DAG);
3433 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3434 SelectionDAG &DAG) const {
3435 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3436 SDLoc dl(Op);
3437 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3438 const TargetMachine &TM = getTargetMachine();
3439 bool IsRO = isReadOnly(GV);
3441 // promoteToConstantPool only if not generating XO text section
3442 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3443 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3444 return V;
3446 if (isPositionIndependent()) {
3447 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3448 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3449 UseGOT_PREL ? ARMII::MO_GOT : 0);
3450 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3451 if (UseGOT_PREL)
3452 Result =
3453 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3454 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3455 return Result;
3456 } else if (Subtarget->isROPI() && IsRO) {
3457 // PC-relative.
3458 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3459 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3460 return Result;
3461 } else if (Subtarget->isRWPI() && !IsRO) {
3462 // SB-relative.
3463 SDValue RelAddr;
3464 if (Subtarget->useMovt()) {
3465 ++NumMovwMovt;
3466 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3467 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3468 } else { // use literal pool for address constant
3469 ARMConstantPoolValue *CPV =
3470 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3471 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3472 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3473 RelAddr = DAG.getLoad(
3474 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3475 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3477 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3478 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3479 return Result;
3482 // If we have T2 ops, we can materialize the address directly via movt/movw
3483 // pair. This is always cheaper.
3484 if (Subtarget->useMovt()) {
3485 ++NumMovwMovt;
3486 // FIXME: Once remat is capable of dealing with instructions with register
3487 // operands, expand this into two nodes.
3488 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3489 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3490 } else {
3491 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3492 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3493 return DAG.getLoad(
3494 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3495 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3499 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3500 SelectionDAG &DAG) const {
3501 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3502 "ROPI/RWPI not currently supported for Darwin");
3503 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3504 SDLoc dl(Op);
3505 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3507 if (Subtarget->useMovt())
3508 ++NumMovwMovt;
3510 // FIXME: Once remat is capable of dealing with instructions with register
3511 // operands, expand this into multiple nodes
3512 unsigned Wrapper =
3513 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3515 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3516 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3518 if (Subtarget->isGVIndirectSymbol(GV))
3519 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3520 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3521 return Result;
3524 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3525 SelectionDAG &DAG) const {
3526 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3527 assert(Subtarget->useMovt() &&
3528 "Windows on ARM expects to use movw/movt");
3529 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3530 "ROPI/RWPI not currently supported for Windows");
3532 const TargetMachine &TM = getTargetMachine();
3533 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3534 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3535 if (GV->hasDLLImportStorageClass())
3536 TargetFlags = ARMII::MO_DLLIMPORT;
3537 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3538 TargetFlags = ARMII::MO_COFFSTUB;
3539 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3540 SDValue Result;
3541 SDLoc DL(Op);
3543 ++NumMovwMovt;
3545 // FIXME: Once remat is capable of dealing with instructions with register
3546 // operands, expand this into two nodes.
3547 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3548 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3549 TargetFlags));
3550 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3551 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3552 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3553 return Result;
3556 SDValue
3557 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3558 SDLoc dl(Op);
3559 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3560 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3561 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3562 Op.getOperand(1), Val);
3565 SDValue
3566 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3567 SDLoc dl(Op);
3568 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3569 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3572 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3573 SelectionDAG &DAG) const {
3574 SDLoc dl(Op);
3575 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3576 Op.getOperand(0));
3579 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3580 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3581 unsigned IntNo =
3582 cast<ConstantSDNode>(
3583 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3584 ->getZExtValue();
3585 switch (IntNo) {
3586 default:
3587 return SDValue(); // Don't custom lower most intrinsics.
3588 case Intrinsic::arm_gnu_eabi_mcount: {
3589 MachineFunction &MF = DAG.getMachineFunction();
3590 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3591 SDLoc dl(Op);
3592 SDValue Chain = Op.getOperand(0);
3593 // call "\01__gnu_mcount_nc"
3594 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3595 const uint32_t *Mask =
3596 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3597 assert(Mask && "Missing call preserved mask for calling convention");
3598 // Mark LR an implicit live-in.
3599 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3600 SDValue ReturnAddress =
3601 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3602 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue};
3603 SDValue Callee =
3604 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3605 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3606 if (Subtarget->isThumb())
3607 return SDValue(
3608 DAG.getMachineNode(
3609 ARM::tBL_PUSHLR, dl, ResultTys,
3610 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3611 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3613 return SDValue(
3614 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3615 {ReturnAddress, Callee, RegisterMask, Chain}),
3621 SDValue
3622 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3623 const ARMSubtarget *Subtarget) const {
3624 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3625 SDLoc dl(Op);
3626 switch (IntNo) {
3627 default: return SDValue(); // Don't custom lower most intrinsics.
3628 case Intrinsic::thread_pointer: {
3629 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3630 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3632 case Intrinsic::eh_sjlj_lsda: {
3633 MachineFunction &MF = DAG.getMachineFunction();
3634 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3635 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3636 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3637 SDValue CPAddr;
3638 bool IsPositionIndependent = isPositionIndependent();
3639 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3640 ARMConstantPoolValue *CPV =
3641 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3642 ARMCP::CPLSDA, PCAdj);
3643 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3644 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3645 SDValue Result = DAG.getLoad(
3646 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3647 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3649 if (IsPositionIndependent) {
3650 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3651 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3653 return Result;
3655 case Intrinsic::arm_neon_vabs:
3656 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3657 Op.getOperand(1));
3658 case Intrinsic::arm_neon_vmulls:
3659 case Intrinsic::arm_neon_vmullu: {
3660 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3661 ? ARMISD::VMULLs : ARMISD::VMULLu;
3662 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3663 Op.getOperand(1), Op.getOperand(2));
3665 case Intrinsic::arm_neon_vminnm:
3666 case Intrinsic::arm_neon_vmaxnm: {
3667 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3668 ? ISD::FMINNUM : ISD::FMAXNUM;
3669 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3670 Op.getOperand(1), Op.getOperand(2));
3672 case Intrinsic::arm_neon_vminu:
3673 case Intrinsic::arm_neon_vmaxu: {
3674 if (Op.getValueType().isFloatingPoint())
3675 return SDValue();
3676 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3677 ? ISD::UMIN : ISD::UMAX;
3678 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3679 Op.getOperand(1), Op.getOperand(2));
3681 case Intrinsic::arm_neon_vmins:
3682 case Intrinsic::arm_neon_vmaxs: {
3683 // v{min,max}s is overloaded between signed integers and floats.
3684 if (!Op.getValueType().isFloatingPoint()) {
3685 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3686 ? ISD::SMIN : ISD::SMAX;
3687 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3688 Op.getOperand(1), Op.getOperand(2));
3690 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3691 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3692 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3693 Op.getOperand(1), Op.getOperand(2));
3695 case Intrinsic::arm_neon_vtbl1:
3696 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3697 Op.getOperand(1), Op.getOperand(2));
3698 case Intrinsic::arm_neon_vtbl2:
3699 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3700 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3704 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3705 const ARMSubtarget *Subtarget) {
3706 SDLoc dl(Op);
3707 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3708 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3709 if (SSID == SyncScope::SingleThread)
3710 return Op;
3712 if (!Subtarget->hasDataBarrier()) {
3713 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3714 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3715 // here.
3716 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3717 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3718 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3719 DAG.getConstant(0, dl, MVT::i32));
3722 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3723 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3724 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3725 if (Subtarget->isMClass()) {
3726 // Only a full system barrier exists in the M-class architectures.
3727 Domain = ARM_MB::SY;
3728 } else if (Subtarget->preferISHSTBarriers() &&
3729 Ord == AtomicOrdering::Release) {
3730 // Swift happens to implement ISHST barriers in a way that's compatible with
3731 // Release semantics but weaker than ISH so we'd be fools not to use
3732 // it. Beware: other processors probably don't!
3733 Domain = ARM_MB::ISHST;
3736 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3737 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3738 DAG.getConstant(Domain, dl, MVT::i32));
3741 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3742 const ARMSubtarget *Subtarget) {
3743 // ARM pre v5TE and Thumb1 does not have preload instructions.
3744 if (!(Subtarget->isThumb2() ||
3745 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3746 // Just preserve the chain.
3747 return Op.getOperand(0);
3749 SDLoc dl(Op);
3750 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3751 if (!isRead &&
3752 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3753 // ARMv7 with MP extension has PLDW.
3754 return Op.getOperand(0);
3756 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3757 if (Subtarget->isThumb()) {
3758 // Invert the bits.
3759 isRead = ~isRead & 1;
3760 isData = ~isData & 1;
3763 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3764 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3765 DAG.getConstant(isData, dl, MVT::i32));
3768 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3769 MachineFunction &MF = DAG.getMachineFunction();
3770 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3772 // vastart just stores the address of the VarArgsFrameIndex slot into the
3773 // memory location argument.
3774 SDLoc dl(Op);
3775 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3776 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3777 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3778 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3779 MachinePointerInfo(SV));
3782 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3783 CCValAssign &NextVA,
3784 SDValue &Root,
3785 SelectionDAG &DAG,
3786 const SDLoc &dl) const {
3787 MachineFunction &MF = DAG.getMachineFunction();
3788 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3790 const TargetRegisterClass *RC;
3791 if (AFI->isThumb1OnlyFunction())
3792 RC = &ARM::tGPRRegClass;
3793 else
3794 RC = &ARM::GPRRegClass;
3796 // Transform the arguments stored in physical registers into virtual ones.
3797 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3798 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3800 SDValue ArgValue2;
3801 if (NextVA.isMemLoc()) {
3802 MachineFrameInfo &MFI = MF.getFrameInfo();
3803 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3805 // Create load node to retrieve arguments from the stack.
3806 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3807 ArgValue2 = DAG.getLoad(
3808 MVT::i32, dl, Root, FIN,
3809 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3810 } else {
3811 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3812 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3814 if (!Subtarget->isLittle())
3815 std::swap (ArgValue, ArgValue2);
3816 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3819 // The remaining GPRs hold either the beginning of variable-argument
3820 // data, or the beginning of an aggregate passed by value (usually
3821 // byval). Either way, we allocate stack slots adjacent to the data
3822 // provided by our caller, and store the unallocated registers there.
3823 // If this is a variadic function, the va_list pointer will begin with
3824 // these values; otherwise, this reassembles a (byval) structure that
3825 // was split between registers and memory.
3826 // Return: The frame index registers were stored into.
3827 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3828 const SDLoc &dl, SDValue &Chain,
3829 const Value *OrigArg,
3830 unsigned InRegsParamRecordIdx,
3831 int ArgOffset, unsigned ArgSize) const {
3832 // Currently, two use-cases possible:
3833 // Case #1. Non-var-args function, and we meet first byval parameter.
3834 // Setup first unallocated register as first byval register;
3835 // eat all remained registers
3836 // (these two actions are performed by HandleByVal method).
3837 // Then, here, we initialize stack frame with
3838 // "store-reg" instructions.
3839 // Case #2. Var-args function, that doesn't contain byval parameters.
3840 // The same: eat all remained unallocated registers,
3841 // initialize stack frame.
3843 MachineFunction &MF = DAG.getMachineFunction();
3844 MachineFrameInfo &MFI = MF.getFrameInfo();
3845 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3846 unsigned RBegin, REnd;
3847 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3848 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3849 } else {
3850 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3851 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3852 REnd = ARM::R4;
3855 if (REnd != RBegin)
3856 ArgOffset = -4 * (ARM::R4 - RBegin);
3858 auto PtrVT = getPointerTy(DAG.getDataLayout());
3859 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3860 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3862 SmallVector<SDValue, 4> MemOps;
3863 const TargetRegisterClass *RC =
3864 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3866 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3867 unsigned VReg = MF.addLiveIn(Reg, RC);
3868 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3869 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3870 MachinePointerInfo(OrigArg, 4 * i));
3871 MemOps.push_back(Store);
3872 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3875 if (!MemOps.empty())
3876 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3877 return FrameIndex;
3880 // Setup stack frame, the va_list pointer will start from.
3881 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3882 const SDLoc &dl, SDValue &Chain,
3883 unsigned ArgOffset,
3884 unsigned TotalArgRegsSaveSize,
3885 bool ForceMutable) const {
3886 MachineFunction &MF = DAG.getMachineFunction();
3887 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3889 // Try to store any remaining integer argument regs
3890 // to their spots on the stack so that they may be loaded by dereferencing
3891 // the result of va_next.
3892 // If there is no regs to be stored, just point address after last
3893 // argument passed via stack.
3894 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3895 CCInfo.getInRegsParamsCount(),
3896 CCInfo.getNextStackOffset(),
3897 std::max(4U, TotalArgRegsSaveSize));
3898 AFI->setVarArgsFrameIndex(FrameIndex);
3901 SDValue ARMTargetLowering::LowerFormalArguments(
3902 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3903 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3904 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3905 MachineFunction &MF = DAG.getMachineFunction();
3906 MachineFrameInfo &MFI = MF.getFrameInfo();
3908 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3910 // Assign locations to all of the incoming arguments.
3911 SmallVector<CCValAssign, 16> ArgLocs;
3912 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3913 *DAG.getContext());
3914 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3916 SmallVector<SDValue, 16> ArgValues;
3917 SDValue ArgValue;
3918 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3919 unsigned CurArgIdx = 0;
3921 // Initially ArgRegsSaveSize is zero.
3922 // Then we increase this value each time we meet byval parameter.
3923 // We also increase this value in case of varargs function.
3924 AFI->setArgRegsSaveSize(0);
3926 // Calculate the amount of stack space that we need to allocate to store
3927 // byval and variadic arguments that are passed in registers.
3928 // We need to know this before we allocate the first byval or variadic
3929 // argument, as they will be allocated a stack slot below the CFA (Canonical
3930 // Frame Address, the stack pointer at entry to the function).
3931 unsigned ArgRegBegin = ARM::R4;
3932 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3933 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3934 break;
3936 CCValAssign &VA = ArgLocs[i];
3937 unsigned Index = VA.getValNo();
3938 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3939 if (!Flags.isByVal())
3940 continue;
3942 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3943 unsigned RBegin, REnd;
3944 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3945 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3947 CCInfo.nextInRegsParam();
3949 CCInfo.rewindByValRegsInfo();
3951 int lastInsIndex = -1;
3952 if (isVarArg && MFI.hasVAStart()) {
3953 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3954 if (RegIdx != array_lengthof(GPRArgRegs))
3955 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3958 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3959 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3960 auto PtrVT = getPointerTy(DAG.getDataLayout());
3962 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3963 CCValAssign &VA = ArgLocs[i];
3964 if (Ins[VA.getValNo()].isOrigArg()) {
3965 std::advance(CurOrigArg,
3966 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3967 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3969 // Arguments stored in registers.
3970 if (VA.isRegLoc()) {
3971 EVT RegVT = VA.getLocVT();
3973 if (VA.needsCustom()) {
3974 // f64 and vector types are split up into multiple registers or
3975 // combinations of registers and stack slots.
3976 if (VA.getLocVT() == MVT::v2f64) {
3977 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3978 Chain, DAG, dl);
3979 VA = ArgLocs[++i]; // skip ahead to next loc
3980 SDValue ArgValue2;
3981 if (VA.isMemLoc()) {
3982 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3983 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3984 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3985 MachinePointerInfo::getFixedStack(
3986 DAG.getMachineFunction(), FI));
3987 } else {
3988 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3989 Chain, DAG, dl);
3991 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3992 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3993 ArgValue, ArgValue1,
3994 DAG.getIntPtrConstant(0, dl));
3995 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3996 ArgValue, ArgValue2,
3997 DAG.getIntPtrConstant(1, dl));
3998 } else
3999 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4000 } else {
4001 const TargetRegisterClass *RC;
4004 if (RegVT == MVT::f16)
4005 RC = &ARM::HPRRegClass;
4006 else if (RegVT == MVT::f32)
4007 RC = &ARM::SPRRegClass;
4008 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
4009 RC = &ARM::DPRRegClass;
4010 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
4011 RC = &ARM::QPRRegClass;
4012 else if (RegVT == MVT::i32)
4013 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4014 : &ARM::GPRRegClass;
4015 else
4016 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4018 // Transform the arguments in physical registers into virtual ones.
4019 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4020 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4022 // If this value is passed in r0 and has the returned attribute (e.g.
4023 // C++ 'structors), record this fact for later use.
4024 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4025 AFI->setPreservesR0();
4029 // If this is an 8 or 16-bit value, it is really passed promoted
4030 // to 32 bits. Insert an assert[sz]ext to capture this, then
4031 // truncate to the right size.
4032 switch (VA.getLocInfo()) {
4033 default: llvm_unreachable("Unknown loc info!");
4034 case CCValAssign::Full: break;
4035 case CCValAssign::BCvt:
4036 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4037 break;
4038 case CCValAssign::SExt:
4039 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4040 DAG.getValueType(VA.getValVT()));
4041 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4042 break;
4043 case CCValAssign::ZExt:
4044 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4045 DAG.getValueType(VA.getValVT()));
4046 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4047 break;
4050 InVals.push_back(ArgValue);
4051 } else { // VA.isRegLoc()
4052 // sanity check
4053 assert(VA.isMemLoc());
4054 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4056 int index = VA.getValNo();
4058 // Some Ins[] entries become multiple ArgLoc[] entries.
4059 // Process them only once.
4060 if (index != lastInsIndex)
4062 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4063 // FIXME: For now, all byval parameter objects are marked mutable.
4064 // This can be changed with more analysis.
4065 // In case of tail call optimization mark all arguments mutable.
4066 // Since they could be overwritten by lowering of arguments in case of
4067 // a tail call.
4068 if (Flags.isByVal()) {
4069 assert(Ins[index].isOrigArg() &&
4070 "Byval arguments cannot be implicit");
4071 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4073 int FrameIndex = StoreByValRegs(
4074 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4075 VA.getLocMemOffset(), Flags.getByValSize());
4076 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4077 CCInfo.nextInRegsParam();
4078 } else {
4079 unsigned FIOffset = VA.getLocMemOffset();
4080 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4081 FIOffset, true);
4083 // Create load nodes to retrieve arguments from the stack.
4084 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4085 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4086 MachinePointerInfo::getFixedStack(
4087 DAG.getMachineFunction(), FI)));
4089 lastInsIndex = index;
4094 // varargs
4095 if (isVarArg && MFI.hasVAStart())
4096 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4097 CCInfo.getNextStackOffset(),
4098 TotalArgRegsSaveSize);
4100 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4102 return Chain;
4105 /// isFloatingPointZero - Return true if this is +0.0.
4106 static bool isFloatingPointZero(SDValue Op) {
4107 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4108 return CFP->getValueAPF().isPosZero();
4109 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4110 // Maybe this has already been legalized into the constant pool?
4111 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4112 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4113 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4114 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4115 return CFP->getValueAPF().isPosZero();
4117 } else if (Op->getOpcode() == ISD::BITCAST &&
4118 Op->getValueType(0) == MVT::f64) {
4119 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4120 // created by LowerConstantFP().
4121 SDValue BitcastOp = Op->getOperand(0);
4122 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4123 isNullConstant(BitcastOp->getOperand(0)))
4124 return true;
4126 return false;
4129 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4130 /// the given operands.
4131 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4132 SDValue &ARMcc, SelectionDAG &DAG,
4133 const SDLoc &dl) const {
4134 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4135 unsigned C = RHSC->getZExtValue();
4136 if (!isLegalICmpImmediate((int32_t)C)) {
4137 // Constant does not fit, try adjusting it by one.
4138 switch (CC) {
4139 default: break;
4140 case ISD::SETLT:
4141 case ISD::SETGE:
4142 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4143 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4144 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4146 break;
4147 case ISD::SETULT:
4148 case ISD::SETUGE:
4149 if (C != 0 && isLegalICmpImmediate(C-1)) {
4150 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4151 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4153 break;
4154 case ISD::SETLE:
4155 case ISD::SETGT:
4156 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4157 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4158 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4160 break;
4161 case ISD::SETULE:
4162 case ISD::SETUGT:
4163 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4164 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4165 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4167 break;
4170 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4171 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4172 // In ARM and Thumb-2, the compare instructions can shift their second
4173 // operand.
4174 CC = ISD::getSetCCSwappedOperands(CC);
4175 std::swap(LHS, RHS);
4178 // Thumb1 has very limited immediate modes, so turning an "and" into a
4179 // shift can save multiple instructions.
4181 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4182 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4183 // own. If it's the operand to an unsigned comparison with an immediate,
4184 // we can eliminate one of the shifts: we transform
4185 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4187 // We avoid transforming cases which aren't profitable due to encoding
4188 // details:
4190 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4191 // would not; in that case, we're essentially trading one immediate load for
4192 // another.
4193 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4194 // 3. C2 is zero; we have other code for this special case.
4196 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4197 // instruction, since the AND is always one instruction anyway, but we could
4198 // use narrow instructions in some cases.
4199 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4200 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4201 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4202 !isSignedIntSetCC(CC)) {
4203 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4204 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4205 uint64_t RHSV = RHSC->getZExtValue();
4206 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4207 unsigned ShiftBits = countLeadingZeros(Mask);
4208 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4209 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4210 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4211 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4216 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4217 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4218 // way a cmp would.
4219 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4220 // some tweaks to the heuristics for the previous and->shift transform.
4221 // FIXME: Optimize cases where the LHS isn't a shift.
4222 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4223 isa<ConstantSDNode>(RHS) &&
4224 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4225 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4226 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4227 unsigned ShiftAmt =
4228 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4229 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4230 DAG.getVTList(MVT::i32, MVT::i32),
4231 LHS.getOperand(0),
4232 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4233 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4234 Shift.getValue(1), SDValue());
4235 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4236 return Chain.getValue(1);
4239 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4241 // If the RHS is a constant zero then the V (overflow) flag will never be
4242 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4243 // simpler for other passes (like the peephole optimiser) to deal with.
4244 if (isNullConstant(RHS)) {
4245 switch (CondCode) {
4246 default: break;
4247 case ARMCC::GE:
4248 CondCode = ARMCC::PL;
4249 break;
4250 case ARMCC::LT:
4251 CondCode = ARMCC::MI;
4252 break;
4256 ARMISD::NodeType CompareType;
4257 switch (CondCode) {
4258 default:
4259 CompareType = ARMISD::CMP;
4260 break;
4261 case ARMCC::EQ:
4262 case ARMCC::NE:
4263 // Uses only Z Flag
4264 CompareType = ARMISD::CMPZ;
4265 break;
4267 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4268 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4271 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4272 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4273 SelectionDAG &DAG, const SDLoc &dl) const {
4274 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4275 SDValue Cmp;
4276 if (!isFloatingPointZero(RHS))
4277 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
4278 else
4279 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
4280 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4283 /// duplicateCmp - Glue values can have only one use, so this function
4284 /// duplicates a comparison node.
4285 SDValue
4286 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4287 unsigned Opc = Cmp.getOpcode();
4288 SDLoc DL(Cmp);
4289 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4290 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4292 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4293 Cmp = Cmp.getOperand(0);
4294 Opc = Cmp.getOpcode();
4295 if (Opc == ARMISD::CMPFP)
4296 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4297 else {
4298 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4299 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4301 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4304 // This function returns three things: the arithmetic computation itself
4305 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4306 // comparison and the condition code define the case in which the arithmetic
4307 // computation *does not* overflow.
4308 std::pair<SDValue, SDValue>
4309 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4310 SDValue &ARMcc) const {
4311 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4313 SDValue Value, OverflowCmp;
4314 SDValue LHS = Op.getOperand(0);
4315 SDValue RHS = Op.getOperand(1);
4316 SDLoc dl(Op);
4318 // FIXME: We are currently always generating CMPs because we don't support
4319 // generating CMN through the backend. This is not as good as the natural
4320 // CMP case because it causes a register dependency and cannot be folded
4321 // later.
4323 switch (Op.getOpcode()) {
4324 default:
4325 llvm_unreachable("Unknown overflow instruction!");
4326 case ISD::SADDO:
4327 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4328 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4329 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4330 break;
4331 case ISD::UADDO:
4332 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4333 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4334 // We do not use it in the USUBO case as Value may not be used.
4335 Value = DAG.getNode(ARMISD::ADDC, dl,
4336 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4337 .getValue(0);
4338 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4339 break;
4340 case ISD::SSUBO:
4341 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4342 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4343 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4344 break;
4345 case ISD::USUBO:
4346 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4347 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4348 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4349 break;
4350 case ISD::UMULO:
4351 // We generate a UMUL_LOHI and then check if the high word is 0.
4352 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4353 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4354 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4355 LHS, RHS);
4356 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4357 DAG.getConstant(0, dl, MVT::i32));
4358 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4359 break;
4360 case ISD::SMULO:
4361 // We generate a SMUL_LOHI and then check if all the bits of the high word
4362 // are the same as the sign bit of the low word.
4363 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4364 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4365 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4366 LHS, RHS);
4367 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4368 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4369 Value.getValue(0),
4370 DAG.getConstant(31, dl, MVT::i32)));
4371 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4372 break;
4373 } // switch (...)
4375 return std::make_pair(Value, OverflowCmp);
4378 SDValue
4379 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4380 // Let legalize expand this if it isn't a legal type yet.
4381 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4382 return SDValue();
4384 SDValue Value, OverflowCmp;
4385 SDValue ARMcc;
4386 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4387 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4388 SDLoc dl(Op);
4389 // We use 0 and 1 as false and true values.
4390 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4391 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4392 EVT VT = Op.getValueType();
4394 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4395 ARMcc, CCR, OverflowCmp);
4397 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4398 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4401 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4402 SelectionDAG &DAG) {
4403 SDLoc DL(BoolCarry);
4404 EVT CarryVT = BoolCarry.getValueType();
4406 // This converts the boolean value carry into the carry flag by doing
4407 // ARMISD::SUBC Carry, 1
4408 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4409 DAG.getVTList(CarryVT, MVT::i32),
4410 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4411 return Carry.getValue(1);
4414 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4415 SelectionDAG &DAG) {
4416 SDLoc DL(Flags);
4418 // Now convert the carry flag into a boolean carry. We do this
4419 // using ARMISD:ADDE 0, 0, Carry
4420 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4421 DAG.getConstant(0, DL, MVT::i32),
4422 DAG.getConstant(0, DL, MVT::i32), Flags);
4425 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4426 SelectionDAG &DAG) const {
4427 // Let legalize expand this if it isn't a legal type yet.
4428 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4429 return SDValue();
4431 SDValue LHS = Op.getOperand(0);
4432 SDValue RHS = Op.getOperand(1);
4433 SDLoc dl(Op);
4435 EVT VT = Op.getValueType();
4436 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4437 SDValue Value;
4438 SDValue Overflow;
4439 switch (Op.getOpcode()) {
4440 default:
4441 llvm_unreachable("Unknown overflow instruction!");
4442 case ISD::UADDO:
4443 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4444 // Convert the carry flag into a boolean value.
4445 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4446 break;
4447 case ISD::USUBO: {
4448 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4449 // Convert the carry flag into a boolean value.
4450 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4451 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4452 // value. So compute 1 - C.
4453 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4454 DAG.getConstant(1, dl, MVT::i32), Overflow);
4455 break;
4459 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4462 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4463 const ARMSubtarget *Subtarget) {
4464 EVT VT = Op.getValueType();
4465 if (!Subtarget->hasDSP())
4466 return SDValue();
4467 if (!VT.isSimple())
4468 return SDValue();
4470 unsigned NewOpcode;
4471 bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4472 switch (VT.getSimpleVT().SimpleTy) {
4473 default:
4474 return SDValue();
4475 case MVT::i8:
4476 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4477 break;
4478 case MVT::i16:
4479 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4480 break;
4483 SDLoc dl(Op);
4484 SDValue Add =
4485 DAG.getNode(NewOpcode, dl, MVT::i32,
4486 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4487 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4488 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4491 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4492 SDValue Cond = Op.getOperand(0);
4493 SDValue SelectTrue = Op.getOperand(1);
4494 SDValue SelectFalse = Op.getOperand(2);
4495 SDLoc dl(Op);
4496 unsigned Opc = Cond.getOpcode();
4498 if (Cond.getResNo() == 1 &&
4499 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4500 Opc == ISD::USUBO)) {
4501 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4502 return SDValue();
4504 SDValue Value, OverflowCmp;
4505 SDValue ARMcc;
4506 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4507 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4508 EVT VT = Op.getValueType();
4510 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4511 OverflowCmp, DAG);
4514 // Convert:
4516 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4517 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4519 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4520 const ConstantSDNode *CMOVTrue =
4521 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4522 const ConstantSDNode *CMOVFalse =
4523 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4525 if (CMOVTrue && CMOVFalse) {
4526 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4527 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4529 SDValue True;
4530 SDValue False;
4531 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4532 True = SelectTrue;
4533 False = SelectFalse;
4534 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4535 True = SelectFalse;
4536 False = SelectTrue;
4539 if (True.getNode() && False.getNode()) {
4540 EVT VT = Op.getValueType();
4541 SDValue ARMcc = Cond.getOperand(2);
4542 SDValue CCR = Cond.getOperand(3);
4543 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4544 assert(True.getValueType() == VT);
4545 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4550 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4551 // undefined bits before doing a full-word comparison with zero.
4552 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4553 DAG.getConstant(1, dl, Cond.getValueType()));
4555 return DAG.getSelectCC(dl, Cond,
4556 DAG.getConstant(0, dl, Cond.getValueType()),
4557 SelectTrue, SelectFalse, ISD::SETNE);
4560 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4561 bool &swpCmpOps, bool &swpVselOps) {
4562 // Start by selecting the GE condition code for opcodes that return true for
4563 // 'equality'
4564 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4565 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4566 CondCode = ARMCC::GE;
4568 // and GT for opcodes that return false for 'equality'.
4569 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4570 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4571 CondCode = ARMCC::GT;
4573 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4574 // to swap the compare operands.
4575 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4576 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4577 swpCmpOps = true;
4579 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4580 // If we have an unordered opcode, we need to swap the operands to the VSEL
4581 // instruction (effectively negating the condition).
4583 // This also has the effect of swapping which one of 'less' or 'greater'
4584 // returns true, so we also swap the compare operands. It also switches
4585 // whether we return true for 'equality', so we compensate by picking the
4586 // opposite condition code to our original choice.
4587 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4588 CC == ISD::SETUGT) {
4589 swpCmpOps = !swpCmpOps;
4590 swpVselOps = !swpVselOps;
4591 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4594 // 'ordered' is 'anything but unordered', so use the VS condition code and
4595 // swap the VSEL operands.
4596 if (CC == ISD::SETO) {
4597 CondCode = ARMCC::VS;
4598 swpVselOps = true;
4601 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4602 // code and swap the VSEL operands. Also do this if we don't care about the
4603 // unordered case.
4604 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4605 CondCode = ARMCC::EQ;
4606 swpVselOps = true;
4610 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4611 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4612 SDValue Cmp, SelectionDAG &DAG) const {
4613 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4614 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4615 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4616 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4617 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4619 SDValue TrueLow = TrueVal.getValue(0);
4620 SDValue TrueHigh = TrueVal.getValue(1);
4621 SDValue FalseLow = FalseVal.getValue(0);
4622 SDValue FalseHigh = FalseVal.getValue(1);
4624 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4625 ARMcc, CCR, Cmp);
4626 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4627 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4629 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4630 } else {
4631 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4632 Cmp);
4636 static bool isGTorGE(ISD::CondCode CC) {
4637 return CC == ISD::SETGT || CC == ISD::SETGE;
4640 static bool isLTorLE(ISD::CondCode CC) {
4641 return CC == ISD::SETLT || CC == ISD::SETLE;
4644 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4645 // All of these conditions (and their <= and >= counterparts) will do:
4646 // x < k ? k : x
4647 // x > k ? x : k
4648 // k < x ? x : k
4649 // k > x ? k : x
4650 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4651 const SDValue TrueVal, const SDValue FalseVal,
4652 const ISD::CondCode CC, const SDValue K) {
4653 return (isGTorGE(CC) &&
4654 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4655 (isLTorLE(CC) &&
4656 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4659 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4660 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4661 const SDValue TrueVal, const SDValue FalseVal,
4662 const ISD::CondCode CC, const SDValue K) {
4663 return (isGTorGE(CC) &&
4664 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4665 (isLTorLE(CC) &&
4666 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4669 // Check if two chained conditionals could be converted into SSAT or USAT.
4671 // SSAT can replace a set of two conditional selectors that bound a number to an
4672 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4674 // x < -k ? -k : (x > k ? k : x)
4675 // x < -k ? -k : (x < k ? x : k)
4676 // x > -k ? (x > k ? k : x) : -k
4677 // x < k ? (x < -k ? -k : x) : k
4678 // etc.
4680 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4681 // a power of 2.
4683 // It returns true if the conversion can be done, false otherwise.
4684 // Additionally, the variable is returned in parameter V, the constant in K and
4685 // usat is set to true if the conditional represents an unsigned saturation
4686 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4687 uint64_t &K, bool &usat) {
4688 SDValue LHS1 = Op.getOperand(0);
4689 SDValue RHS1 = Op.getOperand(1);
4690 SDValue TrueVal1 = Op.getOperand(2);
4691 SDValue FalseVal1 = Op.getOperand(3);
4692 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4694 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4695 if (Op2.getOpcode() != ISD::SELECT_CC)
4696 return false;
4698 SDValue LHS2 = Op2.getOperand(0);
4699 SDValue RHS2 = Op2.getOperand(1);
4700 SDValue TrueVal2 = Op2.getOperand(2);
4701 SDValue FalseVal2 = Op2.getOperand(3);
4702 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4704 // Find out which are the constants and which are the variables
4705 // in each conditional
4706 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4707 ? &RHS1
4708 : nullptr;
4709 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4710 ? &RHS2
4711 : nullptr;
4712 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4713 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4714 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4715 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4717 // We must detect cases where the original operations worked with 16- or
4718 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4719 // must work with sign-extended values but the select operations return
4720 // the original non-extended value.
4721 SDValue V2TmpReg = V2Tmp;
4722 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4723 V2TmpReg = V2Tmp->getOperand(0);
4725 // Check that the registers and the constants have the correct values
4726 // in both conditionals
4727 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4728 V2TmpReg != V2)
4729 return false;
4731 // Figure out which conditional is saturating the lower/upper bound.
4732 const SDValue *LowerCheckOp =
4733 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4734 ? &Op
4735 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4736 ? &Op2
4737 : nullptr;
4738 const SDValue *UpperCheckOp =
4739 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4740 ? &Op
4741 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4742 ? &Op2
4743 : nullptr;
4745 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4746 return false;
4748 // Check that the constant in the lower-bound check is
4749 // the opposite of the constant in the upper-bound check
4750 // in 1's complement.
4751 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4752 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4753 int64_t PosVal = std::max(Val1, Val2);
4754 int64_t NegVal = std::min(Val1, Val2);
4756 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4757 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4758 isPowerOf2_64(PosVal + 1)) {
4760 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4761 if (Val1 == ~Val2)
4762 usat = false;
4763 else if (NegVal == 0)
4764 usat = true;
4765 else
4766 return false;
4768 V = V2;
4769 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4771 return true;
4774 return false;
4777 // Check if a condition of the type x < k ? k : x can be converted into a
4778 // bit operation instead of conditional moves.
4779 // Currently this is allowed given:
4780 // - The conditions and values match up
4781 // - k is 0 or -1 (all ones)
4782 // This function will not check the last condition, thats up to the caller
4783 // It returns true if the transformation can be made, and in such case
4784 // returns x in V, and k in SatK.
4785 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4786 SDValue &SatK)
4788 SDValue LHS = Op.getOperand(0);
4789 SDValue RHS = Op.getOperand(1);
4790 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4791 SDValue TrueVal = Op.getOperand(2);
4792 SDValue FalseVal = Op.getOperand(3);
4794 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4795 ? &RHS
4796 : nullptr;
4798 // No constant operation in comparison, early out
4799 if (!K)
4800 return false;
4802 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4803 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4804 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4806 // If the constant on left and right side, or variable on left and right,
4807 // does not match, early out
4808 if (*K != KTmp || V != VTmp)
4809 return false;
4811 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4812 SatK = *K;
4813 return true;
4816 return false;
4819 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4820 if (VT == MVT::f32)
4821 return !Subtarget->hasVFP2Base();
4822 if (VT == MVT::f64)
4823 return !Subtarget->hasFP64();
4824 if (VT == MVT::f16)
4825 return !Subtarget->hasFullFP16();
4826 return false;
4829 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4830 EVT VT = Op.getValueType();
4831 SDLoc dl(Op);
4833 // Try to convert two saturating conditional selects into a single SSAT
4834 SDValue SatValue;
4835 uint64_t SatConstant;
4836 bool SatUSat;
4837 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4838 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4839 if (SatUSat)
4840 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4841 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4842 else
4843 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4844 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4847 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4848 // into more efficient bit operations, which is possible when k is 0 or -1
4849 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4850 // single instructions. On Thumb the shift and the bit operation will be two
4851 // instructions.
4852 // Only allow this transformation on full-width (32-bit) operations
4853 SDValue LowerSatConstant;
4854 if (VT == MVT::i32 &&
4855 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4856 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4857 DAG.getConstant(31, dl, VT));
4858 if (isNullConstant(LowerSatConstant)) {
4859 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4860 DAG.getAllOnesConstant(dl, VT));
4861 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4862 } else if (isAllOnesConstant(LowerSatConstant))
4863 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4866 SDValue LHS = Op.getOperand(0);
4867 SDValue RHS = Op.getOperand(1);
4868 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4869 SDValue TrueVal = Op.getOperand(2);
4870 SDValue FalseVal = Op.getOperand(3);
4871 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
4872 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
4874 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
4875 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
4876 unsigned TVal = CTVal->getZExtValue();
4877 unsigned FVal = CFVal->getZExtValue();
4878 unsigned Opcode = 0;
4880 if (TVal == ~FVal) {
4881 Opcode = ARMISD::CSINV;
4882 } else if (TVal == ~FVal + 1) {
4883 Opcode = ARMISD::CSNEG;
4884 } else if (TVal + 1 == FVal) {
4885 Opcode = ARMISD::CSINC;
4886 } else if (TVal == FVal + 1) {
4887 Opcode = ARMISD::CSINC;
4888 std::swap(TrueVal, FalseVal);
4889 std::swap(TVal, FVal);
4890 CC = ISD::getSetCCInverse(CC, true);
4893 if (Opcode) {
4894 // If one of the constants is cheaper than another, materialise the
4895 // cheaper one and let the csel generate the other.
4896 if (Opcode != ARMISD::CSINC &&
4897 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
4898 std::swap(TrueVal, FalseVal);
4899 std::swap(TVal, FVal);
4900 CC = ISD::getSetCCInverse(CC, true);
4903 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
4904 // to get there. CSINC not is invertable like the other two (~(~a) == a,
4905 // -(-a) == a, but (a+1)+1 != a).
4906 if (FVal == 0 && Opcode != ARMISD::CSINC) {
4907 std::swap(TrueVal, FalseVal);
4908 std::swap(TVal, FVal);
4909 CC = ISD::getSetCCInverse(CC, true);
4911 if (TVal == 0)
4912 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
4914 // Drops F's value because we can get it by inverting/negating TVal.
4915 FalseVal = TrueVal;
4917 SDValue ARMcc;
4918 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4919 EVT VT = TrueVal.getValueType();
4920 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
4924 if (isUnsupportedFloatingType(LHS.getValueType())) {
4925 DAG.getTargetLoweringInfo().softenSetCCOperands(
4926 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
4928 // If softenSetCCOperands only returned one value, we should compare it to
4929 // zero.
4930 if (!RHS.getNode()) {
4931 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4932 CC = ISD::SETNE;
4936 if (LHS.getValueType() == MVT::i32) {
4937 // Try to generate VSEL on ARMv8.
4938 // The VSEL instruction can't use all the usual ARM condition
4939 // codes: it only has two bits to select the condition code, so it's
4940 // constrained to use only GE, GT, VS and EQ.
4942 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4943 // swap the operands of the previous compare instruction (effectively
4944 // inverting the compare condition, swapping 'less' and 'greater') and
4945 // sometimes need to swap the operands to the VSEL (which inverts the
4946 // condition in the sense of firing whenever the previous condition didn't)
4947 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4948 TrueVal.getValueType() == MVT::f32 ||
4949 TrueVal.getValueType() == MVT::f64)) {
4950 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4951 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4952 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4953 CC = ISD::getSetCCInverse(CC, true);
4954 std::swap(TrueVal, FalseVal);
4958 SDValue ARMcc;
4959 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4960 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4961 // Choose GE over PL, which vsel does now support
4962 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4963 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4964 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4967 ARMCC::CondCodes CondCode, CondCode2;
4968 FPCCToARMCC(CC, CondCode, CondCode2);
4970 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4971 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4972 // must use VSEL (limited condition codes), due to not having conditional f16
4973 // moves.
4974 if (Subtarget->hasFPARMv8Base() &&
4975 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4976 (TrueVal.getValueType() == MVT::f16 ||
4977 TrueVal.getValueType() == MVT::f32 ||
4978 TrueVal.getValueType() == MVT::f64)) {
4979 bool swpCmpOps = false;
4980 bool swpVselOps = false;
4981 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4983 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4984 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4985 if (swpCmpOps)
4986 std::swap(LHS, RHS);
4987 if (swpVselOps)
4988 std::swap(TrueVal, FalseVal);
4992 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4993 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4994 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4995 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4996 if (CondCode2 != ARMCC::AL) {
4997 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4998 // FIXME: Needs another CMP because flag can have but one use.
4999 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5000 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5002 return Result;
5005 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5006 /// to morph to an integer compare sequence.
5007 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5008 const ARMSubtarget *Subtarget) {
5009 SDNode *N = Op.getNode();
5010 if (!N->hasOneUse())
5011 // Otherwise it requires moving the value from fp to integer registers.
5012 return false;
5013 if (!N->getNumValues())
5014 return false;
5015 EVT VT = Op.getValueType();
5016 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5017 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5018 // vmrs are very slow, e.g. cortex-a8.
5019 return false;
5021 if (isFloatingPointZero(Op)) {
5022 SeenZero = true;
5023 return true;
5025 return ISD::isNormalLoad(N);
5028 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5029 if (isFloatingPointZero(Op))
5030 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5032 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5033 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5034 Ld->getPointerInfo(), Ld->getAlignment(),
5035 Ld->getMemOperand()->getFlags());
5037 llvm_unreachable("Unknown VFP cmp argument!");
5040 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5041 SDValue &RetVal1, SDValue &RetVal2) {
5042 SDLoc dl(Op);
5044 if (isFloatingPointZero(Op)) {
5045 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5046 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5047 return;
5050 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5051 SDValue Ptr = Ld->getBasePtr();
5052 RetVal1 =
5053 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5054 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5056 EVT PtrType = Ptr.getValueType();
5057 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5058 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5059 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5060 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5061 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5062 Ld->getMemOperand()->getFlags());
5063 return;
5066 llvm_unreachable("Unknown VFP cmp argument!");
5069 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5070 /// f32 and even f64 comparisons to integer ones.
5071 SDValue
5072 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5073 SDValue Chain = Op.getOperand(0);
5074 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5075 SDValue LHS = Op.getOperand(2);
5076 SDValue RHS = Op.getOperand(3);
5077 SDValue Dest = Op.getOperand(4);
5078 SDLoc dl(Op);
5080 bool LHSSeenZero = false;
5081 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5082 bool RHSSeenZero = false;
5083 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5084 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5085 // If unsafe fp math optimization is enabled and there are no other uses of
5086 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5087 // to an integer comparison.
5088 if (CC == ISD::SETOEQ)
5089 CC = ISD::SETEQ;
5090 else if (CC == ISD::SETUNE)
5091 CC = ISD::SETNE;
5093 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5094 SDValue ARMcc;
5095 if (LHS.getValueType() == MVT::f32) {
5096 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5097 bitcastf32Toi32(LHS, DAG), Mask);
5098 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5099 bitcastf32Toi32(RHS, DAG), Mask);
5100 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5101 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5102 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5103 Chain, Dest, ARMcc, CCR, Cmp);
5106 SDValue LHS1, LHS2;
5107 SDValue RHS1, RHS2;
5108 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5109 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5110 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5111 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5112 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5113 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5114 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5115 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5116 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5119 return SDValue();
5122 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5123 SDValue Chain = Op.getOperand(0);
5124 SDValue Cond = Op.getOperand(1);
5125 SDValue Dest = Op.getOperand(2);
5126 SDLoc dl(Op);
5128 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5129 // instruction.
5130 unsigned Opc = Cond.getOpcode();
5131 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5132 !Subtarget->isThumb1Only();
5133 if (Cond.getResNo() == 1 &&
5134 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5135 Opc == ISD::USUBO || OptimizeMul)) {
5136 // Only lower legal XALUO ops.
5137 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5138 return SDValue();
5140 // The actual operation with overflow check.
5141 SDValue Value, OverflowCmp;
5142 SDValue ARMcc;
5143 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5145 // Reverse the condition code.
5146 ARMCC::CondCodes CondCode =
5147 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5148 CondCode = ARMCC::getOppositeCondition(CondCode);
5149 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5150 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5152 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5153 OverflowCmp);
5156 return SDValue();
5159 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5160 SDValue Chain = Op.getOperand(0);
5161 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5162 SDValue LHS = Op.getOperand(2);
5163 SDValue RHS = Op.getOperand(3);
5164 SDValue Dest = Op.getOperand(4);
5165 SDLoc dl(Op);
5167 if (isUnsupportedFloatingType(LHS.getValueType())) {
5168 DAG.getTargetLoweringInfo().softenSetCCOperands(
5169 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5171 // If softenSetCCOperands only returned one value, we should compare it to
5172 // zero.
5173 if (!RHS.getNode()) {
5174 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5175 CC = ISD::SETNE;
5179 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5180 // instruction.
5181 unsigned Opc = LHS.getOpcode();
5182 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5183 !Subtarget->isThumb1Only();
5184 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5185 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5186 Opc == ISD::USUBO || OptimizeMul) &&
5187 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5188 // Only lower legal XALUO ops.
5189 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5190 return SDValue();
5192 // The actual operation with overflow check.
5193 SDValue Value, OverflowCmp;
5194 SDValue ARMcc;
5195 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5197 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5198 // Reverse the condition code.
5199 ARMCC::CondCodes CondCode =
5200 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5201 CondCode = ARMCC::getOppositeCondition(CondCode);
5202 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5204 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5206 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5207 OverflowCmp);
5210 if (LHS.getValueType() == MVT::i32) {
5211 SDValue ARMcc;
5212 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5213 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5214 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5215 Chain, Dest, ARMcc, CCR, Cmp);
5218 if (getTargetMachine().Options.UnsafeFPMath &&
5219 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5220 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5221 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5222 return Result;
5225 ARMCC::CondCodes CondCode, CondCode2;
5226 FPCCToARMCC(CC, CondCode, CondCode2);
5228 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5229 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5230 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5231 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5232 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5233 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5234 if (CondCode2 != ARMCC::AL) {
5235 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5236 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5237 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5239 return Res;
5242 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5243 SDValue Chain = Op.getOperand(0);
5244 SDValue Table = Op.getOperand(1);
5245 SDValue Index = Op.getOperand(2);
5246 SDLoc dl(Op);
5248 EVT PTy = getPointerTy(DAG.getDataLayout());
5249 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5250 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5251 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5252 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5253 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5254 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5255 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5256 // which does another jump to the destination. This also makes it easier
5257 // to translate it to TBB / TBH later (Thumb2 only).
5258 // FIXME: This might not work if the function is extremely large.
5259 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5260 Addr, Op.getOperand(2), JTI);
5262 if (isPositionIndependent() || Subtarget->isROPI()) {
5263 Addr =
5264 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5265 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5266 Chain = Addr.getValue(1);
5267 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5268 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5269 } else {
5270 Addr =
5271 DAG.getLoad(PTy, dl, Chain, Addr,
5272 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5273 Chain = Addr.getValue(1);
5274 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5278 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5279 EVT VT = Op.getValueType();
5280 SDLoc dl(Op);
5282 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5283 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5284 return Op;
5285 return DAG.UnrollVectorOp(Op.getNode());
5288 const bool HasFullFP16 =
5289 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5291 EVT NewTy;
5292 const EVT OpTy = Op.getOperand(0).getValueType();
5293 if (OpTy == MVT::v4f32)
5294 NewTy = MVT::v4i32;
5295 else if (OpTy == MVT::v4f16 && HasFullFP16)
5296 NewTy = MVT::v4i16;
5297 else if (OpTy == MVT::v8f16 && HasFullFP16)
5298 NewTy = MVT::v8i16;
5299 else
5300 llvm_unreachable("Invalid type for custom lowering!");
5302 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5303 return DAG.UnrollVectorOp(Op.getNode());
5305 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5306 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5309 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5310 EVT VT = Op.getValueType();
5311 if (VT.isVector())
5312 return LowerVectorFP_TO_INT(Op, DAG);
5313 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5314 RTLIB::Libcall LC;
5315 if (Op.getOpcode() == ISD::FP_TO_SINT)
5316 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5317 Op.getValueType());
5318 else
5319 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5320 Op.getValueType());
5321 MakeLibCallOptions CallOptions;
5322 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5323 CallOptions, SDLoc(Op)).first;
5326 return Op;
5329 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5330 EVT VT = Op.getValueType();
5331 SDLoc dl(Op);
5333 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5334 if (VT.getVectorElementType() == MVT::f32)
5335 return Op;
5336 return DAG.UnrollVectorOp(Op.getNode());
5339 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5340 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5341 "Invalid type for custom lowering!");
5343 const bool HasFullFP16 =
5344 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5346 EVT DestVecType;
5347 if (VT == MVT::v4f32)
5348 DestVecType = MVT::v4i32;
5349 else if (VT == MVT::v4f16 && HasFullFP16)
5350 DestVecType = MVT::v4i16;
5351 else if (VT == MVT::v8f16 && HasFullFP16)
5352 DestVecType = MVT::v8i16;
5353 else
5354 return DAG.UnrollVectorOp(Op.getNode());
5356 unsigned CastOpc;
5357 unsigned Opc;
5358 switch (Op.getOpcode()) {
5359 default: llvm_unreachable("Invalid opcode!");
5360 case ISD::SINT_TO_FP:
5361 CastOpc = ISD::SIGN_EXTEND;
5362 Opc = ISD::SINT_TO_FP;
5363 break;
5364 case ISD::UINT_TO_FP:
5365 CastOpc = ISD::ZERO_EXTEND;
5366 Opc = ISD::UINT_TO_FP;
5367 break;
5370 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5371 return DAG.getNode(Opc, dl, VT, Op);
5374 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5375 EVT VT = Op.getValueType();
5376 if (VT.isVector())
5377 return LowerVectorINT_TO_FP(Op, DAG);
5378 if (isUnsupportedFloatingType(VT)) {
5379 RTLIB::Libcall LC;
5380 if (Op.getOpcode() == ISD::SINT_TO_FP)
5381 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5382 Op.getValueType());
5383 else
5384 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5385 Op.getValueType());
5386 MakeLibCallOptions CallOptions;
5387 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5388 CallOptions, SDLoc(Op)).first;
5391 return Op;
5394 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5395 // Implement fcopysign with a fabs and a conditional fneg.
5396 SDValue Tmp0 = Op.getOperand(0);
5397 SDValue Tmp1 = Op.getOperand(1);
5398 SDLoc dl(Op);
5399 EVT VT = Op.getValueType();
5400 EVT SrcVT = Tmp1.getValueType();
5401 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5402 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5403 bool UseNEON = !InGPR && Subtarget->hasNEON();
5405 if (UseNEON) {
5406 // Use VBSL to copy the sign bit.
5407 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5408 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5409 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5410 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5411 if (VT == MVT::f64)
5412 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5413 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5414 DAG.getConstant(32, dl, MVT::i32));
5415 else /*if (VT == MVT::f32)*/
5416 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5417 if (SrcVT == MVT::f32) {
5418 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5419 if (VT == MVT::f64)
5420 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5421 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5422 DAG.getConstant(32, dl, MVT::i32));
5423 } else if (VT == MVT::f32)
5424 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5425 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5426 DAG.getConstant(32, dl, MVT::i32));
5427 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5428 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5430 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5431 dl, MVT::i32);
5432 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5433 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5434 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5436 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5437 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5438 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5439 if (VT == MVT::f32) {
5440 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5441 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5442 DAG.getConstant(0, dl, MVT::i32));
5443 } else {
5444 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5447 return Res;
5450 // Bitcast operand 1 to i32.
5451 if (SrcVT == MVT::f64)
5452 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5453 Tmp1).getValue(1);
5454 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5456 // Or in the signbit with integer operations.
5457 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5458 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5459 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5460 if (VT == MVT::f32) {
5461 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5462 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5463 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5464 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5467 // f64: Or the high part with signbit and then combine two parts.
5468 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5469 Tmp0);
5470 SDValue Lo = Tmp0.getValue(0);
5471 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5472 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5473 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5476 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5477 MachineFunction &MF = DAG.getMachineFunction();
5478 MachineFrameInfo &MFI = MF.getFrameInfo();
5479 MFI.setReturnAddressIsTaken(true);
5481 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5482 return SDValue();
5484 EVT VT = Op.getValueType();
5485 SDLoc dl(Op);
5486 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5487 if (Depth) {
5488 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5489 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5490 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5491 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5492 MachinePointerInfo());
5495 // Return LR, which contains the return address. Mark it an implicit live-in.
5496 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5497 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5500 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5501 const ARMBaseRegisterInfo &ARI =
5502 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5503 MachineFunction &MF = DAG.getMachineFunction();
5504 MachineFrameInfo &MFI = MF.getFrameInfo();
5505 MFI.setFrameAddressIsTaken(true);
5507 EVT VT = Op.getValueType();
5508 SDLoc dl(Op); // FIXME probably not meaningful
5509 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5510 Register FrameReg = ARI.getFrameRegister(MF);
5511 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5512 while (Depth--)
5513 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5514 MachinePointerInfo());
5515 return FrameAddr;
5518 // FIXME? Maybe this could be a TableGen attribute on some registers and
5519 // this table could be generated automatically from RegInfo.
5520 Register ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5521 const MachineFunction &MF) const {
5522 Register Reg = StringSwitch<unsigned>(RegName)
5523 .Case("sp", ARM::SP)
5524 .Default(0);
5525 if (Reg)
5526 return Reg;
5527 report_fatal_error(Twine("Invalid register name \""
5528 + StringRef(RegName) + "\"."));
5531 // Result is 64 bit value so split into two 32 bit values and return as a
5532 // pair of values.
5533 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5534 SelectionDAG &DAG) {
5535 SDLoc DL(N);
5537 // This function is only supposed to be called for i64 type destination.
5538 assert(N->getValueType(0) == MVT::i64
5539 && "ExpandREAD_REGISTER called for non-i64 type result.");
5541 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5542 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5543 N->getOperand(0),
5544 N->getOperand(1));
5546 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5547 Read.getValue(1)));
5548 Results.push_back(Read.getOperand(0));
5551 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5552 /// When \p DstVT, the destination type of \p BC, is on the vector
5553 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5554 /// it might be possible to combine them, such that everything stays on the
5555 /// vector register bank.
5556 /// \p return The node that would replace \p BT, if the combine
5557 /// is possible.
5558 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5559 SelectionDAG &DAG) {
5560 SDValue Op = BC->getOperand(0);
5561 EVT DstVT = BC->getValueType(0);
5563 // The only vector instruction that can produce a scalar (remember,
5564 // since the bitcast was about to be turned into VMOVDRR, the source
5565 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5566 // Moreover, we can do this combine only if there is one use.
5567 // Finally, if the destination type is not a vector, there is not
5568 // much point on forcing everything on the vector bank.
5569 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5570 !Op.hasOneUse())
5571 return SDValue();
5573 // If the index is not constant, we will introduce an additional
5574 // multiply that will stick.
5575 // Give up in that case.
5576 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5577 if (!Index)
5578 return SDValue();
5579 unsigned DstNumElt = DstVT.getVectorNumElements();
5581 // Compute the new index.
5582 const APInt &APIntIndex = Index->getAPIntValue();
5583 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5584 NewIndex *= APIntIndex;
5585 // Check if the new constant index fits into i32.
5586 if (NewIndex.getBitWidth() > 32)
5587 return SDValue();
5589 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5590 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5591 SDLoc dl(Op);
5592 SDValue ExtractSrc = Op.getOperand(0);
5593 EVT VecVT = EVT::getVectorVT(
5594 *DAG.getContext(), DstVT.getScalarType(),
5595 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5596 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5597 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5598 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5601 /// ExpandBITCAST - If the target supports VFP, this function is called to
5602 /// expand a bit convert where either the source or destination type is i64 to
5603 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5604 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5605 /// vectors), since the legalizer won't know what to do with that.
5606 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5607 const ARMSubtarget *Subtarget) {
5608 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5609 SDLoc dl(N);
5610 SDValue Op = N->getOperand(0);
5612 // This function is only supposed to be called for i64 types, either as the
5613 // source or destination of the bit convert.
5614 EVT SrcVT = Op.getValueType();
5615 EVT DstVT = N->getValueType(0);
5616 const bool HasFullFP16 = Subtarget->hasFullFP16();
5618 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5619 // FullFP16: half values are passed in S-registers, and we don't
5620 // need any of the bitcast and moves:
5622 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5623 // t5: i32 = bitcast t2
5624 // t18: f16 = ARMISD::VMOVhr t5
5625 if (Op.getOpcode() != ISD::CopyFromReg ||
5626 Op.getValueType() != MVT::f32)
5627 return SDValue();
5629 auto Move = N->use_begin();
5630 if (Move->getOpcode() != ARMISD::VMOVhr)
5631 return SDValue();
5633 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5634 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5635 DAG.ReplaceAllUsesWith(*Move, &Copy);
5636 return Copy;
5639 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5640 if (!HasFullFP16)
5641 return SDValue();
5642 // SoftFP: read half-precision arguments:
5644 // t2: i32,ch = ...
5645 // t7: i16 = truncate t2 <~~~~ Op
5646 // t8: f16 = bitcast t7 <~~~~ N
5648 if (Op.getOperand(0).getValueType() == MVT::i32)
5649 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5650 MVT::f16, Op.getOperand(0));
5652 return SDValue();
5655 // Half-precision return values
5656 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5657 if (!HasFullFP16)
5658 return SDValue();
5660 // t11: f16 = fadd t8, t10
5661 // t12: i16 = bitcast t11 <~~~ SDNode N
5662 // t13: i32 = zero_extend t12
5663 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5664 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5666 // transform this into:
5668 // t20: i32 = ARMISD::VMOVrh t11
5669 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5671 auto ZeroExtend = N->use_begin();
5672 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5673 ZeroExtend->getValueType(0) != MVT::i32)
5674 return SDValue();
5676 auto Copy = ZeroExtend->use_begin();
5677 if (Copy->getOpcode() == ISD::CopyToReg &&
5678 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5679 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5680 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5681 return Cvt;
5683 return SDValue();
5686 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5687 return SDValue();
5689 // Turn i64->f64 into VMOVDRR.
5690 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5691 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5692 // if we can combine the bitcast with its source.
5693 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5694 return Val;
5696 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5697 DAG.getConstant(0, dl, MVT::i32));
5698 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5699 DAG.getConstant(1, dl, MVT::i32));
5700 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5701 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5704 // Turn f64->i64 into VMOVRRD.
5705 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5706 SDValue Cvt;
5707 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5708 SrcVT.getVectorNumElements() > 1)
5709 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5710 DAG.getVTList(MVT::i32, MVT::i32),
5711 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5712 else
5713 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5714 DAG.getVTList(MVT::i32, MVT::i32), Op);
5715 // Merge the pieces into a single i64 value.
5716 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5719 return SDValue();
5722 /// getZeroVector - Returns a vector of specified type with all zero elements.
5723 /// Zero vectors are used to represent vector negation and in those cases
5724 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5725 /// not support i64 elements, so sometimes the zero vectors will need to be
5726 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5727 /// zero vector.
5728 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5729 assert(VT.isVector() && "Expected a vector type");
5730 // The canonical modified immediate encoding of a zero vector is....0!
5731 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5732 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5733 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5734 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5737 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5738 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5739 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5740 SelectionDAG &DAG) const {
5741 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5742 EVT VT = Op.getValueType();
5743 unsigned VTBits = VT.getSizeInBits();
5744 SDLoc dl(Op);
5745 SDValue ShOpLo = Op.getOperand(0);
5746 SDValue ShOpHi = Op.getOperand(1);
5747 SDValue ShAmt = Op.getOperand(2);
5748 SDValue ARMcc;
5749 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5750 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5752 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5754 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5755 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5756 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5757 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5758 DAG.getConstant(VTBits, dl, MVT::i32));
5759 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5760 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5761 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5762 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5763 ISD::SETGE, ARMcc, DAG, dl);
5764 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5765 ARMcc, CCR, CmpLo);
5767 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5768 SDValue HiBigShift = Opc == ISD::SRA
5769 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5770 DAG.getConstant(VTBits - 1, dl, VT))
5771 : DAG.getConstant(0, dl, VT);
5772 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5773 ISD::SETGE, ARMcc, DAG, dl);
5774 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5775 ARMcc, CCR, CmpHi);
5777 SDValue Ops[2] = { Lo, Hi };
5778 return DAG.getMergeValues(Ops, dl);
5781 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5782 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5783 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5784 SelectionDAG &DAG) const {
5785 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5786 EVT VT = Op.getValueType();
5787 unsigned VTBits = VT.getSizeInBits();
5788 SDLoc dl(Op);
5789 SDValue ShOpLo = Op.getOperand(0);
5790 SDValue ShOpHi = Op.getOperand(1);
5791 SDValue ShAmt = Op.getOperand(2);
5792 SDValue ARMcc;
5793 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5795 assert(Op.getOpcode() == ISD::SHL_PARTS);
5796 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5797 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5798 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5799 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5800 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5802 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5803 DAG.getConstant(VTBits, dl, MVT::i32));
5804 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5805 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5806 ISD::SETGE, ARMcc, DAG, dl);
5807 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5808 ARMcc, CCR, CmpHi);
5810 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5811 ISD::SETGE, ARMcc, DAG, dl);
5812 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5813 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5814 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5816 SDValue Ops[2] = { Lo, Hi };
5817 return DAG.getMergeValues(Ops, dl);
5820 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5821 SelectionDAG &DAG) const {
5822 // The rounding mode is in bits 23:22 of the FPSCR.
5823 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5824 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5825 // so that the shift + and get folded into a bitfield extract.
5826 SDLoc dl(Op);
5827 SDValue Ops[] = { DAG.getEntryNode(),
5828 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5830 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5831 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5832 DAG.getConstant(1U << 22, dl, MVT::i32));
5833 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5834 DAG.getConstant(22, dl, MVT::i32));
5835 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5836 DAG.getConstant(3, dl, MVT::i32));
5839 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5840 const ARMSubtarget *ST) {
5841 SDLoc dl(N);
5842 EVT VT = N->getValueType(0);
5843 if (VT.isVector() && ST->hasNEON()) {
5845 // Compute the least significant set bit: LSB = X & -X
5846 SDValue X = N->getOperand(0);
5847 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5848 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5850 EVT ElemTy = VT.getVectorElementType();
5852 if (ElemTy == MVT::i8) {
5853 // Compute with: cttz(x) = ctpop(lsb - 1)
5854 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5855 DAG.getTargetConstant(1, dl, ElemTy));
5856 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5857 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5860 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5861 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5862 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5863 unsigned NumBits = ElemTy.getSizeInBits();
5864 SDValue WidthMinus1 =
5865 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5866 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5867 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5868 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5871 // Compute with: cttz(x) = ctpop(lsb - 1)
5873 // Compute LSB - 1.
5874 SDValue Bits;
5875 if (ElemTy == MVT::i64) {
5876 // Load constant 0xffff'ffff'ffff'ffff to register.
5877 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5878 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5879 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5880 } else {
5881 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5882 DAG.getTargetConstant(1, dl, ElemTy));
5883 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5885 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5888 if (!ST->hasV6T2Ops())
5889 return SDValue();
5891 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5892 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5895 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5896 const ARMSubtarget *ST) {
5897 EVT VT = N->getValueType(0);
5898 SDLoc DL(N);
5900 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5901 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5902 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5903 "Unexpected type for custom ctpop lowering");
5905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5906 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5907 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5908 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5910 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5911 unsigned EltSize = 8;
5912 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5913 while (EltSize != VT.getScalarSizeInBits()) {
5914 SmallVector<SDValue, 8> Ops;
5915 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5916 TLI.getPointerTy(DAG.getDataLayout())));
5917 Ops.push_back(Res);
5919 EltSize *= 2;
5920 NumElts /= 2;
5921 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5922 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5925 return Res;
5928 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5929 /// operand of a vector shift operation, where all the elements of the
5930 /// build_vector must have the same constant integer value.
5931 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5932 // Ignore bit_converts.
5933 while (Op.getOpcode() == ISD::BITCAST)
5934 Op = Op.getOperand(0);
5935 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5936 APInt SplatBits, SplatUndef;
5937 unsigned SplatBitSize;
5938 bool HasAnyUndefs;
5939 if (!BVN ||
5940 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5941 ElementBits) ||
5942 SplatBitSize > ElementBits)
5943 return false;
5944 Cnt = SplatBits.getSExtValue();
5945 return true;
5948 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5949 /// operand of a vector shift left operation. That value must be in the range:
5950 /// 0 <= Value < ElementBits for a left shift; or
5951 /// 0 <= Value <= ElementBits for a long left shift.
5952 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5953 assert(VT.isVector() && "vector shift count is not a vector type");
5954 int64_t ElementBits = VT.getScalarSizeInBits();
5955 if (!getVShiftImm(Op, ElementBits, Cnt))
5956 return false;
5957 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5960 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5961 /// operand of a vector shift right operation. For a shift opcode, the value
5962 /// is positive, but for an intrinsic the value count must be negative. The
5963 /// absolute value must be in the range:
5964 /// 1 <= |Value| <= ElementBits for a right shift; or
5965 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5966 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5967 int64_t &Cnt) {
5968 assert(VT.isVector() && "vector shift count is not a vector type");
5969 int64_t ElementBits = VT.getScalarSizeInBits();
5970 if (!getVShiftImm(Op, ElementBits, Cnt))
5971 return false;
5972 if (!isIntrinsic)
5973 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5974 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5975 Cnt = -Cnt;
5976 return true;
5978 return false;
5981 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5982 const ARMSubtarget *ST) {
5983 EVT VT = N->getValueType(0);
5984 SDLoc dl(N);
5985 int64_t Cnt;
5987 if (!VT.isVector())
5988 return SDValue();
5990 // We essentially have two forms here. Shift by an immediate and shift by a
5991 // vector register (there are also shift by a gpr, but that is just handled
5992 // with a tablegen pattern). We cannot easily match shift by an immediate in
5993 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5994 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5995 // signed or unsigned, and a negative shift indicates a shift right).
5996 if (N->getOpcode() == ISD::SHL) {
5997 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5998 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5999 DAG.getConstant(Cnt, dl, MVT::i32));
6000 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6001 N->getOperand(1));
6004 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6005 "unexpected vector shift opcode");
6007 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6008 unsigned VShiftOpc =
6009 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6010 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6011 DAG.getConstant(Cnt, dl, MVT::i32));
6014 // Other right shifts we don't have operations for (we use a shift left by a
6015 // negative number).
6016 EVT ShiftVT = N->getOperand(1).getValueType();
6017 SDValue NegatedCount = DAG.getNode(
6018 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6019 unsigned VShiftOpc =
6020 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6021 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6024 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6025 const ARMSubtarget *ST) {
6026 EVT VT = N->getValueType(0);
6027 SDLoc dl(N);
6029 // We can get here for a node like i32 = ISD::SHL i32, i64
6030 if (VT != MVT::i64)
6031 return SDValue();
6033 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6034 N->getOpcode() == ISD::SHL) &&
6035 "Unknown shift to lower!");
6037 unsigned ShOpc = N->getOpcode();
6038 if (ST->hasMVEIntegerOps()) {
6039 SDValue ShAmt = N->getOperand(1);
6040 unsigned ShPartsOpc = ARMISD::LSLL;
6041 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6043 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6044 // then do the default optimisation
6045 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6046 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6047 return SDValue();
6049 // Extract the lower 32 bits of the shift amount if it's not an i32
6050 if (ShAmt->getValueType(0) != MVT::i32)
6051 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6053 if (ShOpc == ISD::SRL) {
6054 if (!Con)
6055 // There is no t2LSRLr instruction so negate and perform an lsll if the
6056 // shift amount is in a register, emulating a right shift.
6057 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6058 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6059 else
6060 // Else generate an lsrl on the immediate shift amount
6061 ShPartsOpc = ARMISD::LSRL;
6062 } else if (ShOpc == ISD::SRA)
6063 ShPartsOpc = ARMISD::ASRL;
6065 // Lower 32 bits of the destination/source
6066 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6067 DAG.getConstant(0, dl, MVT::i32));
6068 // Upper 32 bits of the destination/source
6069 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6070 DAG.getConstant(1, dl, MVT::i32));
6072 // Generate the shift operation as computed above
6073 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6074 ShAmt);
6075 // The upper 32 bits come from the second return value of lsll
6076 Hi = SDValue(Lo.getNode(), 1);
6077 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6080 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6081 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6082 return SDValue();
6084 // If we are in thumb mode, we don't have RRX.
6085 if (ST->isThumb1Only())
6086 return SDValue();
6088 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6089 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6090 DAG.getConstant(0, dl, MVT::i32));
6091 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6092 DAG.getConstant(1, dl, MVT::i32));
6094 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6095 // captures the result into a carry flag.
6096 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6097 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6099 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6100 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6102 // Merge the pieces into a single i64 value.
6103 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6106 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6107 const ARMSubtarget *ST) {
6108 bool Invert = false;
6109 bool Swap = false;
6110 unsigned Opc = ARMCC::AL;
6112 SDValue Op0 = Op.getOperand(0);
6113 SDValue Op1 = Op.getOperand(1);
6114 SDValue CC = Op.getOperand(2);
6115 EVT VT = Op.getValueType();
6116 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6117 SDLoc dl(Op);
6119 EVT CmpVT;
6120 if (ST->hasNEON())
6121 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6122 else {
6123 assert(ST->hasMVEIntegerOps() &&
6124 "No hardware support for integer vector comparison!");
6126 if (Op.getValueType().getVectorElementType() != MVT::i1)
6127 return SDValue();
6129 // Make sure we expand floating point setcc to scalar if we do not have
6130 // mve.fp, so that we can handle them from there.
6131 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6132 return SDValue();
6134 CmpVT = VT;
6137 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6138 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6139 // Special-case integer 64-bit equality comparisons. They aren't legal,
6140 // but they can be lowered with a few vector instructions.
6141 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6142 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6143 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6144 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6145 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6146 DAG.getCondCode(ISD::SETEQ));
6147 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6148 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6149 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6150 if (SetCCOpcode == ISD::SETNE)
6151 Merged = DAG.getNOT(dl, Merged, CmpVT);
6152 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6153 return Merged;
6156 if (CmpVT.getVectorElementType() == MVT::i64)
6157 // 64-bit comparisons are not legal in general.
6158 return SDValue();
6160 if (Op1.getValueType().isFloatingPoint()) {
6161 switch (SetCCOpcode) {
6162 default: llvm_unreachable("Illegal FP comparison");
6163 case ISD::SETUNE:
6164 case ISD::SETNE:
6165 if (ST->hasMVEFloatOps()) {
6166 Opc = ARMCC::NE; break;
6167 } else {
6168 Invert = true; LLVM_FALLTHROUGH;
6170 case ISD::SETOEQ:
6171 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6172 case ISD::SETOLT:
6173 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6174 case ISD::SETOGT:
6175 case ISD::SETGT: Opc = ARMCC::GT; break;
6176 case ISD::SETOLE:
6177 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6178 case ISD::SETOGE:
6179 case ISD::SETGE: Opc = ARMCC::GE; break;
6180 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6181 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6182 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6183 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6184 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6185 case ISD::SETONE: {
6186 // Expand this to (OLT | OGT).
6187 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6188 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6189 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6190 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6191 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6192 if (Invert)
6193 Result = DAG.getNOT(dl, Result, VT);
6194 return Result;
6196 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6197 case ISD::SETO: {
6198 // Expand this to (OLT | OGE).
6199 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6200 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6201 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6202 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6203 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6204 if (Invert)
6205 Result = DAG.getNOT(dl, Result, VT);
6206 return Result;
6209 } else {
6210 // Integer comparisons.
6211 switch (SetCCOpcode) {
6212 default: llvm_unreachable("Illegal integer comparison");
6213 case ISD::SETNE:
6214 if (ST->hasMVEIntegerOps()) {
6215 Opc = ARMCC::NE; break;
6216 } else {
6217 Invert = true; LLVM_FALLTHROUGH;
6219 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6220 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6221 case ISD::SETGT: Opc = ARMCC::GT; break;
6222 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6223 case ISD::SETGE: Opc = ARMCC::GE; break;
6224 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6225 case ISD::SETUGT: Opc = ARMCC::HI; break;
6226 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6227 case ISD::SETUGE: Opc = ARMCC::HS; break;
6230 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6231 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6232 SDValue AndOp;
6233 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6234 AndOp = Op0;
6235 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6236 AndOp = Op1;
6238 // Ignore bitconvert.
6239 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6240 AndOp = AndOp.getOperand(0);
6242 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6243 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6244 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6245 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6246 if (!Invert)
6247 Result = DAG.getNOT(dl, Result, VT);
6248 return Result;
6253 if (Swap)
6254 std::swap(Op0, Op1);
6256 // If one of the operands is a constant vector zero, attempt to fold the
6257 // comparison to a specialized compare-against-zero form.
6258 SDValue SingleOp;
6259 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6260 SingleOp = Op0;
6261 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6262 if (Opc == ARMCC::GE)
6263 Opc = ARMCC::LE;
6264 else if (Opc == ARMCC::GT)
6265 Opc = ARMCC::LT;
6266 SingleOp = Op1;
6269 SDValue Result;
6270 if (SingleOp.getNode()) {
6271 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6272 DAG.getConstant(Opc, dl, MVT::i32));
6273 } else {
6274 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6275 DAG.getConstant(Opc, dl, MVT::i32));
6278 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6280 if (Invert)
6281 Result = DAG.getNOT(dl, Result, VT);
6283 return Result;
6286 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6287 SDValue LHS = Op.getOperand(0);
6288 SDValue RHS = Op.getOperand(1);
6289 SDValue Carry = Op.getOperand(2);
6290 SDValue Cond = Op.getOperand(3);
6291 SDLoc DL(Op);
6293 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6295 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6296 // have to invert the carry first.
6297 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6298 DAG.getConstant(1, DL, MVT::i32), Carry);
6299 // This converts the boolean value carry into the carry flag.
6300 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6302 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6303 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6305 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6306 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6307 SDValue ARMcc = DAG.getConstant(
6308 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6309 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6310 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6311 Cmp.getValue(1), SDValue());
6312 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6313 CCR, Chain.getValue(1));
6316 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6317 /// valid vector constant for a NEON or MVE instruction with a "modified
6318 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6319 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6320 unsigned SplatBitSize, SelectionDAG &DAG,
6321 const SDLoc &dl, EVT &VT, bool is128Bits,
6322 VMOVModImmType type) {
6323 unsigned OpCmode, Imm;
6325 // SplatBitSize is set to the smallest size that splats the vector, so a
6326 // zero vector will always have SplatBitSize == 8. However, NEON modified
6327 // immediate instructions others than VMOV do not support the 8-bit encoding
6328 // of a zero vector, and the default encoding of zero is supposed to be the
6329 // 32-bit version.
6330 if (SplatBits == 0)
6331 SplatBitSize = 32;
6333 switch (SplatBitSize) {
6334 case 8:
6335 if (type != VMOVModImm)
6336 return SDValue();
6337 // Any 1-byte value is OK. Op=0, Cmode=1110.
6338 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6339 OpCmode = 0xe;
6340 Imm = SplatBits;
6341 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6342 break;
6344 case 16:
6345 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6346 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6347 if ((SplatBits & ~0xff) == 0) {
6348 // Value = 0x00nn: Op=x, Cmode=100x.
6349 OpCmode = 0x8;
6350 Imm = SplatBits;
6351 break;
6353 if ((SplatBits & ~0xff00) == 0) {
6354 // Value = 0xnn00: Op=x, Cmode=101x.
6355 OpCmode = 0xa;
6356 Imm = SplatBits >> 8;
6357 break;
6359 return SDValue();
6361 case 32:
6362 // NEON's 32-bit VMOV supports splat values where:
6363 // * only one byte is nonzero, or
6364 // * the least significant byte is 0xff and the second byte is nonzero, or
6365 // * the least significant 2 bytes are 0xff and the third is nonzero.
6366 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6367 if ((SplatBits & ~0xff) == 0) {
6368 // Value = 0x000000nn: Op=x, Cmode=000x.
6369 OpCmode = 0;
6370 Imm = SplatBits;
6371 break;
6373 if ((SplatBits & ~0xff00) == 0) {
6374 // Value = 0x0000nn00: Op=x, Cmode=001x.
6375 OpCmode = 0x2;
6376 Imm = SplatBits >> 8;
6377 break;
6379 if ((SplatBits & ~0xff0000) == 0) {
6380 // Value = 0x00nn0000: Op=x, Cmode=010x.
6381 OpCmode = 0x4;
6382 Imm = SplatBits >> 16;
6383 break;
6385 if ((SplatBits & ~0xff000000) == 0) {
6386 // Value = 0xnn000000: Op=x, Cmode=011x.
6387 OpCmode = 0x6;
6388 Imm = SplatBits >> 24;
6389 break;
6392 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6393 if (type == OtherModImm) return SDValue();
6395 if ((SplatBits & ~0xffff) == 0 &&
6396 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6397 // Value = 0x0000nnff: Op=x, Cmode=1100.
6398 OpCmode = 0xc;
6399 Imm = SplatBits >> 8;
6400 break;
6403 // cmode == 0b1101 is not supported for MVE VMVN
6404 if (type == MVEVMVNModImm)
6405 return SDValue();
6407 if ((SplatBits & ~0xffffff) == 0 &&
6408 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6409 // Value = 0x00nnffff: Op=x, Cmode=1101.
6410 OpCmode = 0xd;
6411 Imm = SplatBits >> 16;
6412 break;
6415 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6416 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6417 // VMOV.I32. A (very) minor optimization would be to replicate the value
6418 // and fall through here to test for a valid 64-bit splat. But, then the
6419 // caller would also need to check and handle the change in size.
6420 return SDValue();
6422 case 64: {
6423 if (type != VMOVModImm)
6424 return SDValue();
6425 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6426 uint64_t BitMask = 0xff;
6427 uint64_t Val = 0;
6428 unsigned ImmMask = 1;
6429 Imm = 0;
6430 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6431 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6432 Val |= BitMask;
6433 Imm |= ImmMask;
6434 } else if ((SplatBits & BitMask) != 0) {
6435 return SDValue();
6437 BitMask <<= 8;
6438 ImmMask <<= 1;
6441 if (DAG.getDataLayout().isBigEndian())
6442 // swap higher and lower 32 bit word
6443 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6445 // Op=1, Cmode=1110.
6446 OpCmode = 0x1e;
6447 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6448 break;
6451 default:
6452 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6455 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6456 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6459 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6460 const ARMSubtarget *ST) const {
6461 EVT VT = Op.getValueType();
6462 bool IsDouble = (VT == MVT::f64);
6463 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6464 const APFloat &FPVal = CFP->getValueAPF();
6466 // Prevent floating-point constants from using literal loads
6467 // when execute-only is enabled.
6468 if (ST->genExecuteOnly()) {
6469 // If we can represent the constant as an immediate, don't lower it
6470 if (isFPImmLegal(FPVal, VT))
6471 return Op;
6472 // Otherwise, construct as integer, and move to float register
6473 APInt INTVal = FPVal.bitcastToAPInt();
6474 SDLoc DL(CFP);
6475 switch (VT.getSimpleVT().SimpleTy) {
6476 default:
6477 llvm_unreachable("Unknown floating point type!");
6478 break;
6479 case MVT::f64: {
6480 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6481 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6482 if (!ST->isLittle())
6483 std::swap(Lo, Hi);
6484 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6486 case MVT::f32:
6487 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6488 DAG.getConstant(INTVal, DL, MVT::i32));
6492 if (!ST->hasVFP3Base())
6493 return SDValue();
6495 // Use the default (constant pool) lowering for double constants when we have
6496 // an SP-only FPU
6497 if (IsDouble && !Subtarget->hasFP64())
6498 return SDValue();
6500 // Try splatting with a VMOV.f32...
6501 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6503 if (ImmVal != -1) {
6504 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6505 // We have code in place to select a valid ConstantFP already, no need to
6506 // do any mangling.
6507 return Op;
6510 // It's a float and we are trying to use NEON operations where
6511 // possible. Lower it to a splat followed by an extract.
6512 SDLoc DL(Op);
6513 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6514 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6515 NewVal);
6516 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6517 DAG.getConstant(0, DL, MVT::i32));
6520 // The rest of our options are NEON only, make sure that's allowed before
6521 // proceeding..
6522 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6523 return SDValue();
6525 EVT VMovVT;
6526 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6528 // It wouldn't really be worth bothering for doubles except for one very
6529 // important value, which does happen to match: 0.0. So make sure we don't do
6530 // anything stupid.
6531 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6532 return SDValue();
6534 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6535 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6536 VMovVT, false, VMOVModImm);
6537 if (NewVal != SDValue()) {
6538 SDLoc DL(Op);
6539 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6540 NewVal);
6541 if (IsDouble)
6542 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6544 // It's a float: cast and extract a vector element.
6545 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6546 VecConstant);
6547 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6548 DAG.getConstant(0, DL, MVT::i32));
6551 // Finally, try a VMVN.i32
6552 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6553 false, VMVNModImm);
6554 if (NewVal != SDValue()) {
6555 SDLoc DL(Op);
6556 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6558 if (IsDouble)
6559 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6561 // It's a float: cast and extract a vector element.
6562 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6563 VecConstant);
6564 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6565 DAG.getConstant(0, DL, MVT::i32));
6568 return SDValue();
6571 // check if an VEXT instruction can handle the shuffle mask when the
6572 // vector sources of the shuffle are the same.
6573 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6574 unsigned NumElts = VT.getVectorNumElements();
6576 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6577 if (M[0] < 0)
6578 return false;
6580 Imm = M[0];
6582 // If this is a VEXT shuffle, the immediate value is the index of the first
6583 // element. The other shuffle indices must be the successive elements after
6584 // the first one.
6585 unsigned ExpectedElt = Imm;
6586 for (unsigned i = 1; i < NumElts; ++i) {
6587 // Increment the expected index. If it wraps around, just follow it
6588 // back to index zero and keep going.
6589 ++ExpectedElt;
6590 if (ExpectedElt == NumElts)
6591 ExpectedElt = 0;
6593 if (M[i] < 0) continue; // ignore UNDEF indices
6594 if (ExpectedElt != static_cast<unsigned>(M[i]))
6595 return false;
6598 return true;
6601 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6602 bool &ReverseVEXT, unsigned &Imm) {
6603 unsigned NumElts = VT.getVectorNumElements();
6604 ReverseVEXT = false;
6606 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6607 if (M[0] < 0)
6608 return false;
6610 Imm = M[0];
6612 // If this is a VEXT shuffle, the immediate value is the index of the first
6613 // element. The other shuffle indices must be the successive elements after
6614 // the first one.
6615 unsigned ExpectedElt = Imm;
6616 for (unsigned i = 1; i < NumElts; ++i) {
6617 // Increment the expected index. If it wraps around, it may still be
6618 // a VEXT but the source vectors must be swapped.
6619 ExpectedElt += 1;
6620 if (ExpectedElt == NumElts * 2) {
6621 ExpectedElt = 0;
6622 ReverseVEXT = true;
6625 if (M[i] < 0) continue; // ignore UNDEF indices
6626 if (ExpectedElt != static_cast<unsigned>(M[i]))
6627 return false;
6630 // Adjust the index value if the source operands will be swapped.
6631 if (ReverseVEXT)
6632 Imm -= NumElts;
6634 return true;
6637 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6638 /// instruction with the specified blocksize. (The order of the elements
6639 /// within each block of the vector is reversed.)
6640 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6641 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6642 "Only possible block sizes for VREV are: 16, 32, 64");
6644 unsigned EltSz = VT.getScalarSizeInBits();
6645 if (EltSz == 64)
6646 return false;
6648 unsigned NumElts = VT.getVectorNumElements();
6649 unsigned BlockElts = M[0] + 1;
6650 // If the first shuffle index is UNDEF, be optimistic.
6651 if (M[0] < 0)
6652 BlockElts = BlockSize / EltSz;
6654 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6655 return false;
6657 for (unsigned i = 0; i < NumElts; ++i) {
6658 if (M[i] < 0) continue; // ignore UNDEF indices
6659 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6660 return false;
6663 return true;
6666 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6667 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6668 // range, then 0 is placed into the resulting vector. So pretty much any mask
6669 // of 8 elements can work here.
6670 return VT == MVT::v8i8 && M.size() == 8;
6673 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6674 unsigned Index) {
6675 if (Mask.size() == Elements * 2)
6676 return Index / Elements;
6677 return Mask[Index] == 0 ? 0 : 1;
6680 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6681 // checking that pairs of elements in the shuffle mask represent the same index
6682 // in each vector, incrementing the expected index by 2 at each step.
6683 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6684 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6685 // v2={e,f,g,h}
6686 // WhichResult gives the offset for each element in the mask based on which
6687 // of the two results it belongs to.
6689 // The transpose can be represented either as:
6690 // result1 = shufflevector v1, v2, result1_shuffle_mask
6691 // result2 = shufflevector v1, v2, result2_shuffle_mask
6692 // where v1/v2 and the shuffle masks have the same number of elements
6693 // (here WhichResult (see below) indicates which result is being checked)
6695 // or as:
6696 // results = shufflevector v1, v2, shuffle_mask
6697 // where both results are returned in one vector and the shuffle mask has twice
6698 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6699 // want to check the low half and high half of the shuffle mask as if it were
6700 // the other case
6701 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6702 unsigned EltSz = VT.getScalarSizeInBits();
6703 if (EltSz == 64)
6704 return false;
6706 unsigned NumElts = VT.getVectorNumElements();
6707 if (M.size() != NumElts && M.size() != NumElts*2)
6708 return false;
6710 // If the mask is twice as long as the input vector then we need to check the
6711 // upper and lower parts of the mask with a matching value for WhichResult
6712 // FIXME: A mask with only even values will be rejected in case the first
6713 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6714 // M[0] is used to determine WhichResult
6715 for (unsigned i = 0; i < M.size(); i += NumElts) {
6716 WhichResult = SelectPairHalf(NumElts, M, i);
6717 for (unsigned j = 0; j < NumElts; j += 2) {
6718 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6719 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6720 return false;
6724 if (M.size() == NumElts*2)
6725 WhichResult = 0;
6727 return true;
6730 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6731 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6732 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6733 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6734 unsigned EltSz = VT.getScalarSizeInBits();
6735 if (EltSz == 64)
6736 return false;
6738 unsigned NumElts = VT.getVectorNumElements();
6739 if (M.size() != NumElts && M.size() != NumElts*2)
6740 return false;
6742 for (unsigned i = 0; i < M.size(); i += NumElts) {
6743 WhichResult = SelectPairHalf(NumElts, M, i);
6744 for (unsigned j = 0; j < NumElts; j += 2) {
6745 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6746 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6747 return false;
6751 if (M.size() == NumElts*2)
6752 WhichResult = 0;
6754 return true;
6757 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6758 // that the mask elements are either all even and in steps of size 2 or all odd
6759 // and in steps of size 2.
6760 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6761 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6762 // v2={e,f,g,h}
6763 // Requires similar checks to that of isVTRNMask with
6764 // respect the how results are returned.
6765 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6766 unsigned EltSz = VT.getScalarSizeInBits();
6767 if (EltSz == 64)
6768 return false;
6770 unsigned NumElts = VT.getVectorNumElements();
6771 if (M.size() != NumElts && M.size() != NumElts*2)
6772 return false;
6774 for (unsigned i = 0; i < M.size(); i += NumElts) {
6775 WhichResult = SelectPairHalf(NumElts, M, i);
6776 for (unsigned j = 0; j < NumElts; ++j) {
6777 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6778 return false;
6782 if (M.size() == NumElts*2)
6783 WhichResult = 0;
6785 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6786 if (VT.is64BitVector() && EltSz == 32)
6787 return false;
6789 return true;
6792 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6793 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6794 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6795 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6796 unsigned EltSz = VT.getScalarSizeInBits();
6797 if (EltSz == 64)
6798 return false;
6800 unsigned NumElts = VT.getVectorNumElements();
6801 if (M.size() != NumElts && M.size() != NumElts*2)
6802 return false;
6804 unsigned Half = NumElts / 2;
6805 for (unsigned i = 0; i < M.size(); i += NumElts) {
6806 WhichResult = SelectPairHalf(NumElts, M, i);
6807 for (unsigned j = 0; j < NumElts; j += Half) {
6808 unsigned Idx = WhichResult;
6809 for (unsigned k = 0; k < Half; ++k) {
6810 int MIdx = M[i + j + k];
6811 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6812 return false;
6813 Idx += 2;
6818 if (M.size() == NumElts*2)
6819 WhichResult = 0;
6821 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6822 if (VT.is64BitVector() && EltSz == 32)
6823 return false;
6825 return true;
6828 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6829 // that pairs of elements of the shufflemask represent the same index in each
6830 // vector incrementing sequentially through the vectors.
6831 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6832 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6833 // v2={e,f,g,h}
6834 // Requires similar checks to that of isVTRNMask with respect the how results
6835 // are returned.
6836 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6837 unsigned EltSz = VT.getScalarSizeInBits();
6838 if (EltSz == 64)
6839 return false;
6841 unsigned NumElts = VT.getVectorNumElements();
6842 if (M.size() != NumElts && M.size() != NumElts*2)
6843 return false;
6845 for (unsigned i = 0; i < M.size(); i += NumElts) {
6846 WhichResult = SelectPairHalf(NumElts, M, i);
6847 unsigned Idx = WhichResult * NumElts / 2;
6848 for (unsigned j = 0; j < NumElts; j += 2) {
6849 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6850 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6851 return false;
6852 Idx += 1;
6856 if (M.size() == NumElts*2)
6857 WhichResult = 0;
6859 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6860 if (VT.is64BitVector() && EltSz == 32)
6861 return false;
6863 return true;
6866 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6867 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6868 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6869 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6870 unsigned EltSz = VT.getScalarSizeInBits();
6871 if (EltSz == 64)
6872 return false;
6874 unsigned NumElts = VT.getVectorNumElements();
6875 if (M.size() != NumElts && M.size() != NumElts*2)
6876 return false;
6878 for (unsigned i = 0; i < M.size(); i += NumElts) {
6879 WhichResult = SelectPairHalf(NumElts, M, i);
6880 unsigned Idx = WhichResult * NumElts / 2;
6881 for (unsigned j = 0; j < NumElts; j += 2) {
6882 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6883 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6884 return false;
6885 Idx += 1;
6889 if (M.size() == NumElts*2)
6890 WhichResult = 0;
6892 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6893 if (VT.is64BitVector() && EltSz == 32)
6894 return false;
6896 return true;
6899 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6900 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6901 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6902 unsigned &WhichResult,
6903 bool &isV_UNDEF) {
6904 isV_UNDEF = false;
6905 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6906 return ARMISD::VTRN;
6907 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6908 return ARMISD::VUZP;
6909 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6910 return ARMISD::VZIP;
6912 isV_UNDEF = true;
6913 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6914 return ARMISD::VTRN;
6915 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6916 return ARMISD::VUZP;
6917 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6918 return ARMISD::VZIP;
6920 return 0;
6923 /// \return true if this is a reverse operation on an vector.
6924 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6925 unsigned NumElts = VT.getVectorNumElements();
6926 // Make sure the mask has the right size.
6927 if (NumElts != M.size())
6928 return false;
6930 // Look for <15, ..., 3, -1, 1, 0>.
6931 for (unsigned i = 0; i != NumElts; ++i)
6932 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6933 return false;
6935 return true;
6938 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
6939 unsigned NumElts = VT.getVectorNumElements();
6940 // Make sure the mask has the right size.
6941 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
6942 return false;
6944 // If Top
6945 // Look for <0, N, 2, N+2, 4, N+4, ..>.
6946 // This inserts Input2 into Input1
6947 // else if not Top
6948 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
6949 // This inserts Input1 into Input2
6950 unsigned Offset = Top ? 0 : 1;
6951 for (unsigned i = 0; i < NumElts; i+=2) {
6952 if (M[i] >= 0 && M[i] != (int)i)
6953 return false;
6954 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
6955 return false;
6958 return true;
6961 // If N is an integer constant that can be moved into a register in one
6962 // instruction, return an SDValue of such a constant (will become a MOV
6963 // instruction). Otherwise return null.
6964 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6965 const ARMSubtarget *ST, const SDLoc &dl) {
6966 uint64_t Val;
6967 if (!isa<ConstantSDNode>(N))
6968 return SDValue();
6969 Val = cast<ConstantSDNode>(N)->getZExtValue();
6971 if (ST->isThumb1Only()) {
6972 if (Val <= 255 || ~Val <= 255)
6973 return DAG.getConstant(Val, dl, MVT::i32);
6974 } else {
6975 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6976 return DAG.getConstant(Val, dl, MVT::i32);
6978 return SDValue();
6981 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6982 const ARMSubtarget *ST) {
6983 SDLoc dl(Op);
6984 EVT VT = Op.getValueType();
6986 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6988 unsigned NumElts = VT.getVectorNumElements();
6989 unsigned BoolMask;
6990 unsigned BitsPerBool;
6991 if (NumElts == 4) {
6992 BitsPerBool = 4;
6993 BoolMask = 0xf;
6994 } else if (NumElts == 8) {
6995 BitsPerBool = 2;
6996 BoolMask = 0x3;
6997 } else if (NumElts == 16) {
6998 BitsPerBool = 1;
6999 BoolMask = 0x1;
7000 } else
7001 return SDValue();
7003 // If this is a single value copied into all lanes (a splat), we can just sign
7004 // extend that single value
7005 SDValue FirstOp = Op.getOperand(0);
7006 if (!isa<ConstantSDNode>(FirstOp) &&
7007 std::all_of(std::next(Op->op_begin()), Op->op_end(),
7008 [&FirstOp](SDUse &U) {
7009 return U.get().isUndef() || U.get() == FirstOp;
7010 })) {
7011 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7012 DAG.getValueType(MVT::i1));
7013 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7016 // First create base with bits set where known
7017 unsigned Bits32 = 0;
7018 for (unsigned i = 0; i < NumElts; ++i) {
7019 SDValue V = Op.getOperand(i);
7020 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7021 continue;
7022 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7023 if (BitSet)
7024 Bits32 |= BoolMask << (i * BitsPerBool);
7027 // Add in unknown nodes
7028 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7029 DAG.getConstant(Bits32, dl, MVT::i32));
7030 for (unsigned i = 0; i < NumElts; ++i) {
7031 SDValue V = Op.getOperand(i);
7032 if (isa<ConstantSDNode>(V) || V.isUndef())
7033 continue;
7034 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7035 DAG.getConstant(i, dl, MVT::i32));
7038 return Base;
7041 // If this is a case we can't handle, return null and let the default
7042 // expansion code take care of it.
7043 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7044 const ARMSubtarget *ST) const {
7045 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7046 SDLoc dl(Op);
7047 EVT VT = Op.getValueType();
7049 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7050 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7052 APInt SplatBits, SplatUndef;
7053 unsigned SplatBitSize;
7054 bool HasAnyUndefs;
7055 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7056 if (SplatUndef.isAllOnesValue())
7057 return DAG.getUNDEF(VT);
7059 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7060 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
7061 // Check if an immediate VMOV works.
7062 EVT VmovVT;
7063 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
7064 SplatUndef.getZExtValue(), SplatBitSize,
7065 DAG, dl, VmovVT, VT.is128BitVector(),
7066 VMOVModImm);
7068 if (Val.getNode()) {
7069 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7070 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7073 // Try an immediate VMVN.
7074 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7075 Val = isVMOVModifiedImm(
7076 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
7077 DAG, dl, VmovVT, VT.is128BitVector(),
7078 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7079 if (Val.getNode()) {
7080 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7081 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7084 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7085 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7086 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7087 if (ImmVal != -1) {
7088 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7089 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7095 // Scan through the operands to see if only one value is used.
7097 // As an optimisation, even if more than one value is used it may be more
7098 // profitable to splat with one value then change some lanes.
7100 // Heuristically we decide to do this if the vector has a "dominant" value,
7101 // defined as splatted to more than half of the lanes.
7102 unsigned NumElts = VT.getVectorNumElements();
7103 bool isOnlyLowElement = true;
7104 bool usesOnlyOneValue = true;
7105 bool hasDominantValue = false;
7106 bool isConstant = true;
7108 // Map of the number of times a particular SDValue appears in the
7109 // element list.
7110 DenseMap<SDValue, unsigned> ValueCounts;
7111 SDValue Value;
7112 for (unsigned i = 0; i < NumElts; ++i) {
7113 SDValue V = Op.getOperand(i);
7114 if (V.isUndef())
7115 continue;
7116 if (i > 0)
7117 isOnlyLowElement = false;
7118 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7119 isConstant = false;
7121 ValueCounts.insert(std::make_pair(V, 0));
7122 unsigned &Count = ValueCounts[V];
7124 // Is this value dominant? (takes up more than half of the lanes)
7125 if (++Count > (NumElts / 2)) {
7126 hasDominantValue = true;
7127 Value = V;
7130 if (ValueCounts.size() != 1)
7131 usesOnlyOneValue = false;
7132 if (!Value.getNode() && !ValueCounts.empty())
7133 Value = ValueCounts.begin()->first;
7135 if (ValueCounts.empty())
7136 return DAG.getUNDEF(VT);
7138 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7139 // Keep going if we are hitting this case.
7140 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7141 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7143 unsigned EltSize = VT.getScalarSizeInBits();
7145 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7146 // i32 and try again.
7147 if (hasDominantValue && EltSize <= 32) {
7148 if (!isConstant) {
7149 SDValue N;
7151 // If we are VDUPing a value that comes directly from a vector, that will
7152 // cause an unnecessary move to and from a GPR, where instead we could
7153 // just use VDUPLANE. We can only do this if the lane being extracted
7154 // is at a constant index, as the VDUP from lane instructions only have
7155 // constant-index forms.
7156 ConstantSDNode *constIndex;
7157 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7158 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7159 // We need to create a new undef vector to use for the VDUPLANE if the
7160 // size of the vector from which we get the value is different than the
7161 // size of the vector that we need to create. We will insert the element
7162 // such that the register coalescer will remove unnecessary copies.
7163 if (VT != Value->getOperand(0).getValueType()) {
7164 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7165 VT.getVectorNumElements();
7166 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7167 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7168 Value, DAG.getConstant(index, dl, MVT::i32)),
7169 DAG.getConstant(index, dl, MVT::i32));
7170 } else
7171 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7172 Value->getOperand(0), Value->getOperand(1));
7173 } else
7174 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7176 if (!usesOnlyOneValue) {
7177 // The dominant value was splatted as 'N', but we now have to insert
7178 // all differing elements.
7179 for (unsigned I = 0; I < NumElts; ++I) {
7180 if (Op.getOperand(I) == Value)
7181 continue;
7182 SmallVector<SDValue, 3> Ops;
7183 Ops.push_back(N);
7184 Ops.push_back(Op.getOperand(I));
7185 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7186 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7189 return N;
7191 if (VT.getVectorElementType().isFloatingPoint()) {
7192 SmallVector<SDValue, 8> Ops;
7193 MVT FVT = VT.getVectorElementType().getSimpleVT();
7194 assert(FVT == MVT::f32 || FVT == MVT::f16);
7195 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7196 for (unsigned i = 0; i < NumElts; ++i)
7197 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7198 Op.getOperand(i)));
7199 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7200 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7201 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7202 if (Val.getNode())
7203 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7205 if (usesOnlyOneValue) {
7206 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7207 if (isConstant && Val.getNode())
7208 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7212 // If all elements are constants and the case above didn't get hit, fall back
7213 // to the default expansion, which will generate a load from the constant
7214 // pool.
7215 if (isConstant)
7216 return SDValue();
7218 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7219 if (NumElts >= 4) {
7220 SDValue shuffle = ReconstructShuffle(Op, DAG);
7221 if (shuffle != SDValue())
7222 return shuffle;
7225 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7226 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7227 // into two 64-bit vectors; we might discover a better way to lower it.
7228 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7229 EVT ExtVT = VT.getVectorElementType();
7230 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7231 SDValue Lower =
7232 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7233 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7234 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7235 SDValue Upper = DAG.getBuildVector(
7236 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7237 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7238 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7239 if (Lower && Upper)
7240 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7243 // Vectors with 32- or 64-bit elements can be built by directly assigning
7244 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7245 // will be legalized.
7246 if (EltSize >= 32) {
7247 // Do the expansion with floating-point types, since that is what the VFP
7248 // registers are defined to use, and since i64 is not legal.
7249 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7250 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7251 SmallVector<SDValue, 8> Ops;
7252 for (unsigned i = 0; i < NumElts; ++i)
7253 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7254 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7255 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7258 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7259 // know the default expansion would otherwise fall back on something even
7260 // worse. For a vector with one or two non-undef values, that's
7261 // scalar_to_vector for the elements followed by a shuffle (provided the
7262 // shuffle is valid for the target) and materialization element by element
7263 // on the stack followed by a load for everything else.
7264 if (!isConstant && !usesOnlyOneValue) {
7265 SDValue Vec = DAG.getUNDEF(VT);
7266 for (unsigned i = 0 ; i < NumElts; ++i) {
7267 SDValue V = Op.getOperand(i);
7268 if (V.isUndef())
7269 continue;
7270 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7271 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7273 return Vec;
7276 return SDValue();
7279 // Gather data to see if the operation can be modelled as a
7280 // shuffle in combination with VEXTs.
7281 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7282 SelectionDAG &DAG) const {
7283 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7284 SDLoc dl(Op);
7285 EVT VT = Op.getValueType();
7286 unsigned NumElts = VT.getVectorNumElements();
7288 struct ShuffleSourceInfo {
7289 SDValue Vec;
7290 unsigned MinElt = std::numeric_limits<unsigned>::max();
7291 unsigned MaxElt = 0;
7293 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7294 // be compatible with the shuffle we intend to construct. As a result
7295 // ShuffleVec will be some sliding window into the original Vec.
7296 SDValue ShuffleVec;
7298 // Code should guarantee that element i in Vec starts at element "WindowBase
7299 // + i * WindowScale in ShuffleVec".
7300 int WindowBase = 0;
7301 int WindowScale = 1;
7303 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7305 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7308 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7309 // node.
7310 SmallVector<ShuffleSourceInfo, 2> Sources;
7311 for (unsigned i = 0; i < NumElts; ++i) {
7312 SDValue V = Op.getOperand(i);
7313 if (V.isUndef())
7314 continue;
7315 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7316 // A shuffle can only come from building a vector from various
7317 // elements of other vectors.
7318 return SDValue();
7319 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7320 // Furthermore, shuffles require a constant mask, whereas extractelts
7321 // accept variable indices.
7322 return SDValue();
7325 // Add this element source to the list if it's not already there.
7326 SDValue SourceVec = V.getOperand(0);
7327 auto Source = llvm::find(Sources, SourceVec);
7328 if (Source == Sources.end())
7329 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7331 // Update the minimum and maximum lane number seen.
7332 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7333 Source->MinElt = std::min(Source->MinElt, EltNo);
7334 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7337 // Currently only do something sane when at most two source vectors
7338 // are involved.
7339 if (Sources.size() > 2)
7340 return SDValue();
7342 // Find out the smallest element size among result and two sources, and use
7343 // it as element size to build the shuffle_vector.
7344 EVT SmallestEltTy = VT.getVectorElementType();
7345 for (auto &Source : Sources) {
7346 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7347 if (SrcEltTy.bitsLT(SmallestEltTy))
7348 SmallestEltTy = SrcEltTy;
7350 unsigned ResMultiplier =
7351 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7352 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7353 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7355 // If the source vector is too wide or too narrow, we may nevertheless be able
7356 // to construct a compatible shuffle either by concatenating it with UNDEF or
7357 // extracting a suitable range of elements.
7358 for (auto &Src : Sources) {
7359 EVT SrcVT = Src.ShuffleVec.getValueType();
7361 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7362 continue;
7364 // This stage of the search produces a source with the same element type as
7365 // the original, but with a total width matching the BUILD_VECTOR output.
7366 EVT EltVT = SrcVT.getVectorElementType();
7367 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7368 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7370 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7371 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7372 return SDValue();
7373 // We can pad out the smaller vector for free, so if it's part of a
7374 // shuffle...
7375 Src.ShuffleVec =
7376 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7377 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7378 continue;
7381 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7382 return SDValue();
7384 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7385 // Span too large for a VEXT to cope
7386 return SDValue();
7389 if (Src.MinElt >= NumSrcElts) {
7390 // The extraction can just take the second half
7391 Src.ShuffleVec =
7392 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7393 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7394 Src.WindowBase = -NumSrcElts;
7395 } else if (Src.MaxElt < NumSrcElts) {
7396 // The extraction can just take the first half
7397 Src.ShuffleVec =
7398 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7399 DAG.getConstant(0, dl, MVT::i32));
7400 } else {
7401 // An actual VEXT is needed
7402 SDValue VEXTSrc1 =
7403 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7404 DAG.getConstant(0, dl, MVT::i32));
7405 SDValue VEXTSrc2 =
7406 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7407 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7409 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7410 VEXTSrc2,
7411 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7412 Src.WindowBase = -Src.MinElt;
7416 // Another possible incompatibility occurs from the vector element types. We
7417 // can fix this by bitcasting the source vectors to the same type we intend
7418 // for the shuffle.
7419 for (auto &Src : Sources) {
7420 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7421 if (SrcEltTy == SmallestEltTy)
7422 continue;
7423 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7424 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7425 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7426 Src.WindowBase *= Src.WindowScale;
7429 // Final sanity check before we try to actually produce a shuffle.
7430 LLVM_DEBUG(for (auto Src
7431 : Sources)
7432 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7434 // The stars all align, our next step is to produce the mask for the shuffle.
7435 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7436 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7437 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7438 SDValue Entry = Op.getOperand(i);
7439 if (Entry.isUndef())
7440 continue;
7442 auto Src = llvm::find(Sources, Entry.getOperand(0));
7443 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7445 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7446 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7447 // segment.
7448 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7449 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7450 VT.getScalarSizeInBits());
7451 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7453 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7454 // starting at the appropriate offset.
7455 int *LaneMask = &Mask[i * ResMultiplier];
7457 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7458 ExtractBase += NumElts * (Src - Sources.begin());
7459 for (int j = 0; j < LanesDefined; ++j)
7460 LaneMask[j] = ExtractBase + j;
7464 // We can't handle more than two sources. This should have already
7465 // been checked before this point.
7466 assert(Sources.size() <= 2 && "Too many sources!");
7468 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7469 for (unsigned i = 0; i < Sources.size(); ++i)
7470 ShuffleOps[i] = Sources[i].ShuffleVec;
7472 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7473 ShuffleOps[1], Mask, DAG);
7474 if (!Shuffle)
7475 return SDValue();
7476 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7479 enum ShuffleOpCodes {
7480 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7481 OP_VREV,
7482 OP_VDUP0,
7483 OP_VDUP1,
7484 OP_VDUP2,
7485 OP_VDUP3,
7486 OP_VEXT1,
7487 OP_VEXT2,
7488 OP_VEXT3,
7489 OP_VUZPL, // VUZP, left result
7490 OP_VUZPR, // VUZP, right result
7491 OP_VZIPL, // VZIP, left result
7492 OP_VZIPR, // VZIP, right result
7493 OP_VTRNL, // VTRN, left result
7494 OP_VTRNR // VTRN, right result
7497 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7498 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7499 switch (OpNum) {
7500 case OP_COPY:
7501 case OP_VREV:
7502 case OP_VDUP0:
7503 case OP_VDUP1:
7504 case OP_VDUP2:
7505 case OP_VDUP3:
7506 return true;
7508 return false;
7511 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7512 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7513 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7514 /// are assumed to be legal.
7515 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7516 if (VT.getVectorNumElements() == 4 &&
7517 (VT.is128BitVector() || VT.is64BitVector())) {
7518 unsigned PFIndexes[4];
7519 for (unsigned i = 0; i != 4; ++i) {
7520 if (M[i] < 0)
7521 PFIndexes[i] = 8;
7522 else
7523 PFIndexes[i] = M[i];
7526 // Compute the index in the perfect shuffle table.
7527 unsigned PFTableIndex =
7528 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7529 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7530 unsigned Cost = (PFEntry >> 30);
7532 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7533 return true;
7536 bool ReverseVEXT, isV_UNDEF;
7537 unsigned Imm, WhichResult;
7539 unsigned EltSize = VT.getScalarSizeInBits();
7540 if (EltSize >= 32 ||
7541 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7542 ShuffleVectorInst::isIdentityMask(M) ||
7543 isVREVMask(M, VT, 64) ||
7544 isVREVMask(M, VT, 32) ||
7545 isVREVMask(M, VT, 16))
7546 return true;
7547 else if (Subtarget->hasNEON() &&
7548 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7549 isVTBLMask(M, VT) ||
7550 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7551 return true;
7552 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7553 isReverseMask(M, VT))
7554 return true;
7555 else if (Subtarget->hasMVEIntegerOps() &&
7556 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7557 return true;
7558 else
7559 return false;
7562 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7563 /// the specified operations to build the shuffle.
7564 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7565 SDValue RHS, SelectionDAG &DAG,
7566 const SDLoc &dl) {
7567 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7568 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7569 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7571 if (OpNum == OP_COPY) {
7572 if (LHSID == (1*9+2)*9+3) return LHS;
7573 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7574 return RHS;
7577 SDValue OpLHS, OpRHS;
7578 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7579 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7580 EVT VT = OpLHS.getValueType();
7582 switch (OpNum) {
7583 default: llvm_unreachable("Unknown shuffle opcode!");
7584 case OP_VREV:
7585 // VREV divides the vector in half and swaps within the half.
7586 if (VT.getVectorElementType() == MVT::i32 ||
7587 VT.getVectorElementType() == MVT::f32)
7588 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7589 // vrev <4 x i16> -> VREV32
7590 if (VT.getVectorElementType() == MVT::i16)
7591 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7592 // vrev <4 x i8> -> VREV16
7593 assert(VT.getVectorElementType() == MVT::i8);
7594 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7595 case OP_VDUP0:
7596 case OP_VDUP1:
7597 case OP_VDUP2:
7598 case OP_VDUP3:
7599 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7600 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7601 case OP_VEXT1:
7602 case OP_VEXT2:
7603 case OP_VEXT3:
7604 return DAG.getNode(ARMISD::VEXT, dl, VT,
7605 OpLHS, OpRHS,
7606 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7607 case OP_VUZPL:
7608 case OP_VUZPR:
7609 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7610 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7611 case OP_VZIPL:
7612 case OP_VZIPR:
7613 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7614 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7615 case OP_VTRNL:
7616 case OP_VTRNR:
7617 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7618 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7622 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7623 ArrayRef<int> ShuffleMask,
7624 SelectionDAG &DAG) {
7625 // Check to see if we can use the VTBL instruction.
7626 SDValue V1 = Op.getOperand(0);
7627 SDValue V2 = Op.getOperand(1);
7628 SDLoc DL(Op);
7630 SmallVector<SDValue, 8> VTBLMask;
7631 for (ArrayRef<int>::iterator
7632 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7633 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7635 if (V2.getNode()->isUndef())
7636 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7637 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7639 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7640 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7643 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7644 SelectionDAG &DAG) {
7645 SDLoc DL(Op);
7646 SDValue OpLHS = Op.getOperand(0);
7647 EVT VT = OpLHS.getValueType();
7649 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7650 "Expect an v8i16/v16i8 type");
7651 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7652 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7653 // extract the first 8 bytes into the top double word and the last 8 bytes
7654 // into the bottom double word. The v8i16 case is similar.
7655 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7656 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7657 DAG.getConstant(ExtractNum, DL, MVT::i32));
7660 static EVT getVectorTyFromPredicateVector(EVT VT) {
7661 switch (VT.getSimpleVT().SimpleTy) {
7662 case MVT::v4i1:
7663 return MVT::v4i32;
7664 case MVT::v8i1:
7665 return MVT::v8i16;
7666 case MVT::v16i1:
7667 return MVT::v16i8;
7668 default:
7669 llvm_unreachable("Unexpected vector predicate type");
7673 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7674 SelectionDAG &DAG) {
7675 // Converting from boolean predicates to integers involves creating a vector
7676 // of all ones or all zeroes and selecting the lanes based upon the real
7677 // predicate.
7678 SDValue AllOnes =
7679 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7680 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7682 SDValue AllZeroes =
7683 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7684 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7686 // Get full vector type from predicate type
7687 EVT NewVT = getVectorTyFromPredicateVector(VT);
7689 SDValue RecastV1;
7690 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7691 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7692 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7693 // since we know in hardware the sizes are really the same.
7694 if (VT != MVT::v16i1)
7695 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7696 else
7697 RecastV1 = Pred;
7699 // Select either all ones or zeroes depending upon the real predicate bits.
7700 SDValue PredAsVector =
7701 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7703 // Recast our new predicate-as-integer v16i8 vector into something
7704 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7705 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7708 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7709 const ARMSubtarget *ST) {
7710 EVT VT = Op.getValueType();
7711 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7712 ArrayRef<int> ShuffleMask = SVN->getMask();
7714 assert(ST->hasMVEIntegerOps() &&
7715 "No support for vector shuffle of boolean predicates");
7717 SDValue V1 = Op.getOperand(0);
7718 SDLoc dl(Op);
7719 if (isReverseMask(ShuffleMask, VT)) {
7720 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7721 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7722 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7723 DAG.getConstant(16, dl, MVT::i32));
7724 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7727 // Until we can come up with optimised cases for every single vector
7728 // shuffle in existence we have chosen the least painful strategy. This is
7729 // to essentially promote the boolean predicate to a 8-bit integer, where
7730 // each predicate represents a byte. Then we fall back on a normal integer
7731 // vector shuffle and convert the result back into a predicate vector. In
7732 // many cases the generated code might be even better than scalar code
7733 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7734 // fields in a register into 8 other arbitrary 2-bit fields!
7735 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7736 EVT NewVT = PredAsVector.getValueType();
7738 // Do the shuffle!
7739 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7740 DAG.getUNDEF(NewVT), ShuffleMask);
7742 // Now return the result of comparing the shuffled vector with zero,
7743 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7744 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7745 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7748 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7749 const ARMSubtarget *ST) {
7750 SDValue V1 = Op.getOperand(0);
7751 SDValue V2 = Op.getOperand(1);
7752 SDLoc dl(Op);
7753 EVT VT = Op.getValueType();
7754 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7755 unsigned EltSize = VT.getScalarSizeInBits();
7757 if (ST->hasMVEIntegerOps() && EltSize == 1)
7758 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7760 // Convert shuffles that are directly supported on NEON to target-specific
7761 // DAG nodes, instead of keeping them as shuffles and matching them again
7762 // during code selection. This is more efficient and avoids the possibility
7763 // of inconsistencies between legalization and selection.
7764 // FIXME: floating-point vectors should be canonicalized to integer vectors
7765 // of the same time so that they get CSEd properly.
7766 ArrayRef<int> ShuffleMask = SVN->getMask();
7768 if (EltSize <= 32) {
7769 if (SVN->isSplat()) {
7770 int Lane = SVN->getSplatIndex();
7771 // If this is undef splat, generate it via "just" vdup, if possible.
7772 if (Lane == -1) Lane = 0;
7774 // Test if V1 is a SCALAR_TO_VECTOR.
7775 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7776 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7778 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7779 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7780 // reaches it).
7781 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7782 !isa<ConstantSDNode>(V1.getOperand(0))) {
7783 bool IsScalarToVector = true;
7784 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7785 if (!V1.getOperand(i).isUndef()) {
7786 IsScalarToVector = false;
7787 break;
7789 if (IsScalarToVector)
7790 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7792 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7793 DAG.getConstant(Lane, dl, MVT::i32));
7796 bool ReverseVEXT = false;
7797 unsigned Imm = 0;
7798 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7799 if (ReverseVEXT)
7800 std::swap(V1, V2);
7801 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7802 DAG.getConstant(Imm, dl, MVT::i32));
7805 if (isVREVMask(ShuffleMask, VT, 64))
7806 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7807 if (isVREVMask(ShuffleMask, VT, 32))
7808 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7809 if (isVREVMask(ShuffleMask, VT, 16))
7810 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7812 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7813 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7814 DAG.getConstant(Imm, dl, MVT::i32));
7817 // Check for Neon shuffles that modify both input vectors in place.
7818 // If both results are used, i.e., if there are two shuffles with the same
7819 // source operands and with masks corresponding to both results of one of
7820 // these operations, DAG memoization will ensure that a single node is
7821 // used for both shuffles.
7822 unsigned WhichResult = 0;
7823 bool isV_UNDEF = false;
7824 if (ST->hasNEON()) {
7825 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7826 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7827 if (isV_UNDEF)
7828 V2 = V1;
7829 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7830 .getValue(WhichResult);
7833 if (ST->hasMVEIntegerOps()) {
7834 if (isVMOVNMask(ShuffleMask, VT, 0))
7835 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
7836 DAG.getConstant(0, dl, MVT::i32));
7837 if (isVMOVNMask(ShuffleMask, VT, 1))
7838 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
7839 DAG.getConstant(1, dl, MVT::i32));
7842 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7843 // shuffles that produce a result larger than their operands with:
7844 // shuffle(concat(v1, undef), concat(v2, undef))
7845 // ->
7846 // shuffle(concat(v1, v2), undef)
7847 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7849 // This is useful in the general case, but there are special cases where
7850 // native shuffles produce larger results: the two-result ops.
7852 // Look through the concat when lowering them:
7853 // shuffle(concat(v1, v2), undef)
7854 // ->
7855 // concat(VZIP(v1, v2):0, :1)
7857 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7858 SDValue SubV1 = V1->getOperand(0);
7859 SDValue SubV2 = V1->getOperand(1);
7860 EVT SubVT = SubV1.getValueType();
7862 // We expect these to have been canonicalized to -1.
7863 assert(llvm::all_of(ShuffleMask, [&](int i) {
7864 return i < (int)VT.getVectorNumElements();
7865 }) && "Unexpected shuffle index into UNDEF operand!");
7867 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7868 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7869 if (isV_UNDEF)
7870 SubV2 = SubV1;
7871 assert((WhichResult == 0) &&
7872 "In-place shuffle of concat can only have one result!");
7873 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7874 SubV1, SubV2);
7875 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7876 Res.getValue(1));
7881 // If the shuffle is not directly supported and it has 4 elements, use
7882 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7883 unsigned NumElts = VT.getVectorNumElements();
7884 if (NumElts == 4) {
7885 unsigned PFIndexes[4];
7886 for (unsigned i = 0; i != 4; ++i) {
7887 if (ShuffleMask[i] < 0)
7888 PFIndexes[i] = 8;
7889 else
7890 PFIndexes[i] = ShuffleMask[i];
7893 // Compute the index in the perfect shuffle table.
7894 unsigned PFTableIndex =
7895 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7896 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7897 unsigned Cost = (PFEntry >> 30);
7899 if (Cost <= 4) {
7900 if (ST->hasNEON())
7901 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7902 else if (isLegalMVEShuffleOp(PFEntry)) {
7903 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7904 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7905 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7906 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7907 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7908 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7913 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7914 if (EltSize >= 32) {
7915 // Do the expansion with floating-point types, since that is what the VFP
7916 // registers are defined to use, and since i64 is not legal.
7917 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7918 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7919 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7920 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7921 SmallVector<SDValue, 8> Ops;
7922 for (unsigned i = 0; i < NumElts; ++i) {
7923 if (ShuffleMask[i] < 0)
7924 Ops.push_back(DAG.getUNDEF(EltVT));
7925 else
7926 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7927 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7928 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7929 dl, MVT::i32)));
7931 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7932 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7935 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7936 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7938 if (ST->hasNEON() && VT == MVT::v8i8)
7939 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7940 return NewOp;
7942 return SDValue();
7945 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7946 const ARMSubtarget *ST) {
7947 EVT VecVT = Op.getOperand(0).getValueType();
7948 SDLoc dl(Op);
7950 assert(ST->hasMVEIntegerOps() &&
7951 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7953 SDValue Conv =
7954 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7955 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7956 unsigned LaneWidth =
7957 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7958 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7959 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7960 Op.getOperand(1), DAG.getValueType(MVT::i1));
7961 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7962 DAG.getConstant(~Mask, dl, MVT::i32));
7963 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7966 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7967 SelectionDAG &DAG) const {
7968 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7969 SDValue Lane = Op.getOperand(2);
7970 if (!isa<ConstantSDNode>(Lane))
7971 return SDValue();
7973 SDValue Elt = Op.getOperand(1);
7974 EVT EltVT = Elt.getValueType();
7976 if (Subtarget->hasMVEIntegerOps() &&
7977 Op.getValueType().getScalarSizeInBits() == 1)
7978 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7980 if (getTypeAction(*DAG.getContext(), EltVT) ==
7981 TargetLowering::TypePromoteFloat) {
7982 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7983 // but the type system will try to do that if we don't intervene.
7984 // Reinterpret any such vector-element insertion as one with the
7985 // corresponding integer types.
7987 SDLoc dl(Op);
7989 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7990 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7991 TargetLowering::TypePromoteFloat);
7993 SDValue VecIn = Op.getOperand(0);
7994 EVT VecVT = VecIn.getValueType();
7995 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7996 VecVT.getVectorNumElements());
7998 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7999 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8000 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8001 IVecIn, IElt, Lane);
8002 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8005 return Op;
8008 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8009 const ARMSubtarget *ST) {
8010 EVT VecVT = Op.getOperand(0).getValueType();
8011 SDLoc dl(Op);
8013 assert(ST->hasMVEIntegerOps() &&
8014 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8016 SDValue Conv =
8017 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8018 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8019 unsigned LaneWidth =
8020 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8021 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8022 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8023 return Shift;
8026 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8027 const ARMSubtarget *ST) {
8028 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8029 SDValue Lane = Op.getOperand(1);
8030 if (!isa<ConstantSDNode>(Lane))
8031 return SDValue();
8033 SDValue Vec = Op.getOperand(0);
8034 EVT VT = Vec.getValueType();
8036 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8037 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8039 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8040 SDLoc dl(Op);
8041 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8044 return Op;
8047 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8048 const ARMSubtarget *ST) {
8049 SDValue V1 = Op.getOperand(0);
8050 SDValue V2 = Op.getOperand(1);
8051 SDLoc dl(Op);
8052 EVT VT = Op.getValueType();
8053 EVT Op1VT = V1.getValueType();
8054 EVT Op2VT = V2.getValueType();
8055 unsigned NumElts = VT.getVectorNumElements();
8057 assert(Op1VT == Op2VT && "Operand types don't match!");
8058 assert(VT.getScalarSizeInBits() == 1 &&
8059 "Unexpected custom CONCAT_VECTORS lowering");
8060 assert(ST->hasMVEIntegerOps() &&
8061 "CONCAT_VECTORS lowering only supported for MVE");
8063 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8064 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8066 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8067 // promoted to v8i16, etc.
8069 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8071 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8072 // to be the right size for the destination. For example, if Op1 is v4i1 then
8073 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8074 // which when promoted is v8i16. That means each i32 element from Op1 needs
8075 // truncating to i16 and inserting in the result.
8076 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8077 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8078 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8079 EVT NewVT = NewV.getValueType();
8080 EVT ConcatVT = ConVec.getValueType();
8081 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8082 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8083 DAG.getIntPtrConstant(i, dl));
8084 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8085 DAG.getConstant(j, dl, MVT::i32));
8087 return ConVec;
8089 unsigned j = 0;
8090 ConVec = ExractInto(NewV1, ConVec, j);
8091 ConVec = ExractInto(NewV2, ConVec, j);
8093 // Now return the result of comparing the subvector with zero,
8094 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8095 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8096 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8099 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8100 const ARMSubtarget *ST) {
8101 EVT VT = Op->getValueType(0);
8102 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8103 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8105 // The only time a CONCAT_VECTORS operation can have legal types is when
8106 // two 64-bit vectors are concatenated to a 128-bit vector.
8107 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8108 "unexpected CONCAT_VECTORS");
8109 SDLoc dl(Op);
8110 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8111 SDValue Op0 = Op.getOperand(0);
8112 SDValue Op1 = Op.getOperand(1);
8113 if (!Op0.isUndef())
8114 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8115 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8116 DAG.getIntPtrConstant(0, dl));
8117 if (!Op1.isUndef())
8118 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8119 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8120 DAG.getIntPtrConstant(1, dl));
8121 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8124 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8125 const ARMSubtarget *ST) {
8126 SDValue V1 = Op.getOperand(0);
8127 SDValue V2 = Op.getOperand(1);
8128 SDLoc dl(Op);
8129 EVT VT = Op.getValueType();
8130 EVT Op1VT = V1.getValueType();
8131 unsigned NumElts = VT.getVectorNumElements();
8132 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8134 assert(VT.getScalarSizeInBits() == 1 &&
8135 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8136 assert(ST->hasMVEIntegerOps() &&
8137 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8139 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8141 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8142 // promoted to v8i16, etc.
8144 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8146 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8147 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8148 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8149 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8150 DAG.getIntPtrConstant(i, dl));
8151 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8152 DAG.getConstant(j, dl, MVT::i32));
8155 // Now return the result of comparing the subvector with zero,
8156 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8157 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8158 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8161 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8162 /// element has been zero/sign-extended, depending on the isSigned parameter,
8163 /// from an integer type half its size.
8164 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8165 bool isSigned) {
8166 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8167 EVT VT = N->getValueType(0);
8168 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8169 SDNode *BVN = N->getOperand(0).getNode();
8170 if (BVN->getValueType(0) != MVT::v4i32 ||
8171 BVN->getOpcode() != ISD::BUILD_VECTOR)
8172 return false;
8173 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8174 unsigned HiElt = 1 - LoElt;
8175 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8176 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8177 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8178 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8179 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8180 return false;
8181 if (isSigned) {
8182 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8183 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8184 return true;
8185 } else {
8186 if (Hi0->isNullValue() && Hi1->isNullValue())
8187 return true;
8189 return false;
8192 if (N->getOpcode() != ISD::BUILD_VECTOR)
8193 return false;
8195 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8196 SDNode *Elt = N->getOperand(i).getNode();
8197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8198 unsigned EltSize = VT.getScalarSizeInBits();
8199 unsigned HalfSize = EltSize / 2;
8200 if (isSigned) {
8201 if (!isIntN(HalfSize, C->getSExtValue()))
8202 return false;
8203 } else {
8204 if (!isUIntN(HalfSize, C->getZExtValue()))
8205 return false;
8207 continue;
8209 return false;
8212 return true;
8215 /// isSignExtended - Check if a node is a vector value that is sign-extended
8216 /// or a constant BUILD_VECTOR with sign-extended elements.
8217 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8218 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8219 return true;
8220 if (isExtendedBUILD_VECTOR(N, DAG, true))
8221 return true;
8222 return false;
8225 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8226 /// or a constant BUILD_VECTOR with zero-extended elements.
8227 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8228 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8229 return true;
8230 if (isExtendedBUILD_VECTOR(N, DAG, false))
8231 return true;
8232 return false;
8235 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8236 if (OrigVT.getSizeInBits() >= 64)
8237 return OrigVT;
8239 assert(OrigVT.isSimple() && "Expecting a simple value type");
8241 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8242 switch (OrigSimpleTy) {
8243 default: llvm_unreachable("Unexpected Vector Type");
8244 case MVT::v2i8:
8245 case MVT::v2i16:
8246 return MVT::v2i32;
8247 case MVT::v4i8:
8248 return MVT::v4i16;
8252 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8253 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8254 /// We insert the required extension here to get the vector to fill a D register.
8255 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8256 const EVT &OrigTy,
8257 const EVT &ExtTy,
8258 unsigned ExtOpcode) {
8259 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8260 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8261 // 64-bits we need to insert a new extension so that it will be 64-bits.
8262 assert(ExtTy.is128BitVector() && "Unexpected extension size");
8263 if (OrigTy.getSizeInBits() >= 64)
8264 return N;
8266 // Must extend size to at least 64 bits to be used as an operand for VMULL.
8267 EVT NewVT = getExtensionTo64Bits(OrigTy);
8269 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8272 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8273 /// does not do any sign/zero extension. If the original vector is less
8274 /// than 64 bits, an appropriate extension will be added after the load to
8275 /// reach a total size of 64 bits. We have to add the extension separately
8276 /// because ARM does not have a sign/zero extending load for vectors.
8277 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8278 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8280 // The load already has the right type.
8281 if (ExtendedTy == LD->getMemoryVT())
8282 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8283 LD->getBasePtr(), LD->getPointerInfo(),
8284 LD->getAlignment(), LD->getMemOperand()->getFlags());
8286 // We need to create a zextload/sextload. We cannot just create a load
8287 // followed by a zext/zext node because LowerMUL is also run during normal
8288 // operation legalization where we can't create illegal types.
8289 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8290 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8291 LD->getMemoryVT(), LD->getAlignment(),
8292 LD->getMemOperand()->getFlags());
8295 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8296 /// extending load, or BUILD_VECTOR with extended elements, return the
8297 /// unextended value. The unextended vector should be 64 bits so that it can
8298 /// be used as an operand to a VMULL instruction. If the original vector size
8299 /// before extension is less than 64 bits we add a an extension to resize
8300 /// the vector to 64 bits.
8301 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8302 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8303 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8304 N->getOperand(0)->getValueType(0),
8305 N->getValueType(0),
8306 N->getOpcode());
8308 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8309 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8310 "Expected extending load");
8312 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8313 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8314 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8315 SDValue extLoad =
8316 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8317 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8319 return newLoad;
8322 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8323 // have been legalized as a BITCAST from v4i32.
8324 if (N->getOpcode() == ISD::BITCAST) {
8325 SDNode *BVN = N->getOperand(0).getNode();
8326 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8327 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8328 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8329 return DAG.getBuildVector(
8330 MVT::v2i32, SDLoc(N),
8331 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8333 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8334 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8335 EVT VT = N->getValueType(0);
8336 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8337 unsigned NumElts = VT.getVectorNumElements();
8338 MVT TruncVT = MVT::getIntegerVT(EltSize);
8339 SmallVector<SDValue, 8> Ops;
8340 SDLoc dl(N);
8341 for (unsigned i = 0; i != NumElts; ++i) {
8342 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8343 const APInt &CInt = C->getAPIntValue();
8344 // Element types smaller than 32 bits are not legal, so use i32 elements.
8345 // The values are implicitly truncated so sext vs. zext doesn't matter.
8346 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8348 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8351 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8352 unsigned Opcode = N->getOpcode();
8353 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8354 SDNode *N0 = N->getOperand(0).getNode();
8355 SDNode *N1 = N->getOperand(1).getNode();
8356 return N0->hasOneUse() && N1->hasOneUse() &&
8357 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8359 return false;
8362 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8363 unsigned Opcode = N->getOpcode();
8364 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8365 SDNode *N0 = N->getOperand(0).getNode();
8366 SDNode *N1 = N->getOperand(1).getNode();
8367 return N0->hasOneUse() && N1->hasOneUse() &&
8368 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8370 return false;
8373 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8374 // Multiplications are only custom-lowered for 128-bit vectors so that
8375 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8376 EVT VT = Op.getValueType();
8377 assert(VT.is128BitVector() && VT.isInteger() &&
8378 "unexpected type for custom-lowering ISD::MUL");
8379 SDNode *N0 = Op.getOperand(0).getNode();
8380 SDNode *N1 = Op.getOperand(1).getNode();
8381 unsigned NewOpc = 0;
8382 bool isMLA = false;
8383 bool isN0SExt = isSignExtended(N0, DAG);
8384 bool isN1SExt = isSignExtended(N1, DAG);
8385 if (isN0SExt && isN1SExt)
8386 NewOpc = ARMISD::VMULLs;
8387 else {
8388 bool isN0ZExt = isZeroExtended(N0, DAG);
8389 bool isN1ZExt = isZeroExtended(N1, DAG);
8390 if (isN0ZExt && isN1ZExt)
8391 NewOpc = ARMISD::VMULLu;
8392 else if (isN1SExt || isN1ZExt) {
8393 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8394 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8395 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8396 NewOpc = ARMISD::VMULLs;
8397 isMLA = true;
8398 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8399 NewOpc = ARMISD::VMULLu;
8400 isMLA = true;
8401 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8402 std::swap(N0, N1);
8403 NewOpc = ARMISD::VMULLu;
8404 isMLA = true;
8408 if (!NewOpc) {
8409 if (VT == MVT::v2i64)
8410 // Fall through to expand this. It is not legal.
8411 return SDValue();
8412 else
8413 // Other vector multiplications are legal.
8414 return Op;
8418 // Legalize to a VMULL instruction.
8419 SDLoc DL(Op);
8420 SDValue Op0;
8421 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8422 if (!isMLA) {
8423 Op0 = SkipExtensionForVMULL(N0, DAG);
8424 assert(Op0.getValueType().is64BitVector() &&
8425 Op1.getValueType().is64BitVector() &&
8426 "unexpected types for extended operands to VMULL");
8427 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8430 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8431 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8432 // vmull q0, d4, d6
8433 // vmlal q0, d5, d6
8434 // is faster than
8435 // vaddl q0, d4, d5
8436 // vmovl q1, d6
8437 // vmul q0, q0, q1
8438 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8439 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8440 EVT Op1VT = Op1.getValueType();
8441 return DAG.getNode(N0->getOpcode(), DL, VT,
8442 DAG.getNode(NewOpc, DL, VT,
8443 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8444 DAG.getNode(NewOpc, DL, VT,
8445 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8448 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8449 SelectionDAG &DAG) {
8450 // TODO: Should this propagate fast-math-flags?
8452 // Convert to float
8453 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8454 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8455 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8456 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8457 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8458 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8459 // Get reciprocal estimate.
8460 // float4 recip = vrecpeq_f32(yf);
8461 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8462 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8464 // Because char has a smaller range than uchar, we can actually get away
8465 // without any newton steps. This requires that we use a weird bias
8466 // of 0xb000, however (again, this has been exhaustively tested).
8467 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8468 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8469 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8470 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8471 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8472 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8473 // Convert back to short.
8474 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8475 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8476 return X;
8479 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8480 SelectionDAG &DAG) {
8481 // TODO: Should this propagate fast-math-flags?
8483 SDValue N2;
8484 // Convert to float.
8485 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8486 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8487 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8488 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8489 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8490 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8492 // Use reciprocal estimate and one refinement step.
8493 // float4 recip = vrecpeq_f32(yf);
8494 // recip *= vrecpsq_f32(yf, recip);
8495 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8496 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8497 N1);
8498 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8499 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8500 N1, N2);
8501 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8502 // Because short has a smaller range than ushort, we can actually get away
8503 // with only a single newton step. This requires that we use a weird bias
8504 // of 89, however (again, this has been exhaustively tested).
8505 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8506 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8507 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8508 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8509 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8510 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8511 // Convert back to integer and return.
8512 // return vmovn_s32(vcvt_s32_f32(result));
8513 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8514 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8515 return N0;
8518 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8519 const ARMSubtarget *ST) {
8520 EVT VT = Op.getValueType();
8521 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8522 "unexpected type for custom-lowering ISD::SDIV");
8524 SDLoc dl(Op);
8525 SDValue N0 = Op.getOperand(0);
8526 SDValue N1 = Op.getOperand(1);
8527 SDValue N2, N3;
8529 if (VT == MVT::v8i8) {
8530 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8531 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8533 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8534 DAG.getIntPtrConstant(4, dl));
8535 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8536 DAG.getIntPtrConstant(4, dl));
8537 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8538 DAG.getIntPtrConstant(0, dl));
8539 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8540 DAG.getIntPtrConstant(0, dl));
8542 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8543 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8545 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8546 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8548 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8549 return N0;
8551 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8554 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8555 const ARMSubtarget *ST) {
8556 // TODO: Should this propagate fast-math-flags?
8557 EVT VT = Op.getValueType();
8558 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8559 "unexpected type for custom-lowering ISD::UDIV");
8561 SDLoc dl(Op);
8562 SDValue N0 = Op.getOperand(0);
8563 SDValue N1 = Op.getOperand(1);
8564 SDValue N2, N3;
8566 if (VT == MVT::v8i8) {
8567 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8568 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8570 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8571 DAG.getIntPtrConstant(4, dl));
8572 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8573 DAG.getIntPtrConstant(4, dl));
8574 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8575 DAG.getIntPtrConstant(0, dl));
8576 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8577 DAG.getIntPtrConstant(0, dl));
8579 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8580 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8582 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8583 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8585 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8586 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8587 MVT::i32),
8588 N0);
8589 return N0;
8592 // v4i16 sdiv ... Convert to float.
8593 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8594 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8595 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8596 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8597 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8598 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8600 // Use reciprocal estimate and two refinement steps.
8601 // float4 recip = vrecpeq_f32(yf);
8602 // recip *= vrecpsq_f32(yf, recip);
8603 // recip *= vrecpsq_f32(yf, recip);
8604 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8605 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8606 BN1);
8607 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8608 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8609 BN1, N2);
8610 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8611 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8612 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8613 BN1, N2);
8614 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8615 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8616 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8617 // and that it will never cause us to return an answer too large).
8618 // float4 result = as_float4(as_int4(xf*recip) + 2);
8619 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8620 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8621 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8622 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8623 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8624 // Convert back to integer and return.
8625 // return vmovn_u32(vcvt_s32_f32(result));
8626 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8627 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8628 return N0;
8631 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8632 SDNode *N = Op.getNode();
8633 EVT VT = N->getValueType(0);
8634 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8636 SDValue Carry = Op.getOperand(2);
8638 SDLoc DL(Op);
8640 SDValue Result;
8641 if (Op.getOpcode() == ISD::ADDCARRY) {
8642 // This converts the boolean value carry into the carry flag.
8643 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8645 // Do the addition proper using the carry flag we wanted.
8646 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8647 Op.getOperand(1), Carry);
8649 // Now convert the carry flag into a boolean value.
8650 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8651 } else {
8652 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8653 // have to invert the carry first.
8654 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8655 DAG.getConstant(1, DL, MVT::i32), Carry);
8656 // This converts the boolean value carry into the carry flag.
8657 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8659 // Do the subtraction proper using the carry flag we wanted.
8660 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8661 Op.getOperand(1), Carry);
8663 // Now convert the carry flag into a boolean value.
8664 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8665 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8666 // by ISD::SUBCARRY, so compute 1 - C.
8667 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8668 DAG.getConstant(1, DL, MVT::i32), Carry);
8671 // Return both values.
8672 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8675 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8676 assert(Subtarget->isTargetDarwin());
8678 // For iOS, we want to call an alternative entry point: __sincos_stret,
8679 // return values are passed via sret.
8680 SDLoc dl(Op);
8681 SDValue Arg = Op.getOperand(0);
8682 EVT ArgVT = Arg.getValueType();
8683 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8684 auto PtrVT = getPointerTy(DAG.getDataLayout());
8686 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8689 // Pair of floats / doubles used to pass the result.
8690 Type *RetTy = StructType::get(ArgTy, ArgTy);
8691 auto &DL = DAG.getDataLayout();
8693 ArgListTy Args;
8694 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8695 SDValue SRet;
8696 if (ShouldUseSRet) {
8697 // Create stack object for sret.
8698 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8699 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8700 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8701 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8703 ArgListEntry Entry;
8704 Entry.Node = SRet;
8705 Entry.Ty = RetTy->getPointerTo();
8706 Entry.IsSExt = false;
8707 Entry.IsZExt = false;
8708 Entry.IsSRet = true;
8709 Args.push_back(Entry);
8710 RetTy = Type::getVoidTy(*DAG.getContext());
8713 ArgListEntry Entry;
8714 Entry.Node = Arg;
8715 Entry.Ty = ArgTy;
8716 Entry.IsSExt = false;
8717 Entry.IsZExt = false;
8718 Args.push_back(Entry);
8720 RTLIB::Libcall LC =
8721 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8722 const char *LibcallName = getLibcallName(LC);
8723 CallingConv::ID CC = getLibcallCallingConv(LC);
8724 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8726 TargetLowering::CallLoweringInfo CLI(DAG);
8727 CLI.setDebugLoc(dl)
8728 .setChain(DAG.getEntryNode())
8729 .setCallee(CC, RetTy, Callee, std::move(Args))
8730 .setDiscardResult(ShouldUseSRet);
8731 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8733 if (!ShouldUseSRet)
8734 return CallResult.first;
8736 SDValue LoadSin =
8737 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8739 // Address of cos field.
8740 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8741 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8742 SDValue LoadCos =
8743 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8745 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8746 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8747 LoadSin.getValue(0), LoadCos.getValue(0));
8750 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8751 bool Signed,
8752 SDValue &Chain) const {
8753 EVT VT = Op.getValueType();
8754 assert((VT == MVT::i32 || VT == MVT::i64) &&
8755 "unexpected type for custom lowering DIV");
8756 SDLoc dl(Op);
8758 const auto &DL = DAG.getDataLayout();
8759 const auto &TLI = DAG.getTargetLoweringInfo();
8761 const char *Name = nullptr;
8762 if (Signed)
8763 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8764 else
8765 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8767 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8769 ARMTargetLowering::ArgListTy Args;
8771 for (auto AI : {1, 0}) {
8772 ArgListEntry Arg;
8773 Arg.Node = Op.getOperand(AI);
8774 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8775 Args.push_back(Arg);
8778 CallLoweringInfo CLI(DAG);
8779 CLI.setDebugLoc(dl)
8780 .setChain(Chain)
8781 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8782 ES, std::move(Args));
8784 return LowerCallTo(CLI).first;
8787 // This is a code size optimisation: return the original SDIV node to
8788 // DAGCombiner when we don't want to expand SDIV into a sequence of
8789 // instructions, and an empty node otherwise which will cause the
8790 // SDIV to be expanded in DAGCombine.
8791 SDValue
8792 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8793 SelectionDAG &DAG,
8794 SmallVectorImpl<SDNode *> &Created) const {
8795 // TODO: Support SREM
8796 if (N->getOpcode() != ISD::SDIV)
8797 return SDValue();
8799 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8800 const bool MinSize = ST.hasMinSize();
8801 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8802 : ST.hasDivideInARMMode();
8804 // Don't touch vector types; rewriting this may lead to scalarizing
8805 // the int divs.
8806 if (N->getOperand(0).getValueType().isVector())
8807 return SDValue();
8809 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8810 // hwdiv support for this to be really profitable.
8811 if (!(MinSize && HasDivide))
8812 return SDValue();
8814 // ARM mode is a bit simpler than Thumb: we can handle large power
8815 // of 2 immediates with 1 mov instruction; no further checks required,
8816 // just return the sdiv node.
8817 if (!ST.isThumb())
8818 return SDValue(N, 0);
8820 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8821 // and thus lose the code size benefits of a MOVS that requires only 2.
8822 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8823 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8824 if (Divisor.sgt(128))
8825 return SDValue();
8827 return SDValue(N, 0);
8830 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8831 bool Signed) const {
8832 assert(Op.getValueType() == MVT::i32 &&
8833 "unexpected type for custom lowering DIV");
8834 SDLoc dl(Op);
8836 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8837 DAG.getEntryNode(), Op.getOperand(1));
8839 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8842 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8843 SDLoc DL(N);
8844 SDValue Op = N->getOperand(1);
8845 if (N->getValueType(0) == MVT::i32)
8846 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8847 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8848 DAG.getConstant(0, DL, MVT::i32));
8849 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8850 DAG.getConstant(1, DL, MVT::i32));
8851 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8852 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8855 void ARMTargetLowering::ExpandDIV_Windows(
8856 SDValue Op, SelectionDAG &DAG, bool Signed,
8857 SmallVectorImpl<SDValue> &Results) const {
8858 const auto &DL = DAG.getDataLayout();
8859 const auto &TLI = DAG.getTargetLoweringInfo();
8861 assert(Op.getValueType() == MVT::i64 &&
8862 "unexpected type for custom lowering DIV");
8863 SDLoc dl(Op);
8865 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8867 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8869 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8870 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8871 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8872 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8874 Results.push_back(Lower);
8875 Results.push_back(Upper);
8878 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
8879 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
8880 EVT MemVT = LD->getMemoryVT();
8881 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
8882 "Expected a predicate type!");
8883 assert(MemVT == Op.getValueType());
8884 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
8885 "Expected a non-extending load");
8886 assert(LD->isUnindexed() && "Expected a unindexed load");
8888 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
8889 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
8890 // need to make sure that 8/4 bits are actually loaded into the correct
8891 // place, which means loading the value and then shuffling the values into
8892 // the bottom bits of the predicate.
8893 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
8894 // for BE).
8896 SDLoc dl(Op);
8897 SDValue Load = DAG.getExtLoad(
8898 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
8899 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
8900 LD->getMemOperand());
8901 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
8902 if (MemVT != MVT::v16i1)
8903 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
8904 DAG.getConstant(0, dl, MVT::i32));
8905 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
8908 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
8909 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
8910 EVT MemVT = ST->getMemoryVT();
8911 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
8912 "Expected a predicate type!");
8913 assert(MemVT == ST->getValue().getValueType());
8914 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
8915 assert(ST->isUnindexed() && "Expected a unindexed store");
8917 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
8918 // unset and a scalar store.
8919 SDLoc dl(Op);
8920 SDValue Build = ST->getValue();
8921 if (MemVT != MVT::v16i1) {
8922 SmallVector<SDValue, 16> Ops;
8923 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
8924 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
8925 DAG.getConstant(I, dl, MVT::i32)));
8926 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
8927 Ops.push_back(DAG.getUNDEF(MVT::i32));
8928 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
8930 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
8931 return DAG.getTruncStore(
8932 ST->getChain(), dl, GRP, ST->getBasePtr(),
8933 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
8934 ST->getMemOperand());
8937 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
8938 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
8939 MVT VT = Op.getSimpleValueType();
8940 SDValue Mask = N->getMask();
8941 SDValue PassThru = N->getPassThru();
8942 SDLoc dl(Op);
8944 auto IsZero = [](SDValue PassThru) {
8945 return (ISD::isBuildVectorAllZeros(PassThru.getNode()) ||
8946 (PassThru->getOpcode() == ARMISD::VMOVIMM &&
8947 isNullConstant(PassThru->getOperand(0))));
8950 if (IsZero(PassThru))
8951 return Op;
8953 // MVE Masked loads use zero as the passthru value. Here we convert undef to
8954 // zero too, and other values are lowered to a select.
8955 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
8956 DAG.getTargetConstant(0, dl, MVT::i32));
8957 SDValue NewLoad = DAG.getMaskedLoad(
8958 VT, dl, N->getChain(), N->getBasePtr(), Mask, ZeroVec, N->getMemoryVT(),
8959 N->getMemOperand(), N->getExtensionType(), N->isExpandingLoad());
8960 SDValue Combo = NewLoad;
8961 if (!PassThru.isUndef() &&
8962 (PassThru.getOpcode() != ISD::BITCAST ||
8963 !IsZero(PassThru->getOperand(0))))
8964 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
8965 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
8968 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8969 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8970 // Acquire/Release load/store is not legal for targets without a dmb or
8971 // equivalent available.
8972 return SDValue();
8974 // Monotonic load/store is legal for all targets.
8975 return Op;
8978 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8979 SmallVectorImpl<SDValue> &Results,
8980 SelectionDAG &DAG,
8981 const ARMSubtarget *Subtarget) {
8982 SDLoc DL(N);
8983 // Under Power Management extensions, the cycle-count is:
8984 // mrc p15, #0, <Rt>, c9, c13, #0
8985 SDValue Ops[] = { N->getOperand(0), // Chain
8986 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8987 DAG.getTargetConstant(15, DL, MVT::i32),
8988 DAG.getTargetConstant(0, DL, MVT::i32),
8989 DAG.getTargetConstant(9, DL, MVT::i32),
8990 DAG.getTargetConstant(13, DL, MVT::i32),
8991 DAG.getTargetConstant(0, DL, MVT::i32)
8994 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8995 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8996 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8997 DAG.getConstant(0, DL, MVT::i32)));
8998 Results.push_back(Cycles32.getValue(1));
9001 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
9002 SDLoc dl(V.getNode());
9003 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9004 SDValue VHi = DAG.getAnyExtOrTrunc(
9005 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9006 dl, MVT::i32);
9007 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9008 if (isBigEndian)
9009 std::swap (VLo, VHi);
9010 SDValue RegClass =
9011 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9012 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9013 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9014 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9015 return SDValue(
9016 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9019 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9020 SmallVectorImpl<SDValue> & Results,
9021 SelectionDAG &DAG) {
9022 assert(N->getValueType(0) == MVT::i64 &&
9023 "AtomicCmpSwap on types less than 64 should be legal");
9024 SDValue Ops[] = {N->getOperand(1),
9025 createGPRPairNode(DAG, N->getOperand(2)),
9026 createGPRPairNode(DAG, N->getOperand(3)),
9027 N->getOperand(0)};
9028 SDNode *CmpSwap = DAG.getMachineNode(
9029 ARM::CMP_SWAP_64, SDLoc(N),
9030 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9032 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9033 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9035 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9037 Results.push_back(
9038 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9039 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
9040 Results.push_back(
9041 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9042 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
9043 Results.push_back(SDValue(CmpSwap, 2));
9046 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
9047 SelectionDAG &DAG) {
9048 const auto &TLI = DAG.getTargetLoweringInfo();
9050 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
9051 "Custom lowering is MSVCRT specific!");
9053 SDLoc dl(Op);
9054 SDValue Val = Op.getOperand(0);
9055 MVT Ty = Val->getSimpleValueType(0);
9056 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
9057 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
9058 TLI.getPointerTy(DAG.getDataLayout()));
9060 TargetLowering::ArgListTy Args;
9061 TargetLowering::ArgListEntry Entry;
9063 Entry.Node = Val;
9064 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
9065 Entry.IsZExt = true;
9066 Args.push_back(Entry);
9068 Entry.Node = Exponent;
9069 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
9070 Entry.IsZExt = true;
9071 Args.push_back(Entry);
9073 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
9075 // In the in-chain to the call is the entry node If we are emitting a
9076 // tailcall, the chain will be mutated if the node has a non-entry input
9077 // chain.
9078 SDValue InChain = DAG.getEntryNode();
9079 SDValue TCChain = InChain;
9081 const Function &F = DAG.getMachineFunction().getFunction();
9082 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
9083 F.getReturnType() == LCRTy;
9084 if (IsTC)
9085 InChain = TCChain;
9087 TargetLowering::CallLoweringInfo CLI(DAG);
9088 CLI.setDebugLoc(dl)
9089 .setChain(InChain)
9090 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
9091 .setTailCall(IsTC);
9092 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
9094 // Return the chain (the DAG root) if it is a tail call
9095 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
9098 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9099 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9100 switch (Op.getOpcode()) {
9101 default: llvm_unreachable("Don't know how to custom lower this!");
9102 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9103 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9104 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9105 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9106 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9107 case ISD::SELECT: return LowerSELECT(Op, DAG);
9108 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
9109 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9110 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
9111 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
9112 case ISD::VASTART: return LowerVASTART(Op, DAG);
9113 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9114 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
9115 case ISD::SINT_TO_FP:
9116 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
9117 case ISD::FP_TO_SINT:
9118 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
9119 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9120 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9121 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9122 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9123 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9124 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9125 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9126 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9127 Subtarget);
9128 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9129 case ISD::SHL:
9130 case ISD::SRL:
9131 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
9132 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
9133 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
9134 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
9135 case ISD::SRL_PARTS:
9136 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
9137 case ISD::CTTZ:
9138 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9139 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9140 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
9141 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
9142 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
9143 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9144 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9145 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9146 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9147 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9148 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9149 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9150 case ISD::MUL: return LowerMUL(Op, DAG);
9151 case ISD::SDIV:
9152 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9153 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9154 return LowerSDIV(Op, DAG, Subtarget);
9155 case ISD::UDIV:
9156 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9157 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9158 return LowerUDIV(Op, DAG, Subtarget);
9159 case ISD::ADDCARRY:
9160 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
9161 case ISD::SADDO:
9162 case ISD::SSUBO:
9163 return LowerSignedALUO(Op, DAG);
9164 case ISD::UADDO:
9165 case ISD::USUBO:
9166 return LowerUnsignedALUO(Op, DAG);
9167 case ISD::SADDSAT:
9168 case ISD::SSUBSAT:
9169 return LowerSADDSUBSAT(Op, DAG, Subtarget);
9170 case ISD::LOAD:
9171 return LowerPredicateLoad(Op, DAG);
9172 case ISD::STORE:
9173 return LowerPredicateStore(Op, DAG);
9174 case ISD::MLOAD:
9175 return LowerMLOAD(Op, DAG);
9176 case ISD::ATOMIC_LOAD:
9177 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
9178 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
9179 case ISD::SDIVREM:
9180 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
9181 case ISD::DYNAMIC_STACKALLOC:
9182 if (Subtarget->isTargetWindows())
9183 return LowerDYNAMIC_STACKALLOC(Op, DAG);
9184 llvm_unreachable("Don't know how to custom lower this!");
9185 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9186 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9187 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
9188 case ARMISD::WIN__DBZCHK: return SDValue();
9192 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9193 SelectionDAG &DAG) {
9194 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9195 unsigned Opc = 0;
9196 if (IntNo == Intrinsic::arm_smlald)
9197 Opc = ARMISD::SMLALD;
9198 else if (IntNo == Intrinsic::arm_smlaldx)
9199 Opc = ARMISD::SMLALDX;
9200 else if (IntNo == Intrinsic::arm_smlsld)
9201 Opc = ARMISD::SMLSLD;
9202 else if (IntNo == Intrinsic::arm_smlsldx)
9203 Opc = ARMISD::SMLSLDX;
9204 else
9205 return;
9207 SDLoc dl(N);
9208 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9209 N->getOperand(3),
9210 DAG.getConstant(0, dl, MVT::i32));
9211 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9212 N->getOperand(3),
9213 DAG.getConstant(1, dl, MVT::i32));
9215 SDValue LongMul = DAG.getNode(Opc, dl,
9216 DAG.getVTList(MVT::i32, MVT::i32),
9217 N->getOperand(1), N->getOperand(2),
9218 Lo, Hi);
9219 Results.push_back(LongMul.getValue(0));
9220 Results.push_back(LongMul.getValue(1));
9223 /// ReplaceNodeResults - Replace the results of node with an illegal result
9224 /// type with new values built out of custom code.
9225 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9226 SmallVectorImpl<SDValue> &Results,
9227 SelectionDAG &DAG) const {
9228 SDValue Res;
9229 switch (N->getOpcode()) {
9230 default:
9231 llvm_unreachable("Don't know how to custom expand this!");
9232 case ISD::READ_REGISTER:
9233 ExpandREAD_REGISTER(N, Results, DAG);
9234 break;
9235 case ISD::BITCAST:
9236 Res = ExpandBITCAST(N, DAG, Subtarget);
9237 break;
9238 case ISD::SRL:
9239 case ISD::SRA:
9240 case ISD::SHL:
9241 Res = Expand64BitShift(N, DAG, Subtarget);
9242 break;
9243 case ISD::SREM:
9244 case ISD::UREM:
9245 Res = LowerREM(N, DAG);
9246 break;
9247 case ISD::SDIVREM:
9248 case ISD::UDIVREM:
9249 Res = LowerDivRem(SDValue(N, 0), DAG);
9250 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9251 Results.push_back(Res.getValue(0));
9252 Results.push_back(Res.getValue(1));
9253 return;
9254 case ISD::SADDSAT:
9255 case ISD::SSUBSAT:
9256 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9257 break;
9258 case ISD::READCYCLECOUNTER:
9259 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9260 return;
9261 case ISD::UDIV:
9262 case ISD::SDIV:
9263 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9264 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9265 Results);
9266 case ISD::ATOMIC_CMP_SWAP:
9267 ReplaceCMP_SWAP_64Results(N, Results, DAG);
9268 return;
9269 case ISD::INTRINSIC_WO_CHAIN:
9270 return ReplaceLongIntrinsic(N, Results, DAG);
9271 case ISD::ABS:
9272 lowerABS(N, Results, DAG);
9273 return ;
9276 if (Res.getNode())
9277 Results.push_back(Res);
9280 //===----------------------------------------------------------------------===//
9281 // ARM Scheduler Hooks
9282 //===----------------------------------------------------------------------===//
9284 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9285 /// registers the function context.
9286 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9287 MachineBasicBlock *MBB,
9288 MachineBasicBlock *DispatchBB,
9289 int FI) const {
9290 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9291 "ROPI/RWPI not currently supported with SjLj");
9292 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9293 DebugLoc dl = MI.getDebugLoc();
9294 MachineFunction *MF = MBB->getParent();
9295 MachineRegisterInfo *MRI = &MF->getRegInfo();
9296 MachineConstantPool *MCP = MF->getConstantPool();
9297 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9298 const Function &F = MF->getFunction();
9300 bool isThumb = Subtarget->isThumb();
9301 bool isThumb2 = Subtarget->isThumb2();
9303 unsigned PCLabelId = AFI->createPICLabelUId();
9304 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9305 ARMConstantPoolValue *CPV =
9306 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9307 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9309 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9310 : &ARM::GPRRegClass;
9312 // Grab constant pool and fixed stack memory operands.
9313 MachineMemOperand *CPMMO =
9314 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9315 MachineMemOperand::MOLoad, 4, 4);
9317 MachineMemOperand *FIMMOSt =
9318 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9319 MachineMemOperand::MOStore, 4, 4);
9321 // Load the address of the dispatch MBB into the jump buffer.
9322 if (isThumb2) {
9323 // Incoming value: jbuf
9324 // ldr.n r5, LCPI1_1
9325 // orr r5, r5, #1
9326 // add r5, pc
9327 // str r5, [$jbuf, #+4] ; &jbuf[1]
9328 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9329 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9330 .addConstantPoolIndex(CPI)
9331 .addMemOperand(CPMMO)
9332 .add(predOps(ARMCC::AL));
9333 // Set the low bit because of thumb mode.
9334 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9335 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9336 .addReg(NewVReg1, RegState::Kill)
9337 .addImm(0x01)
9338 .add(predOps(ARMCC::AL))
9339 .add(condCodeOp());
9340 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9341 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9342 .addReg(NewVReg2, RegState::Kill)
9343 .addImm(PCLabelId);
9344 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9345 .addReg(NewVReg3, RegState::Kill)
9346 .addFrameIndex(FI)
9347 .addImm(36) // &jbuf[1] :: pc
9348 .addMemOperand(FIMMOSt)
9349 .add(predOps(ARMCC::AL));
9350 } else if (isThumb) {
9351 // Incoming value: jbuf
9352 // ldr.n r1, LCPI1_4
9353 // add r1, pc
9354 // mov r2, #1
9355 // orrs r1, r2
9356 // add r2, $jbuf, #+4 ; &jbuf[1]
9357 // str r1, [r2]
9358 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9359 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9360 .addConstantPoolIndex(CPI)
9361 .addMemOperand(CPMMO)
9362 .add(predOps(ARMCC::AL));
9363 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9364 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9365 .addReg(NewVReg1, RegState::Kill)
9366 .addImm(PCLabelId);
9367 // Set the low bit because of thumb mode.
9368 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9369 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9370 .addReg(ARM::CPSR, RegState::Define)
9371 .addImm(1)
9372 .add(predOps(ARMCC::AL));
9373 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9374 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9375 .addReg(ARM::CPSR, RegState::Define)
9376 .addReg(NewVReg2, RegState::Kill)
9377 .addReg(NewVReg3, RegState::Kill)
9378 .add(predOps(ARMCC::AL));
9379 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9380 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9381 .addFrameIndex(FI)
9382 .addImm(36); // &jbuf[1] :: pc
9383 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9384 .addReg(NewVReg4, RegState::Kill)
9385 .addReg(NewVReg5, RegState::Kill)
9386 .addImm(0)
9387 .addMemOperand(FIMMOSt)
9388 .add(predOps(ARMCC::AL));
9389 } else {
9390 // Incoming value: jbuf
9391 // ldr r1, LCPI1_1
9392 // add r1, pc, r1
9393 // str r1, [$jbuf, #+4] ; &jbuf[1]
9394 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9395 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9396 .addConstantPoolIndex(CPI)
9397 .addImm(0)
9398 .addMemOperand(CPMMO)
9399 .add(predOps(ARMCC::AL));
9400 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9401 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9402 .addReg(NewVReg1, RegState::Kill)
9403 .addImm(PCLabelId)
9404 .add(predOps(ARMCC::AL));
9405 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9406 .addReg(NewVReg2, RegState::Kill)
9407 .addFrameIndex(FI)
9408 .addImm(36) // &jbuf[1] :: pc
9409 .addMemOperand(FIMMOSt)
9410 .add(predOps(ARMCC::AL));
9414 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9415 MachineBasicBlock *MBB) const {
9416 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9417 DebugLoc dl = MI.getDebugLoc();
9418 MachineFunction *MF = MBB->getParent();
9419 MachineRegisterInfo *MRI = &MF->getRegInfo();
9420 MachineFrameInfo &MFI = MF->getFrameInfo();
9421 int FI = MFI.getFunctionContextIndex();
9423 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9424 : &ARM::GPRnopcRegClass;
9426 // Get a mapping of the call site numbers to all of the landing pads they're
9427 // associated with.
9428 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9429 unsigned MaxCSNum = 0;
9430 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9431 ++BB) {
9432 if (!BB->isEHPad()) continue;
9434 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9435 // pad.
9436 for (MachineBasicBlock::iterator
9437 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9438 if (!II->isEHLabel()) continue;
9440 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9441 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9443 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9444 for (SmallVectorImpl<unsigned>::iterator
9445 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9446 CSI != CSE; ++CSI) {
9447 CallSiteNumToLPad[*CSI].push_back(&*BB);
9448 MaxCSNum = std::max(MaxCSNum, *CSI);
9450 break;
9454 // Get an ordered list of the machine basic blocks for the jump table.
9455 std::vector<MachineBasicBlock*> LPadList;
9456 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9457 LPadList.reserve(CallSiteNumToLPad.size());
9458 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9459 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9460 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9461 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9462 LPadList.push_back(*II);
9463 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9467 assert(!LPadList.empty() &&
9468 "No landing pad destinations for the dispatch jump table!");
9470 // Create the jump table and associated information.
9471 MachineJumpTableInfo *JTI =
9472 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9473 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9475 // Create the MBBs for the dispatch code.
9477 // Shove the dispatch's address into the return slot in the function context.
9478 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9479 DispatchBB->setIsEHPad();
9481 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9482 unsigned trap_opcode;
9483 if (Subtarget->isThumb())
9484 trap_opcode = ARM::tTRAP;
9485 else
9486 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9488 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9489 DispatchBB->addSuccessor(TrapBB);
9491 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9492 DispatchBB->addSuccessor(DispContBB);
9494 // Insert and MBBs.
9495 MF->insert(MF->end(), DispatchBB);
9496 MF->insert(MF->end(), DispContBB);
9497 MF->insert(MF->end(), TrapBB);
9499 // Insert code into the entry block that creates and registers the function
9500 // context.
9501 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9503 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9504 MachinePointerInfo::getFixedStack(*MF, FI),
9505 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9507 MachineInstrBuilder MIB;
9508 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9510 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9511 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9513 // Add a register mask with no preserved registers. This results in all
9514 // registers being marked as clobbered. This can't work if the dispatch block
9515 // is in a Thumb1 function and is linked with ARM code which uses the FP
9516 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9517 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9519 bool IsPositionIndependent = isPositionIndependent();
9520 unsigned NumLPads = LPadList.size();
9521 if (Subtarget->isThumb2()) {
9522 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9523 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9524 .addFrameIndex(FI)
9525 .addImm(4)
9526 .addMemOperand(FIMMOLd)
9527 .add(predOps(ARMCC::AL));
9529 if (NumLPads < 256) {
9530 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9531 .addReg(NewVReg1)
9532 .addImm(LPadList.size())
9533 .add(predOps(ARMCC::AL));
9534 } else {
9535 Register VReg1 = MRI->createVirtualRegister(TRC);
9536 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9537 .addImm(NumLPads & 0xFFFF)
9538 .add(predOps(ARMCC::AL));
9540 unsigned VReg2 = VReg1;
9541 if ((NumLPads & 0xFFFF0000) != 0) {
9542 VReg2 = MRI->createVirtualRegister(TRC);
9543 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9544 .addReg(VReg1)
9545 .addImm(NumLPads >> 16)
9546 .add(predOps(ARMCC::AL));
9549 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9550 .addReg(NewVReg1)
9551 .addReg(VReg2)
9552 .add(predOps(ARMCC::AL));
9555 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9556 .addMBB(TrapBB)
9557 .addImm(ARMCC::HI)
9558 .addReg(ARM::CPSR);
9560 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9561 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9562 .addJumpTableIndex(MJTI)
9563 .add(predOps(ARMCC::AL));
9565 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9566 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9567 .addReg(NewVReg3, RegState::Kill)
9568 .addReg(NewVReg1)
9569 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9570 .add(predOps(ARMCC::AL))
9571 .add(condCodeOp());
9573 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9574 .addReg(NewVReg4, RegState::Kill)
9575 .addReg(NewVReg1)
9576 .addJumpTableIndex(MJTI);
9577 } else if (Subtarget->isThumb()) {
9578 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9579 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9580 .addFrameIndex(FI)
9581 .addImm(1)
9582 .addMemOperand(FIMMOLd)
9583 .add(predOps(ARMCC::AL));
9585 if (NumLPads < 256) {
9586 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9587 .addReg(NewVReg1)
9588 .addImm(NumLPads)
9589 .add(predOps(ARMCC::AL));
9590 } else {
9591 MachineConstantPool *ConstantPool = MF->getConstantPool();
9592 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9593 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9595 // MachineConstantPool wants an explicit alignment.
9596 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9597 if (Align == 0)
9598 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9599 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9601 Register VReg1 = MRI->createVirtualRegister(TRC);
9602 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9603 .addReg(VReg1, RegState::Define)
9604 .addConstantPoolIndex(Idx)
9605 .add(predOps(ARMCC::AL));
9606 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9607 .addReg(NewVReg1)
9608 .addReg(VReg1)
9609 .add(predOps(ARMCC::AL));
9612 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9613 .addMBB(TrapBB)
9614 .addImm(ARMCC::HI)
9615 .addReg(ARM::CPSR);
9617 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9618 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9619 .addReg(ARM::CPSR, RegState::Define)
9620 .addReg(NewVReg1)
9621 .addImm(2)
9622 .add(predOps(ARMCC::AL));
9624 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9625 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9626 .addJumpTableIndex(MJTI)
9627 .add(predOps(ARMCC::AL));
9629 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9630 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9631 .addReg(ARM::CPSR, RegState::Define)
9632 .addReg(NewVReg2, RegState::Kill)
9633 .addReg(NewVReg3)
9634 .add(predOps(ARMCC::AL));
9636 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9637 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9639 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9640 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9641 .addReg(NewVReg4, RegState::Kill)
9642 .addImm(0)
9643 .addMemOperand(JTMMOLd)
9644 .add(predOps(ARMCC::AL));
9646 unsigned NewVReg6 = NewVReg5;
9647 if (IsPositionIndependent) {
9648 NewVReg6 = MRI->createVirtualRegister(TRC);
9649 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9650 .addReg(ARM::CPSR, RegState::Define)
9651 .addReg(NewVReg5, RegState::Kill)
9652 .addReg(NewVReg3)
9653 .add(predOps(ARMCC::AL));
9656 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9657 .addReg(NewVReg6, RegState::Kill)
9658 .addJumpTableIndex(MJTI);
9659 } else {
9660 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9661 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9662 .addFrameIndex(FI)
9663 .addImm(4)
9664 .addMemOperand(FIMMOLd)
9665 .add(predOps(ARMCC::AL));
9667 if (NumLPads < 256) {
9668 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9669 .addReg(NewVReg1)
9670 .addImm(NumLPads)
9671 .add(predOps(ARMCC::AL));
9672 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9673 Register VReg1 = MRI->createVirtualRegister(TRC);
9674 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9675 .addImm(NumLPads & 0xFFFF)
9676 .add(predOps(ARMCC::AL));
9678 unsigned VReg2 = VReg1;
9679 if ((NumLPads & 0xFFFF0000) != 0) {
9680 VReg2 = MRI->createVirtualRegister(TRC);
9681 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9682 .addReg(VReg1)
9683 .addImm(NumLPads >> 16)
9684 .add(predOps(ARMCC::AL));
9687 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9688 .addReg(NewVReg1)
9689 .addReg(VReg2)
9690 .add(predOps(ARMCC::AL));
9691 } else {
9692 MachineConstantPool *ConstantPool = MF->getConstantPool();
9693 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9694 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9696 // MachineConstantPool wants an explicit alignment.
9697 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9698 if (Align == 0)
9699 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9700 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9702 Register VReg1 = MRI->createVirtualRegister(TRC);
9703 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9704 .addReg(VReg1, RegState::Define)
9705 .addConstantPoolIndex(Idx)
9706 .addImm(0)
9707 .add(predOps(ARMCC::AL));
9708 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9709 .addReg(NewVReg1)
9710 .addReg(VReg1, RegState::Kill)
9711 .add(predOps(ARMCC::AL));
9714 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9715 .addMBB(TrapBB)
9716 .addImm(ARMCC::HI)
9717 .addReg(ARM::CPSR);
9719 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9720 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9721 .addReg(NewVReg1)
9722 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9723 .add(predOps(ARMCC::AL))
9724 .add(condCodeOp());
9725 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9726 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9727 .addJumpTableIndex(MJTI)
9728 .add(predOps(ARMCC::AL));
9730 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9731 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9732 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9733 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9734 .addReg(NewVReg3, RegState::Kill)
9735 .addReg(NewVReg4)
9736 .addImm(0)
9737 .addMemOperand(JTMMOLd)
9738 .add(predOps(ARMCC::AL));
9740 if (IsPositionIndependent) {
9741 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9742 .addReg(NewVReg5, RegState::Kill)
9743 .addReg(NewVReg4)
9744 .addJumpTableIndex(MJTI);
9745 } else {
9746 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9747 .addReg(NewVReg5, RegState::Kill)
9748 .addJumpTableIndex(MJTI);
9752 // Add the jump table entries as successors to the MBB.
9753 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9754 for (std::vector<MachineBasicBlock*>::iterator
9755 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9756 MachineBasicBlock *CurMBB = *I;
9757 if (SeenMBBs.insert(CurMBB).second)
9758 DispContBB->addSuccessor(CurMBB);
9761 // N.B. the order the invoke BBs are processed in doesn't matter here.
9762 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9763 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9764 for (MachineBasicBlock *BB : InvokeBBs) {
9766 // Remove the landing pad successor from the invoke block and replace it
9767 // with the new dispatch block.
9768 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9769 BB->succ_end());
9770 while (!Successors.empty()) {
9771 MachineBasicBlock *SMBB = Successors.pop_back_val();
9772 if (SMBB->isEHPad()) {
9773 BB->removeSuccessor(SMBB);
9774 MBBLPads.push_back(SMBB);
9778 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9779 BB->normalizeSuccProbs();
9781 // Find the invoke call and mark all of the callee-saved registers as
9782 // 'implicit defined' so that they're spilled. This prevents code from
9783 // moving instructions to before the EH block, where they will never be
9784 // executed.
9785 for (MachineBasicBlock::reverse_iterator
9786 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9787 if (!II->isCall()) continue;
9789 DenseMap<unsigned, bool> DefRegs;
9790 for (MachineInstr::mop_iterator
9791 OI = II->operands_begin(), OE = II->operands_end();
9792 OI != OE; ++OI) {
9793 if (!OI->isReg()) continue;
9794 DefRegs[OI->getReg()] = true;
9797 MachineInstrBuilder MIB(*MF, &*II);
9799 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9800 unsigned Reg = SavedRegs[i];
9801 if (Subtarget->isThumb2() &&
9802 !ARM::tGPRRegClass.contains(Reg) &&
9803 !ARM::hGPRRegClass.contains(Reg))
9804 continue;
9805 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9806 continue;
9807 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9808 continue;
9809 if (!DefRegs[Reg])
9810 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9813 break;
9817 // Mark all former landing pads as non-landing pads. The dispatch is the only
9818 // landing pad now.
9819 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9820 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9821 (*I)->setIsEHPad(false);
9823 // The instruction is gone now.
9824 MI.eraseFromParent();
9827 static
9828 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9829 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9830 E = MBB->succ_end(); I != E; ++I)
9831 if (*I != Succ)
9832 return *I;
9833 llvm_unreachable("Expecting a BB with two successors!");
9836 /// Return the load opcode for a given load size. If load size >= 8,
9837 /// neon opcode will be returned.
9838 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9839 if (LdSize >= 8)
9840 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9841 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9842 if (IsThumb1)
9843 return LdSize == 4 ? ARM::tLDRi
9844 : LdSize == 2 ? ARM::tLDRHi
9845 : LdSize == 1 ? ARM::tLDRBi : 0;
9846 if (IsThumb2)
9847 return LdSize == 4 ? ARM::t2LDR_POST
9848 : LdSize == 2 ? ARM::t2LDRH_POST
9849 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9850 return LdSize == 4 ? ARM::LDR_POST_IMM
9851 : LdSize == 2 ? ARM::LDRH_POST
9852 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9855 /// Return the store opcode for a given store size. If store size >= 8,
9856 /// neon opcode will be returned.
9857 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9858 if (StSize >= 8)
9859 return StSize == 16 ? ARM::VST1q32wb_fixed
9860 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9861 if (IsThumb1)
9862 return StSize == 4 ? ARM::tSTRi
9863 : StSize == 2 ? ARM::tSTRHi
9864 : StSize == 1 ? ARM::tSTRBi : 0;
9865 if (IsThumb2)
9866 return StSize == 4 ? ARM::t2STR_POST
9867 : StSize == 2 ? ARM::t2STRH_POST
9868 : StSize == 1 ? ARM::t2STRB_POST : 0;
9869 return StSize == 4 ? ARM::STR_POST_IMM
9870 : StSize == 2 ? ARM::STRH_POST
9871 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9874 /// Emit a post-increment load operation with given size. The instructions
9875 /// will be added to BB at Pos.
9876 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9877 const TargetInstrInfo *TII, const DebugLoc &dl,
9878 unsigned LdSize, unsigned Data, unsigned AddrIn,
9879 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9880 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9881 assert(LdOpc != 0 && "Should have a load opcode");
9882 if (LdSize >= 8) {
9883 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9884 .addReg(AddrOut, RegState::Define)
9885 .addReg(AddrIn)
9886 .addImm(0)
9887 .add(predOps(ARMCC::AL));
9888 } else if (IsThumb1) {
9889 // load + update AddrIn
9890 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9891 .addReg(AddrIn)
9892 .addImm(0)
9893 .add(predOps(ARMCC::AL));
9894 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9895 .add(t1CondCodeOp())
9896 .addReg(AddrIn)
9897 .addImm(LdSize)
9898 .add(predOps(ARMCC::AL));
9899 } else if (IsThumb2) {
9900 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9901 .addReg(AddrOut, RegState::Define)
9902 .addReg(AddrIn)
9903 .addImm(LdSize)
9904 .add(predOps(ARMCC::AL));
9905 } else { // arm
9906 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9907 .addReg(AddrOut, RegState::Define)
9908 .addReg(AddrIn)
9909 .addReg(0)
9910 .addImm(LdSize)
9911 .add(predOps(ARMCC::AL));
9915 /// Emit a post-increment store operation with given size. The instructions
9916 /// will be added to BB at Pos.
9917 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9918 const TargetInstrInfo *TII, const DebugLoc &dl,
9919 unsigned StSize, unsigned Data, unsigned AddrIn,
9920 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9921 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9922 assert(StOpc != 0 && "Should have a store opcode");
9923 if (StSize >= 8) {
9924 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9925 .addReg(AddrIn)
9926 .addImm(0)
9927 .addReg(Data)
9928 .add(predOps(ARMCC::AL));
9929 } else if (IsThumb1) {
9930 // store + update AddrIn
9931 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9932 .addReg(Data)
9933 .addReg(AddrIn)
9934 .addImm(0)
9935 .add(predOps(ARMCC::AL));
9936 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9937 .add(t1CondCodeOp())
9938 .addReg(AddrIn)
9939 .addImm(StSize)
9940 .add(predOps(ARMCC::AL));
9941 } else if (IsThumb2) {
9942 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9943 .addReg(Data)
9944 .addReg(AddrIn)
9945 .addImm(StSize)
9946 .add(predOps(ARMCC::AL));
9947 } else { // arm
9948 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9949 .addReg(Data)
9950 .addReg(AddrIn)
9951 .addReg(0)
9952 .addImm(StSize)
9953 .add(predOps(ARMCC::AL));
9957 MachineBasicBlock *
9958 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9959 MachineBasicBlock *BB) const {
9960 // This pseudo instruction has 3 operands: dst, src, size
9961 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9962 // Otherwise, we will generate unrolled scalar copies.
9963 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9964 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9965 MachineFunction::iterator It = ++BB->getIterator();
9967 Register dest = MI.getOperand(0).getReg();
9968 Register src = MI.getOperand(1).getReg();
9969 unsigned SizeVal = MI.getOperand(2).getImm();
9970 unsigned Align = MI.getOperand(3).getImm();
9971 DebugLoc dl = MI.getDebugLoc();
9973 MachineFunction *MF = BB->getParent();
9974 MachineRegisterInfo &MRI = MF->getRegInfo();
9975 unsigned UnitSize = 0;
9976 const TargetRegisterClass *TRC = nullptr;
9977 const TargetRegisterClass *VecTRC = nullptr;
9979 bool IsThumb1 = Subtarget->isThumb1Only();
9980 bool IsThumb2 = Subtarget->isThumb2();
9981 bool IsThumb = Subtarget->isThumb();
9983 if (Align & 1) {
9984 UnitSize = 1;
9985 } else if (Align & 2) {
9986 UnitSize = 2;
9987 } else {
9988 // Check whether we can use NEON instructions.
9989 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9990 Subtarget->hasNEON()) {
9991 if ((Align % 16 == 0) && SizeVal >= 16)
9992 UnitSize = 16;
9993 else if ((Align % 8 == 0) && SizeVal >= 8)
9994 UnitSize = 8;
9996 // Can't use NEON instructions.
9997 if (UnitSize == 0)
9998 UnitSize = 4;
10001 // Select the correct opcode and register class for unit size load/store
10002 bool IsNeon = UnitSize >= 8;
10003 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10004 if (IsNeon)
10005 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10006 : UnitSize == 8 ? &ARM::DPRRegClass
10007 : nullptr;
10009 unsigned BytesLeft = SizeVal % UnitSize;
10010 unsigned LoopSize = SizeVal - BytesLeft;
10012 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10013 // Use LDR and STR to copy.
10014 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10015 // [destOut] = STR_POST(scratch, destIn, UnitSize)
10016 unsigned srcIn = src;
10017 unsigned destIn = dest;
10018 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10019 Register srcOut = MRI.createVirtualRegister(TRC);
10020 Register destOut = MRI.createVirtualRegister(TRC);
10021 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10022 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10023 IsThumb1, IsThumb2);
10024 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10025 IsThumb1, IsThumb2);
10026 srcIn = srcOut;
10027 destIn = destOut;
10030 // Handle the leftover bytes with LDRB and STRB.
10031 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10032 // [destOut] = STRB_POST(scratch, destIn, 1)
10033 for (unsigned i = 0; i < BytesLeft; i++) {
10034 Register srcOut = MRI.createVirtualRegister(TRC);
10035 Register destOut = MRI.createVirtualRegister(TRC);
10036 Register scratch = MRI.createVirtualRegister(TRC);
10037 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10038 IsThumb1, IsThumb2);
10039 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10040 IsThumb1, IsThumb2);
10041 srcIn = srcOut;
10042 destIn = destOut;
10044 MI.eraseFromParent(); // The instruction is gone now.
10045 return BB;
10048 // Expand the pseudo op to a loop.
10049 // thisMBB:
10050 // ...
10051 // movw varEnd, # --> with thumb2
10052 // movt varEnd, #
10053 // ldrcp varEnd, idx --> without thumb2
10054 // fallthrough --> loopMBB
10055 // loopMBB:
10056 // PHI varPhi, varEnd, varLoop
10057 // PHI srcPhi, src, srcLoop
10058 // PHI destPhi, dst, destLoop
10059 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10060 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10061 // subs varLoop, varPhi, #UnitSize
10062 // bne loopMBB
10063 // fallthrough --> exitMBB
10064 // exitMBB:
10065 // epilogue to handle left-over bytes
10066 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10067 // [destOut] = STRB_POST(scratch, destLoop, 1)
10068 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10069 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10070 MF->insert(It, loopMBB);
10071 MF->insert(It, exitMBB);
10073 // Transfer the remainder of BB and its successor edges to exitMBB.
10074 exitMBB->splice(exitMBB->begin(), BB,
10075 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10076 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10078 // Load an immediate to varEnd.
10079 Register varEnd = MRI.createVirtualRegister(TRC);
10080 if (Subtarget->useMovt()) {
10081 unsigned Vtmp = varEnd;
10082 if ((LoopSize & 0xFFFF0000) != 0)
10083 Vtmp = MRI.createVirtualRegister(TRC);
10084 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10085 .addImm(LoopSize & 0xFFFF)
10086 .add(predOps(ARMCC::AL));
10088 if ((LoopSize & 0xFFFF0000) != 0)
10089 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10090 .addReg(Vtmp)
10091 .addImm(LoopSize >> 16)
10092 .add(predOps(ARMCC::AL));
10093 } else {
10094 MachineConstantPool *ConstantPool = MF->getConstantPool();
10095 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10096 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10098 // MachineConstantPool wants an explicit alignment.
10099 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
10100 if (Align == 0)
10101 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
10102 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
10103 MachineMemOperand *CPMMO =
10104 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10105 MachineMemOperand::MOLoad, 4, 4);
10107 if (IsThumb)
10108 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10109 .addReg(varEnd, RegState::Define)
10110 .addConstantPoolIndex(Idx)
10111 .add(predOps(ARMCC::AL))
10112 .addMemOperand(CPMMO);
10113 else
10114 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10115 .addReg(varEnd, RegState::Define)
10116 .addConstantPoolIndex(Idx)
10117 .addImm(0)
10118 .add(predOps(ARMCC::AL))
10119 .addMemOperand(CPMMO);
10121 BB->addSuccessor(loopMBB);
10123 // Generate the loop body:
10124 // varPhi = PHI(varLoop, varEnd)
10125 // srcPhi = PHI(srcLoop, src)
10126 // destPhi = PHI(destLoop, dst)
10127 MachineBasicBlock *entryBB = BB;
10128 BB = loopMBB;
10129 Register varLoop = MRI.createVirtualRegister(TRC);
10130 Register varPhi = MRI.createVirtualRegister(TRC);
10131 Register srcLoop = MRI.createVirtualRegister(TRC);
10132 Register srcPhi = MRI.createVirtualRegister(TRC);
10133 Register destLoop = MRI.createVirtualRegister(TRC);
10134 Register destPhi = MRI.createVirtualRegister(TRC);
10136 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10137 .addReg(varLoop).addMBB(loopMBB)
10138 .addReg(varEnd).addMBB(entryBB);
10139 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10140 .addReg(srcLoop).addMBB(loopMBB)
10141 .addReg(src).addMBB(entryBB);
10142 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10143 .addReg(destLoop).addMBB(loopMBB)
10144 .addReg(dest).addMBB(entryBB);
10146 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10147 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10148 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10149 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10150 IsThumb1, IsThumb2);
10151 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10152 IsThumb1, IsThumb2);
10154 // Decrement loop variable by UnitSize.
10155 if (IsThumb1) {
10156 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10157 .add(t1CondCodeOp())
10158 .addReg(varPhi)
10159 .addImm(UnitSize)
10160 .add(predOps(ARMCC::AL));
10161 } else {
10162 MachineInstrBuilder MIB =
10163 BuildMI(*BB, BB->end(), dl,
10164 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10165 MIB.addReg(varPhi)
10166 .addImm(UnitSize)
10167 .add(predOps(ARMCC::AL))
10168 .add(condCodeOp());
10169 MIB->getOperand(5).setReg(ARM::CPSR);
10170 MIB->getOperand(5).setIsDef(true);
10172 BuildMI(*BB, BB->end(), dl,
10173 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10174 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10176 // loopMBB can loop back to loopMBB or fall through to exitMBB.
10177 BB->addSuccessor(loopMBB);
10178 BB->addSuccessor(exitMBB);
10180 // Add epilogue to handle BytesLeft.
10181 BB = exitMBB;
10182 auto StartOfExit = exitMBB->begin();
10184 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10185 // [destOut] = STRB_POST(scratch, destLoop, 1)
10186 unsigned srcIn = srcLoop;
10187 unsigned destIn = destLoop;
10188 for (unsigned i = 0; i < BytesLeft; i++) {
10189 Register srcOut = MRI.createVirtualRegister(TRC);
10190 Register destOut = MRI.createVirtualRegister(TRC);
10191 Register scratch = MRI.createVirtualRegister(TRC);
10192 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10193 IsThumb1, IsThumb2);
10194 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10195 IsThumb1, IsThumb2);
10196 srcIn = srcOut;
10197 destIn = destOut;
10200 MI.eraseFromParent(); // The instruction is gone now.
10201 return BB;
10204 MachineBasicBlock *
10205 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10206 MachineBasicBlock *MBB) const {
10207 const TargetMachine &TM = getTargetMachine();
10208 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10209 DebugLoc DL = MI.getDebugLoc();
10211 assert(Subtarget->isTargetWindows() &&
10212 "__chkstk is only supported on Windows");
10213 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10215 // __chkstk takes the number of words to allocate on the stack in R4, and
10216 // returns the stack adjustment in number of bytes in R4. This will not
10217 // clober any other registers (other than the obvious lr).
10219 // Although, technically, IP should be considered a register which may be
10220 // clobbered, the call itself will not touch it. Windows on ARM is a pure
10221 // thumb-2 environment, so there is no interworking required. As a result, we
10222 // do not expect a veneer to be emitted by the linker, clobbering IP.
10224 // Each module receives its own copy of __chkstk, so no import thunk is
10225 // required, again, ensuring that IP is not clobbered.
10227 // Finally, although some linkers may theoretically provide a trampoline for
10228 // out of range calls (which is quite common due to a 32M range limitation of
10229 // branches for Thumb), we can generate the long-call version via
10230 // -mcmodel=large, alleviating the need for the trampoline which may clobber
10231 // IP.
10233 switch (TM.getCodeModel()) {
10234 case CodeModel::Tiny:
10235 llvm_unreachable("Tiny code model not available on ARM.");
10236 case CodeModel::Small:
10237 case CodeModel::Medium:
10238 case CodeModel::Kernel:
10239 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10240 .add(predOps(ARMCC::AL))
10241 .addExternalSymbol("__chkstk")
10242 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10243 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10244 .addReg(ARM::R12,
10245 RegState::Implicit | RegState::Define | RegState::Dead)
10246 .addReg(ARM::CPSR,
10247 RegState::Implicit | RegState::Define | RegState::Dead);
10248 break;
10249 case CodeModel::Large: {
10250 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10251 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10253 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10254 .addExternalSymbol("__chkstk");
10255 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10256 .add(predOps(ARMCC::AL))
10257 .addReg(Reg, RegState::Kill)
10258 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10259 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10260 .addReg(ARM::R12,
10261 RegState::Implicit | RegState::Define | RegState::Dead)
10262 .addReg(ARM::CPSR,
10263 RegState::Implicit | RegState::Define | RegState::Dead);
10264 break;
10268 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10269 .addReg(ARM::SP, RegState::Kill)
10270 .addReg(ARM::R4, RegState::Kill)
10271 .setMIFlags(MachineInstr::FrameSetup)
10272 .add(predOps(ARMCC::AL))
10273 .add(condCodeOp());
10275 MI.eraseFromParent();
10276 return MBB;
10279 MachineBasicBlock *
10280 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10281 MachineBasicBlock *MBB) const {
10282 DebugLoc DL = MI.getDebugLoc();
10283 MachineFunction *MF = MBB->getParent();
10284 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10286 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10287 MF->insert(++MBB->getIterator(), ContBB);
10288 ContBB->splice(ContBB->begin(), MBB,
10289 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10290 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10291 MBB->addSuccessor(ContBB);
10293 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10294 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10295 MF->push_back(TrapBB);
10296 MBB->addSuccessor(TrapBB);
10298 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10299 .addReg(MI.getOperand(0).getReg())
10300 .addImm(0)
10301 .add(predOps(ARMCC::AL));
10302 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10303 .addMBB(TrapBB)
10304 .addImm(ARMCC::EQ)
10305 .addReg(ARM::CPSR);
10307 MI.eraseFromParent();
10308 return ContBB;
10311 // The CPSR operand of SelectItr might be missing a kill marker
10312 // because there were multiple uses of CPSR, and ISel didn't know
10313 // which to mark. Figure out whether SelectItr should have had a
10314 // kill marker, and set it if it should. Returns the correct kill
10315 // marker value.
10316 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10317 MachineBasicBlock* BB,
10318 const TargetRegisterInfo* TRI) {
10319 // Scan forward through BB for a use/def of CPSR.
10320 MachineBasicBlock::iterator miI(std::next(SelectItr));
10321 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10322 const MachineInstr& mi = *miI;
10323 if (mi.readsRegister(ARM::CPSR))
10324 return false;
10325 if (mi.definesRegister(ARM::CPSR))
10326 break; // Should have kill-flag - update below.
10329 // If we hit the end of the block, check whether CPSR is live into a
10330 // successor.
10331 if (miI == BB->end()) {
10332 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10333 sEnd = BB->succ_end();
10334 sItr != sEnd; ++sItr) {
10335 MachineBasicBlock* succ = *sItr;
10336 if (succ->isLiveIn(ARM::CPSR))
10337 return false;
10341 // We found a def, or hit the end of the basic block and CPSR wasn't live
10342 // out. SelectMI should have a kill flag on CPSR.
10343 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10344 return true;
10347 MachineBasicBlock *
10348 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10349 MachineBasicBlock *BB) const {
10350 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10351 DebugLoc dl = MI.getDebugLoc();
10352 bool isThumb2 = Subtarget->isThumb2();
10353 switch (MI.getOpcode()) {
10354 default: {
10355 MI.print(errs());
10356 llvm_unreachable("Unexpected instr type to insert");
10359 // Thumb1 post-indexed loads are really just single-register LDMs.
10360 case ARM::tLDR_postidx: {
10361 MachineOperand Def(MI.getOperand(1));
10362 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10363 .add(Def) // Rn_wb
10364 .add(MI.getOperand(2)) // Rn
10365 .add(MI.getOperand(3)) // PredImm
10366 .add(MI.getOperand(4)) // PredReg
10367 .add(MI.getOperand(0)) // Rt
10368 .cloneMemRefs(MI);
10369 MI.eraseFromParent();
10370 return BB;
10373 // The Thumb2 pre-indexed stores have the same MI operands, they just
10374 // define them differently in the .td files from the isel patterns, so
10375 // they need pseudos.
10376 case ARM::t2STR_preidx:
10377 MI.setDesc(TII->get(ARM::t2STR_PRE));
10378 return BB;
10379 case ARM::t2STRB_preidx:
10380 MI.setDesc(TII->get(ARM::t2STRB_PRE));
10381 return BB;
10382 case ARM::t2STRH_preidx:
10383 MI.setDesc(TII->get(ARM::t2STRH_PRE));
10384 return BB;
10386 case ARM::STRi_preidx:
10387 case ARM::STRBi_preidx: {
10388 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10389 : ARM::STRB_PRE_IMM;
10390 // Decode the offset.
10391 unsigned Offset = MI.getOperand(4).getImm();
10392 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10393 Offset = ARM_AM::getAM2Offset(Offset);
10394 if (isSub)
10395 Offset = -Offset;
10397 MachineMemOperand *MMO = *MI.memoperands_begin();
10398 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10399 .add(MI.getOperand(0)) // Rn_wb
10400 .add(MI.getOperand(1)) // Rt
10401 .add(MI.getOperand(2)) // Rn
10402 .addImm(Offset) // offset (skip GPR==zero_reg)
10403 .add(MI.getOperand(5)) // pred
10404 .add(MI.getOperand(6))
10405 .addMemOperand(MMO);
10406 MI.eraseFromParent();
10407 return BB;
10409 case ARM::STRr_preidx:
10410 case ARM::STRBr_preidx:
10411 case ARM::STRH_preidx: {
10412 unsigned NewOpc;
10413 switch (MI.getOpcode()) {
10414 default: llvm_unreachable("unexpected opcode!");
10415 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10416 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10417 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10419 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10420 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10421 MIB.add(MI.getOperand(i));
10422 MI.eraseFromParent();
10423 return BB;
10426 case ARM::tMOVCCr_pseudo: {
10427 // To "insert" a SELECT_CC instruction, we actually have to insert the
10428 // diamond control-flow pattern. The incoming instruction knows the
10429 // destination vreg to set, the condition code register to branch on, the
10430 // true/false values to select between, and a branch opcode to use.
10431 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10432 MachineFunction::iterator It = ++BB->getIterator();
10434 // thisMBB:
10435 // ...
10436 // TrueVal = ...
10437 // cmpTY ccX, r1, r2
10438 // bCC copy1MBB
10439 // fallthrough --> copy0MBB
10440 MachineBasicBlock *thisMBB = BB;
10441 MachineFunction *F = BB->getParent();
10442 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10443 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10444 F->insert(It, copy0MBB);
10445 F->insert(It, sinkMBB);
10447 // Check whether CPSR is live past the tMOVCCr_pseudo.
10448 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10449 if (!MI.killsRegister(ARM::CPSR) &&
10450 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10451 copy0MBB->addLiveIn(ARM::CPSR);
10452 sinkMBB->addLiveIn(ARM::CPSR);
10455 // Transfer the remainder of BB and its successor edges to sinkMBB.
10456 sinkMBB->splice(sinkMBB->begin(), BB,
10457 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10458 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10460 BB->addSuccessor(copy0MBB);
10461 BB->addSuccessor(sinkMBB);
10463 BuildMI(BB, dl, TII->get(ARM::tBcc))
10464 .addMBB(sinkMBB)
10465 .addImm(MI.getOperand(3).getImm())
10466 .addReg(MI.getOperand(4).getReg());
10468 // copy0MBB:
10469 // %FalseValue = ...
10470 // # fallthrough to sinkMBB
10471 BB = copy0MBB;
10473 // Update machine-CFG edges
10474 BB->addSuccessor(sinkMBB);
10476 // sinkMBB:
10477 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10478 // ...
10479 BB = sinkMBB;
10480 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10481 .addReg(MI.getOperand(1).getReg())
10482 .addMBB(copy0MBB)
10483 .addReg(MI.getOperand(2).getReg())
10484 .addMBB(thisMBB);
10486 MI.eraseFromParent(); // The pseudo instruction is gone now.
10487 return BB;
10490 case ARM::BCCi64:
10491 case ARM::BCCZi64: {
10492 // If there is an unconditional branch to the other successor, remove it.
10493 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10495 // Compare both parts that make up the double comparison separately for
10496 // equality.
10497 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10499 Register LHS1 = MI.getOperand(1).getReg();
10500 Register LHS2 = MI.getOperand(2).getReg();
10501 if (RHSisZero) {
10502 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10503 .addReg(LHS1)
10504 .addImm(0)
10505 .add(predOps(ARMCC::AL));
10506 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10507 .addReg(LHS2).addImm(0)
10508 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10509 } else {
10510 Register RHS1 = MI.getOperand(3).getReg();
10511 Register RHS2 = MI.getOperand(4).getReg();
10512 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10513 .addReg(LHS1)
10514 .addReg(RHS1)
10515 .add(predOps(ARMCC::AL));
10516 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10517 .addReg(LHS2).addReg(RHS2)
10518 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10521 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10522 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10523 if (MI.getOperand(0).getImm() == ARMCC::NE)
10524 std::swap(destMBB, exitMBB);
10526 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10527 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10528 if (isThumb2)
10529 BuildMI(BB, dl, TII->get(ARM::t2B))
10530 .addMBB(exitMBB)
10531 .add(predOps(ARMCC::AL));
10532 else
10533 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10535 MI.eraseFromParent(); // The pseudo instruction is gone now.
10536 return BB;
10539 case ARM::Int_eh_sjlj_setjmp:
10540 case ARM::Int_eh_sjlj_setjmp_nofp:
10541 case ARM::tInt_eh_sjlj_setjmp:
10542 case ARM::t2Int_eh_sjlj_setjmp:
10543 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10544 return BB;
10546 case ARM::Int_eh_sjlj_setup_dispatch:
10547 EmitSjLjDispatchBlock(MI, BB);
10548 return BB;
10550 case ARM::ABS:
10551 case ARM::t2ABS: {
10552 // To insert an ABS instruction, we have to insert the
10553 // diamond control-flow pattern. The incoming instruction knows the
10554 // source vreg to test against 0, the destination vreg to set,
10555 // the condition code register to branch on, the
10556 // true/false values to select between, and a branch opcode to use.
10557 // It transforms
10558 // V1 = ABS V0
10559 // into
10560 // V2 = MOVS V0
10561 // BCC (branch to SinkBB if V0 >= 0)
10562 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10563 // SinkBB: V1 = PHI(V2, V3)
10564 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10565 MachineFunction::iterator BBI = ++BB->getIterator();
10566 MachineFunction *Fn = BB->getParent();
10567 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10568 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10569 Fn->insert(BBI, RSBBB);
10570 Fn->insert(BBI, SinkBB);
10572 Register ABSSrcReg = MI.getOperand(1).getReg();
10573 Register ABSDstReg = MI.getOperand(0).getReg();
10574 bool ABSSrcKIll = MI.getOperand(1).isKill();
10575 bool isThumb2 = Subtarget->isThumb2();
10576 MachineRegisterInfo &MRI = Fn->getRegInfo();
10577 // In Thumb mode S must not be specified if source register is the SP or
10578 // PC and if destination register is the SP, so restrict register class
10579 Register NewRsbDstReg = MRI.createVirtualRegister(
10580 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10582 // Transfer the remainder of BB and its successor edges to sinkMBB.
10583 SinkBB->splice(SinkBB->begin(), BB,
10584 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10585 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10587 BB->addSuccessor(RSBBB);
10588 BB->addSuccessor(SinkBB);
10590 // fall through to SinkMBB
10591 RSBBB->addSuccessor(SinkBB);
10593 // insert a cmp at the end of BB
10594 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10595 .addReg(ABSSrcReg)
10596 .addImm(0)
10597 .add(predOps(ARMCC::AL));
10599 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10600 BuildMI(BB, dl,
10601 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10602 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10604 // insert rsbri in RSBBB
10605 // Note: BCC and rsbri will be converted into predicated rsbmi
10606 // by if-conversion pass
10607 BuildMI(*RSBBB, RSBBB->begin(), dl,
10608 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10609 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10610 .addImm(0)
10611 .add(predOps(ARMCC::AL))
10612 .add(condCodeOp());
10614 // insert PHI in SinkBB,
10615 // reuse ABSDstReg to not change uses of ABS instruction
10616 BuildMI(*SinkBB, SinkBB->begin(), dl,
10617 TII->get(ARM::PHI), ABSDstReg)
10618 .addReg(NewRsbDstReg).addMBB(RSBBB)
10619 .addReg(ABSSrcReg).addMBB(BB);
10621 // remove ABS instruction
10622 MI.eraseFromParent();
10624 // return last added BB
10625 return SinkBB;
10627 case ARM::COPY_STRUCT_BYVAL_I32:
10628 ++NumLoopByVals;
10629 return EmitStructByval(MI, BB);
10630 case ARM::WIN__CHKSTK:
10631 return EmitLowered__chkstk(MI, BB);
10632 case ARM::WIN__DBZCHK:
10633 return EmitLowered__dbzchk(MI, BB);
10637 /// Attaches vregs to MEMCPY that it will use as scratch registers
10638 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10639 /// instead of as a custom inserter because we need the use list from the SDNode.
10640 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10641 MachineInstr &MI, const SDNode *Node) {
10642 bool isThumb1 = Subtarget->isThumb1Only();
10644 DebugLoc DL = MI.getDebugLoc();
10645 MachineFunction *MF = MI.getParent()->getParent();
10646 MachineRegisterInfo &MRI = MF->getRegInfo();
10647 MachineInstrBuilder MIB(*MF, MI);
10649 // If the new dst/src is unused mark it as dead.
10650 if (!Node->hasAnyUseOfValue(0)) {
10651 MI.getOperand(0).setIsDead(true);
10653 if (!Node->hasAnyUseOfValue(1)) {
10654 MI.getOperand(1).setIsDead(true);
10657 // The MEMCPY both defines and kills the scratch registers.
10658 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10659 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10660 : &ARM::GPRRegClass);
10661 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10665 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10666 SDNode *Node) const {
10667 if (MI.getOpcode() == ARM::MEMCPY) {
10668 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10669 return;
10672 const MCInstrDesc *MCID = &MI.getDesc();
10673 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10674 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10675 // operand is still set to noreg. If needed, set the optional operand's
10676 // register to CPSR, and remove the redundant implicit def.
10678 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10680 // Rename pseudo opcodes.
10681 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10682 unsigned ccOutIdx;
10683 if (NewOpc) {
10684 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10685 MCID = &TII->get(NewOpc);
10687 assert(MCID->getNumOperands() ==
10688 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10689 && "converted opcode should be the same except for cc_out"
10690 " (and, on Thumb1, pred)");
10692 MI.setDesc(*MCID);
10694 // Add the optional cc_out operand
10695 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10697 // On Thumb1, move all input operands to the end, then add the predicate
10698 if (Subtarget->isThumb1Only()) {
10699 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10700 MI.addOperand(MI.getOperand(1));
10701 MI.RemoveOperand(1);
10704 // Restore the ties
10705 for (unsigned i = MI.getNumOperands(); i--;) {
10706 const MachineOperand& op = MI.getOperand(i);
10707 if (op.isReg() && op.isUse()) {
10708 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10709 if (DefIdx != -1)
10710 MI.tieOperands(DefIdx, i);
10714 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10715 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10716 ccOutIdx = 1;
10717 } else
10718 ccOutIdx = MCID->getNumOperands() - 1;
10719 } else
10720 ccOutIdx = MCID->getNumOperands() - 1;
10722 // Any ARM instruction that sets the 's' bit should specify an optional
10723 // "cc_out" operand in the last operand position.
10724 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10725 assert(!NewOpc && "Optional cc_out operand required");
10726 return;
10728 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10729 // since we already have an optional CPSR def.
10730 bool definesCPSR = false;
10731 bool deadCPSR = false;
10732 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10733 ++i) {
10734 const MachineOperand &MO = MI.getOperand(i);
10735 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10736 definesCPSR = true;
10737 if (MO.isDead())
10738 deadCPSR = true;
10739 MI.RemoveOperand(i);
10740 break;
10743 if (!definesCPSR) {
10744 assert(!NewOpc && "Optional cc_out operand required");
10745 return;
10747 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10748 if (deadCPSR) {
10749 assert(!MI.getOperand(ccOutIdx).getReg() &&
10750 "expect uninitialized optional cc_out operand");
10751 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10752 if (!Subtarget->isThumb1Only())
10753 return;
10756 // If this instruction was defined with an optional CPSR def and its dag node
10757 // had a live implicit CPSR def, then activate the optional CPSR def.
10758 MachineOperand &MO = MI.getOperand(ccOutIdx);
10759 MO.setReg(ARM::CPSR);
10760 MO.setIsDef(true);
10763 //===----------------------------------------------------------------------===//
10764 // ARM Optimization Hooks
10765 //===----------------------------------------------------------------------===//
10767 // Helper function that checks if N is a null or all ones constant.
10768 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10769 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10772 // Return true if N is conditionally 0 or all ones.
10773 // Detects these expressions where cc is an i1 value:
10775 // (select cc 0, y) [AllOnes=0]
10776 // (select cc y, 0) [AllOnes=0]
10777 // (zext cc) [AllOnes=0]
10778 // (sext cc) [AllOnes=0/1]
10779 // (select cc -1, y) [AllOnes=1]
10780 // (select cc y, -1) [AllOnes=1]
10782 // Invert is set when N is the null/all ones constant when CC is false.
10783 // OtherOp is set to the alternative value of N.
10784 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10785 SDValue &CC, bool &Invert,
10786 SDValue &OtherOp,
10787 SelectionDAG &DAG) {
10788 switch (N->getOpcode()) {
10789 default: return false;
10790 case ISD::SELECT: {
10791 CC = N->getOperand(0);
10792 SDValue N1 = N->getOperand(1);
10793 SDValue N2 = N->getOperand(2);
10794 if (isZeroOrAllOnes(N1, AllOnes)) {
10795 Invert = false;
10796 OtherOp = N2;
10797 return true;
10799 if (isZeroOrAllOnes(N2, AllOnes)) {
10800 Invert = true;
10801 OtherOp = N1;
10802 return true;
10804 return false;
10806 case ISD::ZERO_EXTEND:
10807 // (zext cc) can never be the all ones value.
10808 if (AllOnes)
10809 return false;
10810 LLVM_FALLTHROUGH;
10811 case ISD::SIGN_EXTEND: {
10812 SDLoc dl(N);
10813 EVT VT = N->getValueType(0);
10814 CC = N->getOperand(0);
10815 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10816 return false;
10817 Invert = !AllOnes;
10818 if (AllOnes)
10819 // When looking for an AllOnes constant, N is an sext, and the 'other'
10820 // value is 0.
10821 OtherOp = DAG.getConstant(0, dl, VT);
10822 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10823 // When looking for a 0 constant, N can be zext or sext.
10824 OtherOp = DAG.getConstant(1, dl, VT);
10825 else
10826 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10827 VT);
10828 return true;
10833 // Combine a constant select operand into its use:
10835 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10836 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10837 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10838 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10839 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10841 // The transform is rejected if the select doesn't have a constant operand that
10842 // is null, or all ones when AllOnes is set.
10844 // Also recognize sext/zext from i1:
10846 // (add (zext cc), x) -> (select cc (add x, 1), x)
10847 // (add (sext cc), x) -> (select cc (add x, -1), x)
10849 // These transformations eventually create predicated instructions.
10851 // @param N The node to transform.
10852 // @param Slct The N operand that is a select.
10853 // @param OtherOp The other N operand (x above).
10854 // @param DCI Context.
10855 // @param AllOnes Require the select constant to be all ones instead of null.
10856 // @returns The new node, or SDValue() on failure.
10857 static
10858 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10859 TargetLowering::DAGCombinerInfo &DCI,
10860 bool AllOnes = false) {
10861 SelectionDAG &DAG = DCI.DAG;
10862 EVT VT = N->getValueType(0);
10863 SDValue NonConstantVal;
10864 SDValue CCOp;
10865 bool SwapSelectOps;
10866 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10867 NonConstantVal, DAG))
10868 return SDValue();
10870 // Slct is now know to be the desired identity constant when CC is true.
10871 SDValue TrueVal = OtherOp;
10872 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10873 OtherOp, NonConstantVal);
10874 // Unless SwapSelectOps says CC should be false.
10875 if (SwapSelectOps)
10876 std::swap(TrueVal, FalseVal);
10878 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10879 CCOp, TrueVal, FalseVal);
10882 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10883 static
10884 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10885 TargetLowering::DAGCombinerInfo &DCI) {
10886 SDValue N0 = N->getOperand(0);
10887 SDValue N1 = N->getOperand(1);
10888 if (N0.getNode()->hasOneUse())
10889 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10890 return Result;
10891 if (N1.getNode()->hasOneUse())
10892 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10893 return Result;
10894 return SDValue();
10897 static bool IsVUZPShuffleNode(SDNode *N) {
10898 // VUZP shuffle node.
10899 if (N->getOpcode() == ARMISD::VUZP)
10900 return true;
10902 // "VUZP" on i32 is an alias for VTRN.
10903 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10904 return true;
10906 return false;
10909 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10910 TargetLowering::DAGCombinerInfo &DCI,
10911 const ARMSubtarget *Subtarget) {
10912 // Look for ADD(VUZP.0, VUZP.1).
10913 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10914 N0 == N1)
10915 return SDValue();
10917 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10918 if (!N->getValueType(0).is64BitVector())
10919 return SDValue();
10921 // Generate vpadd.
10922 SelectionDAG &DAG = DCI.DAG;
10923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10924 SDLoc dl(N);
10925 SDNode *Unzip = N0.getNode();
10926 EVT VT = N->getValueType(0);
10928 SmallVector<SDValue, 8> Ops;
10929 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10930 TLI.getPointerTy(DAG.getDataLayout())));
10931 Ops.push_back(Unzip->getOperand(0));
10932 Ops.push_back(Unzip->getOperand(1));
10934 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10937 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10938 TargetLowering::DAGCombinerInfo &DCI,
10939 const ARMSubtarget *Subtarget) {
10940 // Check for two extended operands.
10941 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10942 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10943 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10944 N1.getOpcode() == ISD::ZERO_EXTEND))
10945 return SDValue();
10947 SDValue N00 = N0.getOperand(0);
10948 SDValue N10 = N1.getOperand(0);
10950 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10951 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10952 N00 == N10)
10953 return SDValue();
10955 // We only recognize Q register paddl here; this can't be reached until
10956 // after type legalization.
10957 if (!N00.getValueType().is64BitVector() ||
10958 !N0.getValueType().is128BitVector())
10959 return SDValue();
10961 // Generate vpaddl.
10962 SelectionDAG &DAG = DCI.DAG;
10963 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10964 SDLoc dl(N);
10965 EVT VT = N->getValueType(0);
10967 SmallVector<SDValue, 8> Ops;
10968 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10969 unsigned Opcode;
10970 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10971 Opcode = Intrinsic::arm_neon_vpaddls;
10972 else
10973 Opcode = Intrinsic::arm_neon_vpaddlu;
10974 Ops.push_back(DAG.getConstant(Opcode, dl,
10975 TLI.getPointerTy(DAG.getDataLayout())));
10976 EVT ElemTy = N00.getValueType().getVectorElementType();
10977 unsigned NumElts = VT.getVectorNumElements();
10978 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10979 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10980 N00.getOperand(0), N00.getOperand(1));
10981 Ops.push_back(Concat);
10983 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10986 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10987 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10988 // much easier to match.
10989 static SDValue
10990 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10991 TargetLowering::DAGCombinerInfo &DCI,
10992 const ARMSubtarget *Subtarget) {
10993 // Only perform optimization if after legalize, and if NEON is available. We
10994 // also expected both operands to be BUILD_VECTORs.
10995 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10996 || N0.getOpcode() != ISD::BUILD_VECTOR
10997 || N1.getOpcode() != ISD::BUILD_VECTOR)
10998 return SDValue();
11000 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
11001 EVT VT = N->getValueType(0);
11002 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
11003 return SDValue();
11005 // Check that the vector operands are of the right form.
11006 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11007 // operands, where N is the size of the formed vector.
11008 // Each EXTRACT_VECTOR should have the same input vector and odd or even
11009 // index such that we have a pair wise add pattern.
11011 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11012 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11013 return SDValue();
11014 SDValue Vec = N0->getOperand(0)->getOperand(0);
11015 SDNode *V = Vec.getNode();
11016 unsigned nextIndex = 0;
11018 // For each operands to the ADD which are BUILD_VECTORs,
11019 // check to see if each of their operands are an EXTRACT_VECTOR with
11020 // the same vector and appropriate index.
11021 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11022 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11023 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11025 SDValue ExtVec0 = N0->getOperand(i);
11026 SDValue ExtVec1 = N1->getOperand(i);
11028 // First operand is the vector, verify its the same.
11029 if (V != ExtVec0->getOperand(0).getNode() ||
11030 V != ExtVec1->getOperand(0).getNode())
11031 return SDValue();
11033 // Second is the constant, verify its correct.
11034 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11035 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11037 // For the constant, we want to see all the even or all the odd.
11038 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11039 || C1->getZExtValue() != nextIndex+1)
11040 return SDValue();
11042 // Increment index.
11043 nextIndex+=2;
11044 } else
11045 return SDValue();
11048 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11049 // we're using the entire input vector, otherwise there's a size/legality
11050 // mismatch somewhere.
11051 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11052 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11053 return SDValue();
11055 // Create VPADDL node.
11056 SelectionDAG &DAG = DCI.DAG;
11057 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11059 SDLoc dl(N);
11061 // Build operand list.
11062 SmallVector<SDValue, 8> Ops;
11063 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11064 TLI.getPointerTy(DAG.getDataLayout())));
11066 // Input is the vector.
11067 Ops.push_back(Vec);
11069 // Get widened type and narrowed type.
11070 MVT widenType;
11071 unsigned numElem = VT.getVectorNumElements();
11073 EVT inputLaneType = Vec.getValueType().getVectorElementType();
11074 switch (inputLaneType.getSimpleVT().SimpleTy) {
11075 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11076 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11077 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11078 default:
11079 llvm_unreachable("Invalid vector element type for padd optimization.");
11082 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11083 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11084 return DAG.getNode(ExtOp, dl, VT, tmp);
11087 static SDValue findMUL_LOHI(SDValue V) {
11088 if (V->getOpcode() == ISD::UMUL_LOHI ||
11089 V->getOpcode() == ISD::SMUL_LOHI)
11090 return V;
11091 return SDValue();
11094 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11095 TargetLowering::DAGCombinerInfo &DCI,
11096 const ARMSubtarget *Subtarget) {
11097 if (!Subtarget->hasBaseDSP())
11098 return SDValue();
11100 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11101 // accumulates the product into a 64-bit value. The 16-bit values will
11102 // be sign extended somehow or SRA'd into 32-bit values
11103 // (addc (adde (mul 16bit, 16bit), lo), hi)
11104 SDValue Mul = AddcNode->getOperand(0);
11105 SDValue Lo = AddcNode->getOperand(1);
11106 if (Mul.getOpcode() != ISD::MUL) {
11107 Lo = AddcNode->getOperand(0);
11108 Mul = AddcNode->getOperand(1);
11109 if (Mul.getOpcode() != ISD::MUL)
11110 return SDValue();
11113 SDValue SRA = AddeNode->getOperand(0);
11114 SDValue Hi = AddeNode->getOperand(1);
11115 if (SRA.getOpcode() != ISD::SRA) {
11116 SRA = AddeNode->getOperand(1);
11117 Hi = AddeNode->getOperand(0);
11118 if (SRA.getOpcode() != ISD::SRA)
11119 return SDValue();
11121 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11122 if (Const->getZExtValue() != 31)
11123 return SDValue();
11124 } else
11125 return SDValue();
11127 if (SRA.getOperand(0) != Mul)
11128 return SDValue();
11130 SelectionDAG &DAG = DCI.DAG;
11131 SDLoc dl(AddcNode);
11132 unsigned Opcode = 0;
11133 SDValue Op0;
11134 SDValue Op1;
11136 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11137 Opcode = ARMISD::SMLALBB;
11138 Op0 = Mul.getOperand(0);
11139 Op1 = Mul.getOperand(1);
11140 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11141 Opcode = ARMISD::SMLALBT;
11142 Op0 = Mul.getOperand(0);
11143 Op1 = Mul.getOperand(1).getOperand(0);
11144 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11145 Opcode = ARMISD::SMLALTB;
11146 Op0 = Mul.getOperand(0).getOperand(0);
11147 Op1 = Mul.getOperand(1);
11148 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11149 Opcode = ARMISD::SMLALTT;
11150 Op0 = Mul->getOperand(0).getOperand(0);
11151 Op1 = Mul->getOperand(1).getOperand(0);
11154 if (!Op0 || !Op1)
11155 return SDValue();
11157 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11158 Op0, Op1, Lo, Hi);
11159 // Replace the ADDs' nodes uses by the MLA node's values.
11160 SDValue HiMLALResult(SMLAL.getNode(), 1);
11161 SDValue LoMLALResult(SMLAL.getNode(), 0);
11163 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11164 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11166 // Return original node to notify the driver to stop replacing.
11167 SDValue resNode(AddcNode, 0);
11168 return resNode;
11171 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11172 TargetLowering::DAGCombinerInfo &DCI,
11173 const ARMSubtarget *Subtarget) {
11174 // Look for multiply add opportunities.
11175 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11176 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11177 // a glue link from the first add to the second add.
11178 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11179 // a S/UMLAL instruction.
11180 // UMUL_LOHI
11181 // / :lo \ :hi
11182 // V \ [no multiline comment]
11183 // loAdd -> ADDC |
11184 // \ :carry /
11185 // V V
11186 // ADDE <- hiAdd
11188 // In the special case where only the higher part of a signed result is used
11189 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11190 // a constant with the exact value of 0x80000000, we recognize we are dealing
11191 // with a "rounded multiply and add" (or subtract) and transform it into
11192 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11194 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11195 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11196 "Expect an ADDE or SUBE");
11198 assert(AddeSubeNode->getNumOperands() == 3 &&
11199 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11200 "ADDE node has the wrong inputs");
11202 // Check that we are chained to the right ADDC or SUBC node.
11203 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11204 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11205 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11206 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11207 AddcSubcNode->getOpcode() != ARMISD::SUBC))
11208 return SDValue();
11210 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11211 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11213 // Check if the two operands are from the same mul_lohi node.
11214 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11215 return SDValue();
11217 assert(AddcSubcNode->getNumValues() == 2 &&
11218 AddcSubcNode->getValueType(0) == MVT::i32 &&
11219 "Expect ADDC with two result values. First: i32");
11221 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11222 // maybe a SMLAL which multiplies two 16-bit values.
11223 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11224 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11225 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11226 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11227 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11228 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11230 // Check for the triangle shape.
11231 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11232 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11234 // Make sure that the ADDE/SUBE operands are not coming from the same node.
11235 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11236 return SDValue();
11238 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11239 bool IsLeftOperandMUL = false;
11240 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11241 if (MULOp == SDValue())
11242 MULOp = findMUL_LOHI(AddeSubeOp1);
11243 else
11244 IsLeftOperandMUL = true;
11245 if (MULOp == SDValue())
11246 return SDValue();
11248 // Figure out the right opcode.
11249 unsigned Opc = MULOp->getOpcode();
11250 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11252 // Figure out the high and low input values to the MLAL node.
11253 SDValue *HiAddSub = nullptr;
11254 SDValue *LoMul = nullptr;
11255 SDValue *LowAddSub = nullptr;
11257 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11258 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11259 return SDValue();
11261 if (IsLeftOperandMUL)
11262 HiAddSub = &AddeSubeOp1;
11263 else
11264 HiAddSub = &AddeSubeOp0;
11266 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11267 // whose low result is fed to the ADDC/SUBC we are checking.
11269 if (AddcSubcOp0 == MULOp.getValue(0)) {
11270 LoMul = &AddcSubcOp0;
11271 LowAddSub = &AddcSubcOp1;
11273 if (AddcSubcOp1 == MULOp.getValue(0)) {
11274 LoMul = &AddcSubcOp1;
11275 LowAddSub = &AddcSubcOp0;
11278 if (!LoMul)
11279 return SDValue();
11281 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11282 // the replacement below will create a cycle.
11283 if (AddcSubcNode == HiAddSub->getNode() ||
11284 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11285 return SDValue();
11287 // Create the merged node.
11288 SelectionDAG &DAG = DCI.DAG;
11290 // Start building operand list.
11291 SmallVector<SDValue, 8> Ops;
11292 Ops.push_back(LoMul->getOperand(0));
11293 Ops.push_back(LoMul->getOperand(1));
11295 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
11296 // the case, we must be doing signed multiplication and only use the higher
11297 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11298 // addition or subtraction with the value of 0x800000.
11299 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11300 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11301 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11302 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11303 0x80000000) {
11304 Ops.push_back(*HiAddSub);
11305 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11306 FinalOpc = ARMISD::SMMLSR;
11307 } else {
11308 FinalOpc = ARMISD::SMMLAR;
11310 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11311 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11313 return SDValue(AddeSubeNode, 0);
11314 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11315 // SMMLS is generated during instruction selection and the rest of this
11316 // function can not handle the case where AddcSubcNode is a SUBC.
11317 return SDValue();
11319 // Finish building the operand list for {U/S}MLAL
11320 Ops.push_back(*LowAddSub);
11321 Ops.push_back(*HiAddSub);
11323 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11324 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11326 // Replace the ADDs' nodes uses by the MLA node's values.
11327 SDValue HiMLALResult(MLALNode.getNode(), 1);
11328 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11330 SDValue LoMLALResult(MLALNode.getNode(), 0);
11331 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11333 // Return original node to notify the driver to stop replacing.
11334 return SDValue(AddeSubeNode, 0);
11337 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11338 TargetLowering::DAGCombinerInfo &DCI,
11339 const ARMSubtarget *Subtarget) {
11340 // UMAAL is similar to UMLAL except that it adds two unsigned values.
11341 // While trying to combine for the other MLAL nodes, first search for the
11342 // chance to use UMAAL. Check if Addc uses a node which has already
11343 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11344 // as the addend, and it's handled in PerformUMLALCombine.
11346 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11347 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11349 // Check that we have a glued ADDC node.
11350 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11351 if (AddcNode->getOpcode() != ARMISD::ADDC)
11352 return SDValue();
11354 // Find the converted UMAAL or quit if it doesn't exist.
11355 SDNode *UmlalNode = nullptr;
11356 SDValue AddHi;
11357 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11358 UmlalNode = AddcNode->getOperand(0).getNode();
11359 AddHi = AddcNode->getOperand(1);
11360 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11361 UmlalNode = AddcNode->getOperand(1).getNode();
11362 AddHi = AddcNode->getOperand(0);
11363 } else {
11364 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11367 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11368 // the ADDC as well as Zero.
11369 if (!isNullConstant(UmlalNode->getOperand(3)))
11370 return SDValue();
11372 if ((isNullConstant(AddeNode->getOperand(0)) &&
11373 AddeNode->getOperand(1).getNode() == UmlalNode) ||
11374 (AddeNode->getOperand(0).getNode() == UmlalNode &&
11375 isNullConstant(AddeNode->getOperand(1)))) {
11376 SelectionDAG &DAG = DCI.DAG;
11377 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11378 UmlalNode->getOperand(2), AddHi };
11379 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11380 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11382 // Replace the ADDs' nodes uses by the UMAAL node's values.
11383 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11384 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11386 // Return original node to notify the driver to stop replacing.
11387 return SDValue(AddeNode, 0);
11389 return SDValue();
11392 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11393 const ARMSubtarget *Subtarget) {
11394 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11395 return SDValue();
11397 // Check that we have a pair of ADDC and ADDE as operands.
11398 // Both addends of the ADDE must be zero.
11399 SDNode* AddcNode = N->getOperand(2).getNode();
11400 SDNode* AddeNode = N->getOperand(3).getNode();
11401 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11402 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11403 isNullConstant(AddeNode->getOperand(0)) &&
11404 isNullConstant(AddeNode->getOperand(1)) &&
11405 (AddeNode->getOperand(2).getNode() == AddcNode))
11406 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11407 DAG.getVTList(MVT::i32, MVT::i32),
11408 {N->getOperand(0), N->getOperand(1),
11409 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11410 else
11411 return SDValue();
11414 static SDValue PerformAddcSubcCombine(SDNode *N,
11415 TargetLowering::DAGCombinerInfo &DCI,
11416 const ARMSubtarget *Subtarget) {
11417 SelectionDAG &DAG(DCI.DAG);
11419 if (N->getOpcode() == ARMISD::SUBC) {
11420 // (SUBC (ADDE 0, 0, C), 1) -> C
11421 SDValue LHS = N->getOperand(0);
11422 SDValue RHS = N->getOperand(1);
11423 if (LHS->getOpcode() == ARMISD::ADDE &&
11424 isNullConstant(LHS->getOperand(0)) &&
11425 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11426 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11430 if (Subtarget->isThumb1Only()) {
11431 SDValue RHS = N->getOperand(1);
11432 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11433 int32_t imm = C->getSExtValue();
11434 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11435 SDLoc DL(N);
11436 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11437 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11438 : ARMISD::ADDC;
11439 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11444 return SDValue();
11447 static SDValue PerformAddeSubeCombine(SDNode *N,
11448 TargetLowering::DAGCombinerInfo &DCI,
11449 const ARMSubtarget *Subtarget) {
11450 if (Subtarget->isThumb1Only()) {
11451 SelectionDAG &DAG = DCI.DAG;
11452 SDValue RHS = N->getOperand(1);
11453 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11454 int64_t imm = C->getSExtValue();
11455 if (imm < 0) {
11456 SDLoc DL(N);
11458 // The with-carry-in form matches bitwise not instead of the negation.
11459 // Effectively, the inverse interpretation of the carry flag already
11460 // accounts for part of the negation.
11461 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11463 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11464 : ARMISD::ADDE;
11465 return DAG.getNode(Opcode, DL, N->getVTList(),
11466 N->getOperand(0), RHS, N->getOperand(2));
11469 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11470 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11472 return SDValue();
11475 static SDValue PerformABSCombine(SDNode *N,
11476 TargetLowering::DAGCombinerInfo &DCI,
11477 const ARMSubtarget *Subtarget) {
11478 SDValue res;
11479 SelectionDAG &DAG = DCI.DAG;
11480 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11482 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11483 return SDValue();
11485 if (!TLI.expandABS(N, res, DAG))
11486 return SDValue();
11488 return res;
11491 /// PerformADDECombine - Target-specific dag combine transform from
11492 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11493 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11494 static SDValue PerformADDECombine(SDNode *N,
11495 TargetLowering::DAGCombinerInfo &DCI,
11496 const ARMSubtarget *Subtarget) {
11497 // Only ARM and Thumb2 support UMLAL/SMLAL.
11498 if (Subtarget->isThumb1Only())
11499 return PerformAddeSubeCombine(N, DCI, Subtarget);
11501 // Only perform the checks after legalize when the pattern is available.
11502 if (DCI.isBeforeLegalize()) return SDValue();
11504 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11507 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11508 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11509 /// called with the default operands, and if that fails, with commuted
11510 /// operands.
11511 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11512 TargetLowering::DAGCombinerInfo &DCI,
11513 const ARMSubtarget *Subtarget){
11514 // Attempt to create vpadd for this add.
11515 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11516 return Result;
11518 // Attempt to create vpaddl for this add.
11519 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11520 return Result;
11521 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11522 Subtarget))
11523 return Result;
11525 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11526 if (N0.getNode()->hasOneUse())
11527 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11528 return Result;
11529 return SDValue();
11532 bool
11533 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11534 CombineLevel Level) const {
11535 if (Level == BeforeLegalizeTypes)
11536 return true;
11538 if (N->getOpcode() != ISD::SHL)
11539 return true;
11541 if (Subtarget->isThumb1Only()) {
11542 // Avoid making expensive immediates by commuting shifts. (This logic
11543 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11544 // for free.)
11545 if (N->getOpcode() != ISD::SHL)
11546 return true;
11547 SDValue N1 = N->getOperand(0);
11548 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11549 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11550 return true;
11551 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11552 if (Const->getAPIntValue().ult(256))
11553 return false;
11554 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11555 Const->getAPIntValue().sgt(-256))
11556 return false;
11558 return true;
11561 // Turn off commute-with-shift transform after legalization, so it doesn't
11562 // conflict with PerformSHLSimplify. (We could try to detect when
11563 // PerformSHLSimplify would trigger more precisely, but it isn't
11564 // really necessary.)
11565 return false;
11568 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11569 const SDNode *N, CombineLevel Level) const {
11570 if (!Subtarget->isThumb1Only())
11571 return true;
11573 if (Level == BeforeLegalizeTypes)
11574 return true;
11576 return false;
11579 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11580 if (!Subtarget->hasNEON()) {
11581 if (Subtarget->isThumb1Only())
11582 return VT.getScalarSizeInBits() <= 32;
11583 return true;
11585 return VT.isScalarInteger();
11588 static SDValue PerformSHLSimplify(SDNode *N,
11589 TargetLowering::DAGCombinerInfo &DCI,
11590 const ARMSubtarget *ST) {
11591 // Allow the generic combiner to identify potential bswaps.
11592 if (DCI.isBeforeLegalize())
11593 return SDValue();
11595 // DAG combiner will fold:
11596 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11597 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11598 // Other code patterns that can be also be modified have the following form:
11599 // b + ((a << 1) | 510)
11600 // b + ((a << 1) & 510)
11601 // b + ((a << 1) ^ 510)
11602 // b + ((a << 1) + 510)
11604 // Many instructions can perform the shift for free, but it requires both
11605 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11606 // instruction will needed. So, unfold back to the original pattern if:
11607 // - if c1 and c2 are small enough that they don't require mov imms.
11608 // - the user(s) of the node can perform an shl
11610 // No shifted operands for 16-bit instructions.
11611 if (ST->isThumb() && ST->isThumb1Only())
11612 return SDValue();
11614 // Check that all the users could perform the shl themselves.
11615 for (auto U : N->uses()) {
11616 switch(U->getOpcode()) {
11617 default:
11618 return SDValue();
11619 case ISD::SUB:
11620 case ISD::ADD:
11621 case ISD::AND:
11622 case ISD::OR:
11623 case ISD::XOR:
11624 case ISD::SETCC:
11625 case ARMISD::CMP:
11626 // Check that the user isn't already using a constant because there
11627 // aren't any instructions that support an immediate operand and a
11628 // shifted operand.
11629 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11630 isa<ConstantSDNode>(U->getOperand(1)))
11631 return SDValue();
11633 // Check that it's not already using a shift.
11634 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11635 U->getOperand(1).getOpcode() == ISD::SHL)
11636 return SDValue();
11637 break;
11641 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11642 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11643 return SDValue();
11645 if (N->getOperand(0).getOpcode() != ISD::SHL)
11646 return SDValue();
11648 SDValue SHL = N->getOperand(0);
11650 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11651 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11652 if (!C1ShlC2 || !C2)
11653 return SDValue();
11655 APInt C2Int = C2->getAPIntValue();
11656 APInt C1Int = C1ShlC2->getAPIntValue();
11658 // Check that performing a lshr will not lose any information.
11659 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11660 C2Int.getBitWidth() - C2->getZExtValue());
11661 if ((C1Int & Mask) != C1Int)
11662 return SDValue();
11664 // Shift the first constant.
11665 C1Int.lshrInPlace(C2Int);
11667 // The immediates are encoded as an 8-bit value that can be rotated.
11668 auto LargeImm = [](const APInt &Imm) {
11669 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11670 return Imm.getBitWidth() - Zeros > 8;
11673 if (LargeImm(C1Int) || LargeImm(C2Int))
11674 return SDValue();
11676 SelectionDAG &DAG = DCI.DAG;
11677 SDLoc dl(N);
11678 SDValue X = SHL.getOperand(0);
11679 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11680 DAG.getConstant(C1Int, dl, MVT::i32));
11681 // Shift left to compensate for the lshr of C1Int.
11682 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11684 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11685 SHL.dump(); N->dump());
11686 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11687 return Res;
11691 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11693 static SDValue PerformADDCombine(SDNode *N,
11694 TargetLowering::DAGCombinerInfo &DCI,
11695 const ARMSubtarget *Subtarget) {
11696 SDValue N0 = N->getOperand(0);
11697 SDValue N1 = N->getOperand(1);
11699 // Only works one way, because it needs an immediate operand.
11700 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11701 return Result;
11703 // First try with the default operand order.
11704 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11705 return Result;
11707 // If that didn't work, try again with the operands commuted.
11708 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11711 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11713 static SDValue PerformSUBCombine(SDNode *N,
11714 TargetLowering::DAGCombinerInfo &DCI) {
11715 SDValue N0 = N->getOperand(0);
11716 SDValue N1 = N->getOperand(1);
11718 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11719 if (N1.getNode()->hasOneUse())
11720 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11721 return Result;
11723 return SDValue();
11726 /// PerformVMULCombine
11727 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11728 /// special multiplier accumulator forwarding.
11729 /// vmul d3, d0, d2
11730 /// vmla d3, d1, d2
11731 /// is faster than
11732 /// vadd d3, d0, d1
11733 /// vmul d3, d3, d2
11734 // However, for (A + B) * (A + B),
11735 // vadd d2, d0, d1
11736 // vmul d3, d0, d2
11737 // vmla d3, d1, d2
11738 // is slower than
11739 // vadd d2, d0, d1
11740 // vmul d3, d2, d2
11741 static SDValue PerformVMULCombine(SDNode *N,
11742 TargetLowering::DAGCombinerInfo &DCI,
11743 const ARMSubtarget *Subtarget) {
11744 if (!Subtarget->hasVMLxForwarding())
11745 return SDValue();
11747 SelectionDAG &DAG = DCI.DAG;
11748 SDValue N0 = N->getOperand(0);
11749 SDValue N1 = N->getOperand(1);
11750 unsigned Opcode = N0.getOpcode();
11751 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11752 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11753 Opcode = N1.getOpcode();
11754 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11755 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11756 return SDValue();
11757 std::swap(N0, N1);
11760 if (N0 == N1)
11761 return SDValue();
11763 EVT VT = N->getValueType(0);
11764 SDLoc DL(N);
11765 SDValue N00 = N0->getOperand(0);
11766 SDValue N01 = N0->getOperand(1);
11767 return DAG.getNode(Opcode, DL, VT,
11768 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11769 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11772 static SDValue PerformMULCombine(SDNode *N,
11773 TargetLowering::DAGCombinerInfo &DCI,
11774 const ARMSubtarget *Subtarget) {
11775 SelectionDAG &DAG = DCI.DAG;
11777 if (Subtarget->isThumb1Only())
11778 return SDValue();
11780 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11781 return SDValue();
11783 EVT VT = N->getValueType(0);
11784 if (VT.is64BitVector() || VT.is128BitVector())
11785 return PerformVMULCombine(N, DCI, Subtarget);
11786 if (VT != MVT::i32)
11787 return SDValue();
11789 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11790 if (!C)
11791 return SDValue();
11793 int64_t MulAmt = C->getSExtValue();
11794 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11796 ShiftAmt = ShiftAmt & (32 - 1);
11797 SDValue V = N->getOperand(0);
11798 SDLoc DL(N);
11800 SDValue Res;
11801 MulAmt >>= ShiftAmt;
11803 if (MulAmt >= 0) {
11804 if (isPowerOf2_32(MulAmt - 1)) {
11805 // (mul x, 2^N + 1) => (add (shl x, N), x)
11806 Res = DAG.getNode(ISD::ADD, DL, VT,
11808 DAG.getNode(ISD::SHL, DL, VT,
11810 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11811 MVT::i32)));
11812 } else if (isPowerOf2_32(MulAmt + 1)) {
11813 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11814 Res = DAG.getNode(ISD::SUB, DL, VT,
11815 DAG.getNode(ISD::SHL, DL, VT,
11817 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11818 MVT::i32)),
11820 } else
11821 return SDValue();
11822 } else {
11823 uint64_t MulAmtAbs = -MulAmt;
11824 if (isPowerOf2_32(MulAmtAbs + 1)) {
11825 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11826 Res = DAG.getNode(ISD::SUB, DL, VT,
11828 DAG.getNode(ISD::SHL, DL, VT,
11830 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11831 MVT::i32)));
11832 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11833 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11834 Res = DAG.getNode(ISD::ADD, DL, VT,
11836 DAG.getNode(ISD::SHL, DL, VT,
11838 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11839 MVT::i32)));
11840 Res = DAG.getNode(ISD::SUB, DL, VT,
11841 DAG.getConstant(0, DL, MVT::i32), Res);
11842 } else
11843 return SDValue();
11846 if (ShiftAmt != 0)
11847 Res = DAG.getNode(ISD::SHL, DL, VT,
11848 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11850 // Do not add new nodes to DAG combiner worklist.
11851 DCI.CombineTo(N, Res, false);
11852 return SDValue();
11855 static SDValue CombineANDShift(SDNode *N,
11856 TargetLowering::DAGCombinerInfo &DCI,
11857 const ARMSubtarget *Subtarget) {
11858 // Allow DAGCombine to pattern-match before we touch the canonical form.
11859 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11860 return SDValue();
11862 if (N->getValueType(0) != MVT::i32)
11863 return SDValue();
11865 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11866 if (!N1C)
11867 return SDValue();
11869 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11870 // Don't transform uxtb/uxth.
11871 if (C1 == 255 || C1 == 65535)
11872 return SDValue();
11874 SDNode *N0 = N->getOperand(0).getNode();
11875 if (!N0->hasOneUse())
11876 return SDValue();
11878 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11879 return SDValue();
11881 bool LeftShift = N0->getOpcode() == ISD::SHL;
11883 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11884 if (!N01C)
11885 return SDValue();
11887 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11888 if (!C2 || C2 >= 32)
11889 return SDValue();
11891 // Clear irrelevant bits in the mask.
11892 if (LeftShift)
11893 C1 &= (-1U << C2);
11894 else
11895 C1 &= (-1U >> C2);
11897 SelectionDAG &DAG = DCI.DAG;
11898 SDLoc DL(N);
11900 // We have a pattern of the form "(and (shl x, c2) c1)" or
11901 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11902 // transform to a pair of shifts, to save materializing c1.
11904 // First pattern: right shift, then mask off leading bits.
11905 // FIXME: Use demanded bits?
11906 if (!LeftShift && isMask_32(C1)) {
11907 uint32_t C3 = countLeadingZeros(C1);
11908 if (C2 < C3) {
11909 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11910 DAG.getConstant(C3 - C2, DL, MVT::i32));
11911 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11912 DAG.getConstant(C3, DL, MVT::i32));
11916 // First pattern, reversed: left shift, then mask off trailing bits.
11917 if (LeftShift && isMask_32(~C1)) {
11918 uint32_t C3 = countTrailingZeros(C1);
11919 if (C2 < C3) {
11920 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11921 DAG.getConstant(C3 - C2, DL, MVT::i32));
11922 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11923 DAG.getConstant(C3, DL, MVT::i32));
11927 // Second pattern: left shift, then mask off leading bits.
11928 // FIXME: Use demanded bits?
11929 if (LeftShift && isShiftedMask_32(C1)) {
11930 uint32_t Trailing = countTrailingZeros(C1);
11931 uint32_t C3 = countLeadingZeros(C1);
11932 if (Trailing == C2 && C2 + C3 < 32) {
11933 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11934 DAG.getConstant(C2 + C3, DL, MVT::i32));
11935 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11936 DAG.getConstant(C3, DL, MVT::i32));
11940 // Second pattern, reversed: right shift, then mask off trailing bits.
11941 // FIXME: Handle other patterns of known/demanded bits.
11942 if (!LeftShift && isShiftedMask_32(C1)) {
11943 uint32_t Leading = countLeadingZeros(C1);
11944 uint32_t C3 = countTrailingZeros(C1);
11945 if (Leading == C2 && C2 + C3 < 32) {
11946 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11947 DAG.getConstant(C2 + C3, DL, MVT::i32));
11948 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11949 DAG.getConstant(C3, DL, MVT::i32));
11953 // FIXME: Transform "(and (shl x, c2) c1)" ->
11954 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11955 // c1.
11956 return SDValue();
11959 static SDValue PerformANDCombine(SDNode *N,
11960 TargetLowering::DAGCombinerInfo &DCI,
11961 const ARMSubtarget *Subtarget) {
11962 // Attempt to use immediate-form VBIC
11963 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11964 SDLoc dl(N);
11965 EVT VT = N->getValueType(0);
11966 SelectionDAG &DAG = DCI.DAG;
11968 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11969 return SDValue();
11971 APInt SplatBits, SplatUndef;
11972 unsigned SplatBitSize;
11973 bool HasAnyUndefs;
11974 if (BVN && Subtarget->hasNEON() &&
11975 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11976 if (SplatBitSize <= 64) {
11977 EVT VbicVT;
11978 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11979 SplatUndef.getZExtValue(), SplatBitSize,
11980 DAG, dl, VbicVT, VT.is128BitVector(),
11981 OtherModImm);
11982 if (Val.getNode()) {
11983 SDValue Input =
11984 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11985 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11986 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11991 if (!Subtarget->isThumb1Only()) {
11992 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11993 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11994 return Result;
11996 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11997 return Result;
12000 if (Subtarget->isThumb1Only())
12001 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
12002 return Result;
12004 return SDValue();
12007 // Try combining OR nodes to SMULWB, SMULWT.
12008 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
12009 TargetLowering::DAGCombinerInfo &DCI,
12010 const ARMSubtarget *Subtarget) {
12011 if (!Subtarget->hasV6Ops() ||
12012 (Subtarget->isThumb() &&
12013 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
12014 return SDValue();
12016 SDValue SRL = OR->getOperand(0);
12017 SDValue SHL = OR->getOperand(1);
12019 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
12020 SRL = OR->getOperand(1);
12021 SHL = OR->getOperand(0);
12023 if (!isSRL16(SRL) || !isSHL16(SHL))
12024 return SDValue();
12026 // The first operands to the shifts need to be the two results from the
12027 // same smul_lohi node.
12028 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
12029 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
12030 return SDValue();
12032 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
12033 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
12034 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
12035 return SDValue();
12037 // Now we have:
12038 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
12039 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
12040 // For SMUWB the 16-bit value will signed extended somehow.
12041 // For SMULWT only the SRA is required.
12042 // Check both sides of SMUL_LOHI
12043 SDValue OpS16 = SMULLOHI->getOperand(0);
12044 SDValue OpS32 = SMULLOHI->getOperand(1);
12046 SelectionDAG &DAG = DCI.DAG;
12047 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
12048 OpS16 = OpS32;
12049 OpS32 = SMULLOHI->getOperand(0);
12052 SDLoc dl(OR);
12053 unsigned Opcode = 0;
12054 if (isS16(OpS16, DAG))
12055 Opcode = ARMISD::SMULWB;
12056 else if (isSRA16(OpS16)) {
12057 Opcode = ARMISD::SMULWT;
12058 OpS16 = OpS16->getOperand(0);
12060 else
12061 return SDValue();
12063 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
12064 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
12065 return SDValue(OR, 0);
12068 static SDValue PerformORCombineToBFI(SDNode *N,
12069 TargetLowering::DAGCombinerInfo &DCI,
12070 const ARMSubtarget *Subtarget) {
12071 // BFI is only available on V6T2+
12072 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
12073 return SDValue();
12075 EVT VT = N->getValueType(0);
12076 SDValue N0 = N->getOperand(0);
12077 SDValue N1 = N->getOperand(1);
12078 SelectionDAG &DAG = DCI.DAG;
12079 SDLoc DL(N);
12080 // 1) or (and A, mask), val => ARMbfi A, val, mask
12081 // iff (val & mask) == val
12083 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12084 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
12085 // && mask == ~mask2
12086 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
12087 // && ~mask == mask2
12088 // (i.e., copy a bitfield value into another bitfield of the same width)
12090 if (VT != MVT::i32)
12091 return SDValue();
12093 SDValue N00 = N0.getOperand(0);
12095 // The value and the mask need to be constants so we can verify this is
12096 // actually a bitfield set. If the mask is 0xffff, we can do better
12097 // via a movt instruction, so don't use BFI in that case.
12098 SDValue MaskOp = N0.getOperand(1);
12099 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
12100 if (!MaskC)
12101 return SDValue();
12102 unsigned Mask = MaskC->getZExtValue();
12103 if (Mask == 0xffff)
12104 return SDValue();
12105 SDValue Res;
12106 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
12107 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12108 if (N1C) {
12109 unsigned Val = N1C->getZExtValue();
12110 if ((Val & ~Mask) != Val)
12111 return SDValue();
12113 if (ARM::isBitFieldInvertedMask(Mask)) {
12114 Val >>= countTrailingZeros(~Mask);
12116 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
12117 DAG.getConstant(Val, DL, MVT::i32),
12118 DAG.getConstant(Mask, DL, MVT::i32));
12120 DCI.CombineTo(N, Res, false);
12121 // Return value from the original node to inform the combiner than N is
12122 // now dead.
12123 return SDValue(N, 0);
12125 } else if (N1.getOpcode() == ISD::AND) {
12126 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12127 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12128 if (!N11C)
12129 return SDValue();
12130 unsigned Mask2 = N11C->getZExtValue();
12132 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
12133 // as is to match.
12134 if (ARM::isBitFieldInvertedMask(Mask) &&
12135 (Mask == ~Mask2)) {
12136 // The pack halfword instruction works better for masks that fit it,
12137 // so use that when it's available.
12138 if (Subtarget->hasDSP() &&
12139 (Mask == 0xffff || Mask == 0xffff0000))
12140 return SDValue();
12141 // 2a
12142 unsigned amt = countTrailingZeros(Mask2);
12143 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
12144 DAG.getConstant(amt, DL, MVT::i32));
12145 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
12146 DAG.getConstant(Mask, DL, MVT::i32));
12147 DCI.CombineTo(N, Res, false);
12148 // Return value from the original node to inform the combiner than N is
12149 // now dead.
12150 return SDValue(N, 0);
12151 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
12152 (~Mask == Mask2)) {
12153 // The pack halfword instruction works better for masks that fit it,
12154 // so use that when it's available.
12155 if (Subtarget->hasDSP() &&
12156 (Mask2 == 0xffff || Mask2 == 0xffff0000))
12157 return SDValue();
12158 // 2b
12159 unsigned lsb = countTrailingZeros(Mask);
12160 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
12161 DAG.getConstant(lsb, DL, MVT::i32));
12162 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
12163 DAG.getConstant(Mask2, DL, MVT::i32));
12164 DCI.CombineTo(N, Res, false);
12165 // Return value from the original node to inform the combiner than N is
12166 // now dead.
12167 return SDValue(N, 0);
12171 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
12172 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
12173 ARM::isBitFieldInvertedMask(~Mask)) {
12174 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
12175 // where lsb(mask) == #shamt and masked bits of B are known zero.
12176 SDValue ShAmt = N00.getOperand(1);
12177 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
12178 unsigned LSB = countTrailingZeros(Mask);
12179 if (ShAmtC != LSB)
12180 return SDValue();
12182 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
12183 DAG.getConstant(~Mask, DL, MVT::i32));
12185 DCI.CombineTo(N, Res, false);
12186 // Return value from the original node to inform the combiner than N is
12187 // now dead.
12188 return SDValue(N, 0);
12191 return SDValue();
12194 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12195 switch (CC) {
12196 case ARMCC::EQ:
12197 case ARMCC::NE:
12198 case ARMCC::LE:
12199 case ARMCC::GT:
12200 case ARMCC::GE:
12201 case ARMCC::LT:
12202 return true;
12203 case ARMCC::HS:
12204 case ARMCC::HI:
12205 return !IsFloat;
12206 default:
12207 return false;
12211 static SDValue PerformORCombine_i1(SDNode *N,
12212 TargetLowering::DAGCombinerInfo &DCI,
12213 const ARMSubtarget *Subtarget) {
12214 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12215 // together with predicates
12216 EVT VT = N->getValueType(0);
12217 SDValue N0 = N->getOperand(0);
12218 SDValue N1 = N->getOperand(1);
12220 ARMCC::CondCodes CondCode0 = ARMCC::AL;
12221 ARMCC::CondCodes CondCode1 = ARMCC::AL;
12222 if (N0->getOpcode() == ARMISD::VCMP)
12223 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
12224 ->getZExtValue();
12225 else if (N0->getOpcode() == ARMISD::VCMPZ)
12226 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
12227 ->getZExtValue();
12228 if (N1->getOpcode() == ARMISD::VCMP)
12229 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
12230 ->getZExtValue();
12231 else if (N1->getOpcode() == ARMISD::VCMPZ)
12232 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
12233 ->getZExtValue();
12235 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
12236 return SDValue();
12238 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
12239 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
12241 if (!isValidMVECond(Opposite0,
12242 N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
12243 !isValidMVECond(Opposite1,
12244 N1->getOperand(0)->getValueType(0).isFloatingPoint()))
12245 return SDValue();
12247 SmallVector<SDValue, 4> Ops0;
12248 Ops0.push_back(N0->getOperand(0));
12249 if (N0->getOpcode() == ARMISD::VCMP)
12250 Ops0.push_back(N0->getOperand(1));
12251 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12252 SmallVector<SDValue, 4> Ops1;
12253 Ops1.push_back(N1->getOperand(0));
12254 if (N1->getOpcode() == ARMISD::VCMP)
12255 Ops1.push_back(N1->getOperand(1));
12256 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12258 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12259 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12260 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12261 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12262 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12265 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12266 static SDValue PerformORCombine(SDNode *N,
12267 TargetLowering::DAGCombinerInfo &DCI,
12268 const ARMSubtarget *Subtarget) {
12269 // Attempt to use immediate-form VORR
12270 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12271 SDLoc dl(N);
12272 EVT VT = N->getValueType(0);
12273 SelectionDAG &DAG = DCI.DAG;
12275 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12276 return SDValue();
12278 APInt SplatBits, SplatUndef;
12279 unsigned SplatBitSize;
12280 bool HasAnyUndefs;
12281 if (BVN && Subtarget->hasNEON() &&
12282 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12283 if (SplatBitSize <= 64) {
12284 EVT VorrVT;
12285 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
12286 SplatUndef.getZExtValue(), SplatBitSize,
12287 DAG, dl, VorrVT, VT.is128BitVector(),
12288 OtherModImm);
12289 if (Val.getNode()) {
12290 SDValue Input =
12291 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12292 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12293 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12298 if (!Subtarget->isThumb1Only()) {
12299 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12300 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12301 return Result;
12302 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12303 return Result;
12306 SDValue N0 = N->getOperand(0);
12307 SDValue N1 = N->getOperand(1);
12309 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12310 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12311 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12313 // The code below optimizes (or (and X, Y), Z).
12314 // The AND operand needs to have a single user to make these optimizations
12315 // profitable.
12316 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12317 return SDValue();
12319 APInt SplatUndef;
12320 unsigned SplatBitSize;
12321 bool HasAnyUndefs;
12323 APInt SplatBits0, SplatBits1;
12324 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12325 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12326 // Ensure that the second operand of both ands are constants
12327 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12328 HasAnyUndefs) && !HasAnyUndefs) {
12329 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12330 HasAnyUndefs) && !HasAnyUndefs) {
12331 // Ensure that the bit width of the constants are the same and that
12332 // the splat arguments are logical inverses as per the pattern we
12333 // are trying to simplify.
12334 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12335 SplatBits0 == ~SplatBits1) {
12336 // Canonicalize the vector type to make instruction selection
12337 // simpler.
12338 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12339 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12340 N0->getOperand(1),
12341 N0->getOperand(0),
12342 N1->getOperand(0));
12343 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12349 if (Subtarget->hasMVEIntegerOps() &&
12350 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12351 return PerformORCombine_i1(N, DCI, Subtarget);
12353 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12354 // reasonable.
12355 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12356 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12357 return Res;
12360 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12361 return Result;
12363 return SDValue();
12366 static SDValue PerformXORCombine(SDNode *N,
12367 TargetLowering::DAGCombinerInfo &DCI,
12368 const ARMSubtarget *Subtarget) {
12369 EVT VT = N->getValueType(0);
12370 SelectionDAG &DAG = DCI.DAG;
12372 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12373 return SDValue();
12375 if (!Subtarget->isThumb1Only()) {
12376 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12377 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12378 return Result;
12380 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12381 return Result;
12384 return SDValue();
12387 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12388 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12389 // their position in "to" (Rd).
12390 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12391 assert(N->getOpcode() == ARMISD::BFI);
12393 SDValue From = N->getOperand(1);
12394 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12395 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12397 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12398 // #C in the base of the SHR.
12399 if (From->getOpcode() == ISD::SRL &&
12400 isa<ConstantSDNode>(From->getOperand(1))) {
12401 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12402 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12403 FromMask <<= Shift.getLimitedValue(31);
12404 From = From->getOperand(0);
12407 return From;
12410 // If A and B contain one contiguous set of bits, does A | B == A . B?
12412 // Neither A nor B must be zero.
12413 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12414 unsigned LastActiveBitInA = A.countTrailingZeros();
12415 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12416 return LastActiveBitInA - 1 == FirstActiveBitInB;
12419 static SDValue FindBFIToCombineWith(SDNode *N) {
12420 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12421 // if one exists.
12422 APInt ToMask, FromMask;
12423 SDValue From = ParseBFI(N, ToMask, FromMask);
12424 SDValue To = N->getOperand(0);
12426 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12427 // aren't compatible, but not if they set the same bit in their destination as
12428 // we do (or that of any BFI we're going to combine with).
12429 SDValue V = To;
12430 APInt CombinedToMask = ToMask;
12431 while (V.getOpcode() == ARMISD::BFI) {
12432 APInt NewToMask, NewFromMask;
12433 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12434 if (NewFrom != From) {
12435 // This BFI has a different base. Keep going.
12436 CombinedToMask |= NewToMask;
12437 V = V.getOperand(0);
12438 continue;
12441 // Do the written bits conflict with any we've seen so far?
12442 if ((NewToMask & CombinedToMask).getBoolValue())
12443 // Conflicting bits - bail out because going further is unsafe.
12444 return SDValue();
12446 // Are the new bits contiguous when combined with the old bits?
12447 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12448 BitsProperlyConcatenate(FromMask, NewFromMask))
12449 return V;
12450 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12451 BitsProperlyConcatenate(NewFromMask, FromMask))
12452 return V;
12454 // We've seen a write to some bits, so track it.
12455 CombinedToMask |= NewToMask;
12456 // Keep going...
12457 V = V.getOperand(0);
12460 return SDValue();
12463 static SDValue PerformBFICombine(SDNode *N,
12464 TargetLowering::DAGCombinerInfo &DCI) {
12465 SDValue N1 = N->getOperand(1);
12466 if (N1.getOpcode() == ISD::AND) {
12467 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12468 // the bits being cleared by the AND are not demanded by the BFI.
12469 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12470 if (!N11C)
12471 return SDValue();
12472 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12473 unsigned LSB = countTrailingZeros(~InvMask);
12474 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12475 assert(Width <
12476 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12477 "undefined behavior");
12478 unsigned Mask = (1u << Width) - 1;
12479 unsigned Mask2 = N11C->getZExtValue();
12480 if ((Mask & (~Mask2)) == 0)
12481 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12482 N->getOperand(0), N1.getOperand(0),
12483 N->getOperand(2));
12484 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12485 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12486 // Keep track of any consecutive bits set that all come from the same base
12487 // value. We can combine these together into a single BFI.
12488 SDValue CombineBFI = FindBFIToCombineWith(N);
12489 if (CombineBFI == SDValue())
12490 return SDValue();
12492 // We've found a BFI.
12493 APInt ToMask1, FromMask1;
12494 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12496 APInt ToMask2, FromMask2;
12497 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12498 assert(From1 == From2);
12499 (void)From2;
12501 // First, unlink CombineBFI.
12502 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12503 // Then create a new BFI, combining the two together.
12504 APInt NewFromMask = FromMask1 | FromMask2;
12505 APInt NewToMask = ToMask1 | ToMask2;
12507 EVT VT = N->getValueType(0);
12508 SDLoc dl(N);
12510 if (NewFromMask[0] == 0)
12511 From1 = DCI.DAG.getNode(
12512 ISD::SRL, dl, VT, From1,
12513 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12514 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12515 DCI.DAG.getConstant(~NewToMask, dl, VT));
12517 return SDValue();
12520 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12521 /// ARMISD::VMOVRRD.
12522 static SDValue PerformVMOVRRDCombine(SDNode *N,
12523 TargetLowering::DAGCombinerInfo &DCI,
12524 const ARMSubtarget *Subtarget) {
12525 // vmovrrd(vmovdrr x, y) -> x,y
12526 SDValue InDouble = N->getOperand(0);
12527 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12528 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12530 // vmovrrd(load f64) -> (load i32), (load i32)
12531 SDNode *InNode = InDouble.getNode();
12532 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12533 InNode->getValueType(0) == MVT::f64 &&
12534 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12535 !cast<LoadSDNode>(InNode)->isVolatile()) {
12536 // TODO: Should this be done for non-FrameIndex operands?
12537 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12539 SelectionDAG &DAG = DCI.DAG;
12540 SDLoc DL(LD);
12541 SDValue BasePtr = LD->getBasePtr();
12542 SDValue NewLD1 =
12543 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12544 LD->getAlignment(), LD->getMemOperand()->getFlags());
12546 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12547 DAG.getConstant(4, DL, MVT::i32));
12549 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12550 LD->getPointerInfo().getWithOffset(4),
12551 std::min(4U, LD->getAlignment()),
12552 LD->getMemOperand()->getFlags());
12554 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12555 if (DCI.DAG.getDataLayout().isBigEndian())
12556 std::swap (NewLD1, NewLD2);
12557 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12558 return Result;
12561 return SDValue();
12564 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12565 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12566 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12567 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12568 SDValue Op0 = N->getOperand(0);
12569 SDValue Op1 = N->getOperand(1);
12570 if (Op0.getOpcode() == ISD::BITCAST)
12571 Op0 = Op0.getOperand(0);
12572 if (Op1.getOpcode() == ISD::BITCAST)
12573 Op1 = Op1.getOperand(0);
12574 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12575 Op0.getNode() == Op1.getNode() &&
12576 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12577 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12578 N->getValueType(0), Op0.getOperand(0));
12579 return SDValue();
12582 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12583 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12584 /// i64 vector to have f64 elements, since the value can then be loaded
12585 /// directly into a VFP register.
12586 static bool hasNormalLoadOperand(SDNode *N) {
12587 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12588 for (unsigned i = 0; i < NumElts; ++i) {
12589 SDNode *Elt = N->getOperand(i).getNode();
12590 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12591 return true;
12593 return false;
12596 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12597 /// ISD::BUILD_VECTOR.
12598 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12599 TargetLowering::DAGCombinerInfo &DCI,
12600 const ARMSubtarget *Subtarget) {
12601 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12602 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12603 // into a pair of GPRs, which is fine when the value is used as a scalar,
12604 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12605 SelectionDAG &DAG = DCI.DAG;
12606 if (N->getNumOperands() == 2)
12607 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12608 return RV;
12610 // Load i64 elements as f64 values so that type legalization does not split
12611 // them up into i32 values.
12612 EVT VT = N->getValueType(0);
12613 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12614 return SDValue();
12615 SDLoc dl(N);
12616 SmallVector<SDValue, 8> Ops;
12617 unsigned NumElts = VT.getVectorNumElements();
12618 for (unsigned i = 0; i < NumElts; ++i) {
12619 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12620 Ops.push_back(V);
12621 // Make the DAGCombiner fold the bitcast.
12622 DCI.AddToWorklist(V.getNode());
12624 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12625 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12626 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12629 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12630 static SDValue
12631 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12632 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12633 // At that time, we may have inserted bitcasts from integer to float.
12634 // If these bitcasts have survived DAGCombine, change the lowering of this
12635 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12636 // force to use floating point types.
12638 // Make sure we can change the type of the vector.
12639 // This is possible iff:
12640 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12641 // 1.1. Vector is used only once.
12642 // 1.2. Use is a bit convert to an integer type.
12643 // 2. The size of its operands are 32-bits (64-bits are not legal).
12644 EVT VT = N->getValueType(0);
12645 EVT EltVT = VT.getVectorElementType();
12647 // Check 1.1. and 2.
12648 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12649 return SDValue();
12651 // By construction, the input type must be float.
12652 assert(EltVT == MVT::f32 && "Unexpected type!");
12654 // Check 1.2.
12655 SDNode *Use = *N->use_begin();
12656 if (Use->getOpcode() != ISD::BITCAST ||
12657 Use->getValueType(0).isFloatingPoint())
12658 return SDValue();
12660 // Check profitability.
12661 // Model is, if more than half of the relevant operands are bitcast from
12662 // i32, turn the build_vector into a sequence of insert_vector_elt.
12663 // Relevant operands are everything that is not statically
12664 // (i.e., at compile time) bitcasted.
12665 unsigned NumOfBitCastedElts = 0;
12666 unsigned NumElts = VT.getVectorNumElements();
12667 unsigned NumOfRelevantElts = NumElts;
12668 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12669 SDValue Elt = N->getOperand(Idx);
12670 if (Elt->getOpcode() == ISD::BITCAST) {
12671 // Assume only bit cast to i32 will go away.
12672 if (Elt->getOperand(0).getValueType() == MVT::i32)
12673 ++NumOfBitCastedElts;
12674 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12675 // Constants are statically casted, thus do not count them as
12676 // relevant operands.
12677 --NumOfRelevantElts;
12680 // Check if more than half of the elements require a non-free bitcast.
12681 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12682 return SDValue();
12684 SelectionDAG &DAG = DCI.DAG;
12685 // Create the new vector type.
12686 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12687 // Check if the type is legal.
12688 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12689 if (!TLI.isTypeLegal(VecVT))
12690 return SDValue();
12692 // Combine:
12693 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12694 // => BITCAST INSERT_VECTOR_ELT
12695 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12696 // (BITCAST EN), N.
12697 SDValue Vec = DAG.getUNDEF(VecVT);
12698 SDLoc dl(N);
12699 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12700 SDValue V = N->getOperand(Idx);
12701 if (V.isUndef())
12702 continue;
12703 if (V.getOpcode() == ISD::BITCAST &&
12704 V->getOperand(0).getValueType() == MVT::i32)
12705 // Fold obvious case.
12706 V = V.getOperand(0);
12707 else {
12708 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12709 // Make the DAGCombiner fold the bitcasts.
12710 DCI.AddToWorklist(V.getNode());
12712 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12713 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12715 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12716 // Make the DAGCombiner fold the bitcasts.
12717 DCI.AddToWorklist(Vec.getNode());
12718 return Vec;
12721 static SDValue
12722 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12723 EVT VT = N->getValueType(0);
12724 SDValue Op = N->getOperand(0);
12725 SDLoc dl(N);
12727 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
12728 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
12729 // If the valuetypes are the same, we can remove the cast entirely.
12730 if (Op->getOperand(0).getValueType() == VT)
12731 return Op->getOperand(0);
12732 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl,
12733 Op->getOperand(0).getValueType(), Op->getOperand(0));
12736 return SDValue();
12739 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12740 /// ISD::INSERT_VECTOR_ELT.
12741 static SDValue PerformInsertEltCombine(SDNode *N,
12742 TargetLowering::DAGCombinerInfo &DCI) {
12743 // Bitcast an i64 load inserted into a vector to f64.
12744 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12745 EVT VT = N->getValueType(0);
12746 SDNode *Elt = N->getOperand(1).getNode();
12747 if (VT.getVectorElementType() != MVT::i64 ||
12748 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12749 return SDValue();
12751 SelectionDAG &DAG = DCI.DAG;
12752 SDLoc dl(N);
12753 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12754 VT.getVectorNumElements());
12755 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12756 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12757 // Make the DAGCombiner fold the bitcasts.
12758 DCI.AddToWorklist(Vec.getNode());
12759 DCI.AddToWorklist(V.getNode());
12760 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12761 Vec, V, N->getOperand(2));
12762 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12765 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12766 /// ISD::VECTOR_SHUFFLE.
12767 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12768 // The LLVM shufflevector instruction does not require the shuffle mask
12769 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12770 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12771 // operands do not match the mask length, they are extended by concatenating
12772 // them with undef vectors. That is probably the right thing for other
12773 // targets, but for NEON it is better to concatenate two double-register
12774 // size vector operands into a single quad-register size vector. Do that
12775 // transformation here:
12776 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12777 // shuffle(concat(v1, v2), undef)
12778 SDValue Op0 = N->getOperand(0);
12779 SDValue Op1 = N->getOperand(1);
12780 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12781 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12782 Op0.getNumOperands() != 2 ||
12783 Op1.getNumOperands() != 2)
12784 return SDValue();
12785 SDValue Concat0Op1 = Op0.getOperand(1);
12786 SDValue Concat1Op1 = Op1.getOperand(1);
12787 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12788 return SDValue();
12789 // Skip the transformation if any of the types are illegal.
12790 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12791 EVT VT = N->getValueType(0);
12792 if (!TLI.isTypeLegal(VT) ||
12793 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12794 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12795 return SDValue();
12797 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12798 Op0.getOperand(0), Op1.getOperand(0));
12799 // Translate the shuffle mask.
12800 SmallVector<int, 16> NewMask;
12801 unsigned NumElts = VT.getVectorNumElements();
12802 unsigned HalfElts = NumElts/2;
12803 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12804 for (unsigned n = 0; n < NumElts; ++n) {
12805 int MaskElt = SVN->getMaskElt(n);
12806 int NewElt = -1;
12807 if (MaskElt < (int)HalfElts)
12808 NewElt = MaskElt;
12809 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12810 NewElt = HalfElts + MaskElt - NumElts;
12811 NewMask.push_back(NewElt);
12813 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12814 DAG.getUNDEF(VT), NewMask);
12817 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12818 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12819 /// base address updates.
12820 /// For generic load/stores, the memory type is assumed to be a vector.
12821 /// The caller is assumed to have checked legality.
12822 static SDValue CombineBaseUpdate(SDNode *N,
12823 TargetLowering::DAGCombinerInfo &DCI) {
12824 SelectionDAG &DAG = DCI.DAG;
12825 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12826 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12827 const bool isStore = N->getOpcode() == ISD::STORE;
12828 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12829 SDValue Addr = N->getOperand(AddrOpIdx);
12830 MemSDNode *MemN = cast<MemSDNode>(N);
12831 SDLoc dl(N);
12833 // Search for a use of the address operand that is an increment.
12834 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12835 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12836 SDNode *User = *UI;
12837 if (User->getOpcode() != ISD::ADD ||
12838 UI.getUse().getResNo() != Addr.getResNo())
12839 continue;
12841 // Check that the add is independent of the load/store. Otherwise, folding
12842 // it would create a cycle. We can avoid searching through Addr as it's a
12843 // predecessor to both.
12844 SmallPtrSet<const SDNode *, 32> Visited;
12845 SmallVector<const SDNode *, 16> Worklist;
12846 Visited.insert(Addr.getNode());
12847 Worklist.push_back(N);
12848 Worklist.push_back(User);
12849 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12850 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12851 continue;
12853 // Find the new opcode for the updating load/store.
12854 bool isLoadOp = true;
12855 bool isLaneOp = false;
12856 unsigned NewOpc = 0;
12857 unsigned NumVecs = 0;
12858 if (isIntrinsic) {
12859 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12860 switch (IntNo) {
12861 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12862 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12863 NumVecs = 1; break;
12864 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12865 NumVecs = 2; break;
12866 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12867 NumVecs = 3; break;
12868 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12869 NumVecs = 4; break;
12870 case Intrinsic::arm_neon_vld2dup:
12871 case Intrinsic::arm_neon_vld3dup:
12872 case Intrinsic::arm_neon_vld4dup:
12873 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12874 // combining base updates for such intrinsics.
12875 continue;
12876 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12877 NumVecs = 2; isLaneOp = true; break;
12878 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12879 NumVecs = 3; isLaneOp = true; break;
12880 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12881 NumVecs = 4; isLaneOp = true; break;
12882 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12883 NumVecs = 1; isLoadOp = false; break;
12884 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12885 NumVecs = 2; isLoadOp = false; break;
12886 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12887 NumVecs = 3; isLoadOp = false; break;
12888 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12889 NumVecs = 4; isLoadOp = false; break;
12890 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12891 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12892 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12893 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12894 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12895 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12897 } else {
12898 isLaneOp = true;
12899 switch (N->getOpcode()) {
12900 default: llvm_unreachable("unexpected opcode for Neon base update");
12901 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12902 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12903 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12904 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12905 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12906 NumVecs = 1; isLaneOp = false; break;
12907 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12908 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12912 // Find the size of memory referenced by the load/store.
12913 EVT VecTy;
12914 if (isLoadOp) {
12915 VecTy = N->getValueType(0);
12916 } else if (isIntrinsic) {
12917 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12918 } else {
12919 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12920 VecTy = N->getOperand(1).getValueType();
12923 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12924 if (isLaneOp)
12925 NumBytes /= VecTy.getVectorNumElements();
12927 // If the increment is a constant, it must match the memory ref size.
12928 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12929 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12930 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12931 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12932 // separate instructions that make it harder to use a non-constant update.
12933 continue;
12936 // OK, we found an ADD we can fold into the base update.
12937 // Now, create a _UPD node, taking care of not breaking alignment.
12939 EVT AlignedVecTy = VecTy;
12940 unsigned Alignment = MemN->getAlignment();
12942 // If this is a less-than-standard-aligned load/store, change the type to
12943 // match the standard alignment.
12944 // The alignment is overlooked when selecting _UPD variants; and it's
12945 // easier to introduce bitcasts here than fix that.
12946 // There are 3 ways to get to this base-update combine:
12947 // - intrinsics: they are assumed to be properly aligned (to the standard
12948 // alignment of the memory type), so we don't need to do anything.
12949 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12950 // intrinsics, so, likewise, there's nothing to do.
12951 // - generic load/store instructions: the alignment is specified as an
12952 // explicit operand, rather than implicitly as the standard alignment
12953 // of the memory type (like the intrisics). We need to change the
12954 // memory type to match the explicit alignment. That way, we don't
12955 // generate non-standard-aligned ARMISD::VLDx nodes.
12956 if (isa<LSBaseSDNode>(N)) {
12957 if (Alignment == 0)
12958 Alignment = 1;
12959 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12960 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12961 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12962 assert(!isLaneOp && "Unexpected generic load/store lane.");
12963 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12964 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12966 // Don't set an explicit alignment on regular load/stores that we want
12967 // to transform to VLD/VST 1_UPD nodes.
12968 // This matches the behavior of regular load/stores, which only get an
12969 // explicit alignment if the MMO alignment is larger than the standard
12970 // alignment of the memory type.
12971 // Intrinsics, however, always get an explicit alignment, set to the
12972 // alignment of the MMO.
12973 Alignment = 1;
12976 // Create the new updating load/store node.
12977 // First, create an SDVTList for the new updating node's results.
12978 EVT Tys[6];
12979 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12980 unsigned n;
12981 for (n = 0; n < NumResultVecs; ++n)
12982 Tys[n] = AlignedVecTy;
12983 Tys[n++] = MVT::i32;
12984 Tys[n] = MVT::Other;
12985 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12987 // Then, gather the new node's operands.
12988 SmallVector<SDValue, 8> Ops;
12989 Ops.push_back(N->getOperand(0)); // incoming chain
12990 Ops.push_back(N->getOperand(AddrOpIdx));
12991 Ops.push_back(Inc);
12993 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12994 // Try to match the intrinsic's signature
12995 Ops.push_back(StN->getValue());
12996 } else {
12997 // Loads (and of course intrinsics) match the intrinsics' signature,
12998 // so just add all but the alignment operand.
12999 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
13000 Ops.push_back(N->getOperand(i));
13003 // For all node types, the alignment operand is always the last one.
13004 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
13006 // If this is a non-standard-aligned STORE, the penultimate operand is the
13007 // stored value. Bitcast it to the aligned type.
13008 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
13009 SDValue &StVal = Ops[Ops.size()-2];
13010 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
13013 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
13014 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
13015 MemN->getMemOperand());
13017 // Update the uses.
13018 SmallVector<SDValue, 5> NewResults;
13019 for (unsigned i = 0; i < NumResultVecs; ++i)
13020 NewResults.push_back(SDValue(UpdN.getNode(), i));
13022 // If this is an non-standard-aligned LOAD, the first result is the loaded
13023 // value. Bitcast it to the expected result type.
13024 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
13025 SDValue &LdVal = NewResults[0];
13026 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
13029 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
13030 DCI.CombineTo(N, NewResults);
13031 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13033 break;
13035 return SDValue();
13038 static SDValue PerformVLDCombine(SDNode *N,
13039 TargetLowering::DAGCombinerInfo &DCI) {
13040 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13041 return SDValue();
13043 return CombineBaseUpdate(N, DCI);
13046 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
13047 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
13048 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
13049 /// return true.
13050 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13051 SelectionDAG &DAG = DCI.DAG;
13052 EVT VT = N->getValueType(0);
13053 // vldN-dup instructions only support 64-bit vectors for N > 1.
13054 if (!VT.is64BitVector())
13055 return false;
13057 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
13058 SDNode *VLD = N->getOperand(0).getNode();
13059 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
13060 return false;
13061 unsigned NumVecs = 0;
13062 unsigned NewOpc = 0;
13063 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
13064 if (IntNo == Intrinsic::arm_neon_vld2lane) {
13065 NumVecs = 2;
13066 NewOpc = ARMISD::VLD2DUP;
13067 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
13068 NumVecs = 3;
13069 NewOpc = ARMISD::VLD3DUP;
13070 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
13071 NumVecs = 4;
13072 NewOpc = ARMISD::VLD4DUP;
13073 } else {
13074 return false;
13077 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
13078 // numbers match the load.
13079 unsigned VLDLaneNo =
13080 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
13081 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13082 UI != UE; ++UI) {
13083 // Ignore uses of the chain result.
13084 if (UI.getUse().getResNo() == NumVecs)
13085 continue;
13086 SDNode *User = *UI;
13087 if (User->getOpcode() != ARMISD::VDUPLANE ||
13088 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
13089 return false;
13092 // Create the vldN-dup node.
13093 EVT Tys[5];
13094 unsigned n;
13095 for (n = 0; n < NumVecs; ++n)
13096 Tys[n] = VT;
13097 Tys[n] = MVT::Other;
13098 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
13099 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
13100 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
13101 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
13102 Ops, VLDMemInt->getMemoryVT(),
13103 VLDMemInt->getMemOperand());
13105 // Update the uses.
13106 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13107 UI != UE; ++UI) {
13108 unsigned ResNo = UI.getUse().getResNo();
13109 // Ignore uses of the chain result.
13110 if (ResNo == NumVecs)
13111 continue;
13112 SDNode *User = *UI;
13113 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
13116 // Now the vldN-lane intrinsic is dead except for its chain result.
13117 // Update uses of the chain.
13118 std::vector<SDValue> VLDDupResults;
13119 for (unsigned n = 0; n < NumVecs; ++n)
13120 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
13121 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
13122 DCI.CombineTo(VLD, VLDDupResults);
13124 return true;
13127 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
13128 /// ARMISD::VDUPLANE.
13129 static SDValue PerformVDUPLANECombine(SDNode *N,
13130 TargetLowering::DAGCombinerInfo &DCI) {
13131 SDValue Op = N->getOperand(0);
13133 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
13134 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
13135 if (CombineVLDDUP(N, DCI))
13136 return SDValue(N, 0);
13138 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
13139 // redundant. Ignore bit_converts for now; element sizes are checked below.
13140 while (Op.getOpcode() == ISD::BITCAST)
13141 Op = Op.getOperand(0);
13142 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
13143 return SDValue();
13145 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
13146 unsigned EltSize = Op.getScalarValueSizeInBits();
13147 // The canonical VMOV for a zero vector uses a 32-bit element size.
13148 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13149 unsigned EltBits;
13150 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
13151 EltSize = 8;
13152 EVT VT = N->getValueType(0);
13153 if (EltSize > VT.getScalarSizeInBits())
13154 return SDValue();
13156 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
13159 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
13160 static SDValue PerformVDUPCombine(SDNode *N,
13161 TargetLowering::DAGCombinerInfo &DCI,
13162 const ARMSubtarget *Subtarget) {
13163 SelectionDAG &DAG = DCI.DAG;
13164 SDValue Op = N->getOperand(0);
13166 if (!Subtarget->hasNEON())
13167 return SDValue();
13169 // Match VDUP(LOAD) -> VLD1DUP.
13170 // We match this pattern here rather than waiting for isel because the
13171 // transform is only legal for unindexed loads.
13172 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
13173 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
13174 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
13175 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
13176 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
13177 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
13178 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
13179 Ops, LD->getMemoryVT(),
13180 LD->getMemOperand());
13181 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
13182 return VLDDup;
13185 return SDValue();
13188 static SDValue PerformLOADCombine(SDNode *N,
13189 TargetLowering::DAGCombinerInfo &DCI) {
13190 EVT VT = N->getValueType(0);
13192 // If this is a legal vector load, try to combine it into a VLD1_UPD.
13193 if (ISD::isNormalLoad(N) && VT.isVector() &&
13194 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13195 return CombineBaseUpdate(N, DCI);
13197 return SDValue();
13200 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
13201 // pack all of the elements in one place. Next, store to memory in fewer
13202 // chunks.
13203 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
13204 SelectionDAG &DAG) {
13205 SDValue StVal = St->getValue();
13206 EVT VT = StVal.getValueType();
13207 if (!St->isTruncatingStore() || !VT.isVector())
13208 return SDValue();
13209 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13210 EVT StVT = St->getMemoryVT();
13211 unsigned NumElems = VT.getVectorNumElements();
13212 assert(StVT != VT && "Cannot truncate to the same type");
13213 unsigned FromEltSz = VT.getScalarSizeInBits();
13214 unsigned ToEltSz = StVT.getScalarSizeInBits();
13216 // From, To sizes and ElemCount must be pow of two
13217 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
13218 return SDValue();
13220 // We are going to use the original vector elt for storing.
13221 // Accumulated smaller vector elements must be a multiple of the store size.
13222 if (0 != (NumElems * FromEltSz) % ToEltSz)
13223 return SDValue();
13225 unsigned SizeRatio = FromEltSz / ToEltSz;
13226 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13228 // Create a type on which we perform the shuffle.
13229 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13230 NumElems * SizeRatio);
13231 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13233 SDLoc DL(St);
13234 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13235 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13236 for (unsigned i = 0; i < NumElems; ++i)
13237 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
13238 : i * SizeRatio;
13240 // Can't shuffle using an illegal type.
13241 if (!TLI.isTypeLegal(WideVecVT))
13242 return SDValue();
13244 SDValue Shuff = DAG.getVectorShuffle(
13245 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
13246 // At this point all of the data is stored at the bottom of the
13247 // register. We now need to save it to mem.
13249 // Find the largest store unit
13250 MVT StoreType = MVT::i8;
13251 for (MVT Tp : MVT::integer_valuetypes()) {
13252 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13253 StoreType = Tp;
13255 // Didn't find a legal store type.
13256 if (!TLI.isTypeLegal(StoreType))
13257 return SDValue();
13259 // Bitcast the original vector into a vector of store-size units
13260 EVT StoreVecVT =
13261 EVT::getVectorVT(*DAG.getContext(), StoreType,
13262 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
13263 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13264 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13265 SmallVector<SDValue, 8> Chains;
13266 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13267 TLI.getPointerTy(DAG.getDataLayout()));
13268 SDValue BasePtr = St->getBasePtr();
13270 // Perform one or more big stores into memory.
13271 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
13272 for (unsigned I = 0; I < E; I++) {
13273 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
13274 ShuffWide, DAG.getIntPtrConstant(I, DL));
13275 SDValue Ch =
13276 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
13277 St->getAlignment(), St->getMemOperand()->getFlags());
13278 BasePtr =
13279 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
13280 Chains.push_back(Ch);
13282 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13285 // Try taking a single vector store from an truncate (which would otherwise turn
13286 // into an expensive buildvector) and splitting it into a series of narrowing
13287 // stores.
13288 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
13289 SelectionDAG &DAG) {
13290 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
13291 return SDValue();
13292 SDValue Trunc = St->getValue();
13293 if (Trunc->getOpcode() != ISD::TRUNCATE)
13294 return SDValue();
13295 EVT FromVT = Trunc->getOperand(0).getValueType();
13296 EVT ToVT = Trunc.getValueType();
13297 if (!ToVT.isVector())
13298 return SDValue();
13299 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
13300 EVT ToEltVT = ToVT.getVectorElementType();
13301 EVT FromEltVT = FromVT.getVectorElementType();
13303 unsigned NumElements = 0;
13304 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
13305 NumElements = 4;
13306 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
13307 NumElements = 8;
13308 if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements ||
13309 FromVT.getVectorNumElements() % NumElements != 0)
13310 return SDValue();
13312 SDLoc DL(St);
13313 // Details about the old store
13314 SDValue Ch = St->getChain();
13315 SDValue BasePtr = St->getBasePtr();
13316 unsigned Alignment = St->getOriginalAlignment();
13317 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
13318 AAMDNodes AAInfo = St->getAAInfo();
13320 EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements);
13321 EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements);
13323 SmallVector<SDValue, 4> Stores;
13324 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
13325 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
13326 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
13328 SDValue Extract =
13329 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
13330 DAG.getConstant(i * NumElements, DL, MVT::i32));
13331 SDValue Store = DAG.getTruncStore(
13332 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
13333 NewToVT, Alignment, MMOFlags, AAInfo);
13334 Stores.push_back(Store);
13336 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
13339 /// PerformSTORECombine - Target-specific dag combine xforms for
13340 /// ISD::STORE.
13341 static SDValue PerformSTORECombine(SDNode *N,
13342 TargetLowering::DAGCombinerInfo &DCI,
13343 const ARMSubtarget *Subtarget) {
13344 StoreSDNode *St = cast<StoreSDNode>(N);
13345 if (St->isVolatile())
13346 return SDValue();
13347 SDValue StVal = St->getValue();
13348 EVT VT = StVal.getValueType();
13350 if (Subtarget->hasNEON())
13351 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
13352 return Store;
13354 if (Subtarget->hasMVEIntegerOps())
13355 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
13356 return NewToken;
13358 if (!ISD::isNormalStore(St))
13359 return SDValue();
13361 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
13362 // ARM stores of arguments in the same cache line.
13363 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
13364 StVal.getNode()->hasOneUse()) {
13365 SelectionDAG &DAG = DCI.DAG;
13366 bool isBigEndian = DAG.getDataLayout().isBigEndian();
13367 SDLoc DL(St);
13368 SDValue BasePtr = St->getBasePtr();
13369 SDValue NewST1 = DAG.getStore(
13370 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
13371 BasePtr, St->getPointerInfo(), St->getAlignment(),
13372 St->getMemOperand()->getFlags());
13374 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13375 DAG.getConstant(4, DL, MVT::i32));
13376 return DAG.getStore(NewST1.getValue(0), DL,
13377 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
13378 OffsetPtr, St->getPointerInfo(),
13379 std::min(4U, St->getAlignment() / 2),
13380 St->getMemOperand()->getFlags());
13383 if (StVal.getValueType() == MVT::i64 &&
13384 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13386 // Bitcast an i64 store extracted from a vector to f64.
13387 // Otherwise, the i64 value will be legalized to a pair of i32 values.
13388 SelectionDAG &DAG = DCI.DAG;
13389 SDLoc dl(StVal);
13390 SDValue IntVec = StVal.getOperand(0);
13391 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13392 IntVec.getValueType().getVectorNumElements());
13393 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
13394 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13395 Vec, StVal.getOperand(1));
13396 dl = SDLoc(N);
13397 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
13398 // Make the DAGCombiner fold the bitcasts.
13399 DCI.AddToWorklist(Vec.getNode());
13400 DCI.AddToWorklist(ExtElt.getNode());
13401 DCI.AddToWorklist(V.getNode());
13402 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
13403 St->getPointerInfo(), St->getAlignment(),
13404 St->getMemOperand()->getFlags(), St->getAAInfo());
13407 // If this is a legal vector store, try to combine it into a VST1_UPD.
13408 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
13409 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13410 return CombineBaseUpdate(N, DCI);
13412 return SDValue();
13415 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
13416 /// can replace combinations of VMUL and VCVT (floating-point to integer)
13417 /// when the VMUL has a constant operand that is a power of 2.
13419 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13420 /// vmul.f32 d16, d17, d16
13421 /// vcvt.s32.f32 d16, d16
13422 /// becomes:
13423 /// vcvt.s32.f32 d16, d16, #3
13424 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
13425 const ARMSubtarget *Subtarget) {
13426 if (!Subtarget->hasNEON())
13427 return SDValue();
13429 SDValue Op = N->getOperand(0);
13430 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13431 Op.getOpcode() != ISD::FMUL)
13432 return SDValue();
13434 SDValue ConstVec = Op->getOperand(1);
13435 if (!isa<BuildVectorSDNode>(ConstVec))
13436 return SDValue();
13438 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13439 uint32_t FloatBits = FloatTy.getSizeInBits();
13440 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13441 uint32_t IntBits = IntTy.getSizeInBits();
13442 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13443 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13444 // These instructions only exist converting from f32 to i32. We can handle
13445 // smaller integers by generating an extra truncate, but larger ones would
13446 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13447 // these intructions only support v2i32/v4i32 types.
13448 return SDValue();
13451 BitVector UndefElements;
13452 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13453 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13454 if (C == -1 || C == 0 || C > 32)
13455 return SDValue();
13457 SDLoc dl(N);
13458 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
13459 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
13460 Intrinsic::arm_neon_vcvtfp2fxu;
13461 SDValue FixConv = DAG.getNode(
13462 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13463 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
13464 DAG.getConstant(C, dl, MVT::i32));
13466 if (IntBits < FloatBits)
13467 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
13469 return FixConv;
13472 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13473 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13474 /// when the VDIV has a constant operand that is a power of 2.
13476 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13477 /// vcvt.f32.s32 d16, d16
13478 /// vdiv.f32 d16, d17, d16
13479 /// becomes:
13480 /// vcvt.f32.s32 d16, d16, #3
13481 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13482 const ARMSubtarget *Subtarget) {
13483 if (!Subtarget->hasNEON())
13484 return SDValue();
13486 SDValue Op = N->getOperand(0);
13487 unsigned OpOpcode = Op.getNode()->getOpcode();
13488 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13489 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13490 return SDValue();
13492 SDValue ConstVec = N->getOperand(1);
13493 if (!isa<BuildVectorSDNode>(ConstVec))
13494 return SDValue();
13496 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13497 uint32_t FloatBits = FloatTy.getSizeInBits();
13498 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13499 uint32_t IntBits = IntTy.getSizeInBits();
13500 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13501 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13502 // These instructions only exist converting from i32 to f32. We can handle
13503 // smaller integers by generating an extra extend, but larger ones would
13504 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13505 // these intructions only support v2i32/v4i32 types.
13506 return SDValue();
13509 BitVector UndefElements;
13510 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13511 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13512 if (C == -1 || C == 0 || C > 32)
13513 return SDValue();
13515 SDLoc dl(N);
13516 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13517 SDValue ConvInput = Op.getOperand(0);
13518 if (IntBits < FloatBits)
13519 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13520 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13521 ConvInput);
13523 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13524 Intrinsic::arm_neon_vcvtfxu2fp;
13525 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13526 Op.getValueType(),
13527 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13528 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13531 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13532 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13533 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13534 switch (IntNo) {
13535 default:
13536 // Don't do anything for most intrinsics.
13537 break;
13539 // Vector shifts: check for immediate versions and lower them.
13540 // Note: This is done during DAG combining instead of DAG legalizing because
13541 // the build_vectors for 64-bit vector element shift counts are generally
13542 // not legal, and it is hard to see their values after they get legalized to
13543 // loads from a constant pool.
13544 case Intrinsic::arm_neon_vshifts:
13545 case Intrinsic::arm_neon_vshiftu:
13546 case Intrinsic::arm_neon_vrshifts:
13547 case Intrinsic::arm_neon_vrshiftu:
13548 case Intrinsic::arm_neon_vrshiftn:
13549 case Intrinsic::arm_neon_vqshifts:
13550 case Intrinsic::arm_neon_vqshiftu:
13551 case Intrinsic::arm_neon_vqshiftsu:
13552 case Intrinsic::arm_neon_vqshiftns:
13553 case Intrinsic::arm_neon_vqshiftnu:
13554 case Intrinsic::arm_neon_vqshiftnsu:
13555 case Intrinsic::arm_neon_vqrshiftns:
13556 case Intrinsic::arm_neon_vqrshiftnu:
13557 case Intrinsic::arm_neon_vqrshiftnsu: {
13558 EVT VT = N->getOperand(1).getValueType();
13559 int64_t Cnt;
13560 unsigned VShiftOpc = 0;
13562 switch (IntNo) {
13563 case Intrinsic::arm_neon_vshifts:
13564 case Intrinsic::arm_neon_vshiftu:
13565 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13566 VShiftOpc = ARMISD::VSHLIMM;
13567 break;
13569 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13570 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13571 : ARMISD::VSHRuIMM);
13572 break;
13574 return SDValue();
13576 case Intrinsic::arm_neon_vrshifts:
13577 case Intrinsic::arm_neon_vrshiftu:
13578 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13579 break;
13580 return SDValue();
13582 case Intrinsic::arm_neon_vqshifts:
13583 case Intrinsic::arm_neon_vqshiftu:
13584 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13585 break;
13586 return SDValue();
13588 case Intrinsic::arm_neon_vqshiftsu:
13589 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13590 break;
13591 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13593 case Intrinsic::arm_neon_vrshiftn:
13594 case Intrinsic::arm_neon_vqshiftns:
13595 case Intrinsic::arm_neon_vqshiftnu:
13596 case Intrinsic::arm_neon_vqshiftnsu:
13597 case Intrinsic::arm_neon_vqrshiftns:
13598 case Intrinsic::arm_neon_vqrshiftnu:
13599 case Intrinsic::arm_neon_vqrshiftnsu:
13600 // Narrowing shifts require an immediate right shift.
13601 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13602 break;
13603 llvm_unreachable("invalid shift count for narrowing vector shift "
13604 "intrinsic");
13606 default:
13607 llvm_unreachable("unhandled vector shift");
13610 switch (IntNo) {
13611 case Intrinsic::arm_neon_vshifts:
13612 case Intrinsic::arm_neon_vshiftu:
13613 // Opcode already set above.
13614 break;
13615 case Intrinsic::arm_neon_vrshifts:
13616 VShiftOpc = ARMISD::VRSHRsIMM;
13617 break;
13618 case Intrinsic::arm_neon_vrshiftu:
13619 VShiftOpc = ARMISD::VRSHRuIMM;
13620 break;
13621 case Intrinsic::arm_neon_vrshiftn:
13622 VShiftOpc = ARMISD::VRSHRNIMM;
13623 break;
13624 case Intrinsic::arm_neon_vqshifts:
13625 VShiftOpc = ARMISD::VQSHLsIMM;
13626 break;
13627 case Intrinsic::arm_neon_vqshiftu:
13628 VShiftOpc = ARMISD::VQSHLuIMM;
13629 break;
13630 case Intrinsic::arm_neon_vqshiftsu:
13631 VShiftOpc = ARMISD::VQSHLsuIMM;
13632 break;
13633 case Intrinsic::arm_neon_vqshiftns:
13634 VShiftOpc = ARMISD::VQSHRNsIMM;
13635 break;
13636 case Intrinsic::arm_neon_vqshiftnu:
13637 VShiftOpc = ARMISD::VQSHRNuIMM;
13638 break;
13639 case Intrinsic::arm_neon_vqshiftnsu:
13640 VShiftOpc = ARMISD::VQSHRNsuIMM;
13641 break;
13642 case Intrinsic::arm_neon_vqrshiftns:
13643 VShiftOpc = ARMISD::VQRSHRNsIMM;
13644 break;
13645 case Intrinsic::arm_neon_vqrshiftnu:
13646 VShiftOpc = ARMISD::VQRSHRNuIMM;
13647 break;
13648 case Intrinsic::arm_neon_vqrshiftnsu:
13649 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13650 break;
13653 SDLoc dl(N);
13654 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13655 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13658 case Intrinsic::arm_neon_vshiftins: {
13659 EVT VT = N->getOperand(1).getValueType();
13660 int64_t Cnt;
13661 unsigned VShiftOpc = 0;
13663 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13664 VShiftOpc = ARMISD::VSLIIMM;
13665 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13666 VShiftOpc = ARMISD::VSRIIMM;
13667 else {
13668 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13671 SDLoc dl(N);
13672 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13673 N->getOperand(1), N->getOperand(2),
13674 DAG.getConstant(Cnt, dl, MVT::i32));
13677 case Intrinsic::arm_neon_vqrshifts:
13678 case Intrinsic::arm_neon_vqrshiftu:
13679 // No immediate versions of these to check for.
13680 break;
13683 return SDValue();
13686 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13687 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13688 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13689 /// vector element shift counts are generally not legal, and it is hard to see
13690 /// their values after they get legalized to loads from a constant pool.
13691 static SDValue PerformShiftCombine(SDNode *N,
13692 TargetLowering::DAGCombinerInfo &DCI,
13693 const ARMSubtarget *ST) {
13694 SelectionDAG &DAG = DCI.DAG;
13695 EVT VT = N->getValueType(0);
13696 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13697 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13698 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13699 SDValue N1 = N->getOperand(1);
13700 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13701 SDValue N0 = N->getOperand(0);
13702 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13703 DAG.MaskedValueIsZero(N0.getOperand(0),
13704 APInt::getHighBitsSet(32, 16)))
13705 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13709 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13710 N->getOperand(0)->getOpcode() == ISD::AND &&
13711 N->getOperand(0)->hasOneUse()) {
13712 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13713 return SDValue();
13714 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13715 // usually show up because instcombine prefers to canonicalize it to
13716 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13717 // out of GEP lowering in some cases.
13718 SDValue N0 = N->getOperand(0);
13719 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13720 if (!ShiftAmtNode)
13721 return SDValue();
13722 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13723 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13724 if (!AndMaskNode)
13725 return SDValue();
13726 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13727 // Don't transform uxtb/uxth.
13728 if (AndMask == 255 || AndMask == 65535)
13729 return SDValue();
13730 if (isMask_32(AndMask)) {
13731 uint32_t MaskedBits = countLeadingZeros(AndMask);
13732 if (MaskedBits > ShiftAmt) {
13733 SDLoc DL(N);
13734 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13735 DAG.getConstant(MaskedBits, DL, MVT::i32));
13736 return DAG.getNode(
13737 ISD::SRL, DL, MVT::i32, SHL,
13738 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13743 // Nothing to be done for scalar shifts.
13744 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13745 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13746 return SDValue();
13747 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13748 return SDValue();
13750 int64_t Cnt;
13752 switch (N->getOpcode()) {
13753 default: llvm_unreachable("unexpected shift opcode");
13755 case ISD::SHL:
13756 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13757 SDLoc dl(N);
13758 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13759 DAG.getConstant(Cnt, dl, MVT::i32));
13761 break;
13763 case ISD::SRA:
13764 case ISD::SRL:
13765 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13766 unsigned VShiftOpc =
13767 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13768 SDLoc dl(N);
13769 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13770 DAG.getConstant(Cnt, dl, MVT::i32));
13773 return SDValue();
13776 // Look for a sign/zero extend of a larger than legal load. This can be split
13777 // into two extending loads, which are simpler to deal with than an arbitrary
13778 // sign extend.
13779 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
13780 SDValue N0 = N->getOperand(0);
13781 if (N0.getOpcode() != ISD::LOAD)
13782 return SDValue();
13783 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
13784 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
13785 LD->getExtensionType() != ISD::NON_EXTLOAD)
13786 return SDValue();
13787 EVT FromVT = LD->getValueType(0);
13788 EVT ToVT = N->getValueType(0);
13789 if (!ToVT.isVector())
13790 return SDValue();
13791 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
13792 EVT ToEltVT = ToVT.getVectorElementType();
13793 EVT FromEltVT = FromVT.getVectorElementType();
13795 unsigned NumElements = 0;
13796 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
13797 NumElements = 4;
13798 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
13799 NumElements = 8;
13800 if (NumElements == 0 ||
13801 FromVT.getVectorNumElements() == NumElements ||
13802 FromVT.getVectorNumElements() % NumElements != 0 ||
13803 !isPowerOf2_32(NumElements))
13804 return SDValue();
13806 SDLoc DL(LD);
13807 // Details about the old load
13808 SDValue Ch = LD->getChain();
13809 SDValue BasePtr = LD->getBasePtr();
13810 unsigned Alignment = LD->getOriginalAlignment();
13811 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
13812 AAMDNodes AAInfo = LD->getAAInfo();
13814 ISD::LoadExtType NewExtType =
13815 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
13816 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
13817 EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext());
13818 EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
13819 unsigned NewOffset = NewFromVT.getSizeInBits() / 8;
13820 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
13822 // Split the load in half, each side of which is extended separately. This
13823 // is good enough, as legalisation will take it from there. They are either
13824 // already legal or they will be split further into something that is
13825 // legal.
13826 SDValue NewLoad1 =
13827 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset,
13828 LD->getPointerInfo(), NewFromVT, Alignment, MMOFlags, AAInfo);
13829 SDValue NewLoad2 =
13830 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
13831 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
13832 Alignment, MMOFlags, AAInfo);
13834 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13835 SDValue(NewLoad1.getNode(), 1),
13836 SDValue(NewLoad2.getNode(), 1));
13837 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
13838 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2);
13841 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13842 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13843 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13844 const ARMSubtarget *ST) {
13845 SDValue N0 = N->getOperand(0);
13847 // Check for sign- and zero-extensions of vector extract operations of 8-
13848 // and 16-bit vector elements. NEON supports these directly. They are
13849 // handled during DAG combining because type legalization will promote them
13850 // to 32-bit types and it is messy to recognize the operations after that.
13851 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13852 SDValue Vec = N0.getOperand(0);
13853 SDValue Lane = N0.getOperand(1);
13854 EVT VT = N->getValueType(0);
13855 EVT EltVT = N0.getValueType();
13856 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13858 if (VT == MVT::i32 &&
13859 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13860 TLI.isTypeLegal(Vec.getValueType()) &&
13861 isa<ConstantSDNode>(Lane)) {
13863 unsigned Opc = 0;
13864 switch (N->getOpcode()) {
13865 default: llvm_unreachable("unexpected opcode");
13866 case ISD::SIGN_EXTEND:
13867 Opc = ARMISD::VGETLANEs;
13868 break;
13869 case ISD::ZERO_EXTEND:
13870 case ISD::ANY_EXTEND:
13871 Opc = ARMISD::VGETLANEu;
13872 break;
13874 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13878 if (ST->hasMVEIntegerOps())
13879 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
13880 return NewLoad;
13882 return SDValue();
13885 static const APInt *isPowerOf2Constant(SDValue V) {
13886 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13887 if (!C)
13888 return nullptr;
13889 const APInt *CV = &C->getAPIntValue();
13890 return CV->isPowerOf2() ? CV : nullptr;
13893 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13894 // If we have a CMOV, OR and AND combination such as:
13895 // if (x & CN)
13896 // y |= CM;
13898 // And:
13899 // * CN is a single bit;
13900 // * All bits covered by CM are known zero in y
13902 // Then we can convert this into a sequence of BFI instructions. This will
13903 // always be a win if CM is a single bit, will always be no worse than the
13904 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13905 // three bits (due to the extra IT instruction).
13907 SDValue Op0 = CMOV->getOperand(0);
13908 SDValue Op1 = CMOV->getOperand(1);
13909 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13910 auto CC = CCNode->getAPIntValue().getLimitedValue();
13911 SDValue CmpZ = CMOV->getOperand(4);
13913 // The compare must be against zero.
13914 if (!isNullConstant(CmpZ->getOperand(1)))
13915 return SDValue();
13917 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13918 SDValue And = CmpZ->getOperand(0);
13919 if (And->getOpcode() != ISD::AND)
13920 return SDValue();
13921 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13922 if (!AndC)
13923 return SDValue();
13924 SDValue X = And->getOperand(0);
13926 if (CC == ARMCC::EQ) {
13927 // We're performing an "equal to zero" compare. Swap the operands so we
13928 // canonicalize on a "not equal to zero" compare.
13929 std::swap(Op0, Op1);
13930 } else {
13931 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13934 if (Op1->getOpcode() != ISD::OR)
13935 return SDValue();
13937 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13938 if (!OrC)
13939 return SDValue();
13940 SDValue Y = Op1->getOperand(0);
13942 if (Op0 != Y)
13943 return SDValue();
13945 // Now, is it profitable to continue?
13946 APInt OrCI = OrC->getAPIntValue();
13947 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13948 if (OrCI.countPopulation() > Heuristic)
13949 return SDValue();
13951 // Lastly, can we determine that the bits defined by OrCI
13952 // are zero in Y?
13953 KnownBits Known = DAG.computeKnownBits(Y);
13954 if ((OrCI & Known.Zero) != OrCI)
13955 return SDValue();
13957 // OK, we can do the combine.
13958 SDValue V = Y;
13959 SDLoc dl(X);
13960 EVT VT = X.getValueType();
13961 unsigned BitInX = AndC->logBase2();
13963 if (BitInX != 0) {
13964 // We must shift X first.
13965 X = DAG.getNode(ISD::SRL, dl, VT, X,
13966 DAG.getConstant(BitInX, dl, VT));
13969 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13970 BitInY < NumActiveBits; ++BitInY) {
13971 if (OrCI[BitInY] == 0)
13972 continue;
13973 APInt Mask(VT.getSizeInBits(), 0);
13974 Mask.setBit(BitInY);
13975 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13976 // Confusingly, the operand is an *inverted* mask.
13977 DAG.getConstant(~Mask, dl, VT));
13980 return V;
13983 // Given N, the value controlling the conditional branch, search for the loop
13984 // intrinsic, returning it, along with how the value is used. We need to handle
13985 // patterns such as the following:
13986 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13987 // (brcond (setcc (loop.decrement), 0, eq), exit)
13988 // (brcond (setcc (loop.decrement), 0, ne), header)
13989 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13990 bool &Negate) {
13991 switch (N->getOpcode()) {
13992 default:
13993 break;
13994 case ISD::XOR: {
13995 if (!isa<ConstantSDNode>(N.getOperand(1)))
13996 return SDValue();
13997 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13998 return SDValue();
13999 Negate = !Negate;
14000 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
14002 case ISD::SETCC: {
14003 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
14004 if (!Const)
14005 return SDValue();
14006 if (Const->isNullValue())
14007 Imm = 0;
14008 else if (Const->isOne())
14009 Imm = 1;
14010 else
14011 return SDValue();
14012 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
14013 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
14015 case ISD::INTRINSIC_W_CHAIN: {
14016 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
14017 if (IntOp != Intrinsic::test_set_loop_iterations &&
14018 IntOp != Intrinsic::loop_decrement_reg)
14019 return SDValue();
14020 return N;
14023 return SDValue();
14026 static SDValue PerformHWLoopCombine(SDNode *N,
14027 TargetLowering::DAGCombinerInfo &DCI,
14028 const ARMSubtarget *ST) {
14030 // The hwloop intrinsics that we're interested are used for control-flow,
14031 // either for entering or exiting the loop:
14032 // - test.set.loop.iterations will test whether its operand is zero. If it
14033 // is zero, the proceeding branch should not enter the loop.
14034 // - loop.decrement.reg also tests whether its operand is zero. If it is
14035 // zero, the proceeding branch should not branch back to the beginning of
14036 // the loop.
14037 // So here, we need to check that how the brcond is using the result of each
14038 // of the intrinsics to ensure that we're branching to the right place at the
14039 // right time.
14041 ISD::CondCode CC;
14042 SDValue Cond;
14043 int Imm = 1;
14044 bool Negate = false;
14045 SDValue Chain = N->getOperand(0);
14046 SDValue Dest;
14048 if (N->getOpcode() == ISD::BRCOND) {
14049 CC = ISD::SETEQ;
14050 Cond = N->getOperand(1);
14051 Dest = N->getOperand(2);
14052 } else {
14053 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
14054 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14055 Cond = N->getOperand(2);
14056 Dest = N->getOperand(4);
14057 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
14058 if (!Const->isOne() && !Const->isNullValue())
14059 return SDValue();
14060 Imm = Const->getZExtValue();
14061 } else
14062 return SDValue();
14065 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
14066 if (!Int)
14067 return SDValue();
14069 if (Negate)
14070 CC = ISD::getSetCCInverse(CC, true);
14072 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
14073 return (CC == ISD::SETEQ && Imm == 0) ||
14074 (CC == ISD::SETNE && Imm == 1) ||
14075 (CC == ISD::SETLT && Imm == 1) ||
14076 (CC == ISD::SETULT && Imm == 1);
14079 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
14080 return (CC == ISD::SETEQ && Imm == 1) ||
14081 (CC == ISD::SETNE && Imm == 0) ||
14082 (CC == ISD::SETGT && Imm == 0) ||
14083 (CC == ISD::SETUGT && Imm == 0) ||
14084 (CC == ISD::SETGE && Imm == 1) ||
14085 (CC == ISD::SETUGE && Imm == 1);
14088 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
14089 "unsupported condition");
14091 SDLoc dl(Int);
14092 SelectionDAG &DAG = DCI.DAG;
14093 SDValue Elements = Int.getOperand(2);
14094 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
14095 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
14096 && "expected single br user");
14097 SDNode *Br = *N->use_begin();
14098 SDValue OtherTarget = Br->getOperand(1);
14100 // Update the unconditional branch to branch to the given Dest.
14101 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
14102 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
14103 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
14104 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
14107 if (IntOp == Intrinsic::test_set_loop_iterations) {
14108 SDValue Res;
14109 // We expect this 'instruction' to branch when the counter is zero.
14110 if (IsTrueIfZero(CC, Imm)) {
14111 SDValue Ops[] = { Chain, Elements, Dest };
14112 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14113 } else {
14114 // The logic is the reverse of what we need for WLS, so find the other
14115 // basic block target: the target of the proceeding br.
14116 UpdateUncondBr(Br, Dest, DAG);
14118 SDValue Ops[] = { Chain, Elements, OtherTarget };
14119 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14121 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
14122 return Res;
14123 } else {
14124 SDValue Size = DAG.getTargetConstant(
14125 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
14126 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
14127 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
14128 DAG.getVTList(MVT::i32, MVT::Other), Args);
14129 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
14131 // We expect this instruction to branch when the count is not zero.
14132 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
14134 // Update the unconditional branch to target the loop preheader if we've
14135 // found the condition has been reversed.
14136 if (Target == OtherTarget)
14137 UpdateUncondBr(Br, Dest, DAG);
14139 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14140 SDValue(LoopDec.getNode(), 1), Chain);
14142 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
14143 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
14145 return SDValue();
14148 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
14149 SDValue
14150 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
14151 SDValue Cmp = N->getOperand(4);
14152 if (Cmp.getOpcode() != ARMISD::CMPZ)
14153 // Only looking at NE cases.
14154 return SDValue();
14156 EVT VT = N->getValueType(0);
14157 SDLoc dl(N);
14158 SDValue LHS = Cmp.getOperand(0);
14159 SDValue RHS = Cmp.getOperand(1);
14160 SDValue Chain = N->getOperand(0);
14161 SDValue BB = N->getOperand(1);
14162 SDValue ARMcc = N->getOperand(2);
14163 ARMCC::CondCodes CC =
14164 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
14166 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
14167 // -> (brcond Chain BB CC CPSR Cmp)
14168 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
14169 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
14170 LHS->getOperand(0)->hasOneUse()) {
14171 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
14172 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
14173 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14174 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
14175 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
14176 (LHS01C && LHS01C->getZExtValue() == 1) &&
14177 (LHS1C && LHS1C->getZExtValue() == 1) &&
14178 (RHSC && RHSC->getZExtValue() == 0)) {
14179 return DAG.getNode(
14180 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
14181 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
14185 return SDValue();
14188 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
14189 SDValue
14190 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
14191 SDValue Cmp = N->getOperand(4);
14192 if (Cmp.getOpcode() != ARMISD::CMPZ)
14193 // Only looking at EQ and NE cases.
14194 return SDValue();
14196 EVT VT = N->getValueType(0);
14197 SDLoc dl(N);
14198 SDValue LHS = Cmp.getOperand(0);
14199 SDValue RHS = Cmp.getOperand(1);
14200 SDValue FalseVal = N->getOperand(0);
14201 SDValue TrueVal = N->getOperand(1);
14202 SDValue ARMcc = N->getOperand(2);
14203 ARMCC::CondCodes CC =
14204 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
14206 // BFI is only available on V6T2+.
14207 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
14208 SDValue R = PerformCMOVToBFICombine(N, DAG);
14209 if (R)
14210 return R;
14213 // Simplify
14214 // mov r1, r0
14215 // cmp r1, x
14216 // mov r0, y
14217 // moveq r0, x
14218 // to
14219 // cmp r0, x
14220 // movne r0, y
14222 // mov r1, r0
14223 // cmp r1, x
14224 // mov r0, x
14225 // movne r0, y
14226 // to
14227 // cmp r0, x
14228 // movne r0, y
14229 /// FIXME: Turn this into a target neutral optimization?
14230 SDValue Res;
14231 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
14232 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
14233 N->getOperand(3), Cmp);
14234 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
14235 SDValue ARMcc;
14236 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
14237 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
14238 N->getOperand(3), NewCmp);
14241 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
14242 // -> (cmov F T CC CPSR Cmp)
14243 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
14244 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
14245 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14246 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
14247 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
14248 (LHS1C && LHS1C->getZExtValue() == 1) &&
14249 (RHSC && RHSC->getZExtValue() == 0)) {
14250 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
14251 LHS->getOperand(2), LHS->getOperand(3),
14252 LHS->getOperand(4));
14256 if (!VT.isInteger())
14257 return SDValue();
14259 // Materialize a boolean comparison for integers so we can avoid branching.
14260 if (isNullConstant(FalseVal)) {
14261 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
14262 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
14263 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
14264 // right 5 bits will make that 32 be 1, otherwise it will be 0.
14265 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
14266 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
14267 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
14268 DAG.getConstant(5, dl, MVT::i32));
14269 } else {
14270 // CMOV 0, 1, ==, (CMPZ x, y) ->
14271 // (ADDCARRY (SUB x, y), t:0, t:1)
14272 // where t = (SUBCARRY 0, (SUB x, y), 0)
14274 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
14275 // x != y. In other words, a carry C == 1 when x == y, C == 0
14276 // otherwise.
14277 // The final ADDCARRY computes
14278 // x - y + (0 - (x - y)) + C == C
14279 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
14280 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14281 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
14282 // ISD::SUBCARRY returns a borrow but we want the carry here
14283 // actually.
14284 SDValue Carry =
14285 DAG.getNode(ISD::SUB, dl, MVT::i32,
14286 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
14287 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
14289 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
14290 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
14291 // This seems pointless but will allow us to combine it further below.
14292 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14293 SDValue Sub =
14294 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14295 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14296 Sub.getValue(1), SDValue());
14297 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
14298 N->getOperand(3), CPSRGlue.getValue(1));
14299 FalseVal = Sub;
14301 } else if (isNullConstant(TrueVal)) {
14302 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
14303 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
14304 // This seems pointless but will allow us to combine it further below
14305 // Note that we change == for != as this is the dual for the case above.
14306 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14307 SDValue Sub =
14308 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14309 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14310 Sub.getValue(1), SDValue());
14311 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
14312 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
14313 N->getOperand(3), CPSRGlue.getValue(1));
14314 FalseVal = Sub;
14318 // On Thumb1, the DAG above may be further combined if z is a power of 2
14319 // (z == 2 ^ K).
14320 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
14321 // t1 = (USUBO (SUB x, y), 1)
14322 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
14323 // Result = if K != 0 then (SHL t2:0, K) else t2:0
14325 // This also handles the special case of comparing against zero; it's
14326 // essentially, the same pattern, except there's no SUBS:
14327 // CMOV x, z, !=, (CMPZ x, 0) ->
14328 // t1 = (USUBO x, 1)
14329 // t2 = (SUBCARRY x, t1:0, t1:1)
14330 // Result = if K != 0 then (SHL t2:0, K) else t2:0
14331 const APInt *TrueConst;
14332 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
14333 ((FalseVal.getOpcode() == ARMISD::SUBS &&
14334 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
14335 (FalseVal == LHS && isNullConstant(RHS))) &&
14336 (TrueConst = isPowerOf2Constant(TrueVal))) {
14337 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14338 unsigned ShiftAmount = TrueConst->logBase2();
14339 if (ShiftAmount)
14340 TrueVal = DAG.getConstant(1, dl, VT);
14341 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
14342 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
14344 if (ShiftAmount)
14345 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
14346 DAG.getConstant(ShiftAmount, dl, MVT::i32));
14349 if (Res.getNode()) {
14350 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
14351 // Capture demanded bits information that would be otherwise lost.
14352 if (Known.Zero == 0xfffffffe)
14353 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14354 DAG.getValueType(MVT::i1));
14355 else if (Known.Zero == 0xffffff00)
14356 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14357 DAG.getValueType(MVT::i8));
14358 else if (Known.Zero == 0xffff0000)
14359 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14360 DAG.getValueType(MVT::i16));
14363 return Res;
14366 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
14367 DAGCombinerInfo &DCI) const {
14368 switch (N->getOpcode()) {
14369 default: break;
14370 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
14371 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
14372 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
14373 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
14374 case ISD::SUB: return PerformSUBCombine(N, DCI);
14375 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
14376 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
14377 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
14378 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
14379 case ISD::BRCOND:
14380 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
14381 case ARMISD::ADDC:
14382 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
14383 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
14384 case ARMISD::BFI: return PerformBFICombine(N, DCI);
14385 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
14386 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
14387 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
14388 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
14389 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
14390 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
14391 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
14392 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
14393 case ISD::FP_TO_SINT:
14394 case ISD::FP_TO_UINT:
14395 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
14396 case ISD::FDIV:
14397 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
14398 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
14399 case ISD::SHL:
14400 case ISD::SRA:
14401 case ISD::SRL:
14402 return PerformShiftCombine(N, DCI, Subtarget);
14403 case ISD::SIGN_EXTEND:
14404 case ISD::ZERO_EXTEND:
14405 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
14406 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
14407 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
14408 case ISD::LOAD: return PerformLOADCombine(N, DCI);
14409 case ARMISD::VLD1DUP:
14410 case ARMISD::VLD2DUP:
14411 case ARMISD::VLD3DUP:
14412 case ARMISD::VLD4DUP:
14413 return PerformVLDCombine(N, DCI);
14414 case ARMISD::BUILD_VECTOR:
14415 return PerformARMBUILD_VECTORCombine(N, DCI);
14416 case ARMISD::PREDICATE_CAST:
14417 return PerformPREDICATE_CASTCombine(N, DCI);
14418 case ARMISD::SMULWB: {
14419 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14420 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14421 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14422 return SDValue();
14423 break;
14425 case ARMISD::SMULWT: {
14426 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14427 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14428 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14429 return SDValue();
14430 break;
14432 case ARMISD::SMLALBB:
14433 case ARMISD::QADD16b:
14434 case ARMISD::QSUB16b: {
14435 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14436 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14437 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14438 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14439 return SDValue();
14440 break;
14442 case ARMISD::SMLALBT: {
14443 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
14444 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14445 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
14446 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14447 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
14448 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
14449 return SDValue();
14450 break;
14452 case ARMISD::SMLALTB: {
14453 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
14454 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14455 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
14456 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14457 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
14458 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
14459 return SDValue();
14460 break;
14462 case ARMISD::SMLALTT: {
14463 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14464 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14465 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14466 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14467 return SDValue();
14468 break;
14470 case ARMISD::QADD8b:
14471 case ARMISD::QSUB8b: {
14472 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14473 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
14474 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14475 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14476 return SDValue();
14477 break;
14479 case ISD::INTRINSIC_VOID:
14480 case ISD::INTRINSIC_W_CHAIN:
14481 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14482 case Intrinsic::arm_neon_vld1:
14483 case Intrinsic::arm_neon_vld1x2:
14484 case Intrinsic::arm_neon_vld1x3:
14485 case Intrinsic::arm_neon_vld1x4:
14486 case Intrinsic::arm_neon_vld2:
14487 case Intrinsic::arm_neon_vld3:
14488 case Intrinsic::arm_neon_vld4:
14489 case Intrinsic::arm_neon_vld2lane:
14490 case Intrinsic::arm_neon_vld3lane:
14491 case Intrinsic::arm_neon_vld4lane:
14492 case Intrinsic::arm_neon_vld2dup:
14493 case Intrinsic::arm_neon_vld3dup:
14494 case Intrinsic::arm_neon_vld4dup:
14495 case Intrinsic::arm_neon_vst1:
14496 case Intrinsic::arm_neon_vst1x2:
14497 case Intrinsic::arm_neon_vst1x3:
14498 case Intrinsic::arm_neon_vst1x4:
14499 case Intrinsic::arm_neon_vst2:
14500 case Intrinsic::arm_neon_vst3:
14501 case Intrinsic::arm_neon_vst4:
14502 case Intrinsic::arm_neon_vst2lane:
14503 case Intrinsic::arm_neon_vst3lane:
14504 case Intrinsic::arm_neon_vst4lane:
14505 return PerformVLDCombine(N, DCI);
14506 default: break;
14508 break;
14510 return SDValue();
14513 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
14514 EVT VT) const {
14515 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
14518 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
14519 unsigned Alignment,
14520 MachineMemOperand::Flags,
14521 bool *Fast) const {
14522 // Depends what it gets converted into if the type is weird.
14523 if (!VT.isSimple())
14524 return false;
14526 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
14527 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
14528 auto Ty = VT.getSimpleVT().SimpleTy;
14530 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
14531 // Unaligned access can use (for example) LRDB, LRDH, LDR
14532 if (AllowsUnaligned) {
14533 if (Fast)
14534 *Fast = Subtarget->hasV7Ops();
14535 return true;
14539 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
14540 // For any little-endian targets with neon, we can support unaligned ld/st
14541 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
14542 // A big-endian target may also explicitly support unaligned accesses
14543 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
14544 if (Fast)
14545 *Fast = true;
14546 return true;
14550 if (!Subtarget->hasMVEIntegerOps())
14551 return false;
14553 // These are for predicates
14554 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14555 if (Fast)
14556 *Fast = true;
14557 return true;
14560 // These are for truncated stores/narrowing loads. They are fine so long as
14561 // the alignment is at least the size of the item being loaded
14562 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
14563 Alignment >= VT.getScalarSizeInBits() / 8) {
14564 if (Fast)
14565 *Fast = true;
14566 return true;
14569 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
14570 // VSTRW.U32 all store the vector register in exactly the same format, and
14571 // differ only in the range of their immediate offset field and the required
14572 // alignment. So there is always a store that can be used, regardless of
14573 // actual type.
14575 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
14576 // VREV64.8) pair and get the same effect. This will likely be better than
14577 // aligning the vector through the stack.
14578 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
14579 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
14580 Ty == MVT::v2f64) {
14581 if (Fast)
14582 *Fast = true;
14583 return true;
14586 return false;
14589 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14590 unsigned AlignCheck) {
14591 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14592 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14595 EVT ARMTargetLowering::getOptimalMemOpType(
14596 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14597 bool ZeroMemset, bool MemcpyStrSrc,
14598 const AttributeList &FuncAttributes) const {
14599 // See if we can use NEON instructions for this...
14600 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14601 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14602 bool Fast;
14603 if (Size >= 16 &&
14604 (memOpAlign(SrcAlign, DstAlign, 16) ||
14605 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14606 MachineMemOperand::MONone, &Fast) &&
14607 Fast))) {
14608 return MVT::v2f64;
14609 } else if (Size >= 8 &&
14610 (memOpAlign(SrcAlign, DstAlign, 8) ||
14611 (allowsMisalignedMemoryAccesses(
14612 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14613 Fast))) {
14614 return MVT::f64;
14618 // Let the target-independent logic figure it out.
14619 return MVT::Other;
14622 // 64-bit integers are split into their high and low parts and held in two
14623 // different registers, so the trunc is free since the low register can just
14624 // be used.
14625 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14626 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14627 return false;
14628 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14629 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14630 return (SrcBits == 64 && DestBits == 32);
14633 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14634 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14635 !DstVT.isInteger())
14636 return false;
14637 unsigned SrcBits = SrcVT.getSizeInBits();
14638 unsigned DestBits = DstVT.getSizeInBits();
14639 return (SrcBits == 64 && DestBits == 32);
14642 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14643 if (Val.getOpcode() != ISD::LOAD)
14644 return false;
14646 EVT VT1 = Val.getValueType();
14647 if (!VT1.isSimple() || !VT1.isInteger() ||
14648 !VT2.isSimple() || !VT2.isInteger())
14649 return false;
14651 switch (VT1.getSimpleVT().SimpleTy) {
14652 default: break;
14653 case MVT::i1:
14654 case MVT::i8:
14655 case MVT::i16:
14656 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14657 return true;
14660 return false;
14663 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14664 if (!VT.isSimple())
14665 return false;
14667 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14668 // negate values directly (fneg is free). So, we don't want to let the DAG
14669 // combiner rewrite fneg into xors and some other instructions. For f16 and
14670 // FullFP16 argument passing, some bitcast nodes may be introduced,
14671 // triggering this DAG combine rewrite, so we are avoiding that with this.
14672 switch (VT.getSimpleVT().SimpleTy) {
14673 default: break;
14674 case MVT::f16:
14675 return Subtarget->hasFullFP16();
14678 return false;
14681 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14682 /// of the vector elements.
14683 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14684 auto areExtDoubled = [](Instruction *Ext) {
14685 return Ext->getType()->getScalarSizeInBits() ==
14686 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14689 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14690 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14691 !areExtDoubled(cast<Instruction>(Ext1)) ||
14692 !areExtDoubled(cast<Instruction>(Ext2)))
14693 return false;
14695 return true;
14698 /// Check if sinking \p I's operands to I's basic block is profitable, because
14699 /// the operands can be folded into a target instruction, e.g.
14700 /// sext/zext can be folded into vsubl.
14701 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14702 SmallVectorImpl<Use *> &Ops) const {
14703 if (!I->getType()->isVectorTy())
14704 return false;
14706 if (Subtarget->hasNEON()) {
14707 switch (I->getOpcode()) {
14708 case Instruction::Sub:
14709 case Instruction::Add: {
14710 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14711 return false;
14712 Ops.push_back(&I->getOperandUse(0));
14713 Ops.push_back(&I->getOperandUse(1));
14714 return true;
14716 default:
14717 return false;
14721 if (!Subtarget->hasMVEIntegerOps())
14722 return false;
14724 auto IsSinker = [](Instruction *I, int Operand) {
14725 switch (I->getOpcode()) {
14726 case Instruction::Add:
14727 case Instruction::Mul:
14728 return true;
14729 case Instruction::Sub:
14730 return Operand == 1;
14731 default:
14732 return false;
14736 int Op = 0;
14737 if (!isa<ShuffleVectorInst>(I->getOperand(Op)))
14738 Op = 1;
14739 if (!IsSinker(I, Op))
14740 return false;
14741 if (!match(I->getOperand(Op),
14742 m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()),
14743 m_Undef(), m_Zero()))) {
14744 return false;
14746 Instruction *Shuffle = cast<Instruction>(I->getOperand(Op));
14747 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
14748 // and vector registers
14749 for (Use &U : Shuffle->uses()) {
14750 Instruction *Insn = cast<Instruction>(U.getUser());
14751 if (!IsSinker(Insn, U.getOperandNo()))
14752 return false;
14754 Ops.push_back(&Shuffle->getOperandUse(0));
14755 Ops.push_back(&I->getOperandUse(Op));
14756 return true;
14759 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14760 EVT VT = ExtVal.getValueType();
14762 if (!isTypeLegal(VT))
14763 return false;
14765 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
14766 if (Ld->isExpandingLoad())
14767 return false;
14770 // Don't create a loadext if we can fold the extension into a wide/long
14771 // instruction.
14772 // If there's more than one user instruction, the loadext is desirable no
14773 // matter what. There can be two uses by the same instruction.
14774 if (ExtVal->use_empty() ||
14775 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14776 return true;
14778 SDNode *U = *ExtVal->use_begin();
14779 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14780 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14781 return false;
14783 return true;
14786 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14787 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14788 return false;
14790 if (!isTypeLegal(EVT::getEVT(Ty1)))
14791 return false;
14793 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14795 // Assuming the caller doesn't have a zeroext or signext return parameter,
14796 // truncation all the way down to i1 is valid.
14797 return true;
14800 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14801 const AddrMode &AM, Type *Ty,
14802 unsigned AS) const {
14803 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14804 if (Subtarget->hasFPAO())
14805 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14806 return 0;
14808 return -1;
14811 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14812 if (V < 0)
14813 return false;
14815 unsigned Scale = 1;
14816 switch (VT.getSimpleVT().SimpleTy) {
14817 case MVT::i1:
14818 case MVT::i8:
14819 // Scale == 1;
14820 break;
14821 case MVT::i16:
14822 // Scale == 2;
14823 Scale = 2;
14824 break;
14825 default:
14826 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14827 // Scale == 4;
14828 Scale = 4;
14829 break;
14832 if ((V & (Scale - 1)) != 0)
14833 return false;
14834 return isUInt<5>(V / Scale);
14837 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14838 const ARMSubtarget *Subtarget) {
14839 if (!VT.isInteger() && !VT.isFloatingPoint())
14840 return false;
14841 if (VT.isVector() && Subtarget->hasNEON())
14842 return false;
14843 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14844 !Subtarget->hasMVEFloatOps())
14845 return false;
14847 bool IsNeg = false;
14848 if (V < 0) {
14849 IsNeg = true;
14850 V = -V;
14853 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14855 // MVE: size * imm7
14856 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14857 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14858 case MVT::i32:
14859 case MVT::f32:
14860 return isShiftedUInt<7,2>(V);
14861 case MVT::i16:
14862 case MVT::f16:
14863 return isShiftedUInt<7,1>(V);
14864 case MVT::i8:
14865 return isUInt<7>(V);
14866 default:
14867 return false;
14871 // half VLDR: 2 * imm8
14872 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14873 return isShiftedUInt<8, 1>(V);
14874 // VLDR and LDRD: 4 * imm8
14875 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14876 return isShiftedUInt<8, 2>(V);
14878 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14879 // + imm12 or - imm8
14880 if (IsNeg)
14881 return isUInt<8>(V);
14882 return isUInt<12>(V);
14885 return false;
14888 /// isLegalAddressImmediate - Return true if the integer value can be used
14889 /// as the offset of the target addressing mode for load / store of the
14890 /// given type.
14891 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14892 const ARMSubtarget *Subtarget) {
14893 if (V == 0)
14894 return true;
14896 if (!VT.isSimple())
14897 return false;
14899 if (Subtarget->isThumb1Only())
14900 return isLegalT1AddressImmediate(V, VT);
14901 else if (Subtarget->isThumb2())
14902 return isLegalT2AddressImmediate(V, VT, Subtarget);
14904 // ARM mode.
14905 if (V < 0)
14906 V = - V;
14907 switch (VT.getSimpleVT().SimpleTy) {
14908 default: return false;
14909 case MVT::i1:
14910 case MVT::i8:
14911 case MVT::i32:
14912 // +- imm12
14913 return isUInt<12>(V);
14914 case MVT::i16:
14915 // +- imm8
14916 return isUInt<8>(V);
14917 case MVT::f32:
14918 case MVT::f64:
14919 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14920 return false;
14921 return isShiftedUInt<8, 2>(V);
14925 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14926 EVT VT) const {
14927 int Scale = AM.Scale;
14928 if (Scale < 0)
14929 return false;
14931 switch (VT.getSimpleVT().SimpleTy) {
14932 default: return false;
14933 case MVT::i1:
14934 case MVT::i8:
14935 case MVT::i16:
14936 case MVT::i32:
14937 if (Scale == 1)
14938 return true;
14939 // r + r << imm
14940 Scale = Scale & ~1;
14941 return Scale == 2 || Scale == 4 || Scale == 8;
14942 case MVT::i64:
14943 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14944 // version in Thumb mode.
14945 // r + r
14946 if (Scale == 1)
14947 return true;
14948 // r * 2 (this can be lowered to r + r).
14949 if (!AM.HasBaseReg && Scale == 2)
14950 return true;
14951 return false;
14952 case MVT::isVoid:
14953 // Note, we allow "void" uses (basically, uses that aren't loads or
14954 // stores), because arm allows folding a scale into many arithmetic
14955 // operations. This should be made more precise and revisited later.
14957 // Allow r << imm, but the imm has to be a multiple of two.
14958 if (Scale & 1) return false;
14959 return isPowerOf2_32(Scale);
14963 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14964 EVT VT) const {
14965 const int Scale = AM.Scale;
14967 // Negative scales are not supported in Thumb1.
14968 if (Scale < 0)
14969 return false;
14971 // Thumb1 addressing modes do not support register scaling excepting the
14972 // following cases:
14973 // 1. Scale == 1 means no scaling.
14974 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14975 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14978 /// isLegalAddressingMode - Return true if the addressing mode represented
14979 /// by AM is legal for this target, for a load/store of the specified type.
14980 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14981 const AddrMode &AM, Type *Ty,
14982 unsigned AS, Instruction *I) const {
14983 EVT VT = getValueType(DL, Ty, true);
14984 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14985 return false;
14987 // Can never fold addr of global into load/store.
14988 if (AM.BaseGV)
14989 return false;
14991 switch (AM.Scale) {
14992 case 0: // no scale reg, must be "r+i" or "r", or "i".
14993 break;
14994 default:
14995 // ARM doesn't support any R+R*scale+imm addr modes.
14996 if (AM.BaseOffs)
14997 return false;
14999 if (!VT.isSimple())
15000 return false;
15002 if (Subtarget->isThumb1Only())
15003 return isLegalT1ScaledAddressingMode(AM, VT);
15005 if (Subtarget->isThumb2())
15006 return isLegalT2ScaledAddressingMode(AM, VT);
15008 int Scale = AM.Scale;
15009 switch (VT.getSimpleVT().SimpleTy) {
15010 default: return false;
15011 case MVT::i1:
15012 case MVT::i8:
15013 case MVT::i32:
15014 if (Scale < 0) Scale = -Scale;
15015 if (Scale == 1)
15016 return true;
15017 // r + r << imm
15018 return isPowerOf2_32(Scale & ~1);
15019 case MVT::i16:
15020 case MVT::i64:
15021 // r +/- r
15022 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
15023 return true;
15024 // r * 2 (this can be lowered to r + r).
15025 if (!AM.HasBaseReg && Scale == 2)
15026 return true;
15027 return false;
15029 case MVT::isVoid:
15030 // Note, we allow "void" uses (basically, uses that aren't loads or
15031 // stores), because arm allows folding a scale into many arithmetic
15032 // operations. This should be made more precise and revisited later.
15034 // Allow r << imm, but the imm has to be a multiple of two.
15035 if (Scale & 1) return false;
15036 return isPowerOf2_32(Scale);
15039 return true;
15042 /// isLegalICmpImmediate - Return true if the specified immediate is legal
15043 /// icmp immediate, that is the target has icmp instructions which can compare
15044 /// a register against the immediate without having to materialize the
15045 /// immediate into a register.
15046 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15047 // Thumb2 and ARM modes can use cmn for negative immediates.
15048 if (!Subtarget->isThumb())
15049 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
15050 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
15051 if (Subtarget->isThumb2())
15052 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
15053 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
15054 // Thumb1 doesn't have cmn, and only 8-bit immediates.
15055 return Imm >= 0 && Imm <= 255;
15058 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
15059 /// *or sub* immediate, that is the target has add or sub instructions which can
15060 /// add a register with the immediate without having to materialize the
15061 /// immediate into a register.
15062 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15063 // Same encoding for add/sub, just flip the sign.
15064 int64_t AbsImm = std::abs(Imm);
15065 if (!Subtarget->isThumb())
15066 return ARM_AM::getSOImmVal(AbsImm) != -1;
15067 if (Subtarget->isThumb2())
15068 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
15069 // Thumb1 only has 8-bit unsigned immediate.
15070 return AbsImm >= 0 && AbsImm <= 255;
15073 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
15074 bool isSEXTLoad, SDValue &Base,
15075 SDValue &Offset, bool &isInc,
15076 SelectionDAG &DAG) {
15077 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15078 return false;
15080 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
15081 // AddressingMode 3
15082 Base = Ptr->getOperand(0);
15083 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15084 int RHSC = (int)RHS->getZExtValue();
15085 if (RHSC < 0 && RHSC > -256) {
15086 assert(Ptr->getOpcode() == ISD::ADD);
15087 isInc = false;
15088 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15089 return true;
15092 isInc = (Ptr->getOpcode() == ISD::ADD);
15093 Offset = Ptr->getOperand(1);
15094 return true;
15095 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
15096 // AddressingMode 2
15097 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15098 int RHSC = (int)RHS->getZExtValue();
15099 if (RHSC < 0 && RHSC > -0x1000) {
15100 assert(Ptr->getOpcode() == ISD::ADD);
15101 isInc = false;
15102 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15103 Base = Ptr->getOperand(0);
15104 return true;
15108 if (Ptr->getOpcode() == ISD::ADD) {
15109 isInc = true;
15110 ARM_AM::ShiftOpc ShOpcVal=
15111 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
15112 if (ShOpcVal != ARM_AM::no_shift) {
15113 Base = Ptr->getOperand(1);
15114 Offset = Ptr->getOperand(0);
15115 } else {
15116 Base = Ptr->getOperand(0);
15117 Offset = Ptr->getOperand(1);
15119 return true;
15122 isInc = (Ptr->getOpcode() == ISD::ADD);
15123 Base = Ptr->getOperand(0);
15124 Offset = Ptr->getOperand(1);
15125 return true;
15128 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
15129 return false;
15132 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
15133 bool isSEXTLoad, SDValue &Base,
15134 SDValue &Offset, bool &isInc,
15135 SelectionDAG &DAG) {
15136 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15137 return false;
15139 Base = Ptr->getOperand(0);
15140 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15141 int RHSC = (int)RHS->getZExtValue();
15142 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
15143 assert(Ptr->getOpcode() == ISD::ADD);
15144 isInc = false;
15145 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15146 return true;
15147 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
15148 isInc = Ptr->getOpcode() == ISD::ADD;
15149 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
15150 return true;
15154 return false;
15157 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
15158 bool isSEXTLoad, bool isLE, SDValue &Base,
15159 SDValue &Offset, bool &isInc,
15160 SelectionDAG &DAG) {
15161 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15162 return false;
15163 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
15164 return false;
15166 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
15167 int RHSC = (int)RHS->getZExtValue();
15169 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
15170 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
15171 assert(Ptr->getOpcode() == ISD::ADD);
15172 isInc = false;
15173 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15174 return true;
15175 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
15176 isInc = Ptr->getOpcode() == ISD::ADD;
15177 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
15178 return true;
15180 return false;
15183 // Try to find a matching instruction based on s/zext, Alignment, Offset and
15184 // (in BE) type.
15185 Base = Ptr->getOperand(0);
15186 if (VT == MVT::v4i16) {
15187 if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
15188 return true;
15189 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
15190 if (IsInRange(RHSC, 0x80, 1))
15191 return true;
15192 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) &&
15193 IsInRange(RHSC, 0x80, 4))
15194 return true;
15195 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) &&
15196 IsInRange(RHSC, 0x80, 2))
15197 return true;
15198 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
15199 return true;
15200 return false;
15203 /// getPreIndexedAddressParts - returns true by value, base pointer and
15204 /// offset pointer and addressing mode by reference if the node's address
15205 /// can be legally represented as pre-indexed load / store address.
15206 bool
15207 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
15208 SDValue &Offset,
15209 ISD::MemIndexedMode &AM,
15210 SelectionDAG &DAG) const {
15211 if (Subtarget->isThumb1Only())
15212 return false;
15214 EVT VT;
15215 SDValue Ptr;
15216 unsigned Align;
15217 bool isSEXTLoad = false;
15218 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15219 Ptr = LD->getBasePtr();
15220 VT = LD->getMemoryVT();
15221 Align = LD->getAlignment();
15222 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15223 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15224 Ptr = ST->getBasePtr();
15225 VT = ST->getMemoryVT();
15226 Align = ST->getAlignment();
15227 } else
15228 return false;
15230 bool isInc;
15231 bool isLegal = false;
15232 if (VT.isVector())
15233 isLegal = Subtarget->hasMVEIntegerOps() &&
15234 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
15235 Subtarget->isLittle(), Base, Offset,
15236 isInc, DAG);
15237 else {
15238 if (Subtarget->isThumb2())
15239 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
15240 Offset, isInc, DAG);
15241 else
15242 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
15243 Offset, isInc, DAG);
15245 if (!isLegal)
15246 return false;
15248 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
15249 return true;
15252 /// getPostIndexedAddressParts - returns true by value, base pointer and
15253 /// offset pointer and addressing mode by reference if this node can be
15254 /// combined with a load / store to form a post-indexed load / store.
15255 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
15256 SDValue &Base,
15257 SDValue &Offset,
15258 ISD::MemIndexedMode &AM,
15259 SelectionDAG &DAG) const {
15260 EVT VT;
15261 SDValue Ptr;
15262 unsigned Align;
15263 bool isSEXTLoad = false, isNonExt;
15264 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15265 VT = LD->getMemoryVT();
15266 Ptr = LD->getBasePtr();
15267 Align = LD->getAlignment();
15268 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15269 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
15270 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15271 VT = ST->getMemoryVT();
15272 Ptr = ST->getBasePtr();
15273 Align = ST->getAlignment();
15274 isNonExt = !ST->isTruncatingStore();
15275 } else
15276 return false;
15278 if (Subtarget->isThumb1Only()) {
15279 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
15280 // must be non-extending/truncating, i32, with an offset of 4.
15281 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
15282 if (Op->getOpcode() != ISD::ADD || !isNonExt)
15283 return false;
15284 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15285 if (!RHS || RHS->getZExtValue() != 4)
15286 return false;
15288 Offset = Op->getOperand(1);
15289 Base = Op->getOperand(0);
15290 AM = ISD::POST_INC;
15291 return true;
15294 bool isInc;
15295 bool isLegal = false;
15296 if (VT.isVector())
15297 isLegal = Subtarget->hasMVEIntegerOps() &&
15298 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad,
15299 Subtarget->isLittle(), Base, Offset,
15300 isInc, DAG);
15301 else {
15302 if (Subtarget->isThumb2())
15303 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15304 isInc, DAG);
15305 else
15306 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15307 isInc, DAG);
15309 if (!isLegal)
15310 return false;
15312 if (Ptr != Base) {
15313 // Swap base ptr and offset to catch more post-index load / store when
15314 // it's legal. In Thumb2 mode, offset must be an immediate.
15315 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
15316 !Subtarget->isThumb2())
15317 std::swap(Base, Offset);
15319 // Post-indexed load / store update the base pointer.
15320 if (Ptr != Base)
15321 return false;
15324 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
15325 return true;
15328 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15329 KnownBits &Known,
15330 const APInt &DemandedElts,
15331 const SelectionDAG &DAG,
15332 unsigned Depth) const {
15333 unsigned BitWidth = Known.getBitWidth();
15334 Known.resetAll();
15335 switch (Op.getOpcode()) {
15336 default: break;
15337 case ARMISD::ADDC:
15338 case ARMISD::ADDE:
15339 case ARMISD::SUBC:
15340 case ARMISD::SUBE:
15341 // Special cases when we convert a carry to a boolean.
15342 if (Op.getResNo() == 0) {
15343 SDValue LHS = Op.getOperand(0);
15344 SDValue RHS = Op.getOperand(1);
15345 // (ADDE 0, 0, C) will give us a single bit.
15346 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
15347 isNullConstant(RHS)) {
15348 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15349 return;
15352 break;
15353 case ARMISD::CMOV: {
15354 // Bits are known zero/one if known on the LHS and RHS.
15355 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
15356 if (Known.isUnknown())
15357 return;
15359 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
15360 Known.Zero &= KnownRHS.Zero;
15361 Known.One &= KnownRHS.One;
15362 return;
15364 case ISD::INTRINSIC_W_CHAIN: {
15365 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
15366 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
15367 switch (IntID) {
15368 default: return;
15369 case Intrinsic::arm_ldaex:
15370 case Intrinsic::arm_ldrex: {
15371 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
15372 unsigned MemBits = VT.getScalarSizeInBits();
15373 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
15374 return;
15378 case ARMISD::BFI: {
15379 // Conservatively, we can recurse down the first operand
15380 // and just mask out all affected bits.
15381 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
15383 // The operand to BFI is already a mask suitable for removing the bits it
15384 // sets.
15385 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
15386 const APInt &Mask = CI->getAPIntValue();
15387 Known.Zero &= Mask;
15388 Known.One &= Mask;
15389 return;
15391 case ARMISD::VGETLANEs:
15392 case ARMISD::VGETLANEu: {
15393 const SDValue &SrcSV = Op.getOperand(0);
15394 EVT VecVT = SrcSV.getValueType();
15395 assert(VecVT.isVector() && "VGETLANE expected a vector type");
15396 const unsigned NumSrcElts = VecVT.getVectorNumElements();
15397 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
15398 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
15399 "VGETLANE index out of bounds");
15400 unsigned Idx = Pos->getZExtValue();
15401 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
15402 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
15404 EVT VT = Op.getValueType();
15405 const unsigned DstSz = VT.getScalarSizeInBits();
15406 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
15407 (void)SrcSz;
15408 assert(SrcSz == Known.getBitWidth());
15409 assert(DstSz > SrcSz);
15410 if (Op.getOpcode() == ARMISD::VGETLANEs)
15411 Known = Known.sext(DstSz);
15412 else {
15413 Known = Known.zext(DstSz, true /* extended bits are known zero */);
15415 assert(DstSz == Known.getBitWidth());
15416 break;
15421 bool
15422 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
15423 const APInt &DemandedAPInt,
15424 TargetLoweringOpt &TLO) const {
15425 // Delay optimization, so we don't have to deal with illegal types, or block
15426 // optimizations.
15427 if (!TLO.LegalOps)
15428 return false;
15430 // Only optimize AND for now.
15431 if (Op.getOpcode() != ISD::AND)
15432 return false;
15434 EVT VT = Op.getValueType();
15436 // Ignore vectors.
15437 if (VT.isVector())
15438 return false;
15440 assert(VT == MVT::i32 && "Unexpected integer type");
15442 // Make sure the RHS really is a constant.
15443 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15444 if (!C)
15445 return false;
15447 unsigned Mask = C->getZExtValue();
15449 unsigned Demanded = DemandedAPInt.getZExtValue();
15450 unsigned ShrunkMask = Mask & Demanded;
15451 unsigned ExpandedMask = Mask | ~Demanded;
15453 // If the mask is all zeros, let the target-independent code replace the
15454 // result with zero.
15455 if (ShrunkMask == 0)
15456 return false;
15458 // If the mask is all ones, erase the AND. (Currently, the target-independent
15459 // code won't do this, so we have to do it explicitly to avoid an infinite
15460 // loop in obscure cases.)
15461 if (ExpandedMask == ~0U)
15462 return TLO.CombineTo(Op, Op.getOperand(0));
15464 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
15465 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
15467 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
15468 if (NewMask == Mask)
15469 return true;
15470 SDLoc DL(Op);
15471 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
15472 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
15473 return TLO.CombineTo(Op, NewOp);
15476 // Prefer uxtb mask.
15477 if (IsLegalMask(0xFF))
15478 return UseMask(0xFF);
15480 // Prefer uxth mask.
15481 if (IsLegalMask(0xFFFF))
15482 return UseMask(0xFFFF);
15484 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
15485 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15486 if (ShrunkMask < 256)
15487 return UseMask(ShrunkMask);
15489 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
15490 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15491 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
15492 return UseMask(ExpandedMask);
15494 // Potential improvements:
15496 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
15497 // We could try to prefer Thumb1 immediates which can be lowered to a
15498 // two-instruction sequence.
15499 // We could try to recognize more legal ARM/Thumb2 immediates here.
15501 return false;
15505 //===----------------------------------------------------------------------===//
15506 // ARM Inline Assembly Support
15507 //===----------------------------------------------------------------------===//
15509 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
15510 // Looking for "rev" which is V6+.
15511 if (!Subtarget->hasV6Ops())
15512 return false;
15514 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15515 std::string AsmStr = IA->getAsmString();
15516 SmallVector<StringRef, 4> AsmPieces;
15517 SplitString(AsmStr, AsmPieces, ";\n");
15519 switch (AsmPieces.size()) {
15520 default: return false;
15521 case 1:
15522 AsmStr = AsmPieces[0];
15523 AsmPieces.clear();
15524 SplitString(AsmStr, AsmPieces, " \t,");
15526 // rev $0, $1
15527 if (AsmPieces.size() == 3 &&
15528 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
15529 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
15530 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15531 if (Ty && Ty->getBitWidth() == 32)
15532 return IntrinsicLowering::LowerToByteSwap(CI);
15534 break;
15537 return false;
15540 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
15541 // At this point, we have to lower this constraint to something else, so we
15542 // lower it to an "r" or "w". However, by doing this we will force the result
15543 // to be in register, while the X constraint is much more permissive.
15545 // Although we are correct (we are free to emit anything, without
15546 // constraints), we might break use cases that would expect us to be more
15547 // efficient and emit something else.
15548 if (!Subtarget->hasVFP2Base())
15549 return "r";
15550 if (ConstraintVT.isFloatingPoint())
15551 return "w";
15552 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
15553 (ConstraintVT.getSizeInBits() == 64 ||
15554 ConstraintVT.getSizeInBits() == 128))
15555 return "w";
15557 return "r";
15560 /// getConstraintType - Given a constraint letter, return the type of
15561 /// constraint it is for this target.
15562 ARMTargetLowering::ConstraintType
15563 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
15564 unsigned S = Constraint.size();
15565 if (S == 1) {
15566 switch (Constraint[0]) {
15567 default: break;
15568 case 'l': return C_RegisterClass;
15569 case 'w': return C_RegisterClass;
15570 case 'h': return C_RegisterClass;
15571 case 'x': return C_RegisterClass;
15572 case 't': return C_RegisterClass;
15573 case 'j': return C_Immediate; // Constant for movw.
15574 // An address with a single base register. Due to the way we
15575 // currently handle addresses it is the same as an 'r' memory constraint.
15576 case 'Q': return C_Memory;
15578 } else if (S == 2) {
15579 switch (Constraint[0]) {
15580 default: break;
15581 case 'T': return C_RegisterClass;
15582 // All 'U+' constraints are addresses.
15583 case 'U': return C_Memory;
15586 return TargetLowering::getConstraintType(Constraint);
15589 /// Examine constraint type and operand type and determine a weight value.
15590 /// This object must already have been set up with the operand type
15591 /// and the current alternative constraint selected.
15592 TargetLowering::ConstraintWeight
15593 ARMTargetLowering::getSingleConstraintMatchWeight(
15594 AsmOperandInfo &info, const char *constraint) const {
15595 ConstraintWeight weight = CW_Invalid;
15596 Value *CallOperandVal = info.CallOperandVal;
15597 // If we don't have a value, we can't do a match,
15598 // but allow it at the lowest weight.
15599 if (!CallOperandVal)
15600 return CW_Default;
15601 Type *type = CallOperandVal->getType();
15602 // Look at the constraint type.
15603 switch (*constraint) {
15604 default:
15605 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15606 break;
15607 case 'l':
15608 if (type->isIntegerTy()) {
15609 if (Subtarget->isThumb())
15610 weight = CW_SpecificReg;
15611 else
15612 weight = CW_Register;
15614 break;
15615 case 'w':
15616 if (type->isFloatingPointTy())
15617 weight = CW_Register;
15618 break;
15620 return weight;
15623 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
15625 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
15626 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
15627 switch (Constraint.size()) {
15628 case 1:
15629 // GCC ARM Constraint Letters
15630 switch (Constraint[0]) {
15631 case 'l': // Low regs or general regs.
15632 if (Subtarget->isThumb())
15633 return RCPair(0U, &ARM::tGPRRegClass);
15634 return RCPair(0U, &ARM::GPRRegClass);
15635 case 'h': // High regs or no regs.
15636 if (Subtarget->isThumb())
15637 return RCPair(0U, &ARM::hGPRRegClass);
15638 break;
15639 case 'r':
15640 if (Subtarget->isThumb1Only())
15641 return RCPair(0U, &ARM::tGPRRegClass);
15642 return RCPair(0U, &ARM::GPRRegClass);
15643 case 'w':
15644 if (VT == MVT::Other)
15645 break;
15646 if (VT == MVT::f32)
15647 return RCPair(0U, &ARM::SPRRegClass);
15648 if (VT.getSizeInBits() == 64)
15649 return RCPair(0U, &ARM::DPRRegClass);
15650 if (VT.getSizeInBits() == 128)
15651 return RCPair(0U, &ARM::QPRRegClass);
15652 break;
15653 case 'x':
15654 if (VT == MVT::Other)
15655 break;
15656 if (VT == MVT::f32)
15657 return RCPair(0U, &ARM::SPR_8RegClass);
15658 if (VT.getSizeInBits() == 64)
15659 return RCPair(0U, &ARM::DPR_8RegClass);
15660 if (VT.getSizeInBits() == 128)
15661 return RCPair(0U, &ARM::QPR_8RegClass);
15662 break;
15663 case 't':
15664 if (VT == MVT::Other)
15665 break;
15666 if (VT == MVT::f32 || VT == MVT::i32)
15667 return RCPair(0U, &ARM::SPRRegClass);
15668 if (VT.getSizeInBits() == 64)
15669 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15670 if (VT.getSizeInBits() == 128)
15671 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15672 break;
15674 break;
15676 case 2:
15677 if (Constraint[0] == 'T') {
15678 switch (Constraint[1]) {
15679 default:
15680 break;
15681 case 'e':
15682 return RCPair(0U, &ARM::tGPREvenRegClass);
15683 case 'o':
15684 return RCPair(0U, &ARM::tGPROddRegClass);
15687 break;
15689 default:
15690 break;
15693 if (StringRef("{cc}").equals_lower(Constraint))
15694 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15696 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15699 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15700 /// vector. If it is invalid, don't add anything to Ops.
15701 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15702 std::string &Constraint,
15703 std::vector<SDValue>&Ops,
15704 SelectionDAG &DAG) const {
15705 SDValue Result;
15707 // Currently only support length 1 constraints.
15708 if (Constraint.length() != 1) return;
15710 char ConstraintLetter = Constraint[0];
15711 switch (ConstraintLetter) {
15712 default: break;
15713 case 'j':
15714 case 'I': case 'J': case 'K': case 'L':
15715 case 'M': case 'N': case 'O':
15716 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15717 if (!C)
15718 return;
15720 int64_t CVal64 = C->getSExtValue();
15721 int CVal = (int) CVal64;
15722 // None of these constraints allow values larger than 32 bits. Check
15723 // that the value fits in an int.
15724 if (CVal != CVal64)
15725 return;
15727 switch (ConstraintLetter) {
15728 case 'j':
15729 // Constant suitable for movw, must be between 0 and
15730 // 65535.
15731 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
15732 if (CVal >= 0 && CVal <= 65535)
15733 break;
15734 return;
15735 case 'I':
15736 if (Subtarget->isThumb1Only()) {
15737 // This must be a constant between 0 and 255, for ADD
15738 // immediates.
15739 if (CVal >= 0 && CVal <= 255)
15740 break;
15741 } else if (Subtarget->isThumb2()) {
15742 // A constant that can be used as an immediate value in a
15743 // data-processing instruction.
15744 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15745 break;
15746 } else {
15747 // A constant that can be used as an immediate value in a
15748 // data-processing instruction.
15749 if (ARM_AM::getSOImmVal(CVal) != -1)
15750 break;
15752 return;
15754 case 'J':
15755 if (Subtarget->isThumb1Only()) {
15756 // This must be a constant between -255 and -1, for negated ADD
15757 // immediates. This can be used in GCC with an "n" modifier that
15758 // prints the negated value, for use with SUB instructions. It is
15759 // not useful otherwise but is implemented for compatibility.
15760 if (CVal >= -255 && CVal <= -1)
15761 break;
15762 } else {
15763 // This must be a constant between -4095 and 4095. It is not clear
15764 // what this constraint is intended for. Implemented for
15765 // compatibility with GCC.
15766 if (CVal >= -4095 && CVal <= 4095)
15767 break;
15769 return;
15771 case 'K':
15772 if (Subtarget->isThumb1Only()) {
15773 // A 32-bit value where only one byte has a nonzero value. Exclude
15774 // zero to match GCC. This constraint is used by GCC internally for
15775 // constants that can be loaded with a move/shift combination.
15776 // It is not useful otherwise but is implemented for compatibility.
15777 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15778 break;
15779 } else if (Subtarget->isThumb2()) {
15780 // A constant whose bitwise inverse can be used as an immediate
15781 // value in a data-processing instruction. This can be used in GCC
15782 // with a "B" modifier that prints the inverted value, for use with
15783 // BIC and MVN instructions. It is not useful otherwise but is
15784 // implemented for compatibility.
15785 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15786 break;
15787 } else {
15788 // A constant whose bitwise inverse can be used as an immediate
15789 // value in a data-processing instruction. This can be used in GCC
15790 // with a "B" modifier that prints the inverted value, for use with
15791 // BIC and MVN instructions. It is not useful otherwise but is
15792 // implemented for compatibility.
15793 if (ARM_AM::getSOImmVal(~CVal) != -1)
15794 break;
15796 return;
15798 case 'L':
15799 if (Subtarget->isThumb1Only()) {
15800 // This must be a constant between -7 and 7,
15801 // for 3-operand ADD/SUB immediate instructions.
15802 if (CVal >= -7 && CVal < 7)
15803 break;
15804 } else if (Subtarget->isThumb2()) {
15805 // A constant whose negation can be used as an immediate value in a
15806 // data-processing instruction. This can be used in GCC with an "n"
15807 // modifier that prints the negated value, for use with SUB
15808 // instructions. It is not useful otherwise but is implemented for
15809 // compatibility.
15810 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15811 break;
15812 } else {
15813 // A constant whose negation can be used as an immediate value in a
15814 // data-processing instruction. This can be used in GCC with an "n"
15815 // modifier that prints the negated value, for use with SUB
15816 // instructions. It is not useful otherwise but is implemented for
15817 // compatibility.
15818 if (ARM_AM::getSOImmVal(-CVal) != -1)
15819 break;
15821 return;
15823 case 'M':
15824 if (Subtarget->isThumb1Only()) {
15825 // This must be a multiple of 4 between 0 and 1020, for
15826 // ADD sp + immediate.
15827 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15828 break;
15829 } else {
15830 // A power of two or a constant between 0 and 32. This is used in
15831 // GCC for the shift amount on shifted register operands, but it is
15832 // useful in general for any shift amounts.
15833 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15834 break;
15836 return;
15838 case 'N':
15839 if (Subtarget->isThumb1Only()) {
15840 // This must be a constant between 0 and 31, for shift amounts.
15841 if (CVal >= 0 && CVal <= 31)
15842 break;
15844 return;
15846 case 'O':
15847 if (Subtarget->isThumb1Only()) {
15848 // This must be a multiple of 4 between -508 and 508, for
15849 // ADD/SUB sp = sp + immediate.
15850 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15851 break;
15853 return;
15855 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15856 break;
15859 if (Result.getNode()) {
15860 Ops.push_back(Result);
15861 return;
15863 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15866 static RTLIB::Libcall getDivRemLibcall(
15867 const SDNode *N, MVT::SimpleValueType SVT) {
15868 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15869 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15870 "Unhandled Opcode in getDivRemLibcall");
15871 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15872 N->getOpcode() == ISD::SREM;
15873 RTLIB::Libcall LC;
15874 switch (SVT) {
15875 default: llvm_unreachable("Unexpected request for libcall!");
15876 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15877 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15878 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15879 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15881 return LC;
15884 static TargetLowering::ArgListTy getDivRemArgList(
15885 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15886 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15887 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15888 "Unhandled Opcode in getDivRemArgList");
15889 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15890 N->getOpcode() == ISD::SREM;
15891 TargetLowering::ArgListTy Args;
15892 TargetLowering::ArgListEntry Entry;
15893 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15894 EVT ArgVT = N->getOperand(i).getValueType();
15895 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15896 Entry.Node = N->getOperand(i);
15897 Entry.Ty = ArgTy;
15898 Entry.IsSExt = isSigned;
15899 Entry.IsZExt = !isSigned;
15900 Args.push_back(Entry);
15902 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15903 std::swap(Args[0], Args[1]);
15904 return Args;
15907 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15908 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15909 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15910 Subtarget->isTargetWindows()) &&
15911 "Register-based DivRem lowering only");
15912 unsigned Opcode = Op->getOpcode();
15913 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15914 "Invalid opcode for Div/Rem lowering");
15915 bool isSigned = (Opcode == ISD::SDIVREM);
15916 EVT VT = Op->getValueType(0);
15917 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15918 SDLoc dl(Op);
15920 // If the target has hardware divide, use divide + multiply + subtract:
15921 // div = a / b
15922 // rem = a - b * div
15923 // return {div, rem}
15924 // This should be lowered into UDIV/SDIV + MLS later on.
15925 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15926 : Subtarget->hasDivideInARMMode();
15927 if (hasDivide && Op->getValueType(0).isSimple() &&
15928 Op->getSimpleValueType(0) == MVT::i32) {
15929 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15930 const SDValue Dividend = Op->getOperand(0);
15931 const SDValue Divisor = Op->getOperand(1);
15932 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15933 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15934 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15936 SDValue Values[2] = {Div, Rem};
15937 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15940 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15941 VT.getSimpleVT().SimpleTy);
15942 SDValue InChain = DAG.getEntryNode();
15944 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15945 DAG.getContext(),
15946 Subtarget);
15948 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15949 getPointerTy(DAG.getDataLayout()));
15951 Type *RetTy = StructType::get(Ty, Ty);
15953 if (Subtarget->isTargetWindows())
15954 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15956 TargetLowering::CallLoweringInfo CLI(DAG);
15957 CLI.setDebugLoc(dl).setChain(InChain)
15958 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15959 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15961 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15962 return CallInfo.first;
15965 // Lowers REM using divmod helpers
15966 // see RTABI section 4.2/4.3
15967 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15968 // Build return types (div and rem)
15969 std::vector<Type*> RetTyParams;
15970 Type *RetTyElement;
15972 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15973 default: llvm_unreachable("Unexpected request for libcall!");
15974 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15975 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15976 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15977 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15980 RetTyParams.push_back(RetTyElement);
15981 RetTyParams.push_back(RetTyElement);
15982 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15983 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15985 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15986 SimpleTy);
15987 SDValue InChain = DAG.getEntryNode();
15988 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15989 Subtarget);
15990 bool isSigned = N->getOpcode() == ISD::SREM;
15991 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15992 getPointerTy(DAG.getDataLayout()));
15994 if (Subtarget->isTargetWindows())
15995 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15997 // Lower call
15998 CallLoweringInfo CLI(DAG);
15999 CLI.setChain(InChain)
16000 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
16001 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
16002 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
16004 // Return second (rem) result operand (first contains div)
16005 SDNode *ResNode = CallResult.first.getNode();
16006 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
16007 return ResNode->getOperand(1);
16010 SDValue
16011 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
16012 assert(Subtarget->isTargetWindows() && "unsupported target platform");
16013 SDLoc DL(Op);
16015 // Get the inputs.
16016 SDValue Chain = Op.getOperand(0);
16017 SDValue Size = Op.getOperand(1);
16019 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
16020 "no-stack-arg-probe")) {
16021 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16022 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
16023 Chain = SP.getValue(1);
16024 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
16025 if (Align)
16026 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
16027 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
16028 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
16029 SDValue Ops[2] = { SP, Chain };
16030 return DAG.getMergeValues(Ops, DL);
16033 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
16034 DAG.getConstant(2, DL, MVT::i32));
16036 SDValue Flag;
16037 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
16038 Flag = Chain.getValue(1);
16040 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16041 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
16043 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
16044 Chain = NewSP.getValue(1);
16046 SDValue Ops[2] = { NewSP, Chain };
16047 return DAG.getMergeValues(Ops, DL);
16050 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
16051 SDValue SrcVal = Op.getOperand(0);
16052 const unsigned DstSz = Op.getValueType().getSizeInBits();
16053 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
16054 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
16055 "Unexpected type for custom-lowering FP_EXTEND");
16057 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
16058 "With both FP DP and 16, any FP conversion is legal!");
16060 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
16061 "With FP16, 16 to 32 conversion is legal!");
16063 // Either we are converting from 16 -> 64, without FP16 and/or
16064 // FP.double-precision or without Armv8-fp. So we must do it in two
16065 // steps.
16066 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
16067 // without FP16. So we must do a function call.
16068 SDLoc Loc(Op);
16069 RTLIB::Libcall LC;
16070 MakeLibCallOptions CallOptions;
16071 if (SrcSz == 16) {
16072 // Instruction from 16 -> 32
16073 if (Subtarget->hasFP16())
16074 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
16075 // Lib call from 16 -> 32
16076 else {
16077 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
16078 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
16079 "Unexpected type for custom-lowering FP_EXTEND");
16080 SrcVal =
16081 makeLibCall(DAG, LC, MVT::f32, SrcVal, CallOptions, Loc).first;
16085 if (DstSz != 64)
16086 return SrcVal;
16087 // For sure now SrcVal is 32 bits
16088 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
16089 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
16091 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
16092 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
16093 "Unexpected type for custom-lowering FP_EXTEND");
16094 return makeLibCall(DAG, LC, MVT::f64, SrcVal, CallOptions, Loc).first;
16097 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
16098 SDValue SrcVal = Op.getOperand(0);
16099 EVT SrcVT = SrcVal.getValueType();
16100 EVT DstVT = Op.getValueType();
16101 const unsigned DstSz = Op.getValueType().getSizeInBits();
16102 const unsigned SrcSz = SrcVT.getSizeInBits();
16103 (void)DstSz;
16104 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
16105 "Unexpected type for custom-lowering FP_ROUND");
16107 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
16108 "With both FP DP and 16, any FP conversion is legal!");
16110 SDLoc Loc(Op);
16112 // Instruction from 32 -> 16 if hasFP16 is valid
16113 if (SrcSz == 32 && Subtarget->hasFP16())
16114 return Op;
16116 // Lib call from 32 -> 16 / 64 -> [32, 16]
16117 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
16118 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
16119 "Unexpected type for custom-lowering FP_ROUND");
16120 MakeLibCallOptions CallOptions;
16121 return makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, Loc).first;
16124 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
16125 SelectionDAG &DAG) const {
16126 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
16127 MVT HalfT = MVT::i32;
16128 SDLoc dl(N);
16129 SDValue Hi, Lo, Tmp;
16131 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
16132 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
16133 return ;
16135 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
16136 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
16138 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
16139 DAG.getConstant(0, dl, HalfT));
16140 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
16141 DAG.getConstant(1, dl, HalfT));
16143 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
16144 DAG.getConstant(OpTypeBits - 1, dl,
16145 getShiftAmountTy(HalfT, DAG.getDataLayout())));
16146 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
16147 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
16148 SDValue(Lo.getNode(), 1));
16149 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
16150 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
16152 Results.push_back(Lo);
16153 Results.push_back(Hi);
16156 bool
16157 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16158 // The ARM target isn't yet aware of offsets.
16159 return false;
16162 bool ARM::isBitFieldInvertedMask(unsigned v) {
16163 if (v == 0xffffffff)
16164 return false;
16166 // there can be 1's on either or both "outsides", all the "inside"
16167 // bits must be 0's
16168 return isShiftedMask_32(~v);
16171 /// isFPImmLegal - Returns true if the target can instruction select the
16172 /// specified FP immediate natively. If false, the legalizer will
16173 /// materialize the FP immediate as a load from a constant pool.
16174 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16175 bool ForCodeSize) const {
16176 if (!Subtarget->hasVFP3Base())
16177 return false;
16178 if (VT == MVT::f16 && Subtarget->hasFullFP16())
16179 return ARM_AM::getFP16Imm(Imm) != -1;
16180 if (VT == MVT::f32)
16181 return ARM_AM::getFP32Imm(Imm) != -1;
16182 if (VT == MVT::f64 && Subtarget->hasFP64())
16183 return ARM_AM::getFP64Imm(Imm) != -1;
16184 return false;
16187 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
16188 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
16189 /// specified in the intrinsic calls.
16190 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16191 const CallInst &I,
16192 MachineFunction &MF,
16193 unsigned Intrinsic) const {
16194 switch (Intrinsic) {
16195 case Intrinsic::arm_neon_vld1:
16196 case Intrinsic::arm_neon_vld2:
16197 case Intrinsic::arm_neon_vld3:
16198 case Intrinsic::arm_neon_vld4:
16199 case Intrinsic::arm_neon_vld2lane:
16200 case Intrinsic::arm_neon_vld3lane:
16201 case Intrinsic::arm_neon_vld4lane:
16202 case Intrinsic::arm_neon_vld2dup:
16203 case Intrinsic::arm_neon_vld3dup:
16204 case Intrinsic::arm_neon_vld4dup: {
16205 Info.opc = ISD::INTRINSIC_W_CHAIN;
16206 // Conservatively set memVT to the entire set of vectors loaded.
16207 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16208 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
16209 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16210 Info.ptrVal = I.getArgOperand(0);
16211 Info.offset = 0;
16212 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
16213 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
16214 // volatile loads with NEON intrinsics not supported
16215 Info.flags = MachineMemOperand::MOLoad;
16216 return true;
16218 case Intrinsic::arm_neon_vld1x2:
16219 case Intrinsic::arm_neon_vld1x3:
16220 case Intrinsic::arm_neon_vld1x4: {
16221 Info.opc = ISD::INTRINSIC_W_CHAIN;
16222 // Conservatively set memVT to the entire set of vectors loaded.
16223 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16224 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
16225 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16226 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
16227 Info.offset = 0;
16228 Info.align.reset();
16229 // volatile loads with NEON intrinsics not supported
16230 Info.flags = MachineMemOperand::MOLoad;
16231 return true;
16233 case Intrinsic::arm_neon_vst1:
16234 case Intrinsic::arm_neon_vst2:
16235 case Intrinsic::arm_neon_vst3:
16236 case Intrinsic::arm_neon_vst4:
16237 case Intrinsic::arm_neon_vst2lane:
16238 case Intrinsic::arm_neon_vst3lane:
16239 case Intrinsic::arm_neon_vst4lane: {
16240 Info.opc = ISD::INTRINSIC_VOID;
16241 // Conservatively set memVT to the entire set of vectors stored.
16242 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16243 unsigned NumElts = 0;
16244 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
16245 Type *ArgTy = I.getArgOperand(ArgI)->getType();
16246 if (!ArgTy->isVectorTy())
16247 break;
16248 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
16250 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16251 Info.ptrVal = I.getArgOperand(0);
16252 Info.offset = 0;
16253 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
16254 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
16255 // volatile stores with NEON intrinsics not supported
16256 Info.flags = MachineMemOperand::MOStore;
16257 return true;
16259 case Intrinsic::arm_neon_vst1x2:
16260 case Intrinsic::arm_neon_vst1x3:
16261 case Intrinsic::arm_neon_vst1x4: {
16262 Info.opc = ISD::INTRINSIC_VOID;
16263 // Conservatively set memVT to the entire set of vectors stored.
16264 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16265 unsigned NumElts = 0;
16266 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
16267 Type *ArgTy = I.getArgOperand(ArgI)->getType();
16268 if (!ArgTy->isVectorTy())
16269 break;
16270 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
16272 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16273 Info.ptrVal = I.getArgOperand(0);
16274 Info.offset = 0;
16275 Info.align.reset();
16276 // volatile stores with NEON intrinsics not supported
16277 Info.flags = MachineMemOperand::MOStore;
16278 return true;
16280 case Intrinsic::arm_ldaex:
16281 case Intrinsic::arm_ldrex: {
16282 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16283 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
16284 Info.opc = ISD::INTRINSIC_W_CHAIN;
16285 Info.memVT = MVT::getVT(PtrTy->getElementType());
16286 Info.ptrVal = I.getArgOperand(0);
16287 Info.offset = 0;
16288 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
16289 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16290 return true;
16292 case Intrinsic::arm_stlex:
16293 case Intrinsic::arm_strex: {
16294 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16295 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
16296 Info.opc = ISD::INTRINSIC_W_CHAIN;
16297 Info.memVT = MVT::getVT(PtrTy->getElementType());
16298 Info.ptrVal = I.getArgOperand(1);
16299 Info.offset = 0;
16300 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
16301 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16302 return true;
16304 case Intrinsic::arm_stlexd:
16305 case Intrinsic::arm_strexd:
16306 Info.opc = ISD::INTRINSIC_W_CHAIN;
16307 Info.memVT = MVT::i64;
16308 Info.ptrVal = I.getArgOperand(2);
16309 Info.offset = 0;
16310 Info.align = Align(8);
16311 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16312 return true;
16314 case Intrinsic::arm_ldaexd:
16315 case Intrinsic::arm_ldrexd:
16316 Info.opc = ISD::INTRINSIC_W_CHAIN;
16317 Info.memVT = MVT::i64;
16318 Info.ptrVal = I.getArgOperand(0);
16319 Info.offset = 0;
16320 Info.align = Align(8);
16321 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16322 return true;
16324 default:
16325 break;
16328 return false;
16331 /// Returns true if it is beneficial to convert a load of a constant
16332 /// to just the constant itself.
16333 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16334 Type *Ty) const {
16335 assert(Ty->isIntegerTy());
16337 unsigned Bits = Ty->getPrimitiveSizeInBits();
16338 if (Bits == 0 || Bits > 32)
16339 return false;
16340 return true;
16343 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
16344 unsigned Index) const {
16345 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
16346 return false;
16348 return (Index == 0 || Index == ResVT.getVectorNumElements());
16351 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
16352 ARM_MB::MemBOpt Domain) const {
16353 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16355 // First, if the target has no DMB, see what fallback we can use.
16356 if (!Subtarget->hasDataBarrier()) {
16357 // Some ARMv6 cpus can support data barriers with an mcr instruction.
16358 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
16359 // here.
16360 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
16361 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
16362 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
16363 Builder.getInt32(0), Builder.getInt32(7),
16364 Builder.getInt32(10), Builder.getInt32(5)};
16365 return Builder.CreateCall(MCR, args);
16366 } else {
16367 // Instead of using barriers, atomic accesses on these subtargets use
16368 // libcalls.
16369 llvm_unreachable("makeDMB on a target so old that it has no barriers");
16371 } else {
16372 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
16373 // Only a full system barrier exists in the M-class architectures.
16374 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
16375 Constant *CDomain = Builder.getInt32(Domain);
16376 return Builder.CreateCall(DMB, CDomain);
16380 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
16381 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
16382 Instruction *Inst,
16383 AtomicOrdering Ord) const {
16384 switch (Ord) {
16385 case AtomicOrdering::NotAtomic:
16386 case AtomicOrdering::Unordered:
16387 llvm_unreachable("Invalid fence: unordered/non-atomic");
16388 case AtomicOrdering::Monotonic:
16389 case AtomicOrdering::Acquire:
16390 return nullptr; // Nothing to do
16391 case AtomicOrdering::SequentiallyConsistent:
16392 if (!Inst->hasAtomicStore())
16393 return nullptr; // Nothing to do
16394 LLVM_FALLTHROUGH;
16395 case AtomicOrdering::Release:
16396 case AtomicOrdering::AcquireRelease:
16397 if (Subtarget->preferISHSTBarriers())
16398 return makeDMB(Builder, ARM_MB::ISHST);
16399 // FIXME: add a comment with a link to documentation justifying this.
16400 else
16401 return makeDMB(Builder, ARM_MB::ISH);
16403 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
16406 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
16407 Instruction *Inst,
16408 AtomicOrdering Ord) const {
16409 switch (Ord) {
16410 case AtomicOrdering::NotAtomic:
16411 case AtomicOrdering::Unordered:
16412 llvm_unreachable("Invalid fence: unordered/not-atomic");
16413 case AtomicOrdering::Monotonic:
16414 case AtomicOrdering::Release:
16415 return nullptr; // Nothing to do
16416 case AtomicOrdering::Acquire:
16417 case AtomicOrdering::AcquireRelease:
16418 case AtomicOrdering::SequentiallyConsistent:
16419 return makeDMB(Builder, ARM_MB::ISH);
16421 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
16424 // Loads and stores less than 64-bits are already atomic; ones above that
16425 // are doomed anyway, so defer to the default libcall and blame the OS when
16426 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16427 // anything for those.
16428 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16429 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
16430 return (Size == 64) && !Subtarget->isMClass();
16433 // Loads and stores less than 64-bits are already atomic; ones above that
16434 // are doomed anyway, so defer to the default libcall and blame the OS when
16435 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16436 // anything for those.
16437 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
16438 // guarantee, see DDI0406C ARM architecture reference manual,
16439 // sections A8.8.72-74 LDRD)
16440 TargetLowering::AtomicExpansionKind
16441 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16442 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
16443 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
16444 : AtomicExpansionKind::None;
16447 // For the real atomic operations, we have ldrex/strex up to 32 bits,
16448 // and up to 64 bits on the non-M profiles
16449 TargetLowering::AtomicExpansionKind
16450 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16451 if (AI->isFloatingPointOperation())
16452 return AtomicExpansionKind::CmpXChg;
16454 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
16455 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16456 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
16457 ? AtomicExpansionKind::LLSC
16458 : AtomicExpansionKind::None;
16461 TargetLowering::AtomicExpansionKind
16462 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
16463 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16464 // implement cmpxchg without spilling. If the address being exchanged is also
16465 // on the stack and close enough to the spill slot, this can lead to a
16466 // situation where the monitor always gets cleared and the atomic operation
16467 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16468 bool HasAtomicCmpXchg =
16469 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16470 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
16471 return AtomicExpansionKind::LLSC;
16472 return AtomicExpansionKind::None;
16475 bool ARMTargetLowering::shouldInsertFencesForAtomic(
16476 const Instruction *I) const {
16477 return InsertFencesForAtomic;
16480 // This has so far only been implemented for MachO.
16481 bool ARMTargetLowering::useLoadStackGuardNode() const {
16482 return Subtarget->isTargetMachO();
16485 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
16486 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16487 return TargetLowering::insertSSPDeclarations(M);
16489 // MSVC CRT has a global variable holding security cookie.
16490 M.getOrInsertGlobal("__security_cookie",
16491 Type::getInt8PtrTy(M.getContext()));
16493 // MSVC CRT has a function to validate security cookie.
16494 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16495 "__security_check_cookie", Type::getVoidTy(M.getContext()),
16496 Type::getInt8PtrTy(M.getContext()));
16497 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
16498 F->addAttribute(1, Attribute::AttrKind::InReg);
16501 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
16502 // MSVC CRT has a global variable holding security cookie.
16503 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16504 return M.getGlobalVariable("__security_cookie");
16505 return TargetLowering::getSDagStackGuard(M);
16508 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
16509 // MSVC CRT has a function to validate security cookie.
16510 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16511 return M.getFunction("__security_check_cookie");
16512 return TargetLowering::getSSPStackGuardCheck(M);
16515 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
16516 unsigned &Cost) const {
16517 // If we do not have NEON, vector types are not natively supported.
16518 if (!Subtarget->hasNEON())
16519 return false;
16521 // Floating point values and vector values map to the same register file.
16522 // Therefore, although we could do a store extract of a vector type, this is
16523 // better to leave at float as we have more freedom in the addressing mode for
16524 // those.
16525 if (VectorTy->isFPOrFPVectorTy())
16526 return false;
16528 // If the index is unknown at compile time, this is very expensive to lower
16529 // and it is not possible to combine the store with the extract.
16530 if (!isa<ConstantInt>(Idx))
16531 return false;
16533 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
16534 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
16535 // We can do a store + vector extract on any vector that fits perfectly in a D
16536 // or Q register.
16537 if (BitWidth == 64 || BitWidth == 128) {
16538 Cost = 0;
16539 return true;
16541 return false;
16544 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
16545 return Subtarget->hasV6T2Ops();
16548 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
16549 return Subtarget->hasV6T2Ops();
16552 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
16553 return !Subtarget->hasMinSize();
16556 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16557 AtomicOrdering Ord) const {
16558 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16559 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16560 bool IsAcquire = isAcquireOrStronger(Ord);
16562 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
16563 // intrinsic must return {i32, i32} and we have to recombine them into a
16564 // single i64 here.
16565 if (ValTy->getPrimitiveSizeInBits() == 64) {
16566 Intrinsic::ID Int =
16567 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
16568 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
16570 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16571 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
16573 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16574 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16575 if (!Subtarget->isLittle())
16576 std::swap (Lo, Hi);
16577 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16578 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16579 return Builder.CreateOr(
16580 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
16583 Type *Tys[] = { Addr->getType() };
16584 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
16585 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
16587 return Builder.CreateTruncOrBitCast(
16588 Builder.CreateCall(Ldrex, Addr),
16589 cast<PointerType>(Addr->getType())->getElementType());
16592 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16593 IRBuilder<> &Builder) const {
16594 if (!Subtarget->hasV7Ops())
16595 return;
16596 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16597 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
16600 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
16601 Value *Addr,
16602 AtomicOrdering Ord) const {
16603 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16604 bool IsRelease = isReleaseOrStronger(Ord);
16606 // Since the intrinsics must have legal type, the i64 intrinsics take two
16607 // parameters: "i32, i32". We must marshal Val into the appropriate form
16608 // before the call.
16609 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
16610 Intrinsic::ID Int =
16611 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
16612 Function *Strex = Intrinsic::getDeclaration(M, Int);
16613 Type *Int32Ty = Type::getInt32Ty(M->getContext());
16615 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
16616 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
16617 if (!Subtarget->isLittle())
16618 std::swap(Lo, Hi);
16619 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16620 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
16623 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
16624 Type *Tys[] = { Addr->getType() };
16625 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
16627 return Builder.CreateCall(
16628 Strex, {Builder.CreateZExtOrBitCast(
16629 Val, Strex->getFunctionType()->getParamType(0)),
16630 Addr});
16634 bool ARMTargetLowering::alignLoopsWithOptSize() const {
16635 return Subtarget->isMClass();
16638 /// A helper function for determining the number of interleaved accesses we
16639 /// will generate when lowering accesses of the given type.
16640 unsigned
16641 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
16642 const DataLayout &DL) const {
16643 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
16646 bool ARMTargetLowering::isLegalInterleavedAccessType(
16647 VectorType *VecTy, const DataLayout &DL) const {
16649 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16650 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16652 // Ensure the vector doesn't have f16 elements. Even though we could do an
16653 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16654 // f32.
16655 if (VecTy->getElementType()->isHalfTy())
16656 return false;
16658 // Ensure the number of vector elements is greater than 1.
16659 if (VecTy->getNumElements() < 2)
16660 return false;
16662 // Ensure the element type is legal.
16663 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16664 return false;
16666 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16667 // 128 will be split into multiple interleaved accesses.
16668 return VecSize == 64 || VecSize % 128 == 0;
16671 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
16672 if (Subtarget->hasNEON())
16673 return 4;
16674 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
16677 /// Lower an interleaved load into a vldN intrinsic.
16679 /// E.g. Lower an interleaved load (Factor = 2):
16680 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16681 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16682 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16684 /// Into:
16685 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16686 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16687 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16688 bool ARMTargetLowering::lowerInterleavedLoad(
16689 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16690 ArrayRef<unsigned> Indices, unsigned Factor) const {
16691 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16692 "Invalid interleave factor");
16693 assert(!Shuffles.empty() && "Empty shufflevector input");
16694 assert(Shuffles.size() == Indices.size() &&
16695 "Unmatched number of shufflevectors and indices");
16697 VectorType *VecTy = Shuffles[0]->getType();
16698 Type *EltTy = VecTy->getVectorElementType();
16700 const DataLayout &DL = LI->getModule()->getDataLayout();
16702 // Skip if we do not have NEON and skip illegal vector types. We can
16703 // "legalize" wide vector types into multiple interleaved accesses as long as
16704 // the vector types are divisible by 128.
16705 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16706 return false;
16708 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16710 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16711 // load integer vectors first and then convert to pointer vectors.
16712 if (EltTy->isPointerTy())
16713 VecTy =
16714 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16716 IRBuilder<> Builder(LI);
16718 // The base address of the load.
16719 Value *BaseAddr = LI->getPointerOperand();
16721 if (NumLoads > 1) {
16722 // If we're going to generate more than one load, reset the sub-vector type
16723 // to something legal.
16724 VecTy = VectorType::get(VecTy->getVectorElementType(),
16725 VecTy->getVectorNumElements() / NumLoads);
16727 // We will compute the pointer operand of each load from the original base
16728 // address using GEPs. Cast the base address to a pointer to the scalar
16729 // element type.
16730 BaseAddr = Builder.CreateBitCast(
16731 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16732 LI->getPointerAddressSpace()));
16735 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16737 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16738 Type *Tys[] = {VecTy, Int8Ptr};
16739 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16740 Intrinsic::arm_neon_vld3,
16741 Intrinsic::arm_neon_vld4};
16742 Function *VldnFunc =
16743 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16745 // Holds sub-vectors extracted from the load intrinsic return values. The
16746 // sub-vectors are associated with the shufflevector instructions they will
16747 // replace.
16748 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16750 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16751 // If we're generating more than one load, compute the base address of
16752 // subsequent loads as an offset from the previous.
16753 if (LoadCount > 0)
16754 BaseAddr =
16755 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16756 VecTy->getVectorNumElements() * Factor);
16758 SmallVector<Value *, 2> Ops;
16759 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16760 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16762 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16764 // Replace uses of each shufflevector with the corresponding vector loaded
16765 // by ldN.
16766 for (unsigned i = 0; i < Shuffles.size(); i++) {
16767 ShuffleVectorInst *SV = Shuffles[i];
16768 unsigned Index = Indices[i];
16770 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16772 // Convert the integer vector to pointer vector if the element is pointer.
16773 if (EltTy->isPointerTy())
16774 SubVec = Builder.CreateIntToPtr(
16775 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16776 VecTy->getVectorNumElements()));
16778 SubVecs[SV].push_back(SubVec);
16782 // Replace uses of the shufflevector instructions with the sub-vectors
16783 // returned by the load intrinsic. If a shufflevector instruction is
16784 // associated with more than one sub-vector, those sub-vectors will be
16785 // concatenated into a single wide vector.
16786 for (ShuffleVectorInst *SVI : Shuffles) {
16787 auto &SubVec = SubVecs[SVI];
16788 auto *WideVec =
16789 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16790 SVI->replaceAllUsesWith(WideVec);
16793 return true;
16796 /// Lower an interleaved store into a vstN intrinsic.
16798 /// E.g. Lower an interleaved store (Factor = 3):
16799 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16800 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16801 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16803 /// Into:
16804 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16805 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16806 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16807 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16809 /// Note that the new shufflevectors will be removed and we'll only generate one
16810 /// vst3 instruction in CodeGen.
16812 /// Example for a more general valid mask (Factor 3). Lower:
16813 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16814 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16815 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16817 /// Into:
16818 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16819 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16820 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16821 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16822 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16823 ShuffleVectorInst *SVI,
16824 unsigned Factor) const {
16825 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16826 "Invalid interleave factor");
16828 VectorType *VecTy = SVI->getType();
16829 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16830 "Invalid interleaved store");
16832 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16833 Type *EltTy = VecTy->getVectorElementType();
16834 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16836 const DataLayout &DL = SI->getModule()->getDataLayout();
16838 // Skip if we do not have NEON and skip illegal vector types. We can
16839 // "legalize" wide vector types into multiple interleaved accesses as long as
16840 // the vector types are divisible by 128.
16841 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16842 return false;
16844 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16846 Value *Op0 = SVI->getOperand(0);
16847 Value *Op1 = SVI->getOperand(1);
16848 IRBuilder<> Builder(SI);
16850 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16851 // vectors to integer vectors.
16852 if (EltTy->isPointerTy()) {
16853 Type *IntTy = DL.getIntPtrType(EltTy);
16855 // Convert to the corresponding integer vector.
16856 Type *IntVecTy =
16857 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16858 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16859 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16861 SubVecTy = VectorType::get(IntTy, LaneLen);
16864 // The base address of the store.
16865 Value *BaseAddr = SI->getPointerOperand();
16867 if (NumStores > 1) {
16868 // If we're going to generate more than one store, reset the lane length
16869 // and sub-vector type to something legal.
16870 LaneLen /= NumStores;
16871 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16873 // We will compute the pointer operand of each store from the original base
16874 // address using GEPs. Cast the base address to a pointer to the scalar
16875 // element type.
16876 BaseAddr = Builder.CreateBitCast(
16877 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16878 SI->getPointerAddressSpace()));
16881 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16883 auto Mask = SVI->getShuffleMask();
16885 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16886 Type *Tys[] = {Int8Ptr, SubVecTy};
16887 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16888 Intrinsic::arm_neon_vst3,
16889 Intrinsic::arm_neon_vst4};
16891 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16892 // If we generating more than one store, we compute the base address of
16893 // subsequent stores as an offset from the previous.
16894 if (StoreCount > 0)
16895 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16896 BaseAddr, LaneLen * Factor);
16898 SmallVector<Value *, 6> Ops;
16899 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16901 Function *VstNFunc =
16902 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16904 // Split the shufflevector operands into sub vectors for the new vstN call.
16905 for (unsigned i = 0; i < Factor; i++) {
16906 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16907 if (Mask[IdxI] >= 0) {
16908 Ops.push_back(Builder.CreateShuffleVector(
16909 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16910 } else {
16911 unsigned StartMask = 0;
16912 for (unsigned j = 1; j < LaneLen; j++) {
16913 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16914 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16915 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16916 break;
16919 // Note: If all elements in a chunk are undefs, StartMask=0!
16920 // Note: Filling undef gaps with random elements is ok, since
16921 // those elements were being written anyway (with undefs).
16922 // In the case of all undefs we're defaulting to using elems from 0
16923 // Note: StartMask cannot be negative, it's checked in
16924 // isReInterleaveMask
16925 Ops.push_back(Builder.CreateShuffleVector(
16926 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16930 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16931 Builder.CreateCall(VstNFunc, Ops);
16933 return true;
16936 enum HABaseType {
16937 HA_UNKNOWN = 0,
16938 HA_FLOAT,
16939 HA_DOUBLE,
16940 HA_VECT64,
16941 HA_VECT128
16944 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16945 uint64_t &Members) {
16946 if (auto *ST = dyn_cast<StructType>(Ty)) {
16947 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16948 uint64_t SubMembers = 0;
16949 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16950 return false;
16951 Members += SubMembers;
16953 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16954 uint64_t SubMembers = 0;
16955 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16956 return false;
16957 Members += SubMembers * AT->getNumElements();
16958 } else if (Ty->isFloatTy()) {
16959 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16960 return false;
16961 Members = 1;
16962 Base = HA_FLOAT;
16963 } else if (Ty->isDoubleTy()) {
16964 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16965 return false;
16966 Members = 1;
16967 Base = HA_DOUBLE;
16968 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16969 Members = 1;
16970 switch (Base) {
16971 case HA_FLOAT:
16972 case HA_DOUBLE:
16973 return false;
16974 case HA_VECT64:
16975 return VT->getBitWidth() == 64;
16976 case HA_VECT128:
16977 return VT->getBitWidth() == 128;
16978 case HA_UNKNOWN:
16979 switch (VT->getBitWidth()) {
16980 case 64:
16981 Base = HA_VECT64;
16982 return true;
16983 case 128:
16984 Base = HA_VECT128;
16985 return true;
16986 default:
16987 return false;
16992 return (Members > 0 && Members <= 4);
16995 /// Return the correct alignment for the current calling convention.
16996 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16997 DataLayout DL) const {
16998 const Align ABITypeAlign(DL.getABITypeAlignment(ArgTy));
16999 if (!ArgTy->isVectorTy())
17000 return ABITypeAlign;
17002 // Avoid over-aligning vector parameters. It would require realigning the
17003 // stack and waste space for no real benefit.
17004 return std::min(ABITypeAlign, DL.getStackAlignment());
17007 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
17008 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
17009 /// passing according to AAPCS rules.
17010 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
17011 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
17012 if (getEffectiveCallingConv(CallConv, isVarArg) !=
17013 CallingConv::ARM_AAPCS_VFP)
17014 return false;
17016 HABaseType Base = HA_UNKNOWN;
17017 uint64_t Members = 0;
17018 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
17019 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
17021 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
17022 return IsHA || IsIntArray;
17025 unsigned ARMTargetLowering::getExceptionPointerRegister(
17026 const Constant *PersonalityFn) const {
17027 // Platforms which do not use SjLj EH may return values in these registers
17028 // via the personality function.
17029 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
17032 unsigned ARMTargetLowering::getExceptionSelectorRegister(
17033 const Constant *PersonalityFn) const {
17034 // Platforms which do not use SjLj EH may return values in these registers
17035 // via the personality function.
17036 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
17039 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
17040 // Update IsSplitCSR in ARMFunctionInfo.
17041 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
17042 AFI->setIsSplitCSR(true);
17045 void ARMTargetLowering::insertCopiesSplitCSR(
17046 MachineBasicBlock *Entry,
17047 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
17048 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
17049 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
17050 if (!IStart)
17051 return;
17053 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17054 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
17055 MachineBasicBlock::iterator MBBI = Entry->begin();
17056 for (const MCPhysReg *I = IStart; *I; ++I) {
17057 const TargetRegisterClass *RC = nullptr;
17058 if (ARM::GPRRegClass.contains(*I))
17059 RC = &ARM::GPRRegClass;
17060 else if (ARM::DPRRegClass.contains(*I))
17061 RC = &ARM::DPRRegClass;
17062 else
17063 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
17065 Register NewVR = MRI->createVirtualRegister(RC);
17066 // Create copy from CSR to a virtual register.
17067 // FIXME: this currently does not emit CFI pseudo-instructions, it works
17068 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
17069 // nounwind. If we want to generalize this later, we may need to emit
17070 // CFI pseudo-instructions.
17071 assert(Entry->getParent()->getFunction().hasFnAttribute(
17072 Attribute::NoUnwind) &&
17073 "Function should be nounwind in insertCopiesSplitCSR!");
17074 Entry->addLiveIn(*I);
17075 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
17076 .addReg(*I);
17078 // Insert the copy-back instructions right before the terminator.
17079 for (auto *Exit : Exits)
17080 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
17081 TII->get(TargetOpcode::COPY), *I)
17082 .addReg(NewVR);
17086 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
17087 MF.getFrameInfo().computeMaxCallFrameSize(MF);
17088 TargetLoweringBase::finalizeLowering(MF);