[ARM] Fix loads and stores for predicate vectors
[llvm-complete.git] / lib / Target / ARM / ARMISelLowering.cpp
blobcedd8981d573bbdccc419a9c72bb87987d9db185
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);
263 // No native support for these.
264 setOperationAction(ISD::UDIV, VT, Expand);
265 setOperationAction(ISD::SDIV, VT, Expand);
266 setOperationAction(ISD::UREM, VT, Expand);
267 setOperationAction(ISD::SREM, VT, Expand);
268 setOperationAction(ISD::CTPOP, VT, Expand);
270 // Vector reductions
271 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
273 if (!HasMVEFP) {
274 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
275 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
276 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
277 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
280 // Pre and Post inc are supported on loads and stores
281 for (unsigned im = (unsigned)ISD::PRE_INC;
282 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
283 setIndexedLoadAction(im, VT, Legal);
284 setIndexedStoreAction(im, VT, Legal);
288 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
289 for (auto VT : FloatTypes) {
290 addRegisterClass(VT, &ARM::MQPRRegClass);
291 if (!HasMVEFP)
292 setAllExpand(VT);
294 // These are legal or custom whether we have MVE.fp or not
295 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
296 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
297 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
298 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
299 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
300 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
301 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
302 setOperationAction(ISD::SETCC, VT, Custom);
304 // Pre and Post inc are supported on loads and stores
305 for (unsigned im = (unsigned)ISD::PRE_INC;
306 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
307 setIndexedLoadAction(im, VT, Legal);
308 setIndexedStoreAction(im, VT, Legal);
311 if (HasMVEFP) {
312 setOperationAction(ISD::FMINNUM, VT, Legal);
313 setOperationAction(ISD::FMAXNUM, VT, Legal);
314 setOperationAction(ISD::FROUND, VT, Legal);
316 // No native support for these.
317 setOperationAction(ISD::FDIV, VT, Expand);
318 setOperationAction(ISD::FREM, VT, Expand);
319 setOperationAction(ISD::FSQRT, VT, Expand);
320 setOperationAction(ISD::FSIN, VT, Expand);
321 setOperationAction(ISD::FCOS, VT, Expand);
322 setOperationAction(ISD::FPOW, VT, Expand);
323 setOperationAction(ISD::FLOG, VT, Expand);
324 setOperationAction(ISD::FLOG2, VT, Expand);
325 setOperationAction(ISD::FLOG10, VT, Expand);
326 setOperationAction(ISD::FEXP, VT, Expand);
327 setOperationAction(ISD::FEXP2, VT, Expand);
328 setOperationAction(ISD::FNEARBYINT, VT, Expand);
332 // We 'support' these types up to bitcast/load/store level, regardless of
333 // MVE integer-only / float support. Only doing FP data processing on the FP
334 // vector types is inhibited at integer-only level.
335 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
336 for (auto VT : LongTypes) {
337 addRegisterClass(VT, &ARM::MQPRRegClass);
338 setAllExpand(VT);
339 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
340 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
341 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
343 // We can do bitwise operations on v2i64 vectors
344 setOperationAction(ISD::AND, MVT::v2i64, Legal);
345 setOperationAction(ISD::OR, MVT::v2i64, Legal);
346 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
348 // It is legal to extload from v4i8 to v4i16 or v4i32.
349 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
350 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
351 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
353 // Some truncating stores are legal too.
354 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
355 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
356 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
358 // Pre and Post inc on these are legal, given the correct extends
359 for (unsigned im = (unsigned)ISD::PRE_INC;
360 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
361 setIndexedLoadAction(im, MVT::v8i8, Legal);
362 setIndexedStoreAction(im, MVT::v8i8, Legal);
363 setIndexedLoadAction(im, MVT::v4i8, Legal);
364 setIndexedStoreAction(im, MVT::v4i8, Legal);
365 setIndexedLoadAction(im, MVT::v4i16, Legal);
366 setIndexedStoreAction(im, MVT::v4i16, Legal);
369 // Predicate types
370 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
371 for (auto VT : pTypes) {
372 addRegisterClass(VT, &ARM::VCCRRegClass);
373 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
374 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
375 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
376 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
377 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
378 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
379 setOperationAction(ISD::SETCC, VT, Custom);
380 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
381 setOperationAction(ISD::LOAD, VT, Custom);
382 setOperationAction(ISD::STORE, VT, Custom);
386 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
387 const ARMSubtarget &STI)
388 : TargetLowering(TM), Subtarget(&STI) {
389 RegInfo = Subtarget->getRegisterInfo();
390 Itins = Subtarget->getInstrItineraryData();
392 setBooleanContents(ZeroOrOneBooleanContent);
393 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
395 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
396 !Subtarget->isTargetWatchOS()) {
397 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
398 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
399 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
400 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
401 : CallingConv::ARM_AAPCS);
404 if (Subtarget->isTargetMachO()) {
405 // Uses VFP for Thumb libfuncs if available.
406 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
407 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
408 static const struct {
409 const RTLIB::Libcall Op;
410 const char * const Name;
411 const ISD::CondCode Cond;
412 } LibraryCalls[] = {
413 // Single-precision floating-point arithmetic.
414 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
415 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
416 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
417 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
419 // Double-precision floating-point arithmetic.
420 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
421 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
422 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
423 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
425 // Single-precision comparisons.
426 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
427 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
428 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
429 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
430 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
431 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
432 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
433 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
435 // Double-precision comparisons.
436 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
437 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
438 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
439 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
440 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
441 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
442 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
443 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
445 // Floating-point to integer conversions.
446 // i64 conversions are done via library routines even when generating VFP
447 // instructions, so use the same ones.
448 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
449 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
450 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
451 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
453 // Conversions between floating types.
454 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
455 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
457 // Integer to floating-point conversions.
458 // i64 conversions are done via library routines even when generating VFP
459 // instructions, so use the same ones.
460 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
461 // e.g., __floatunsidf vs. __floatunssidfvfp.
462 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
463 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
464 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
465 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
468 for (const auto &LC : LibraryCalls) {
469 setLibcallName(LC.Op, LC.Name);
470 if (LC.Cond != ISD::SETCC_INVALID)
471 setCmpLibcallCC(LC.Op, LC.Cond);
476 // These libcalls are not available in 32-bit.
477 setLibcallName(RTLIB::SHL_I128, nullptr);
478 setLibcallName(RTLIB::SRL_I128, nullptr);
479 setLibcallName(RTLIB::SRA_I128, nullptr);
481 // RTLIB
482 if (Subtarget->isAAPCS_ABI() &&
483 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
484 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
485 static const struct {
486 const RTLIB::Libcall Op;
487 const char * const Name;
488 const CallingConv::ID CC;
489 const ISD::CondCode Cond;
490 } LibraryCalls[] = {
491 // Double-precision floating-point arithmetic helper functions
492 // RTABI chapter 4.1.2, Table 2
493 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
494 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
495 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
496 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
498 // Double-precision floating-point comparison helper functions
499 // RTABI chapter 4.1.2, Table 3
500 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
501 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
502 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
503 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
504 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
505 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
506 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
507 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
509 // Single-precision floating-point arithmetic helper functions
510 // RTABI chapter 4.1.2, Table 4
511 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
512 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
513 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
514 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
516 // Single-precision floating-point comparison helper functions
517 // RTABI chapter 4.1.2, Table 5
518 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
519 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
520 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
521 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
522 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
523 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
524 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
525 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
527 // Floating-point to integer conversions.
528 // RTABI chapter 4.1.2, Table 6
529 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
530 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
531 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
532 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
533 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
534 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
535 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
536 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
538 // Conversions between floating types.
539 // RTABI chapter 4.1.2, Table 7
540 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
541 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
542 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
544 // Integer to floating-point conversions.
545 // RTABI chapter 4.1.2, Table 8
546 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
547 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
548 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
549 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
550 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
552 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
553 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
555 // Long long helper functions
556 // RTABI chapter 4.2, Table 9
557 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
558 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
559 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
560 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
562 // Integer division functions
563 // RTABI chapter 4.3.1
564 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
570 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
571 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
574 for (const auto &LC : LibraryCalls) {
575 setLibcallName(LC.Op, LC.Name);
576 setLibcallCallingConv(LC.Op, LC.CC);
577 if (LC.Cond != ISD::SETCC_INVALID)
578 setCmpLibcallCC(LC.Op, LC.Cond);
581 // EABI dependent RTLIB
582 if (TM.Options.EABIVersion == EABI::EABI4 ||
583 TM.Options.EABIVersion == EABI::EABI5) {
584 static const struct {
585 const RTLIB::Libcall Op;
586 const char *const Name;
587 const CallingConv::ID CC;
588 const ISD::CondCode Cond;
589 } MemOpsLibraryCalls[] = {
590 // Memory operations
591 // RTABI chapter 4.3.4
592 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
593 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
594 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
597 for (const auto &LC : MemOpsLibraryCalls) {
598 setLibcallName(LC.Op, LC.Name);
599 setLibcallCallingConv(LC.Op, LC.CC);
600 if (LC.Cond != ISD::SETCC_INVALID)
601 setCmpLibcallCC(LC.Op, LC.Cond);
606 if (Subtarget->isTargetWindows()) {
607 static const struct {
608 const RTLIB::Libcall Op;
609 const char * const Name;
610 const CallingConv::ID CC;
611 } LibraryCalls[] = {
612 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
613 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
614 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
615 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
616 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
617 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
618 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
619 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
622 for (const auto &LC : LibraryCalls) {
623 setLibcallName(LC.Op, LC.Name);
624 setLibcallCallingConv(LC.Op, LC.CC);
628 // Use divmod compiler-rt calls for iOS 5.0 and later.
629 if (Subtarget->isTargetMachO() &&
630 !(Subtarget->isTargetIOS() &&
631 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
632 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
633 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
636 // The half <-> float conversion functions are always soft-float on
637 // non-watchos platforms, but are needed for some targets which use a
638 // hard-float calling convention by default.
639 if (!Subtarget->isTargetWatchABI()) {
640 if (Subtarget->isAAPCS_ABI()) {
641 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
642 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
643 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
644 } else {
645 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
646 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
647 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
651 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
652 // a __gnu_ prefix (which is the default).
653 if (Subtarget->isTargetAEABI()) {
654 static const struct {
655 const RTLIB::Libcall Op;
656 const char * const Name;
657 const CallingConv::ID CC;
658 } LibraryCalls[] = {
659 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
660 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
661 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
664 for (const auto &LC : LibraryCalls) {
665 setLibcallName(LC.Op, LC.Name);
666 setLibcallCallingConv(LC.Op, LC.CC);
670 if (Subtarget->isThumb1Only())
671 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
672 else
673 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
675 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
676 Subtarget->hasFPRegs()) {
677 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
678 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
679 if (!Subtarget->hasVFP2Base())
680 setAllExpand(MVT::f32);
681 if (!Subtarget->hasFP64())
682 setAllExpand(MVT::f64);
685 if (Subtarget->hasFullFP16()) {
686 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
687 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
688 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
689 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
691 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
692 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
695 for (MVT VT : MVT::vector_valuetypes()) {
696 for (MVT InnerVT : MVT::vector_valuetypes()) {
697 setTruncStoreAction(VT, InnerVT, Expand);
698 addAllExtLoads(VT, InnerVT, Expand);
701 setOperationAction(ISD::MULHS, VT, Expand);
702 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703 setOperationAction(ISD::MULHU, VT, Expand);
704 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
706 setOperationAction(ISD::BSWAP, VT, Expand);
709 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
710 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
712 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
713 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
715 if (Subtarget->hasMVEIntegerOps())
716 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
718 // Combine low-overhead loop intrinsics so that we can lower i1 types.
719 if (Subtarget->hasLOB()) {
720 setTargetDAGCombine(ISD::BRCOND);
721 setTargetDAGCombine(ISD::BR_CC);
724 if (Subtarget->hasNEON()) {
725 addDRTypeForNEON(MVT::v2f32);
726 addDRTypeForNEON(MVT::v8i8);
727 addDRTypeForNEON(MVT::v4i16);
728 addDRTypeForNEON(MVT::v2i32);
729 addDRTypeForNEON(MVT::v1i64);
731 addQRTypeForNEON(MVT::v4f32);
732 addQRTypeForNEON(MVT::v2f64);
733 addQRTypeForNEON(MVT::v16i8);
734 addQRTypeForNEON(MVT::v8i16);
735 addQRTypeForNEON(MVT::v4i32);
736 addQRTypeForNEON(MVT::v2i64);
738 if (Subtarget->hasFullFP16()) {
739 addQRTypeForNEON(MVT::v8f16);
740 addDRTypeForNEON(MVT::v4f16);
744 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
745 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
746 // none of Neon, MVE or VFP supports any arithmetic operations on it.
747 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
748 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
749 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
750 // FIXME: Code duplication: FDIV and FREM are expanded always, see
751 // ARMTargetLowering::addTypeForNEON method for details.
752 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
753 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
754 // FIXME: Create unittest.
755 // In another words, find a way when "copysign" appears in DAG with vector
756 // operands.
757 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
758 // FIXME: Code duplication: SETCC has custom operation action, see
759 // ARMTargetLowering::addTypeForNEON method for details.
760 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
761 // FIXME: Create unittest for FNEG and for FABS.
762 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
763 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
764 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
765 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
766 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
767 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
768 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
769 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
770 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
771 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
772 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
773 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
774 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
775 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
776 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
777 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
778 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
779 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
782 if (Subtarget->hasNEON()) {
783 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
784 // supported for v4f32.
785 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
786 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
787 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
788 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
789 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
790 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
791 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
792 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
793 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
794 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
795 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
796 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
797 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
798 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
800 // Mark v2f32 intrinsics.
801 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
802 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
803 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
804 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
805 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
806 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
807 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
808 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
809 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
810 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
811 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
812 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
813 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
814 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
816 // Neon does not support some operations on v1i64 and v2i64 types.
817 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
818 // Custom handling for some quad-vector types to detect VMULL.
819 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
820 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
821 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
822 // Custom handling for some vector types to avoid expensive expansions
823 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
824 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
825 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
826 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
827 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
828 // a destination type that is wider than the source, and nor does
829 // it have a FP_TO_[SU]INT instruction with a narrower destination than
830 // source.
831 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
832 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
833 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
834 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
835 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
836 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
837 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
838 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
840 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
841 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
843 // NEON does not have single instruction CTPOP for vectors with element
844 // types wider than 8-bits. However, custom lowering can leverage the
845 // v8i8/v16i8 vcnt instruction.
846 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
847 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
848 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
849 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
850 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
851 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
853 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
854 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
856 // NEON does not have single instruction CTTZ for vectors.
857 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
858 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
859 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
860 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
862 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
863 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
864 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
865 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
867 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
868 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
869 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
870 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
872 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
874 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
875 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
877 // NEON only has FMA instructions as of VFP4.
878 if (!Subtarget->hasVFP4Base()) {
879 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
880 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
883 setTargetDAGCombine(ISD::INTRINSIC_VOID);
884 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
885 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
886 setTargetDAGCombine(ISD::SHL);
887 setTargetDAGCombine(ISD::SRL);
888 setTargetDAGCombine(ISD::SRA);
889 setTargetDAGCombine(ISD::SIGN_EXTEND);
890 setTargetDAGCombine(ISD::ZERO_EXTEND);
891 setTargetDAGCombine(ISD::ANY_EXTEND);
892 setTargetDAGCombine(ISD::STORE);
893 setTargetDAGCombine(ISD::FP_TO_SINT);
894 setTargetDAGCombine(ISD::FP_TO_UINT);
895 setTargetDAGCombine(ISD::FDIV);
896 setTargetDAGCombine(ISD::LOAD);
898 // It is legal to extload from v4i8 to v4i16 or v4i32.
899 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
900 MVT::v2i32}) {
901 for (MVT VT : MVT::integer_vector_valuetypes()) {
902 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
903 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
904 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
909 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
910 setTargetDAGCombine(ISD::BUILD_VECTOR);
911 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
912 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
915 if (!Subtarget->hasFP64()) {
916 // When targeting a floating-point unit with only single-precision
917 // operations, f64 is legal for the few double-precision instructions which
918 // are present However, no double-precision operations other than moves,
919 // loads and stores are provided by the hardware.
920 setOperationAction(ISD::FADD, MVT::f64, Expand);
921 setOperationAction(ISD::FSUB, MVT::f64, Expand);
922 setOperationAction(ISD::FMUL, MVT::f64, Expand);
923 setOperationAction(ISD::FMA, MVT::f64, Expand);
924 setOperationAction(ISD::FDIV, MVT::f64, Expand);
925 setOperationAction(ISD::FREM, MVT::f64, Expand);
926 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
927 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
928 setOperationAction(ISD::FNEG, MVT::f64, Expand);
929 setOperationAction(ISD::FABS, MVT::f64, Expand);
930 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
931 setOperationAction(ISD::FSIN, MVT::f64, Expand);
932 setOperationAction(ISD::FCOS, MVT::f64, Expand);
933 setOperationAction(ISD::FPOW, MVT::f64, Expand);
934 setOperationAction(ISD::FLOG, MVT::f64, Expand);
935 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
936 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
937 setOperationAction(ISD::FEXP, MVT::f64, Expand);
938 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
939 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
940 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
941 setOperationAction(ISD::FRINT, MVT::f64, Expand);
942 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
943 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
944 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
945 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
946 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
947 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
948 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
949 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
950 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
953 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
954 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
955 if (Subtarget->hasFullFP16())
956 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
959 if (!Subtarget->hasFP16())
960 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
962 if (!Subtarget->hasFP64())
963 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
965 computeRegisterProperties(Subtarget->getRegisterInfo());
967 // ARM does not have floating-point extending loads.
968 for (MVT VT : MVT::fp_valuetypes()) {
969 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
970 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
973 // ... or truncating stores
974 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
975 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
976 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
978 // ARM does not have i1 sign extending load.
979 for (MVT VT : MVT::integer_valuetypes())
980 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
982 // ARM supports all 4 flavors of integer indexed load / store.
983 if (!Subtarget->isThumb1Only()) {
984 for (unsigned im = (unsigned)ISD::PRE_INC;
985 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
986 setIndexedLoadAction(im, MVT::i1, Legal);
987 setIndexedLoadAction(im, MVT::i8, Legal);
988 setIndexedLoadAction(im, MVT::i16, Legal);
989 setIndexedLoadAction(im, MVT::i32, Legal);
990 setIndexedStoreAction(im, MVT::i1, Legal);
991 setIndexedStoreAction(im, MVT::i8, Legal);
992 setIndexedStoreAction(im, MVT::i16, Legal);
993 setIndexedStoreAction(im, MVT::i32, Legal);
995 } else {
996 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
997 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
998 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1001 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1002 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1003 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1004 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1006 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1007 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1009 // i64 operation support.
1010 setOperationAction(ISD::MUL, MVT::i64, Expand);
1011 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1012 if (Subtarget->isThumb1Only()) {
1013 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1014 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1016 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1017 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1018 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1020 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1021 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1022 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1023 setOperationAction(ISD::SRL, MVT::i64, Custom);
1024 setOperationAction(ISD::SRA, MVT::i64, Custom);
1025 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1026 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1028 // MVE lowers 64 bit shifts to lsll and lsrl
1029 // assuming that ISD::SRL and SRA of i64 are already marked custom
1030 if (Subtarget->hasMVEIntegerOps())
1031 setOperationAction(ISD::SHL, MVT::i64, Custom);
1033 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1034 if (Subtarget->isThumb1Only()) {
1035 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1036 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1037 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1040 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1041 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1043 // ARM does not have ROTL.
1044 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1045 for (MVT VT : MVT::vector_valuetypes()) {
1046 setOperationAction(ISD::ROTL, VT, Expand);
1047 setOperationAction(ISD::ROTR, VT, Expand);
1049 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1050 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1051 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1052 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1053 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1056 // @llvm.readcyclecounter requires the Performance Monitors extension.
1057 // Default to the 0 expansion on unsupported platforms.
1058 // FIXME: Technically there are older ARM CPUs that have
1059 // implementation-specific ways of obtaining this information.
1060 if (Subtarget->hasPerfMon())
1061 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1063 // Only ARMv6 has BSWAP.
1064 if (!Subtarget->hasV6Ops())
1065 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1067 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1068 : Subtarget->hasDivideInARMMode();
1069 if (!hasDivide) {
1070 // These are expanded into libcalls if the cpu doesn't have HW divider.
1071 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1072 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1075 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1076 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1077 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1079 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1080 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1083 setOperationAction(ISD::SREM, MVT::i32, Expand);
1084 setOperationAction(ISD::UREM, MVT::i32, Expand);
1086 // Register based DivRem for AEABI (RTABI 4.2)
1087 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1088 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1089 Subtarget->isTargetWindows()) {
1090 setOperationAction(ISD::SREM, MVT::i64, Custom);
1091 setOperationAction(ISD::UREM, MVT::i64, Custom);
1092 HasStandaloneRem = false;
1094 if (Subtarget->isTargetWindows()) {
1095 const struct {
1096 const RTLIB::Libcall Op;
1097 const char * const Name;
1098 const CallingConv::ID CC;
1099 } LibraryCalls[] = {
1100 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1101 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1102 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1103 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1105 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1106 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1107 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1108 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1111 for (const auto &LC : LibraryCalls) {
1112 setLibcallName(LC.Op, LC.Name);
1113 setLibcallCallingConv(LC.Op, LC.CC);
1115 } else {
1116 const struct {
1117 const RTLIB::Libcall Op;
1118 const char * const Name;
1119 const CallingConv::ID CC;
1120 } LibraryCalls[] = {
1121 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1122 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1123 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1124 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1126 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1127 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1128 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1129 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1132 for (const auto &LC : LibraryCalls) {
1133 setLibcallName(LC.Op, LC.Name);
1134 setLibcallCallingConv(LC.Op, LC.CC);
1138 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1139 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1140 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1141 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1142 } else {
1143 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1144 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1147 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
1148 for (auto &VT : {MVT::f32, MVT::f64})
1149 setOperationAction(ISD::FPOWI, VT, Custom);
1151 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1152 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1153 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1154 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1156 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1157 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1159 // Use the default implementation.
1160 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1161 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1162 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1163 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1164 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1165 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1167 if (Subtarget->isTargetWindows())
1168 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1169 else
1170 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1172 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1173 // the default expansion.
1174 InsertFencesForAtomic = false;
1175 if (Subtarget->hasAnyDataBarrier() &&
1176 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1177 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1178 // to ldrex/strex loops already.
1179 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1180 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1181 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1183 // On v8, we have particularly efficient implementations of atomic fences
1184 // if they can be combined with nearby atomic loads and stores.
1185 if (!Subtarget->hasAcquireRelease() ||
1186 getTargetMachine().getOptLevel() == 0) {
1187 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1188 InsertFencesForAtomic = true;
1190 } else {
1191 // If there's anything we can use as a barrier, go through custom lowering
1192 // for ATOMIC_FENCE.
1193 // If target has DMB in thumb, Fences can be inserted.
1194 if (Subtarget->hasDataBarrier())
1195 InsertFencesForAtomic = true;
1197 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1198 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1200 // Set them all for expansion, which will force libcalls.
1201 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1202 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1203 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1204 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1205 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1206 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1207 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1208 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1209 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1210 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1211 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1212 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1213 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1214 // Unordered/Monotonic case.
1215 if (!InsertFencesForAtomic) {
1216 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1217 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1221 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1223 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1224 if (!Subtarget->hasV6Ops()) {
1225 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1230 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1231 !Subtarget->isThumb1Only()) {
1232 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1233 // iff target supports vfp2.
1234 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1235 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1238 // We want to custom lower some of our intrinsics.
1239 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1240 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1241 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1242 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1243 if (Subtarget->useSjLjEH())
1244 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1246 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1247 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1248 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1249 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1250 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1251 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1252 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1253 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1254 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1255 if (Subtarget->hasFullFP16()) {
1256 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1257 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1258 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1261 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1263 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1264 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1265 if (Subtarget->hasFullFP16())
1266 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1267 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1268 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1269 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1271 // We don't support sin/cos/fmod/copysign/pow
1272 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1273 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1274 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1275 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1276 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1277 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1278 setOperationAction(ISD::FREM, MVT::f64, Expand);
1279 setOperationAction(ISD::FREM, MVT::f32, Expand);
1280 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1281 !Subtarget->isThumb1Only()) {
1282 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1283 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1285 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1286 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1288 if (!Subtarget->hasVFP4Base()) {
1289 setOperationAction(ISD::FMA, MVT::f64, Expand);
1290 setOperationAction(ISD::FMA, MVT::f32, Expand);
1293 // Various VFP goodness
1294 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1295 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1296 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1297 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1298 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1301 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1302 if (!Subtarget->hasFP16()) {
1303 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1304 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1308 // Use __sincos_stret if available.
1309 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1310 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1311 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1312 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1315 // FP-ARMv8 implements a lot of rounding-like FP operations.
1316 if (Subtarget->hasFPARMv8Base()) {
1317 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1318 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1319 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1320 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1321 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1322 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1323 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1324 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1325 if (Subtarget->hasNEON()) {
1326 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1327 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1328 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1329 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1332 if (Subtarget->hasFP64()) {
1333 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1334 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1335 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1336 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1337 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1338 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1339 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1340 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1344 // FP16 often need to be promoted to call lib functions
1345 if (Subtarget->hasFullFP16()) {
1346 setOperationAction(ISD::FREM, MVT::f16, Promote);
1347 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1348 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1349 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1350 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1351 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1352 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1353 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1354 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1355 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1356 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1357 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1359 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1362 if (Subtarget->hasNEON()) {
1363 // vmin and vmax aren't available in a scalar form, so we use
1364 // a NEON instruction with an undef lane instead.
1365 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1366 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1367 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1368 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1369 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1370 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1371 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1372 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1374 if (Subtarget->hasFullFP16()) {
1375 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1376 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1377 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1378 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1380 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1381 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1382 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1383 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1387 // We have target-specific dag combine patterns for the following nodes:
1388 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1389 setTargetDAGCombine(ISD::ADD);
1390 setTargetDAGCombine(ISD::SUB);
1391 setTargetDAGCombine(ISD::MUL);
1392 setTargetDAGCombine(ISD::AND);
1393 setTargetDAGCombine(ISD::OR);
1394 setTargetDAGCombine(ISD::XOR);
1396 if (Subtarget->hasV6Ops())
1397 setTargetDAGCombine(ISD::SRL);
1398 if (Subtarget->isThumb1Only())
1399 setTargetDAGCombine(ISD::SHL);
1401 setStackPointerRegisterToSaveRestore(ARM::SP);
1403 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1404 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1405 setSchedulingPreference(Sched::RegPressure);
1406 else
1407 setSchedulingPreference(Sched::Hybrid);
1409 //// temporary - rewrite interface to use type
1410 MaxStoresPerMemset = 8;
1411 MaxStoresPerMemsetOptSize = 4;
1412 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1413 MaxStoresPerMemcpyOptSize = 2;
1414 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1415 MaxStoresPerMemmoveOptSize = 2;
1417 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1418 // are at least 4 bytes aligned.
1419 setMinStackArgumentAlignment(4);
1421 // Prefer likely predicted branches to selects on out-of-order cores.
1422 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1424 setPrefLoopAlignment(
1425 llvm::Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1427 setMinFunctionAlignment(Subtarget->isThumb() ? llvm::Align(2)
1428 : llvm::Align(4));
1430 if (Subtarget->isThumb() || Subtarget->isThumb2())
1431 setTargetDAGCombine(ISD::ABS);
1434 bool ARMTargetLowering::useSoftFloat() const {
1435 return Subtarget->useSoftFloat();
1438 // FIXME: It might make sense to define the representative register class as the
1439 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1440 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1441 // SPR's representative would be DPR_VFP2. This should work well if register
1442 // pressure tracking were modified such that a register use would increment the
1443 // pressure of the register class's representative and all of it's super
1444 // classes' representatives transitively. We have not implemented this because
1445 // of the difficulty prior to coalescing of modeling operand register classes
1446 // due to the common occurrence of cross class copies and subregister insertions
1447 // and extractions.
1448 std::pair<const TargetRegisterClass *, uint8_t>
1449 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1450 MVT VT) const {
1451 const TargetRegisterClass *RRC = nullptr;
1452 uint8_t Cost = 1;
1453 switch (VT.SimpleTy) {
1454 default:
1455 return TargetLowering::findRepresentativeClass(TRI, VT);
1456 // Use DPR as representative register class for all floating point
1457 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1458 // the cost is 1 for both f32 and f64.
1459 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1460 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1461 RRC = &ARM::DPRRegClass;
1462 // When NEON is used for SP, only half of the register file is available
1463 // because operations that define both SP and DP results will be constrained
1464 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1465 // coalescing by double-counting the SP regs. See the FIXME above.
1466 if (Subtarget->useNEONForSinglePrecisionFP())
1467 Cost = 2;
1468 break;
1469 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1470 case MVT::v4f32: case MVT::v2f64:
1471 RRC = &ARM::DPRRegClass;
1472 Cost = 2;
1473 break;
1474 case MVT::v4i64:
1475 RRC = &ARM::DPRRegClass;
1476 Cost = 4;
1477 break;
1478 case MVT::v8i64:
1479 RRC = &ARM::DPRRegClass;
1480 Cost = 8;
1481 break;
1483 return std::make_pair(RRC, Cost);
1486 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1487 switch ((ARMISD::NodeType)Opcode) {
1488 case ARMISD::FIRST_NUMBER: break;
1489 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1490 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1491 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1492 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1493 case ARMISD::CALL: return "ARMISD::CALL";
1494 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1495 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1496 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1497 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1498 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1499 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1500 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1501 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1502 case ARMISD::CMP: return "ARMISD::CMP";
1503 case ARMISD::CMN: return "ARMISD::CMN";
1504 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1505 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1506 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1507 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1508 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1510 case ARMISD::CMOV: return "ARMISD::CMOV";
1511 case ARMISD::SUBS: return "ARMISD::SUBS";
1513 case ARMISD::SSAT: return "ARMISD::SSAT";
1514 case ARMISD::USAT: return "ARMISD::USAT";
1516 case ARMISD::ASRL: return "ARMISD::ASRL";
1517 case ARMISD::LSRL: return "ARMISD::LSRL";
1518 case ARMISD::LSLL: return "ARMISD::LSLL";
1520 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1521 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1522 case ARMISD::RRX: return "ARMISD::RRX";
1524 case ARMISD::ADDC: return "ARMISD::ADDC";
1525 case ARMISD::ADDE: return "ARMISD::ADDE";
1526 case ARMISD::SUBC: return "ARMISD::SUBC";
1527 case ARMISD::SUBE: return "ARMISD::SUBE";
1528 case ARMISD::LSLS: return "ARMISD::LSLS";
1530 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1531 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1532 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1533 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1534 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1536 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1537 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1538 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1540 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1542 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1544 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1546 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1548 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1550 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1551 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1553 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1554 case ARMISD::VCMP: return "ARMISD::VCMP";
1555 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1556 case ARMISD::VTST: return "ARMISD::VTST";
1558 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1559 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1560 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1561 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1562 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1563 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1564 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1565 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1566 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1567 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1568 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1569 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1570 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1571 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1572 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1573 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1574 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1575 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1576 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1577 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1578 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1579 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1580 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1581 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1582 case ARMISD::VDUP: return "ARMISD::VDUP";
1583 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1584 case ARMISD::VEXT: return "ARMISD::VEXT";
1585 case ARMISD::VREV64: return "ARMISD::VREV64";
1586 case ARMISD::VREV32: return "ARMISD::VREV32";
1587 case ARMISD::VREV16: return "ARMISD::VREV16";
1588 case ARMISD::VZIP: return "ARMISD::VZIP";
1589 case ARMISD::VUZP: return "ARMISD::VUZP";
1590 case ARMISD::VTRN: return "ARMISD::VTRN";
1591 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1592 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1593 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1594 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1595 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1596 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1597 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1598 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1599 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1600 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1601 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1602 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1603 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1604 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1605 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1606 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1607 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1608 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1609 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1610 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1611 case ARMISD::BFI: return "ARMISD::BFI";
1612 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1613 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1614 case ARMISD::VBSL: return "ARMISD::VBSL";
1615 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1616 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1617 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1618 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1619 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1620 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1621 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1622 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1623 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1624 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1625 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1626 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1627 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1628 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1629 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1630 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1631 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1632 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1633 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1634 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1635 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1636 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1637 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1638 case ARMISD::WLS: return "ARMISD::WLS";
1639 case ARMISD::LE: return "ARMISD::LE";
1640 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1641 case ARMISD::CSINV: return "ARMISD::CSINV";
1642 case ARMISD::CSNEG: return "ARMISD::CSNEG";
1643 case ARMISD::CSINC: return "ARMISD::CSINC";
1645 return nullptr;
1648 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1649 EVT VT) const {
1650 if (!VT.isVector())
1651 return getPointerTy(DL);
1653 // MVE has a predicate register.
1654 if (Subtarget->hasMVEIntegerOps() &&
1655 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1656 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1657 return VT.changeVectorElementTypeToInteger();
1660 /// getRegClassFor - Return the register class that should be used for the
1661 /// specified value type.
1662 const TargetRegisterClass *
1663 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1664 (void)isDivergent;
1665 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1666 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1667 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1668 // MVE Q registers.
1669 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1670 if (VT == MVT::v4i64)
1671 return &ARM::QQPRRegClass;
1672 if (VT == MVT::v8i64)
1673 return &ARM::QQQQPRRegClass;
1675 return TargetLowering::getRegClassFor(VT);
1678 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1679 // source/dest is aligned and the copy size is large enough. We therefore want
1680 // to align such objects passed to memory intrinsics.
1681 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1682 unsigned &PrefAlign) const {
1683 if (!isa<MemIntrinsic>(CI))
1684 return false;
1685 MinSize = 8;
1686 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1687 // cycle faster than 4-byte aligned LDM.
1688 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1689 return true;
1692 // Create a fast isel object.
1693 FastISel *
1694 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1695 const TargetLibraryInfo *libInfo) const {
1696 return ARM::createFastISel(funcInfo, libInfo);
1699 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1700 unsigned NumVals = N->getNumValues();
1701 if (!NumVals)
1702 return Sched::RegPressure;
1704 for (unsigned i = 0; i != NumVals; ++i) {
1705 EVT VT = N->getValueType(i);
1706 if (VT == MVT::Glue || VT == MVT::Other)
1707 continue;
1708 if (VT.isFloatingPoint() || VT.isVector())
1709 return Sched::ILP;
1712 if (!N->isMachineOpcode())
1713 return Sched::RegPressure;
1715 // Load are scheduled for latency even if there instruction itinerary
1716 // is not available.
1717 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1718 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1720 if (MCID.getNumDefs() == 0)
1721 return Sched::RegPressure;
1722 if (!Itins->isEmpty() &&
1723 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1724 return Sched::ILP;
1726 return Sched::RegPressure;
1729 //===----------------------------------------------------------------------===//
1730 // Lowering Code
1731 //===----------------------------------------------------------------------===//
1733 static bool isSRL16(const SDValue &Op) {
1734 if (Op.getOpcode() != ISD::SRL)
1735 return false;
1736 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1737 return Const->getZExtValue() == 16;
1738 return false;
1741 static bool isSRA16(const SDValue &Op) {
1742 if (Op.getOpcode() != ISD::SRA)
1743 return false;
1744 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1745 return Const->getZExtValue() == 16;
1746 return false;
1749 static bool isSHL16(const SDValue &Op) {
1750 if (Op.getOpcode() != ISD::SHL)
1751 return false;
1752 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1753 return Const->getZExtValue() == 16;
1754 return false;
1757 // Check for a signed 16-bit value. We special case SRA because it makes it
1758 // more simple when also looking for SRAs that aren't sign extending a
1759 // smaller value. Without the check, we'd need to take extra care with
1760 // checking order for some operations.
1761 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1762 if (isSRA16(Op))
1763 return isSHL16(Op.getOperand(0));
1764 return DAG.ComputeNumSignBits(Op) == 17;
1767 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1768 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1769 switch (CC) {
1770 default: llvm_unreachable("Unknown condition code!");
1771 case ISD::SETNE: return ARMCC::NE;
1772 case ISD::SETEQ: return ARMCC::EQ;
1773 case ISD::SETGT: return ARMCC::GT;
1774 case ISD::SETGE: return ARMCC::GE;
1775 case ISD::SETLT: return ARMCC::LT;
1776 case ISD::SETLE: return ARMCC::LE;
1777 case ISD::SETUGT: return ARMCC::HI;
1778 case ISD::SETUGE: return ARMCC::HS;
1779 case ISD::SETULT: return ARMCC::LO;
1780 case ISD::SETULE: return ARMCC::LS;
1784 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1785 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1786 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1787 CondCode2 = ARMCC::AL;
1788 InvalidOnQNaN = true;
1789 switch (CC) {
1790 default: llvm_unreachable("Unknown FP condition!");
1791 case ISD::SETEQ:
1792 case ISD::SETOEQ:
1793 CondCode = ARMCC::EQ;
1794 InvalidOnQNaN = false;
1795 break;
1796 case ISD::SETGT:
1797 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1798 case ISD::SETGE:
1799 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1800 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1801 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1802 case ISD::SETONE:
1803 CondCode = ARMCC::MI;
1804 CondCode2 = ARMCC::GT;
1805 InvalidOnQNaN = false;
1806 break;
1807 case ISD::SETO: CondCode = ARMCC::VC; break;
1808 case ISD::SETUO: CondCode = ARMCC::VS; break;
1809 case ISD::SETUEQ:
1810 CondCode = ARMCC::EQ;
1811 CondCode2 = ARMCC::VS;
1812 InvalidOnQNaN = false;
1813 break;
1814 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1815 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1816 case ISD::SETLT:
1817 case ISD::SETULT: CondCode = ARMCC::LT; break;
1818 case ISD::SETLE:
1819 case ISD::SETULE: CondCode = ARMCC::LE; break;
1820 case ISD::SETNE:
1821 case ISD::SETUNE:
1822 CondCode = ARMCC::NE;
1823 InvalidOnQNaN = false;
1824 break;
1828 //===----------------------------------------------------------------------===//
1829 // Calling Convention Implementation
1830 //===----------------------------------------------------------------------===//
1832 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1833 /// account presence of floating point hardware and calling convention
1834 /// limitations, such as support for variadic functions.
1835 CallingConv::ID
1836 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1837 bool isVarArg) const {
1838 switch (CC) {
1839 default:
1840 report_fatal_error("Unsupported calling convention");
1841 case CallingConv::ARM_AAPCS:
1842 case CallingConv::ARM_APCS:
1843 case CallingConv::GHC:
1844 return CC;
1845 case CallingConv::PreserveMost:
1846 return CallingConv::PreserveMost;
1847 case CallingConv::ARM_AAPCS_VFP:
1848 case CallingConv::Swift:
1849 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1850 case CallingConv::C:
1851 if (!Subtarget->isAAPCS_ABI())
1852 return CallingConv::ARM_APCS;
1853 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1854 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1855 !isVarArg)
1856 return CallingConv::ARM_AAPCS_VFP;
1857 else
1858 return CallingConv::ARM_AAPCS;
1859 case CallingConv::Fast:
1860 case CallingConv::CXX_FAST_TLS:
1861 if (!Subtarget->isAAPCS_ABI()) {
1862 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1863 return CallingConv::Fast;
1864 return CallingConv::ARM_APCS;
1865 } else if (Subtarget->hasVFP2Base() &&
1866 !Subtarget->isThumb1Only() && !isVarArg)
1867 return CallingConv::ARM_AAPCS_VFP;
1868 else
1869 return CallingConv::ARM_AAPCS;
1873 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1874 bool isVarArg) const {
1875 return CCAssignFnForNode(CC, false, isVarArg);
1878 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1879 bool isVarArg) const {
1880 return CCAssignFnForNode(CC, true, isVarArg);
1883 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1884 /// CallingConvention.
1885 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1886 bool Return,
1887 bool isVarArg) const {
1888 switch (getEffectiveCallingConv(CC, isVarArg)) {
1889 default:
1890 report_fatal_error("Unsupported calling convention");
1891 case CallingConv::ARM_APCS:
1892 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1893 case CallingConv::ARM_AAPCS:
1894 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1895 case CallingConv::ARM_AAPCS_VFP:
1896 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1897 case CallingConv::Fast:
1898 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1899 case CallingConv::GHC:
1900 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1901 case CallingConv::PreserveMost:
1902 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1906 /// LowerCallResult - Lower the result values of a call into the
1907 /// appropriate copies out of appropriate physical registers.
1908 SDValue ARMTargetLowering::LowerCallResult(
1909 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1910 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1911 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1912 SDValue ThisVal) const {
1913 // Assign locations to each value returned by this call.
1914 SmallVector<CCValAssign, 16> RVLocs;
1915 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1916 *DAG.getContext());
1917 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1919 // Copy all of the result registers out of their specified physreg.
1920 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1921 CCValAssign VA = RVLocs[i];
1923 // Pass 'this' value directly from the argument to return value, to avoid
1924 // reg unit interference
1925 if (i == 0 && isThisReturn) {
1926 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1927 "unexpected return calling convention register assignment");
1928 InVals.push_back(ThisVal);
1929 continue;
1932 SDValue Val;
1933 if (VA.needsCustom()) {
1934 // Handle f64 or half of a v2f64.
1935 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1936 InFlag);
1937 Chain = Lo.getValue(1);
1938 InFlag = Lo.getValue(2);
1939 VA = RVLocs[++i]; // skip ahead to next loc
1940 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1941 InFlag);
1942 Chain = Hi.getValue(1);
1943 InFlag = Hi.getValue(2);
1944 if (!Subtarget->isLittle())
1945 std::swap (Lo, Hi);
1946 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1948 if (VA.getLocVT() == MVT::v2f64) {
1949 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1950 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1951 DAG.getConstant(0, dl, MVT::i32));
1953 VA = RVLocs[++i]; // skip ahead to next loc
1954 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1955 Chain = Lo.getValue(1);
1956 InFlag = Lo.getValue(2);
1957 VA = RVLocs[++i]; // skip ahead to next loc
1958 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1959 Chain = Hi.getValue(1);
1960 InFlag = Hi.getValue(2);
1961 if (!Subtarget->isLittle())
1962 std::swap (Lo, Hi);
1963 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1964 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1965 DAG.getConstant(1, dl, MVT::i32));
1967 } else {
1968 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1969 InFlag);
1970 Chain = Val.getValue(1);
1971 InFlag = Val.getValue(2);
1974 switch (VA.getLocInfo()) {
1975 default: llvm_unreachable("Unknown loc info!");
1976 case CCValAssign::Full: break;
1977 case CCValAssign::BCvt:
1978 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1979 break;
1982 InVals.push_back(Val);
1985 return Chain;
1988 /// LowerMemOpCallTo - Store the argument to the stack.
1989 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1990 SDValue Arg, const SDLoc &dl,
1991 SelectionDAG &DAG,
1992 const CCValAssign &VA,
1993 ISD::ArgFlagsTy Flags) const {
1994 unsigned LocMemOffset = VA.getLocMemOffset();
1995 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1996 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1997 StackPtr, PtrOff);
1998 return DAG.getStore(
1999 Chain, dl, Arg, PtrOff,
2000 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2003 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2004 SDValue Chain, SDValue &Arg,
2005 RegsToPassVector &RegsToPass,
2006 CCValAssign &VA, CCValAssign &NextVA,
2007 SDValue &StackPtr,
2008 SmallVectorImpl<SDValue> &MemOpChains,
2009 ISD::ArgFlagsTy Flags) const {
2010 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2011 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2012 unsigned id = Subtarget->isLittle() ? 0 : 1;
2013 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2015 if (NextVA.isRegLoc())
2016 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2017 else {
2018 assert(NextVA.isMemLoc());
2019 if (!StackPtr.getNode())
2020 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2021 getPointerTy(DAG.getDataLayout()));
2023 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2024 dl, DAG, NextVA,
2025 Flags));
2029 /// LowerCall - Lowering a call into a callseq_start <-
2030 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2031 /// nodes.
2032 SDValue
2033 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2034 SmallVectorImpl<SDValue> &InVals) const {
2035 SelectionDAG &DAG = CLI.DAG;
2036 SDLoc &dl = CLI.DL;
2037 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2038 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2039 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2040 SDValue Chain = CLI.Chain;
2041 SDValue Callee = CLI.Callee;
2042 bool &isTailCall = CLI.IsTailCall;
2043 CallingConv::ID CallConv = CLI.CallConv;
2044 bool doesNotRet = CLI.DoesNotReturn;
2045 bool isVarArg = CLI.IsVarArg;
2047 MachineFunction &MF = DAG.getMachineFunction();
2048 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2049 bool isThisReturn = false;
2050 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2051 bool PreferIndirect = false;
2053 // Disable tail calls if they're not supported.
2054 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2055 isTailCall = false;
2057 if (isa<GlobalAddressSDNode>(Callee)) {
2058 // If we're optimizing for minimum size and the function is called three or
2059 // more times in this block, we can improve codesize by calling indirectly
2060 // as BLXr has a 16-bit encoding.
2061 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2062 if (CLI.CS) {
2063 auto *BB = CLI.CS.getParent();
2064 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2065 count_if(GV->users(), [&BB](const User *U) {
2066 return isa<Instruction>(U) &&
2067 cast<Instruction>(U)->getParent() == BB;
2068 }) > 2;
2071 if (isTailCall) {
2072 // Check if it's really possible to do a tail call.
2073 isTailCall = IsEligibleForTailCallOptimization(
2074 Callee, CallConv, isVarArg, isStructRet,
2075 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2076 PreferIndirect);
2077 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2078 report_fatal_error("failed to perform tail call elimination on a call "
2079 "site marked musttail");
2080 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2081 // detected sibcalls.
2082 if (isTailCall)
2083 ++NumTailCalls;
2086 // Analyze operands of the call, assigning locations to each operand.
2087 SmallVector<CCValAssign, 16> ArgLocs;
2088 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2089 *DAG.getContext());
2090 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2092 // Get a count of how many bytes are to be pushed on the stack.
2093 unsigned NumBytes = CCInfo.getNextStackOffset();
2095 if (isTailCall) {
2096 // For tail calls, memory operands are available in our caller's stack.
2097 NumBytes = 0;
2098 } else {
2099 // Adjust the stack pointer for the new arguments...
2100 // These operations are automatically eliminated by the prolog/epilog pass
2101 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2104 SDValue StackPtr =
2105 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2107 RegsToPassVector RegsToPass;
2108 SmallVector<SDValue, 8> MemOpChains;
2110 // Walk the register/memloc assignments, inserting copies/loads. In the case
2111 // of tail call optimization, arguments are handled later.
2112 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2113 i != e;
2114 ++i, ++realArgIdx) {
2115 CCValAssign &VA = ArgLocs[i];
2116 SDValue Arg = OutVals[realArgIdx];
2117 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2118 bool isByVal = Flags.isByVal();
2120 // Promote the value if needed.
2121 switch (VA.getLocInfo()) {
2122 default: llvm_unreachable("Unknown loc info!");
2123 case CCValAssign::Full: break;
2124 case CCValAssign::SExt:
2125 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2126 break;
2127 case CCValAssign::ZExt:
2128 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2129 break;
2130 case CCValAssign::AExt:
2131 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2132 break;
2133 case CCValAssign::BCvt:
2134 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2135 break;
2138 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2139 if (VA.needsCustom()) {
2140 if (VA.getLocVT() == MVT::v2f64) {
2141 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2142 DAG.getConstant(0, dl, MVT::i32));
2143 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2144 DAG.getConstant(1, dl, MVT::i32));
2146 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2147 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2149 VA = ArgLocs[++i]; // skip ahead to next loc
2150 if (VA.isRegLoc()) {
2151 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2152 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2153 } else {
2154 assert(VA.isMemLoc());
2156 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2157 dl, DAG, VA, Flags));
2159 } else {
2160 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2161 StackPtr, MemOpChains, Flags);
2163 } else if (VA.isRegLoc()) {
2164 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2165 Outs[0].VT == MVT::i32) {
2166 assert(VA.getLocVT() == MVT::i32 &&
2167 "unexpected calling convention register assignment");
2168 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2169 "unexpected use of 'returned'");
2170 isThisReturn = true;
2172 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2173 } else if (isByVal) {
2174 assert(VA.isMemLoc());
2175 unsigned offset = 0;
2177 // True if this byval aggregate will be split between registers
2178 // and memory.
2179 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2180 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2182 if (CurByValIdx < ByValArgsCount) {
2184 unsigned RegBegin, RegEnd;
2185 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2187 EVT PtrVT =
2188 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2189 unsigned int i, j;
2190 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2191 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2192 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2193 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2194 MachinePointerInfo(),
2195 DAG.InferPtrAlignment(AddArg));
2196 MemOpChains.push_back(Load.getValue(1));
2197 RegsToPass.push_back(std::make_pair(j, Load));
2200 // If parameter size outsides register area, "offset" value
2201 // helps us to calculate stack slot for remained part properly.
2202 offset = RegEnd - RegBegin;
2204 CCInfo.nextInRegsParam();
2207 if (Flags.getByValSize() > 4*offset) {
2208 auto PtrVT = getPointerTy(DAG.getDataLayout());
2209 unsigned LocMemOffset = VA.getLocMemOffset();
2210 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2211 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2212 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2213 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2214 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2215 MVT::i32);
2216 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2217 MVT::i32);
2219 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2220 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2221 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2222 Ops));
2224 } else if (!isTailCall) {
2225 assert(VA.isMemLoc());
2227 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2228 dl, DAG, VA, Flags));
2232 if (!MemOpChains.empty())
2233 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2235 // Build a sequence of copy-to-reg nodes chained together with token chain
2236 // and flag operands which copy the outgoing args into the appropriate regs.
2237 SDValue InFlag;
2238 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2239 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2240 RegsToPass[i].second, InFlag);
2241 InFlag = Chain.getValue(1);
2244 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2245 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2246 // node so that legalize doesn't hack it.
2247 bool isDirect = false;
2249 const TargetMachine &TM = getTargetMachine();
2250 const Module *Mod = MF.getFunction().getParent();
2251 const GlobalValue *GV = nullptr;
2252 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2253 GV = G->getGlobal();
2254 bool isStub =
2255 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2257 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2258 bool isLocalARMFunc = false;
2259 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2260 auto PtrVt = getPointerTy(DAG.getDataLayout());
2262 if (Subtarget->genLongCalls()) {
2263 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2264 "long-calls codegen is not position independent!");
2265 // Handle a global address or an external symbol. If it's not one of
2266 // those, the target's already in a register, so we don't need to do
2267 // anything extra.
2268 if (isa<GlobalAddressSDNode>(Callee)) {
2269 // Create a constant pool entry for the callee address
2270 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2271 ARMConstantPoolValue *CPV =
2272 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2274 // Get the address of the callee into a register
2275 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2276 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2277 Callee = DAG.getLoad(
2278 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2279 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2280 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2281 const char *Sym = S->getSymbol();
2283 // Create a constant pool entry for the callee address
2284 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2285 ARMConstantPoolValue *CPV =
2286 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2287 ARMPCLabelIndex, 0);
2288 // Get the address of the callee into a register
2289 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2290 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2291 Callee = DAG.getLoad(
2292 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2293 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2295 } else if (isa<GlobalAddressSDNode>(Callee)) {
2296 if (!PreferIndirect) {
2297 isDirect = true;
2298 bool isDef = GV->isStrongDefinitionForLinker();
2300 // ARM call to a local ARM function is predicable.
2301 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2302 // tBX takes a register source operand.
2303 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2304 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2305 Callee = DAG.getNode(
2306 ARMISD::WrapperPIC, dl, PtrVt,
2307 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2308 Callee = DAG.getLoad(
2309 PtrVt, dl, DAG.getEntryNode(), Callee,
2310 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2311 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2312 MachineMemOperand::MOInvariant);
2313 } else if (Subtarget->isTargetCOFF()) {
2314 assert(Subtarget->isTargetWindows() &&
2315 "Windows is the only supported COFF target");
2316 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2317 ? ARMII::MO_DLLIMPORT
2318 : ARMII::MO_NO_FLAG;
2319 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2320 TargetFlags);
2321 if (GV->hasDLLImportStorageClass())
2322 Callee =
2323 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2324 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2325 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2326 } else {
2327 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2330 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2331 isDirect = true;
2332 // tBX takes a register source operand.
2333 const char *Sym = S->getSymbol();
2334 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2335 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2336 ARMConstantPoolValue *CPV =
2337 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2338 ARMPCLabelIndex, 4);
2339 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2340 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2341 Callee = DAG.getLoad(
2342 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2343 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2344 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2345 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2346 } else {
2347 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2351 // FIXME: handle tail calls differently.
2352 unsigned CallOpc;
2353 if (Subtarget->isThumb()) {
2354 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2355 CallOpc = ARMISD::CALL_NOLINK;
2356 else
2357 CallOpc = ARMISD::CALL;
2358 } else {
2359 if (!isDirect && !Subtarget->hasV5TOps())
2360 CallOpc = ARMISD::CALL_NOLINK;
2361 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2362 // Emit regular call when code size is the priority
2363 !Subtarget->hasMinSize())
2364 // "mov lr, pc; b _foo" to avoid confusing the RSP
2365 CallOpc = ARMISD::CALL_NOLINK;
2366 else
2367 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2370 std::vector<SDValue> Ops;
2371 Ops.push_back(Chain);
2372 Ops.push_back(Callee);
2374 // Add argument registers to the end of the list so that they are known live
2375 // into the call.
2376 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2377 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2378 RegsToPass[i].second.getValueType()));
2380 // Add a register mask operand representing the call-preserved registers.
2381 if (!isTailCall) {
2382 const uint32_t *Mask;
2383 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2384 if (isThisReturn) {
2385 // For 'this' returns, use the R0-preserving mask if applicable
2386 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2387 if (!Mask) {
2388 // Set isThisReturn to false if the calling convention is not one that
2389 // allows 'returned' to be modeled in this way, so LowerCallResult does
2390 // not try to pass 'this' straight through
2391 isThisReturn = false;
2392 Mask = ARI->getCallPreservedMask(MF, CallConv);
2394 } else
2395 Mask = ARI->getCallPreservedMask(MF, CallConv);
2397 assert(Mask && "Missing call preserved mask for calling convention");
2398 Ops.push_back(DAG.getRegisterMask(Mask));
2401 if (InFlag.getNode())
2402 Ops.push_back(InFlag);
2404 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2405 if (isTailCall) {
2406 MF.getFrameInfo().setHasTailCall();
2407 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2410 // Returns a chain and a flag for retval copy to use.
2411 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2412 InFlag = Chain.getValue(1);
2414 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2415 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2416 if (!Ins.empty())
2417 InFlag = Chain.getValue(1);
2419 // Handle result values, copying them out of physregs into vregs that we
2420 // return.
2421 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2422 InVals, isThisReturn,
2423 isThisReturn ? OutVals[0] : SDValue());
2426 /// HandleByVal - Every parameter *after* a byval parameter is passed
2427 /// on the stack. Remember the next parameter register to allocate,
2428 /// and then confiscate the rest of the parameter registers to insure
2429 /// this.
2430 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2431 unsigned Align) const {
2432 // Byval (as with any stack) slots are always at least 4 byte aligned.
2433 Align = std::max(Align, 4U);
2435 unsigned Reg = State->AllocateReg(GPRArgRegs);
2436 if (!Reg)
2437 return;
2439 unsigned AlignInRegs = Align / 4;
2440 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2441 for (unsigned i = 0; i < Waste; ++i)
2442 Reg = State->AllocateReg(GPRArgRegs);
2444 if (!Reg)
2445 return;
2447 unsigned Excess = 4 * (ARM::R4 - Reg);
2449 // Special case when NSAA != SP and parameter size greater than size of
2450 // all remained GPR regs. In that case we can't split parameter, we must
2451 // send it to stack. We also must set NCRN to R4, so waste all
2452 // remained registers.
2453 const unsigned NSAAOffset = State->getNextStackOffset();
2454 if (NSAAOffset != 0 && Size > Excess) {
2455 while (State->AllocateReg(GPRArgRegs))
2457 return;
2460 // First register for byval parameter is the first register that wasn't
2461 // allocated before this method call, so it would be "reg".
2462 // If parameter is small enough to be saved in range [reg, r4), then
2463 // the end (first after last) register would be reg + param-size-in-regs,
2464 // else parameter would be splitted between registers and stack,
2465 // end register would be r4 in this case.
2466 unsigned ByValRegBegin = Reg;
2467 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2468 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2469 // Note, first register is allocated in the beginning of function already,
2470 // allocate remained amount of registers we need.
2471 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2472 State->AllocateReg(GPRArgRegs);
2473 // A byval parameter that is split between registers and memory needs its
2474 // size truncated here.
2475 // In the case where the entire structure fits in registers, we set the
2476 // size in memory to zero.
2477 Size = std::max<int>(Size - Excess, 0);
2480 /// MatchingStackOffset - Return true if the given stack call argument is
2481 /// already available in the same position (relatively) of the caller's
2482 /// incoming argument stack.
2483 static
2484 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2485 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2486 const TargetInstrInfo *TII) {
2487 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2488 int FI = std::numeric_limits<int>::max();
2489 if (Arg.getOpcode() == ISD::CopyFromReg) {
2490 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2491 if (!Register::isVirtualRegister(VR))
2492 return false;
2493 MachineInstr *Def = MRI->getVRegDef(VR);
2494 if (!Def)
2495 return false;
2496 if (!Flags.isByVal()) {
2497 if (!TII->isLoadFromStackSlot(*Def, FI))
2498 return false;
2499 } else {
2500 return false;
2502 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2503 if (Flags.isByVal())
2504 // ByVal argument is passed in as a pointer but it's now being
2505 // dereferenced. e.g.
2506 // define @foo(%struct.X* %A) {
2507 // tail call @bar(%struct.X* byval %A)
2508 // }
2509 return false;
2510 SDValue Ptr = Ld->getBasePtr();
2511 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2512 if (!FINode)
2513 return false;
2514 FI = FINode->getIndex();
2515 } else
2516 return false;
2518 assert(FI != std::numeric_limits<int>::max());
2519 if (!MFI.isFixedObjectIndex(FI))
2520 return false;
2521 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2524 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2525 /// for tail call optimization. Targets which want to do tail call
2526 /// optimization should implement this function.
2527 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2528 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2529 bool isCalleeStructRet, bool isCallerStructRet,
2530 const SmallVectorImpl<ISD::OutputArg> &Outs,
2531 const SmallVectorImpl<SDValue> &OutVals,
2532 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2533 const bool isIndirect) const {
2534 MachineFunction &MF = DAG.getMachineFunction();
2535 const Function &CallerF = MF.getFunction();
2536 CallingConv::ID CallerCC = CallerF.getCallingConv();
2538 assert(Subtarget->supportsTailCall());
2540 // Indirect tail calls cannot be optimized for Thumb1 if the args
2541 // to the call take up r0-r3. The reason is that there are no legal registers
2542 // left to hold the pointer to the function to be called.
2543 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2544 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2545 return false;
2547 // Look for obvious safe cases to perform tail call optimization that do not
2548 // require ABI changes. This is what gcc calls sibcall.
2550 // Exception-handling functions need a special set of instructions to indicate
2551 // a return to the hardware. Tail-calling another function would probably
2552 // break this.
2553 if (CallerF.hasFnAttribute("interrupt"))
2554 return false;
2556 // Also avoid sibcall optimization if either caller or callee uses struct
2557 // return semantics.
2558 if (isCalleeStructRet || isCallerStructRet)
2559 return false;
2561 // Externally-defined functions with weak linkage should not be
2562 // tail-called on ARM when the OS does not support dynamic
2563 // pre-emption of symbols, as the AAELF spec requires normal calls
2564 // to undefined weak functions to be replaced with a NOP or jump to the
2565 // next instruction. The behaviour of branch instructions in this
2566 // situation (as used for tail calls) is implementation-defined, so we
2567 // cannot rely on the linker replacing the tail call with a return.
2568 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2569 const GlobalValue *GV = G->getGlobal();
2570 const Triple &TT = getTargetMachine().getTargetTriple();
2571 if (GV->hasExternalWeakLinkage() &&
2572 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2573 return false;
2576 // Check that the call results are passed in the same way.
2577 LLVMContext &C = *DAG.getContext();
2578 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2579 CCAssignFnForReturn(CalleeCC, isVarArg),
2580 CCAssignFnForReturn(CallerCC, isVarArg)))
2581 return false;
2582 // The callee has to preserve all registers the caller needs to preserve.
2583 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2584 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2585 if (CalleeCC != CallerCC) {
2586 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2587 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2588 return false;
2591 // If Caller's vararg or byval argument has been split between registers and
2592 // stack, do not perform tail call, since part of the argument is in caller's
2593 // local frame.
2594 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2595 if (AFI_Caller->getArgRegsSaveSize())
2596 return false;
2598 // If the callee takes no arguments then go on to check the results of the
2599 // call.
2600 if (!Outs.empty()) {
2601 // Check if stack adjustment is needed. For now, do not do this if any
2602 // argument is passed on the stack.
2603 SmallVector<CCValAssign, 16> ArgLocs;
2604 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2605 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2606 if (CCInfo.getNextStackOffset()) {
2607 // Check if the arguments are already laid out in the right way as
2608 // the caller's fixed stack objects.
2609 MachineFrameInfo &MFI = MF.getFrameInfo();
2610 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2611 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2612 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2613 i != e;
2614 ++i, ++realArgIdx) {
2615 CCValAssign &VA = ArgLocs[i];
2616 EVT RegVT = VA.getLocVT();
2617 SDValue Arg = OutVals[realArgIdx];
2618 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2619 if (VA.getLocInfo() == CCValAssign::Indirect)
2620 return false;
2621 if (VA.needsCustom()) {
2622 // f64 and vector types are split into multiple registers or
2623 // register/stack-slot combinations. The types will not match
2624 // the registers; give up on memory f64 refs until we figure
2625 // out what to do about this.
2626 if (!VA.isRegLoc())
2627 return false;
2628 if (!ArgLocs[++i].isRegLoc())
2629 return false;
2630 if (RegVT == MVT::v2f64) {
2631 if (!ArgLocs[++i].isRegLoc())
2632 return false;
2633 if (!ArgLocs[++i].isRegLoc())
2634 return false;
2636 } else if (!VA.isRegLoc()) {
2637 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2638 MFI, MRI, TII))
2639 return false;
2644 const MachineRegisterInfo &MRI = MF.getRegInfo();
2645 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2646 return false;
2649 return true;
2652 bool
2653 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2654 MachineFunction &MF, bool isVarArg,
2655 const SmallVectorImpl<ISD::OutputArg> &Outs,
2656 LLVMContext &Context) const {
2657 SmallVector<CCValAssign, 16> RVLocs;
2658 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2659 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2662 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2663 const SDLoc &DL, SelectionDAG &DAG) {
2664 const MachineFunction &MF = DAG.getMachineFunction();
2665 const Function &F = MF.getFunction();
2667 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2669 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2670 // version of the "preferred return address". These offsets affect the return
2671 // instruction if this is a return from PL1 without hypervisor extensions.
2672 // IRQ/FIQ: +4 "subs pc, lr, #4"
2673 // SWI: 0 "subs pc, lr, #0"
2674 // ABORT: +4 "subs pc, lr, #4"
2675 // UNDEF: +4/+2 "subs pc, lr, #0"
2676 // UNDEF varies depending on where the exception came from ARM or Thumb
2677 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2679 int64_t LROffset;
2680 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2681 IntKind == "ABORT")
2682 LROffset = 4;
2683 else if (IntKind == "SWI" || IntKind == "UNDEF")
2684 LROffset = 0;
2685 else
2686 report_fatal_error("Unsupported interrupt attribute. If present, value "
2687 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2689 RetOps.insert(RetOps.begin() + 1,
2690 DAG.getConstant(LROffset, DL, MVT::i32, false));
2692 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2695 SDValue
2696 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2697 bool isVarArg,
2698 const SmallVectorImpl<ISD::OutputArg> &Outs,
2699 const SmallVectorImpl<SDValue> &OutVals,
2700 const SDLoc &dl, SelectionDAG &DAG) const {
2701 // CCValAssign - represent the assignment of the return value to a location.
2702 SmallVector<CCValAssign, 16> RVLocs;
2704 // CCState - Info about the registers and stack slots.
2705 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2706 *DAG.getContext());
2708 // Analyze outgoing return values.
2709 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2711 SDValue Flag;
2712 SmallVector<SDValue, 4> RetOps;
2713 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2714 bool isLittleEndian = Subtarget->isLittle();
2716 MachineFunction &MF = DAG.getMachineFunction();
2717 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2718 AFI->setReturnRegsCount(RVLocs.size());
2720 // Copy the result values into the output registers.
2721 for (unsigned i = 0, realRVLocIdx = 0;
2722 i != RVLocs.size();
2723 ++i, ++realRVLocIdx) {
2724 CCValAssign &VA = RVLocs[i];
2725 assert(VA.isRegLoc() && "Can only return in registers!");
2727 SDValue Arg = OutVals[realRVLocIdx];
2728 bool ReturnF16 = false;
2730 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2731 // Half-precision return values can be returned like this:
2733 // t11 f16 = fadd ...
2734 // t12: i16 = bitcast t11
2735 // t13: i32 = zero_extend t12
2736 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2738 // to avoid code generation for bitcasts, we simply set Arg to the node
2739 // that produces the f16 value, t11 in this case.
2741 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2742 SDValue ZE = Arg.getOperand(0);
2743 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2744 SDValue BC = ZE.getOperand(0);
2745 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2746 Arg = BC.getOperand(0);
2747 ReturnF16 = true;
2753 switch (VA.getLocInfo()) {
2754 default: llvm_unreachable("Unknown loc info!");
2755 case CCValAssign::Full: break;
2756 case CCValAssign::BCvt:
2757 if (!ReturnF16)
2758 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2759 break;
2762 if (VA.needsCustom()) {
2763 if (VA.getLocVT() == MVT::v2f64) {
2764 // Extract the first half and return it in two registers.
2765 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2766 DAG.getConstant(0, dl, MVT::i32));
2767 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2768 DAG.getVTList(MVT::i32, MVT::i32), Half);
2770 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2771 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2772 Flag);
2773 Flag = Chain.getValue(1);
2774 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2775 VA = RVLocs[++i]; // skip ahead to next loc
2776 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2777 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2778 Flag);
2779 Flag = Chain.getValue(1);
2780 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2781 VA = RVLocs[++i]; // skip ahead to next loc
2783 // Extract the 2nd half and fall through to handle it as an f64 value.
2784 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2785 DAG.getConstant(1, dl, MVT::i32));
2787 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2788 // available.
2789 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2790 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2791 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2792 fmrrd.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 fmrrd.getValue(isLittleEndian ? 1 : 0),
2799 Flag);
2800 } else
2801 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2803 // Guarantee that all emitted copies are
2804 // stuck together, avoiding something bad.
2805 Flag = Chain.getValue(1);
2806 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2807 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2809 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2810 const MCPhysReg *I =
2811 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2812 if (I) {
2813 for (; *I; ++I) {
2814 if (ARM::GPRRegClass.contains(*I))
2815 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2816 else if (ARM::DPRRegClass.contains(*I))
2817 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2818 else
2819 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2823 // Update chain and glue.
2824 RetOps[0] = Chain;
2825 if (Flag.getNode())
2826 RetOps.push_back(Flag);
2828 // CPUs which aren't M-class use a special sequence to return from
2829 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2830 // though we use "subs pc, lr, #N").
2832 // M-class CPUs actually use a normal return sequence with a special
2833 // (hardware-provided) value in LR, so the normal code path works.
2834 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2835 !Subtarget->isMClass()) {
2836 if (Subtarget->isThumb1Only())
2837 report_fatal_error("interrupt attribute is not supported in Thumb1");
2838 return LowerInterruptReturn(RetOps, dl, DAG);
2841 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2844 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2845 if (N->getNumValues() != 1)
2846 return false;
2847 if (!N->hasNUsesOfValue(1, 0))
2848 return false;
2850 SDValue TCChain = Chain;
2851 SDNode *Copy = *N->use_begin();
2852 if (Copy->getOpcode() == ISD::CopyToReg) {
2853 // If the copy has a glue operand, we conservatively assume it isn't safe to
2854 // perform a tail call.
2855 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2856 return false;
2857 TCChain = Copy->getOperand(0);
2858 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2859 SDNode *VMov = Copy;
2860 // f64 returned in a pair of GPRs.
2861 SmallPtrSet<SDNode*, 2> Copies;
2862 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2863 UI != UE; ++UI) {
2864 if (UI->getOpcode() != ISD::CopyToReg)
2865 return false;
2866 Copies.insert(*UI);
2868 if (Copies.size() > 2)
2869 return false;
2871 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2872 UI != UE; ++UI) {
2873 SDValue UseChain = UI->getOperand(0);
2874 if (Copies.count(UseChain.getNode()))
2875 // Second CopyToReg
2876 Copy = *UI;
2877 else {
2878 // We are at the top of this chain.
2879 // If the copy has a glue operand, we conservatively assume it
2880 // isn't safe to perform a tail call.
2881 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2882 return false;
2883 // First CopyToReg
2884 TCChain = UseChain;
2887 } else if (Copy->getOpcode() == ISD::BITCAST) {
2888 // f32 returned in a single GPR.
2889 if (!Copy->hasOneUse())
2890 return false;
2891 Copy = *Copy->use_begin();
2892 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2893 return false;
2894 // If the copy has a glue operand, we conservatively assume it isn't safe to
2895 // perform a tail call.
2896 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2897 return false;
2898 TCChain = Copy->getOperand(0);
2899 } else {
2900 return false;
2903 bool HasRet = false;
2904 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2905 UI != UE; ++UI) {
2906 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2907 UI->getOpcode() != ARMISD::INTRET_FLAG)
2908 return false;
2909 HasRet = true;
2912 if (!HasRet)
2913 return false;
2915 Chain = TCChain;
2916 return true;
2919 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2920 if (!Subtarget->supportsTailCall())
2921 return false;
2923 auto Attr =
2924 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2925 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2926 return false;
2928 return true;
2931 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2932 // and pass the lower and high parts through.
2933 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2934 SDLoc DL(Op);
2935 SDValue WriteValue = Op->getOperand(2);
2937 // This function is only supposed to be called for i64 type argument.
2938 assert(WriteValue.getValueType() == MVT::i64
2939 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2941 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2942 DAG.getConstant(0, DL, MVT::i32));
2943 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2944 DAG.getConstant(1, DL, MVT::i32));
2945 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2946 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2949 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2950 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2951 // one of the above mentioned nodes. It has to be wrapped because otherwise
2952 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2953 // be used to form addressing mode. These wrapped nodes will be selected
2954 // into MOVi.
2955 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2956 SelectionDAG &DAG) const {
2957 EVT PtrVT = Op.getValueType();
2958 // FIXME there is no actual debug info here
2959 SDLoc dl(Op);
2960 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2961 SDValue Res;
2963 // When generating execute-only code Constant Pools must be promoted to the
2964 // global data section. It's a bit ugly that we can't share them across basic
2965 // blocks, but this way we guarantee that execute-only behaves correct with
2966 // position-independent addressing modes.
2967 if (Subtarget->genExecuteOnly()) {
2968 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2969 auto T = const_cast<Type*>(CP->getType());
2970 auto C = const_cast<Constant*>(CP->getConstVal());
2971 auto M = const_cast<Module*>(DAG.getMachineFunction().
2972 getFunction().getParent());
2973 auto GV = new GlobalVariable(
2974 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2975 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2976 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2977 Twine(AFI->createPICLabelUId())
2979 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2980 dl, PtrVT);
2981 return LowerGlobalAddress(GA, DAG);
2984 if (CP->isMachineConstantPoolEntry())
2985 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2986 CP->getAlignment());
2987 else
2988 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2989 CP->getAlignment());
2990 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2993 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2994 return MachineJumpTableInfo::EK_Inline;
2997 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2998 SelectionDAG &DAG) const {
2999 MachineFunction &MF = DAG.getMachineFunction();
3000 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3001 unsigned ARMPCLabelIndex = 0;
3002 SDLoc DL(Op);
3003 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3004 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3005 SDValue CPAddr;
3006 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3007 if (!IsPositionIndependent) {
3008 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3009 } else {
3010 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3011 ARMPCLabelIndex = AFI->createPICLabelUId();
3012 ARMConstantPoolValue *CPV =
3013 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3014 ARMCP::CPBlockAddress, PCAdj);
3015 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3017 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3018 SDValue Result = DAG.getLoad(
3019 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3020 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3021 if (!IsPositionIndependent)
3022 return Result;
3023 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3024 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3027 /// Convert a TLS address reference into the correct sequence of loads
3028 /// and calls to compute the variable's address for Darwin, and return an
3029 /// SDValue containing the final node.
3031 /// Darwin only has one TLS scheme which must be capable of dealing with the
3032 /// fully general situation, in the worst case. This means:
3033 /// + "extern __thread" declaration.
3034 /// + Defined in a possibly unknown dynamic library.
3036 /// The general system is that each __thread variable has a [3 x i32] descriptor
3037 /// which contains information used by the runtime to calculate the address. The
3038 /// only part of this the compiler needs to know about is the first word, which
3039 /// contains a function pointer that must be called with the address of the
3040 /// entire descriptor in "r0".
3042 /// Since this descriptor may be in a different unit, in general access must
3043 /// proceed along the usual ARM rules. A common sequence to produce is:
3045 /// movw rT1, :lower16:_var$non_lazy_ptr
3046 /// movt rT1, :upper16:_var$non_lazy_ptr
3047 /// ldr r0, [rT1]
3048 /// ldr rT2, [r0]
3049 /// blx rT2
3050 /// [...address now in r0...]
3051 SDValue
3052 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3053 SelectionDAG &DAG) const {
3054 assert(Subtarget->isTargetDarwin() &&
3055 "This function expects a Darwin target");
3056 SDLoc DL(Op);
3058 // First step is to get the address of the actua global symbol. This is where
3059 // the TLS descriptor lives.
3060 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3062 // The first entry in the descriptor is a function pointer that we must call
3063 // to obtain the address of the variable.
3064 SDValue Chain = DAG.getEntryNode();
3065 SDValue FuncTLVGet = DAG.getLoad(
3066 MVT::i32, DL, Chain, DescAddr,
3067 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3068 /* Alignment = */ 4,
3069 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3070 MachineMemOperand::MOInvariant);
3071 Chain = FuncTLVGet.getValue(1);
3073 MachineFunction &F = DAG.getMachineFunction();
3074 MachineFrameInfo &MFI = F.getFrameInfo();
3075 MFI.setAdjustsStack(true);
3077 // TLS calls preserve all registers except those that absolutely must be
3078 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3079 // silly).
3080 auto TRI =
3081 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3082 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3083 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3085 // Finally, we can make the call. This is just a degenerate version of a
3086 // normal AArch64 call node: r0 takes the address of the descriptor, and
3087 // returns the address of the variable in this thread.
3088 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3089 Chain =
3090 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3091 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3092 DAG.getRegisterMask(Mask), Chain.getValue(1));
3093 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3096 SDValue
3097 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3098 SelectionDAG &DAG) const {
3099 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3101 SDValue Chain = DAG.getEntryNode();
3102 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3103 SDLoc DL(Op);
3105 // Load the current TEB (thread environment block)
3106 SDValue Ops[] = {Chain,
3107 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3108 DAG.getConstant(15, DL, MVT::i32),
3109 DAG.getConstant(0, DL, MVT::i32),
3110 DAG.getConstant(13, DL, MVT::i32),
3111 DAG.getConstant(0, DL, MVT::i32),
3112 DAG.getConstant(2, DL, MVT::i32)};
3113 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3114 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3116 SDValue TEB = CurrentTEB.getValue(0);
3117 Chain = CurrentTEB.getValue(1);
3119 // Load the ThreadLocalStoragePointer from the TEB
3120 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3121 SDValue TLSArray =
3122 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3123 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3125 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3126 // offset into the TLSArray.
3128 // Load the TLS index from the C runtime
3129 SDValue TLSIndex =
3130 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3131 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3132 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3134 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3135 DAG.getConstant(2, DL, MVT::i32));
3136 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3137 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3138 MachinePointerInfo());
3140 // Get the offset of the start of the .tls section (section base)
3141 const auto *GA = cast<GlobalAddressSDNode>(Op);
3142 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3143 SDValue Offset = DAG.getLoad(
3144 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3145 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3146 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3148 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3151 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3152 SDValue
3153 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3154 SelectionDAG &DAG) const {
3155 SDLoc dl(GA);
3156 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3157 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3158 MachineFunction &MF = DAG.getMachineFunction();
3159 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3160 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3161 ARMConstantPoolValue *CPV =
3162 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3163 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3164 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3165 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3166 Argument = DAG.getLoad(
3167 PtrVT, dl, DAG.getEntryNode(), Argument,
3168 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3169 SDValue Chain = Argument.getValue(1);
3171 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3172 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3174 // call __tls_get_addr.
3175 ArgListTy Args;
3176 ArgListEntry Entry;
3177 Entry.Node = Argument;
3178 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3179 Args.push_back(Entry);
3181 // FIXME: is there useful debug info available here?
3182 TargetLowering::CallLoweringInfo CLI(DAG);
3183 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3184 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3185 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3187 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3188 return CallResult.first;
3191 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3192 // "local exec" model.
3193 SDValue
3194 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3195 SelectionDAG &DAG,
3196 TLSModel::Model model) const {
3197 const GlobalValue *GV = GA->getGlobal();
3198 SDLoc dl(GA);
3199 SDValue Offset;
3200 SDValue Chain = DAG.getEntryNode();
3201 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3202 // Get the Thread Pointer
3203 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3205 if (model == TLSModel::InitialExec) {
3206 MachineFunction &MF = DAG.getMachineFunction();
3207 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3208 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3209 // Initial exec model.
3210 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3211 ARMConstantPoolValue *CPV =
3212 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3213 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3214 true);
3215 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3216 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3217 Offset = DAG.getLoad(
3218 PtrVT, dl, Chain, Offset,
3219 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3220 Chain = Offset.getValue(1);
3222 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3223 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3225 Offset = DAG.getLoad(
3226 PtrVT, dl, Chain, Offset,
3227 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3228 } else {
3229 // local exec model
3230 assert(model == TLSModel::LocalExec);
3231 ARMConstantPoolValue *CPV =
3232 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3233 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3234 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3235 Offset = DAG.getLoad(
3236 PtrVT, dl, Chain, Offset,
3237 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3240 // The address of the thread local variable is the add of the thread
3241 // pointer with the offset of the variable.
3242 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3245 SDValue
3246 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3247 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3248 if (DAG.getTarget().useEmulatedTLS())
3249 return LowerToTLSEmulatedModel(GA, DAG);
3251 if (Subtarget->isTargetDarwin())
3252 return LowerGlobalTLSAddressDarwin(Op, DAG);
3254 if (Subtarget->isTargetWindows())
3255 return LowerGlobalTLSAddressWindows(Op, DAG);
3257 // TODO: implement the "local dynamic" model
3258 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3259 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3261 switch (model) {
3262 case TLSModel::GeneralDynamic:
3263 case TLSModel::LocalDynamic:
3264 return LowerToTLSGeneralDynamicModel(GA, DAG);
3265 case TLSModel::InitialExec:
3266 case TLSModel::LocalExec:
3267 return LowerToTLSExecModels(GA, DAG, model);
3269 llvm_unreachable("bogus TLS model");
3272 /// Return true if all users of V are within function F, looking through
3273 /// ConstantExprs.
3274 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3275 SmallVector<const User*,4> Worklist;
3276 for (auto *U : V->users())
3277 Worklist.push_back(U);
3278 while (!Worklist.empty()) {
3279 auto *U = Worklist.pop_back_val();
3280 if (isa<ConstantExpr>(U)) {
3281 for (auto *UU : U->users())
3282 Worklist.push_back(UU);
3283 continue;
3286 auto *I = dyn_cast<Instruction>(U);
3287 if (!I || I->getParent()->getParent() != F)
3288 return false;
3290 return true;
3293 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3294 const GlobalValue *GV, SelectionDAG &DAG,
3295 EVT PtrVT, const SDLoc &dl) {
3296 // If we're creating a pool entry for a constant global with unnamed address,
3297 // and the global is small enough, we can emit it inline into the constant pool
3298 // to save ourselves an indirection.
3300 // This is a win if the constant is only used in one function (so it doesn't
3301 // need to be duplicated) or duplicating the constant wouldn't increase code
3302 // size (implying the constant is no larger than 4 bytes).
3303 const Function &F = DAG.getMachineFunction().getFunction();
3305 // We rely on this decision to inline being idemopotent and unrelated to the
3306 // use-site. We know that if we inline a variable at one use site, we'll
3307 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3308 // doesn't know about this optimization, so bail out if it's enabled else
3309 // we could decide to inline here (and thus never emit the GV) but require
3310 // the GV from fast-isel generated code.
3311 if (!EnableConstpoolPromotion ||
3312 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3313 return SDValue();
3315 auto *GVar = dyn_cast<GlobalVariable>(GV);
3316 if (!GVar || !GVar->hasInitializer() ||
3317 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3318 !GVar->hasLocalLinkage())
3319 return SDValue();
3321 // If we inline a value that contains relocations, we move the relocations
3322 // from .data to .text. This is not allowed in position-independent code.
3323 auto *Init = GVar->getInitializer();
3324 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3325 Init->needsRelocation())
3326 return SDValue();
3328 // The constant islands pass can only really deal with alignment requests
3329 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3330 // any type wanting greater alignment requirements than 4 bytes. We also
3331 // can only promote constants that are multiples of 4 bytes in size or
3332 // are paddable to a multiple of 4. Currently we only try and pad constants
3333 // that are strings for simplicity.
3334 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3335 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3336 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3337 unsigned RequiredPadding = 4 - (Size % 4);
3338 bool PaddingPossible =
3339 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3340 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3341 Size == 0)
3342 return SDValue();
3344 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3345 MachineFunction &MF = DAG.getMachineFunction();
3346 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3348 // We can't bloat the constant pool too much, else the ConstantIslands pass
3349 // may fail to converge. If we haven't promoted this global yet (it may have
3350 // multiple uses), and promoting it would increase the constant pool size (Sz
3351 // > 4), ensure we have space to do so up to MaxTotal.
3352 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3353 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3354 ConstpoolPromotionMaxTotal)
3355 return SDValue();
3357 // This is only valid if all users are in a single function; we can't clone
3358 // the constant in general. The LLVM IR unnamed_addr allows merging
3359 // constants, but not cloning them.
3361 // We could potentially allow cloning if we could prove all uses of the
3362 // constant in the current function don't care about the address, like
3363 // printf format strings. But that isn't implemented for now.
3364 if (!allUsersAreInFunction(GVar, &F))
3365 return SDValue();
3367 // We're going to inline this global. Pad it out if needed.
3368 if (RequiredPadding != 4) {
3369 StringRef S = CDAInit->getAsString();
3371 SmallVector<uint8_t,16> V(S.size());
3372 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3373 while (RequiredPadding--)
3374 V.push_back(0);
3375 Init = ConstantDataArray::get(*DAG.getContext(), V);
3378 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3379 SDValue CPAddr =
3380 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3381 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3382 AFI->markGlobalAsPromotedToConstantPool(GVar);
3383 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3384 PaddedSize - 4);
3386 ++NumConstpoolPromoted;
3387 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3390 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3391 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3392 if (!(GV = GA->getBaseObject()))
3393 return false;
3394 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3395 return V->isConstant();
3396 return isa<Function>(GV);
3399 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3400 SelectionDAG &DAG) const {
3401 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3402 default: llvm_unreachable("unknown object format");
3403 case Triple::COFF:
3404 return LowerGlobalAddressWindows(Op, DAG);
3405 case Triple::ELF:
3406 return LowerGlobalAddressELF(Op, DAG);
3407 case Triple::MachO:
3408 return LowerGlobalAddressDarwin(Op, DAG);
3412 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3413 SelectionDAG &DAG) const {
3414 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3415 SDLoc dl(Op);
3416 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3417 const TargetMachine &TM = getTargetMachine();
3418 bool IsRO = isReadOnly(GV);
3420 // promoteToConstantPool only if not generating XO text section
3421 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3422 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3423 return V;
3425 if (isPositionIndependent()) {
3426 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3427 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3428 UseGOT_PREL ? ARMII::MO_GOT : 0);
3429 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3430 if (UseGOT_PREL)
3431 Result =
3432 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3433 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3434 return Result;
3435 } else if (Subtarget->isROPI() && IsRO) {
3436 // PC-relative.
3437 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3438 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3439 return Result;
3440 } else if (Subtarget->isRWPI() && !IsRO) {
3441 // SB-relative.
3442 SDValue RelAddr;
3443 if (Subtarget->useMovt()) {
3444 ++NumMovwMovt;
3445 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3446 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3447 } else { // use literal pool for address constant
3448 ARMConstantPoolValue *CPV =
3449 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3450 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3451 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3452 RelAddr = DAG.getLoad(
3453 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3454 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3456 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3457 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3458 return Result;
3461 // If we have T2 ops, we can materialize the address directly via movt/movw
3462 // pair. This is always cheaper.
3463 if (Subtarget->useMovt()) {
3464 ++NumMovwMovt;
3465 // FIXME: Once remat is capable of dealing with instructions with register
3466 // operands, expand this into two nodes.
3467 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3468 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3469 } else {
3470 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3471 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3472 return DAG.getLoad(
3473 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3474 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3478 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3479 SelectionDAG &DAG) const {
3480 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3481 "ROPI/RWPI not currently supported for Darwin");
3482 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3483 SDLoc dl(Op);
3484 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3486 if (Subtarget->useMovt())
3487 ++NumMovwMovt;
3489 // FIXME: Once remat is capable of dealing with instructions with register
3490 // operands, expand this into multiple nodes
3491 unsigned Wrapper =
3492 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3494 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3495 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3497 if (Subtarget->isGVIndirectSymbol(GV))
3498 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3499 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3500 return Result;
3503 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3504 SelectionDAG &DAG) const {
3505 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3506 assert(Subtarget->useMovt() &&
3507 "Windows on ARM expects to use movw/movt");
3508 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3509 "ROPI/RWPI not currently supported for Windows");
3511 const TargetMachine &TM = getTargetMachine();
3512 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3513 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3514 if (GV->hasDLLImportStorageClass())
3515 TargetFlags = ARMII::MO_DLLIMPORT;
3516 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3517 TargetFlags = ARMII::MO_COFFSTUB;
3518 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3519 SDValue Result;
3520 SDLoc DL(Op);
3522 ++NumMovwMovt;
3524 // FIXME: Once remat is capable of dealing with instructions with register
3525 // operands, expand this into two nodes.
3526 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3527 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3528 TargetFlags));
3529 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3530 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3531 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3532 return Result;
3535 SDValue
3536 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3537 SDLoc dl(Op);
3538 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3539 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3540 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3541 Op.getOperand(1), Val);
3544 SDValue
3545 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3546 SDLoc dl(Op);
3547 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3548 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3551 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3552 SelectionDAG &DAG) const {
3553 SDLoc dl(Op);
3554 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3555 Op.getOperand(0));
3558 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3559 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3560 unsigned IntNo =
3561 cast<ConstantSDNode>(
3562 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3563 ->getZExtValue();
3564 switch (IntNo) {
3565 default:
3566 return SDValue(); // Don't custom lower most intrinsics.
3567 case Intrinsic::arm_gnu_eabi_mcount: {
3568 MachineFunction &MF = DAG.getMachineFunction();
3569 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3570 SDLoc dl(Op);
3571 SDValue Chain = Op.getOperand(0);
3572 // call "\01__gnu_mcount_nc"
3573 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3574 const uint32_t *Mask =
3575 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3576 assert(Mask && "Missing call preserved mask for calling convention");
3577 // Mark LR an implicit live-in.
3578 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3579 SDValue ReturnAddress =
3580 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3581 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue};
3582 SDValue Callee =
3583 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3584 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3585 if (Subtarget->isThumb())
3586 return SDValue(
3587 DAG.getMachineNode(
3588 ARM::tBL_PUSHLR, dl, ResultTys,
3589 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3590 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3592 return SDValue(
3593 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3594 {ReturnAddress, Callee, RegisterMask, Chain}),
3600 SDValue
3601 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3602 const ARMSubtarget *Subtarget) const {
3603 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3604 SDLoc dl(Op);
3605 switch (IntNo) {
3606 default: return SDValue(); // Don't custom lower most intrinsics.
3607 case Intrinsic::thread_pointer: {
3608 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3609 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3611 case Intrinsic::eh_sjlj_lsda: {
3612 MachineFunction &MF = DAG.getMachineFunction();
3613 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3614 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3615 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3616 SDValue CPAddr;
3617 bool IsPositionIndependent = isPositionIndependent();
3618 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3619 ARMConstantPoolValue *CPV =
3620 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3621 ARMCP::CPLSDA, PCAdj);
3622 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3623 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3624 SDValue Result = DAG.getLoad(
3625 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3626 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3628 if (IsPositionIndependent) {
3629 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3630 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3632 return Result;
3634 case Intrinsic::arm_neon_vabs:
3635 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3636 Op.getOperand(1));
3637 case Intrinsic::arm_neon_vmulls:
3638 case Intrinsic::arm_neon_vmullu: {
3639 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3640 ? ARMISD::VMULLs : ARMISD::VMULLu;
3641 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3642 Op.getOperand(1), Op.getOperand(2));
3644 case Intrinsic::arm_neon_vminnm:
3645 case Intrinsic::arm_neon_vmaxnm: {
3646 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3647 ? ISD::FMINNUM : ISD::FMAXNUM;
3648 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3649 Op.getOperand(1), Op.getOperand(2));
3651 case Intrinsic::arm_neon_vminu:
3652 case Intrinsic::arm_neon_vmaxu: {
3653 if (Op.getValueType().isFloatingPoint())
3654 return SDValue();
3655 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3656 ? ISD::UMIN : ISD::UMAX;
3657 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3658 Op.getOperand(1), Op.getOperand(2));
3660 case Intrinsic::arm_neon_vmins:
3661 case Intrinsic::arm_neon_vmaxs: {
3662 // v{min,max}s is overloaded between signed integers and floats.
3663 if (!Op.getValueType().isFloatingPoint()) {
3664 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3665 ? ISD::SMIN : ISD::SMAX;
3666 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3667 Op.getOperand(1), Op.getOperand(2));
3669 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3670 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3671 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3672 Op.getOperand(1), Op.getOperand(2));
3674 case Intrinsic::arm_neon_vtbl1:
3675 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3676 Op.getOperand(1), Op.getOperand(2));
3677 case Intrinsic::arm_neon_vtbl2:
3678 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3679 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3683 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3684 const ARMSubtarget *Subtarget) {
3685 SDLoc dl(Op);
3686 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3687 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3688 if (SSID == SyncScope::SingleThread)
3689 return Op;
3691 if (!Subtarget->hasDataBarrier()) {
3692 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3693 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3694 // here.
3695 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3696 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3697 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3698 DAG.getConstant(0, dl, MVT::i32));
3701 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3702 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3703 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3704 if (Subtarget->isMClass()) {
3705 // Only a full system barrier exists in the M-class architectures.
3706 Domain = ARM_MB::SY;
3707 } else if (Subtarget->preferISHSTBarriers() &&
3708 Ord == AtomicOrdering::Release) {
3709 // Swift happens to implement ISHST barriers in a way that's compatible with
3710 // Release semantics but weaker than ISH so we'd be fools not to use
3711 // it. Beware: other processors probably don't!
3712 Domain = ARM_MB::ISHST;
3715 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3716 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3717 DAG.getConstant(Domain, dl, MVT::i32));
3720 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3721 const ARMSubtarget *Subtarget) {
3722 // ARM pre v5TE and Thumb1 does not have preload instructions.
3723 if (!(Subtarget->isThumb2() ||
3724 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3725 // Just preserve the chain.
3726 return Op.getOperand(0);
3728 SDLoc dl(Op);
3729 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3730 if (!isRead &&
3731 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3732 // ARMv7 with MP extension has PLDW.
3733 return Op.getOperand(0);
3735 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3736 if (Subtarget->isThumb()) {
3737 // Invert the bits.
3738 isRead = ~isRead & 1;
3739 isData = ~isData & 1;
3742 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3743 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3744 DAG.getConstant(isData, dl, MVT::i32));
3747 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3748 MachineFunction &MF = DAG.getMachineFunction();
3749 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3751 // vastart just stores the address of the VarArgsFrameIndex slot into the
3752 // memory location argument.
3753 SDLoc dl(Op);
3754 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3755 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3756 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3757 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3758 MachinePointerInfo(SV));
3761 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3762 CCValAssign &NextVA,
3763 SDValue &Root,
3764 SelectionDAG &DAG,
3765 const SDLoc &dl) const {
3766 MachineFunction &MF = DAG.getMachineFunction();
3767 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3769 const TargetRegisterClass *RC;
3770 if (AFI->isThumb1OnlyFunction())
3771 RC = &ARM::tGPRRegClass;
3772 else
3773 RC = &ARM::GPRRegClass;
3775 // Transform the arguments stored in physical registers into virtual ones.
3776 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3777 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3779 SDValue ArgValue2;
3780 if (NextVA.isMemLoc()) {
3781 MachineFrameInfo &MFI = MF.getFrameInfo();
3782 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3784 // Create load node to retrieve arguments from the stack.
3785 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3786 ArgValue2 = DAG.getLoad(
3787 MVT::i32, dl, Root, FIN,
3788 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3789 } else {
3790 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3791 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3793 if (!Subtarget->isLittle())
3794 std::swap (ArgValue, ArgValue2);
3795 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3798 // The remaining GPRs hold either the beginning of variable-argument
3799 // data, or the beginning of an aggregate passed by value (usually
3800 // byval). Either way, we allocate stack slots adjacent to the data
3801 // provided by our caller, and store the unallocated registers there.
3802 // If this is a variadic function, the va_list pointer will begin with
3803 // these values; otherwise, this reassembles a (byval) structure that
3804 // was split between registers and memory.
3805 // Return: The frame index registers were stored into.
3806 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3807 const SDLoc &dl, SDValue &Chain,
3808 const Value *OrigArg,
3809 unsigned InRegsParamRecordIdx,
3810 int ArgOffset, unsigned ArgSize) const {
3811 // Currently, two use-cases possible:
3812 // Case #1. Non-var-args function, and we meet first byval parameter.
3813 // Setup first unallocated register as first byval register;
3814 // eat all remained registers
3815 // (these two actions are performed by HandleByVal method).
3816 // Then, here, we initialize stack frame with
3817 // "store-reg" instructions.
3818 // Case #2. Var-args function, that doesn't contain byval parameters.
3819 // The same: eat all remained unallocated registers,
3820 // initialize stack frame.
3822 MachineFunction &MF = DAG.getMachineFunction();
3823 MachineFrameInfo &MFI = MF.getFrameInfo();
3824 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3825 unsigned RBegin, REnd;
3826 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3827 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3828 } else {
3829 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3830 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3831 REnd = ARM::R4;
3834 if (REnd != RBegin)
3835 ArgOffset = -4 * (ARM::R4 - RBegin);
3837 auto PtrVT = getPointerTy(DAG.getDataLayout());
3838 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3839 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3841 SmallVector<SDValue, 4> MemOps;
3842 const TargetRegisterClass *RC =
3843 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3845 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3846 unsigned VReg = MF.addLiveIn(Reg, RC);
3847 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3848 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3849 MachinePointerInfo(OrigArg, 4 * i));
3850 MemOps.push_back(Store);
3851 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3854 if (!MemOps.empty())
3855 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3856 return FrameIndex;
3859 // Setup stack frame, the va_list pointer will start from.
3860 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3861 const SDLoc &dl, SDValue &Chain,
3862 unsigned ArgOffset,
3863 unsigned TotalArgRegsSaveSize,
3864 bool ForceMutable) const {
3865 MachineFunction &MF = DAG.getMachineFunction();
3866 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3868 // Try to store any remaining integer argument regs
3869 // to their spots on the stack so that they may be loaded by dereferencing
3870 // the result of va_next.
3871 // If there is no regs to be stored, just point address after last
3872 // argument passed via stack.
3873 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3874 CCInfo.getInRegsParamsCount(),
3875 CCInfo.getNextStackOffset(),
3876 std::max(4U, TotalArgRegsSaveSize));
3877 AFI->setVarArgsFrameIndex(FrameIndex);
3880 SDValue ARMTargetLowering::LowerFormalArguments(
3881 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3882 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3883 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3884 MachineFunction &MF = DAG.getMachineFunction();
3885 MachineFrameInfo &MFI = MF.getFrameInfo();
3887 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3889 // Assign locations to all of the incoming arguments.
3890 SmallVector<CCValAssign, 16> ArgLocs;
3891 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3892 *DAG.getContext());
3893 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3895 SmallVector<SDValue, 16> ArgValues;
3896 SDValue ArgValue;
3897 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3898 unsigned CurArgIdx = 0;
3900 // Initially ArgRegsSaveSize is zero.
3901 // Then we increase this value each time we meet byval parameter.
3902 // We also increase this value in case of varargs function.
3903 AFI->setArgRegsSaveSize(0);
3905 // Calculate the amount of stack space that we need to allocate to store
3906 // byval and variadic arguments that are passed in registers.
3907 // We need to know this before we allocate the first byval or variadic
3908 // argument, as they will be allocated a stack slot below the CFA (Canonical
3909 // Frame Address, the stack pointer at entry to the function).
3910 unsigned ArgRegBegin = ARM::R4;
3911 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3912 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3913 break;
3915 CCValAssign &VA = ArgLocs[i];
3916 unsigned Index = VA.getValNo();
3917 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3918 if (!Flags.isByVal())
3919 continue;
3921 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3922 unsigned RBegin, REnd;
3923 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3924 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3926 CCInfo.nextInRegsParam();
3928 CCInfo.rewindByValRegsInfo();
3930 int lastInsIndex = -1;
3931 if (isVarArg && MFI.hasVAStart()) {
3932 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3933 if (RegIdx != array_lengthof(GPRArgRegs))
3934 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3937 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3938 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3939 auto PtrVT = getPointerTy(DAG.getDataLayout());
3941 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3942 CCValAssign &VA = ArgLocs[i];
3943 if (Ins[VA.getValNo()].isOrigArg()) {
3944 std::advance(CurOrigArg,
3945 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3946 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3948 // Arguments stored in registers.
3949 if (VA.isRegLoc()) {
3950 EVT RegVT = VA.getLocVT();
3952 if (VA.needsCustom()) {
3953 // f64 and vector types are split up into multiple registers or
3954 // combinations of registers and stack slots.
3955 if (VA.getLocVT() == MVT::v2f64) {
3956 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3957 Chain, DAG, dl);
3958 VA = ArgLocs[++i]; // skip ahead to next loc
3959 SDValue ArgValue2;
3960 if (VA.isMemLoc()) {
3961 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3962 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3963 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3964 MachinePointerInfo::getFixedStack(
3965 DAG.getMachineFunction(), FI));
3966 } else {
3967 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3968 Chain, DAG, dl);
3970 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3971 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3972 ArgValue, ArgValue1,
3973 DAG.getIntPtrConstant(0, dl));
3974 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3975 ArgValue, ArgValue2,
3976 DAG.getIntPtrConstant(1, dl));
3977 } else
3978 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3979 } else {
3980 const TargetRegisterClass *RC;
3983 if (RegVT == MVT::f16)
3984 RC = &ARM::HPRRegClass;
3985 else if (RegVT == MVT::f32)
3986 RC = &ARM::SPRRegClass;
3987 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3988 RC = &ARM::DPRRegClass;
3989 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3990 RC = &ARM::QPRRegClass;
3991 else if (RegVT == MVT::i32)
3992 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3993 : &ARM::GPRRegClass;
3994 else
3995 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3997 // Transform the arguments in physical registers into virtual ones.
3998 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3999 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4001 // If this value is passed in r0 and has the returned attribute (e.g.
4002 // C++ 'structors), record this fact for later use.
4003 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4004 AFI->setPreservesR0();
4008 // If this is an 8 or 16-bit value, it is really passed promoted
4009 // to 32 bits. Insert an assert[sz]ext to capture this, then
4010 // truncate to the right size.
4011 switch (VA.getLocInfo()) {
4012 default: llvm_unreachable("Unknown loc info!");
4013 case CCValAssign::Full: break;
4014 case CCValAssign::BCvt:
4015 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4016 break;
4017 case CCValAssign::SExt:
4018 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4019 DAG.getValueType(VA.getValVT()));
4020 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4021 break;
4022 case CCValAssign::ZExt:
4023 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4024 DAG.getValueType(VA.getValVT()));
4025 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4026 break;
4029 InVals.push_back(ArgValue);
4030 } else { // VA.isRegLoc()
4031 // sanity check
4032 assert(VA.isMemLoc());
4033 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4035 int index = VA.getValNo();
4037 // Some Ins[] entries become multiple ArgLoc[] entries.
4038 // Process them only once.
4039 if (index != lastInsIndex)
4041 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4042 // FIXME: For now, all byval parameter objects are marked mutable.
4043 // This can be changed with more analysis.
4044 // In case of tail call optimization mark all arguments mutable.
4045 // Since they could be overwritten by lowering of arguments in case of
4046 // a tail call.
4047 if (Flags.isByVal()) {
4048 assert(Ins[index].isOrigArg() &&
4049 "Byval arguments cannot be implicit");
4050 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4052 int FrameIndex = StoreByValRegs(
4053 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4054 VA.getLocMemOffset(), Flags.getByValSize());
4055 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4056 CCInfo.nextInRegsParam();
4057 } else {
4058 unsigned FIOffset = VA.getLocMemOffset();
4059 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4060 FIOffset, true);
4062 // Create load nodes to retrieve arguments from the stack.
4063 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4064 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4065 MachinePointerInfo::getFixedStack(
4066 DAG.getMachineFunction(), FI)));
4068 lastInsIndex = index;
4073 // varargs
4074 if (isVarArg && MFI.hasVAStart())
4075 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4076 CCInfo.getNextStackOffset(),
4077 TotalArgRegsSaveSize);
4079 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4081 return Chain;
4084 /// isFloatingPointZero - Return true if this is +0.0.
4085 static bool isFloatingPointZero(SDValue Op) {
4086 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4087 return CFP->getValueAPF().isPosZero();
4088 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4089 // Maybe this has already been legalized into the constant pool?
4090 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4091 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4092 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4093 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4094 return CFP->getValueAPF().isPosZero();
4096 } else if (Op->getOpcode() == ISD::BITCAST &&
4097 Op->getValueType(0) == MVT::f64) {
4098 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4099 // created by LowerConstantFP().
4100 SDValue BitcastOp = Op->getOperand(0);
4101 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4102 isNullConstant(BitcastOp->getOperand(0)))
4103 return true;
4105 return false;
4108 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4109 /// the given operands.
4110 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4111 SDValue &ARMcc, SelectionDAG &DAG,
4112 const SDLoc &dl) const {
4113 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4114 unsigned C = RHSC->getZExtValue();
4115 if (!isLegalICmpImmediate((int32_t)C)) {
4116 // Constant does not fit, try adjusting it by one.
4117 switch (CC) {
4118 default: break;
4119 case ISD::SETLT:
4120 case ISD::SETGE:
4121 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4122 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4123 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4125 break;
4126 case ISD::SETULT:
4127 case ISD::SETUGE:
4128 if (C != 0 && isLegalICmpImmediate(C-1)) {
4129 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4130 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4132 break;
4133 case ISD::SETLE:
4134 case ISD::SETGT:
4135 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4136 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4137 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4139 break;
4140 case ISD::SETULE:
4141 case ISD::SETUGT:
4142 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4143 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4144 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4146 break;
4149 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4150 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4151 // In ARM and Thumb-2, the compare instructions can shift their second
4152 // operand.
4153 CC = ISD::getSetCCSwappedOperands(CC);
4154 std::swap(LHS, RHS);
4157 // Thumb1 has very limited immediate modes, so turning an "and" into a
4158 // shift can save multiple instructions.
4160 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4161 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4162 // own. If it's the operand to an unsigned comparison with an immediate,
4163 // we can eliminate one of the shifts: we transform
4164 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4166 // We avoid transforming cases which aren't profitable due to encoding
4167 // details:
4169 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4170 // would not; in that case, we're essentially trading one immediate load for
4171 // another.
4172 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4173 // 3. C2 is zero; we have other code for this special case.
4175 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4176 // instruction, since the AND is always one instruction anyway, but we could
4177 // use narrow instructions in some cases.
4178 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4179 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4180 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4181 !isSignedIntSetCC(CC)) {
4182 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4183 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4184 uint64_t RHSV = RHSC->getZExtValue();
4185 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4186 unsigned ShiftBits = countLeadingZeros(Mask);
4187 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4188 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4189 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4190 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4195 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4196 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4197 // way a cmp would.
4198 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4199 // some tweaks to the heuristics for the previous and->shift transform.
4200 // FIXME: Optimize cases where the LHS isn't a shift.
4201 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4202 isa<ConstantSDNode>(RHS) &&
4203 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4204 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4205 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4206 unsigned ShiftAmt =
4207 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4208 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4209 DAG.getVTList(MVT::i32, MVT::i32),
4210 LHS.getOperand(0),
4211 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4212 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4213 Shift.getValue(1), SDValue());
4214 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4215 return Chain.getValue(1);
4218 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4220 // If the RHS is a constant zero then the V (overflow) flag will never be
4221 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4222 // simpler for other passes (like the peephole optimiser) to deal with.
4223 if (isNullConstant(RHS)) {
4224 switch (CondCode) {
4225 default: break;
4226 case ARMCC::GE:
4227 CondCode = ARMCC::PL;
4228 break;
4229 case ARMCC::LT:
4230 CondCode = ARMCC::MI;
4231 break;
4235 ARMISD::NodeType CompareType;
4236 switch (CondCode) {
4237 default:
4238 CompareType = ARMISD::CMP;
4239 break;
4240 case ARMCC::EQ:
4241 case ARMCC::NE:
4242 // Uses only Z Flag
4243 CompareType = ARMISD::CMPZ;
4244 break;
4246 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4247 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4250 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4251 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4252 SelectionDAG &DAG, const SDLoc &dl,
4253 bool InvalidOnQNaN) const {
4254 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4255 SDValue Cmp;
4256 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
4257 if (!isFloatingPointZero(RHS))
4258 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
4259 else
4260 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
4261 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4264 /// duplicateCmp - Glue values can have only one use, so this function
4265 /// duplicates a comparison node.
4266 SDValue
4267 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4268 unsigned Opc = Cmp.getOpcode();
4269 SDLoc DL(Cmp);
4270 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4271 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4273 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4274 Cmp = Cmp.getOperand(0);
4275 Opc = Cmp.getOpcode();
4276 if (Opc == ARMISD::CMPFP)
4277 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4278 Cmp.getOperand(1), Cmp.getOperand(2));
4279 else {
4280 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4281 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4282 Cmp.getOperand(1));
4284 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4287 // This function returns three things: the arithmetic computation itself
4288 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4289 // comparison and the condition code define the case in which the arithmetic
4290 // computation *does not* overflow.
4291 std::pair<SDValue, SDValue>
4292 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4293 SDValue &ARMcc) const {
4294 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4296 SDValue Value, OverflowCmp;
4297 SDValue LHS = Op.getOperand(0);
4298 SDValue RHS = Op.getOperand(1);
4299 SDLoc dl(Op);
4301 // FIXME: We are currently always generating CMPs because we don't support
4302 // generating CMN through the backend. This is not as good as the natural
4303 // CMP case because it causes a register dependency and cannot be folded
4304 // later.
4306 switch (Op.getOpcode()) {
4307 default:
4308 llvm_unreachable("Unknown overflow instruction!");
4309 case ISD::SADDO:
4310 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4311 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4312 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4313 break;
4314 case ISD::UADDO:
4315 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4316 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4317 // We do not use it in the USUBO case as Value may not be used.
4318 Value = DAG.getNode(ARMISD::ADDC, dl,
4319 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4320 .getValue(0);
4321 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4322 break;
4323 case ISD::SSUBO:
4324 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4325 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4326 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4327 break;
4328 case ISD::USUBO:
4329 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4330 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4331 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4332 break;
4333 case ISD::UMULO:
4334 // We generate a UMUL_LOHI and then check if the high word is 0.
4335 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4336 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4337 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4338 LHS, RHS);
4339 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4340 DAG.getConstant(0, dl, MVT::i32));
4341 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4342 break;
4343 case ISD::SMULO:
4344 // We generate a SMUL_LOHI and then check if all the bits of the high word
4345 // are the same as the sign bit of the low word.
4346 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4347 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4348 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4349 LHS, RHS);
4350 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4351 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4352 Value.getValue(0),
4353 DAG.getConstant(31, dl, MVT::i32)));
4354 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4355 break;
4356 } // switch (...)
4358 return std::make_pair(Value, OverflowCmp);
4361 SDValue
4362 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4363 // Let legalize expand this if it isn't a legal type yet.
4364 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4365 return SDValue();
4367 SDValue Value, OverflowCmp;
4368 SDValue ARMcc;
4369 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4370 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4371 SDLoc dl(Op);
4372 // We use 0 and 1 as false and true values.
4373 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4374 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4375 EVT VT = Op.getValueType();
4377 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4378 ARMcc, CCR, OverflowCmp);
4380 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4381 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4384 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4385 SelectionDAG &DAG) {
4386 SDLoc DL(BoolCarry);
4387 EVT CarryVT = BoolCarry.getValueType();
4389 // This converts the boolean value carry into the carry flag by doing
4390 // ARMISD::SUBC Carry, 1
4391 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4392 DAG.getVTList(CarryVT, MVT::i32),
4393 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4394 return Carry.getValue(1);
4397 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4398 SelectionDAG &DAG) {
4399 SDLoc DL(Flags);
4401 // Now convert the carry flag into a boolean carry. We do this
4402 // using ARMISD:ADDE 0, 0, Carry
4403 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4404 DAG.getConstant(0, DL, MVT::i32),
4405 DAG.getConstant(0, DL, MVT::i32), Flags);
4408 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4409 SelectionDAG &DAG) const {
4410 // Let legalize expand this if it isn't a legal type yet.
4411 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4412 return SDValue();
4414 SDValue LHS = Op.getOperand(0);
4415 SDValue RHS = Op.getOperand(1);
4416 SDLoc dl(Op);
4418 EVT VT = Op.getValueType();
4419 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4420 SDValue Value;
4421 SDValue Overflow;
4422 switch (Op.getOpcode()) {
4423 default:
4424 llvm_unreachable("Unknown overflow instruction!");
4425 case ISD::UADDO:
4426 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4427 // Convert the carry flag into a boolean value.
4428 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4429 break;
4430 case ISD::USUBO: {
4431 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4432 // Convert the carry flag into a boolean value.
4433 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4434 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4435 // value. So compute 1 - C.
4436 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4437 DAG.getConstant(1, dl, MVT::i32), Overflow);
4438 break;
4442 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4445 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4446 SDValue Cond = Op.getOperand(0);
4447 SDValue SelectTrue = Op.getOperand(1);
4448 SDValue SelectFalse = Op.getOperand(2);
4449 SDLoc dl(Op);
4450 unsigned Opc = Cond.getOpcode();
4452 if (Cond.getResNo() == 1 &&
4453 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4454 Opc == ISD::USUBO)) {
4455 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4456 return SDValue();
4458 SDValue Value, OverflowCmp;
4459 SDValue ARMcc;
4460 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4461 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4462 EVT VT = Op.getValueType();
4464 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4465 OverflowCmp, DAG);
4468 // Convert:
4470 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4471 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4473 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4474 const ConstantSDNode *CMOVTrue =
4475 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4476 const ConstantSDNode *CMOVFalse =
4477 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4479 if (CMOVTrue && CMOVFalse) {
4480 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4481 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4483 SDValue True;
4484 SDValue False;
4485 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4486 True = SelectTrue;
4487 False = SelectFalse;
4488 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4489 True = SelectFalse;
4490 False = SelectTrue;
4493 if (True.getNode() && False.getNode()) {
4494 EVT VT = Op.getValueType();
4495 SDValue ARMcc = Cond.getOperand(2);
4496 SDValue CCR = Cond.getOperand(3);
4497 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4498 assert(True.getValueType() == VT);
4499 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4504 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4505 // undefined bits before doing a full-word comparison with zero.
4506 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4507 DAG.getConstant(1, dl, Cond.getValueType()));
4509 return DAG.getSelectCC(dl, Cond,
4510 DAG.getConstant(0, dl, Cond.getValueType()),
4511 SelectTrue, SelectFalse, ISD::SETNE);
4514 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4515 bool &swpCmpOps, bool &swpVselOps) {
4516 // Start by selecting the GE condition code for opcodes that return true for
4517 // 'equality'
4518 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4519 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4520 CondCode = ARMCC::GE;
4522 // and GT for opcodes that return false for 'equality'.
4523 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4524 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4525 CondCode = ARMCC::GT;
4527 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4528 // to swap the compare operands.
4529 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4530 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4531 swpCmpOps = true;
4533 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4534 // If we have an unordered opcode, we need to swap the operands to the VSEL
4535 // instruction (effectively negating the condition).
4537 // This also has the effect of swapping which one of 'less' or 'greater'
4538 // returns true, so we also swap the compare operands. It also switches
4539 // whether we return true for 'equality', so we compensate by picking the
4540 // opposite condition code to our original choice.
4541 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4542 CC == ISD::SETUGT) {
4543 swpCmpOps = !swpCmpOps;
4544 swpVselOps = !swpVselOps;
4545 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4548 // 'ordered' is 'anything but unordered', so use the VS condition code and
4549 // swap the VSEL operands.
4550 if (CC == ISD::SETO) {
4551 CondCode = ARMCC::VS;
4552 swpVselOps = true;
4555 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4556 // code and swap the VSEL operands. Also do this if we don't care about the
4557 // unordered case.
4558 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4559 CondCode = ARMCC::EQ;
4560 swpVselOps = true;
4564 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4565 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4566 SDValue Cmp, SelectionDAG &DAG) const {
4567 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4568 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4569 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4570 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4571 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4573 SDValue TrueLow = TrueVal.getValue(0);
4574 SDValue TrueHigh = TrueVal.getValue(1);
4575 SDValue FalseLow = FalseVal.getValue(0);
4576 SDValue FalseHigh = FalseVal.getValue(1);
4578 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4579 ARMcc, CCR, Cmp);
4580 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4581 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4583 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4584 } else {
4585 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4586 Cmp);
4590 static bool isGTorGE(ISD::CondCode CC) {
4591 return CC == ISD::SETGT || CC == ISD::SETGE;
4594 static bool isLTorLE(ISD::CondCode CC) {
4595 return CC == ISD::SETLT || CC == ISD::SETLE;
4598 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4599 // All of these conditions (and their <= and >= counterparts) will do:
4600 // x < k ? k : x
4601 // x > k ? x : k
4602 // k < x ? x : k
4603 // k > x ? k : x
4604 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4605 const SDValue TrueVal, const SDValue FalseVal,
4606 const ISD::CondCode CC, const SDValue K) {
4607 return (isGTorGE(CC) &&
4608 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4609 (isLTorLE(CC) &&
4610 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4613 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4614 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4615 const SDValue TrueVal, const SDValue FalseVal,
4616 const ISD::CondCode CC, const SDValue K) {
4617 return (isGTorGE(CC) &&
4618 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4619 (isLTorLE(CC) &&
4620 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4623 // Check if two chained conditionals could be converted into SSAT or USAT.
4625 // SSAT can replace a set of two conditional selectors that bound a number to an
4626 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4628 // x < -k ? -k : (x > k ? k : x)
4629 // x < -k ? -k : (x < k ? x : k)
4630 // x > -k ? (x > k ? k : x) : -k
4631 // x < k ? (x < -k ? -k : x) : k
4632 // etc.
4634 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4635 // a power of 2.
4637 // It returns true if the conversion can be done, false otherwise.
4638 // Additionally, the variable is returned in parameter V, the constant in K and
4639 // usat is set to true if the conditional represents an unsigned saturation
4640 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4641 uint64_t &K, bool &usat) {
4642 SDValue LHS1 = Op.getOperand(0);
4643 SDValue RHS1 = Op.getOperand(1);
4644 SDValue TrueVal1 = Op.getOperand(2);
4645 SDValue FalseVal1 = Op.getOperand(3);
4646 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4648 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4649 if (Op2.getOpcode() != ISD::SELECT_CC)
4650 return false;
4652 SDValue LHS2 = Op2.getOperand(0);
4653 SDValue RHS2 = Op2.getOperand(1);
4654 SDValue TrueVal2 = Op2.getOperand(2);
4655 SDValue FalseVal2 = Op2.getOperand(3);
4656 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4658 // Find out which are the constants and which are the variables
4659 // in each conditional
4660 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4661 ? &RHS1
4662 : nullptr;
4663 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4664 ? &RHS2
4665 : nullptr;
4666 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4667 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4668 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4669 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4671 // We must detect cases where the original operations worked with 16- or
4672 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4673 // must work with sign-extended values but the select operations return
4674 // the original non-extended value.
4675 SDValue V2TmpReg = V2Tmp;
4676 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4677 V2TmpReg = V2Tmp->getOperand(0);
4679 // Check that the registers and the constants have the correct values
4680 // in both conditionals
4681 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4682 V2TmpReg != V2)
4683 return false;
4685 // Figure out which conditional is saturating the lower/upper bound.
4686 const SDValue *LowerCheckOp =
4687 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4688 ? &Op
4689 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4690 ? &Op2
4691 : nullptr;
4692 const SDValue *UpperCheckOp =
4693 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4694 ? &Op
4695 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4696 ? &Op2
4697 : nullptr;
4699 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4700 return false;
4702 // Check that the constant in the lower-bound check is
4703 // the opposite of the constant in the upper-bound check
4704 // in 1's complement.
4705 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4706 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4707 int64_t PosVal = std::max(Val1, Val2);
4708 int64_t NegVal = std::min(Val1, Val2);
4710 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4711 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4712 isPowerOf2_64(PosVal + 1)) {
4714 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4715 if (Val1 == ~Val2)
4716 usat = false;
4717 else if (NegVal == 0)
4718 usat = true;
4719 else
4720 return false;
4722 V = V2;
4723 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4725 return true;
4728 return false;
4731 // Check if a condition of the type x < k ? k : x can be converted into a
4732 // bit operation instead of conditional moves.
4733 // Currently this is allowed given:
4734 // - The conditions and values match up
4735 // - k is 0 or -1 (all ones)
4736 // This function will not check the last condition, thats up to the caller
4737 // It returns true if the transformation can be made, and in such case
4738 // returns x in V, and k in SatK.
4739 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4740 SDValue &SatK)
4742 SDValue LHS = Op.getOperand(0);
4743 SDValue RHS = Op.getOperand(1);
4744 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4745 SDValue TrueVal = Op.getOperand(2);
4746 SDValue FalseVal = Op.getOperand(3);
4748 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4749 ? &RHS
4750 : nullptr;
4752 // No constant operation in comparison, early out
4753 if (!K)
4754 return false;
4756 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4757 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4758 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4760 // If the constant on left and right side, or variable on left and right,
4761 // does not match, early out
4762 if (*K != KTmp || V != VTmp)
4763 return false;
4765 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4766 SatK = *K;
4767 return true;
4770 return false;
4773 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4774 if (VT == MVT::f32)
4775 return !Subtarget->hasVFP2Base();
4776 if (VT == MVT::f64)
4777 return !Subtarget->hasFP64();
4778 if (VT == MVT::f16)
4779 return !Subtarget->hasFullFP16();
4780 return false;
4783 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4784 EVT VT = Op.getValueType();
4785 SDLoc dl(Op);
4787 // Try to convert two saturating conditional selects into a single SSAT
4788 SDValue SatValue;
4789 uint64_t SatConstant;
4790 bool SatUSat;
4791 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4792 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4793 if (SatUSat)
4794 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4795 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4796 else
4797 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4798 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4801 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4802 // into more efficient bit operations, which is possible when k is 0 or -1
4803 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4804 // single instructions. On Thumb the shift and the bit operation will be two
4805 // instructions.
4806 // Only allow this transformation on full-width (32-bit) operations
4807 SDValue LowerSatConstant;
4808 if (VT == MVT::i32 &&
4809 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4810 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4811 DAG.getConstant(31, dl, VT));
4812 if (isNullConstant(LowerSatConstant)) {
4813 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4814 DAG.getAllOnesConstant(dl, VT));
4815 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4816 } else if (isAllOnesConstant(LowerSatConstant))
4817 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4820 SDValue LHS = Op.getOperand(0);
4821 SDValue RHS = Op.getOperand(1);
4822 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4823 SDValue TrueVal = Op.getOperand(2);
4824 SDValue FalseVal = Op.getOperand(3);
4825 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
4826 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
4828 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
4829 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
4830 unsigned TVal = CTVal->getZExtValue();
4831 unsigned FVal = CFVal->getZExtValue();
4832 unsigned Opcode = 0;
4834 if (TVal == ~FVal) {
4835 Opcode = ARMISD::CSINV;
4836 } else if (TVal == ~FVal + 1) {
4837 Opcode = ARMISD::CSNEG;
4838 } else if (TVal + 1 == FVal) {
4839 Opcode = ARMISD::CSINC;
4840 } else if (TVal == FVal + 1) {
4841 Opcode = ARMISD::CSINC;
4842 std::swap(TrueVal, FalseVal);
4843 std::swap(TVal, FVal);
4844 CC = ISD::getSetCCInverse(CC, true);
4847 if (Opcode) {
4848 // If one of the constants is cheaper than another, materialise the
4849 // cheaper one and let the csel generate the other.
4850 if (Opcode != ARMISD::CSINC &&
4851 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
4852 std::swap(TrueVal, FalseVal);
4853 std::swap(TVal, FVal);
4854 CC = ISD::getSetCCInverse(CC, true);
4857 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
4858 // to get there. CSINC not is invertable like the other two (~(~a) == a,
4859 // -(-a) == a, but (a+1)+1 != a).
4860 if (FVal == 0 && Opcode != ARMISD::CSINC) {
4861 std::swap(TrueVal, FalseVal);
4862 std::swap(TVal, FVal);
4863 CC = ISD::getSetCCInverse(CC, true);
4865 if (TVal == 0)
4866 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
4868 // Drops F's value because we can get it by inverting/negating TVal.
4869 FalseVal = TrueVal;
4871 SDValue ARMcc;
4872 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4873 EVT VT = TrueVal.getValueType();
4874 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
4878 if (isUnsupportedFloatingType(LHS.getValueType())) {
4879 DAG.getTargetLoweringInfo().softenSetCCOperands(
4880 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
4882 // If softenSetCCOperands only returned one value, we should compare it to
4883 // zero.
4884 if (!RHS.getNode()) {
4885 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4886 CC = ISD::SETNE;
4890 if (LHS.getValueType() == MVT::i32) {
4891 // Try to generate VSEL on ARMv8.
4892 // The VSEL instruction can't use all the usual ARM condition
4893 // codes: it only has two bits to select the condition code, so it's
4894 // constrained to use only GE, GT, VS and EQ.
4896 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4897 // swap the operands of the previous compare instruction (effectively
4898 // inverting the compare condition, swapping 'less' and 'greater') and
4899 // sometimes need to swap the operands to the VSEL (which inverts the
4900 // condition in the sense of firing whenever the previous condition didn't)
4901 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4902 TrueVal.getValueType() == MVT::f32 ||
4903 TrueVal.getValueType() == MVT::f64)) {
4904 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4905 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4906 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4907 CC = ISD::getSetCCInverse(CC, true);
4908 std::swap(TrueVal, FalseVal);
4912 SDValue ARMcc;
4913 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4914 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4915 // Choose GE over PL, which vsel does now support
4916 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4917 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4918 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4921 ARMCC::CondCodes CondCode, CondCode2;
4922 bool InvalidOnQNaN;
4923 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4925 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4926 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4927 // must use VSEL (limited condition codes), due to not having conditional f16
4928 // moves.
4929 if (Subtarget->hasFPARMv8Base() &&
4930 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4931 (TrueVal.getValueType() == MVT::f16 ||
4932 TrueVal.getValueType() == MVT::f32 ||
4933 TrueVal.getValueType() == MVT::f64)) {
4934 bool swpCmpOps = false;
4935 bool swpVselOps = false;
4936 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4938 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4939 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4940 if (swpCmpOps)
4941 std::swap(LHS, RHS);
4942 if (swpVselOps)
4943 std::swap(TrueVal, FalseVal);
4947 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4948 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4949 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4950 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4951 if (CondCode2 != ARMCC::AL) {
4952 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4953 // FIXME: Needs another CMP because flag can have but one use.
4954 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4955 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4957 return Result;
4960 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4961 /// to morph to an integer compare sequence.
4962 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4963 const ARMSubtarget *Subtarget) {
4964 SDNode *N = Op.getNode();
4965 if (!N->hasOneUse())
4966 // Otherwise it requires moving the value from fp to integer registers.
4967 return false;
4968 if (!N->getNumValues())
4969 return false;
4970 EVT VT = Op.getValueType();
4971 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4972 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4973 // vmrs are very slow, e.g. cortex-a8.
4974 return false;
4976 if (isFloatingPointZero(Op)) {
4977 SeenZero = true;
4978 return true;
4980 return ISD::isNormalLoad(N);
4983 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4984 if (isFloatingPointZero(Op))
4985 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4987 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4988 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4989 Ld->getPointerInfo(), Ld->getAlignment(),
4990 Ld->getMemOperand()->getFlags());
4992 llvm_unreachable("Unknown VFP cmp argument!");
4995 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4996 SDValue &RetVal1, SDValue &RetVal2) {
4997 SDLoc dl(Op);
4999 if (isFloatingPointZero(Op)) {
5000 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5001 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5002 return;
5005 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5006 SDValue Ptr = Ld->getBasePtr();
5007 RetVal1 =
5008 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5009 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5011 EVT PtrType = Ptr.getValueType();
5012 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5013 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5014 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5015 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5016 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5017 Ld->getMemOperand()->getFlags());
5018 return;
5021 llvm_unreachable("Unknown VFP cmp argument!");
5024 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5025 /// f32 and even f64 comparisons to integer ones.
5026 SDValue
5027 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5028 SDValue Chain = Op.getOperand(0);
5029 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5030 SDValue LHS = Op.getOperand(2);
5031 SDValue RHS = Op.getOperand(3);
5032 SDValue Dest = Op.getOperand(4);
5033 SDLoc dl(Op);
5035 bool LHSSeenZero = false;
5036 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5037 bool RHSSeenZero = false;
5038 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5039 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5040 // If unsafe fp math optimization is enabled and there are no other uses of
5041 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5042 // to an integer comparison.
5043 if (CC == ISD::SETOEQ)
5044 CC = ISD::SETEQ;
5045 else if (CC == ISD::SETUNE)
5046 CC = ISD::SETNE;
5048 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5049 SDValue ARMcc;
5050 if (LHS.getValueType() == MVT::f32) {
5051 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5052 bitcastf32Toi32(LHS, DAG), Mask);
5053 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5054 bitcastf32Toi32(RHS, DAG), Mask);
5055 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5056 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5057 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5058 Chain, Dest, ARMcc, CCR, Cmp);
5061 SDValue LHS1, LHS2;
5062 SDValue RHS1, RHS2;
5063 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5064 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5065 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5066 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5067 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5068 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5069 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5070 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5071 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5074 return SDValue();
5077 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5078 SDValue Chain = Op.getOperand(0);
5079 SDValue Cond = Op.getOperand(1);
5080 SDValue Dest = Op.getOperand(2);
5081 SDLoc dl(Op);
5083 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5084 // instruction.
5085 unsigned Opc = Cond.getOpcode();
5086 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5087 !Subtarget->isThumb1Only();
5088 if (Cond.getResNo() == 1 &&
5089 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5090 Opc == ISD::USUBO || OptimizeMul)) {
5091 // Only lower legal XALUO ops.
5092 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5093 return SDValue();
5095 // The actual operation with overflow check.
5096 SDValue Value, OverflowCmp;
5097 SDValue ARMcc;
5098 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5100 // Reverse the condition code.
5101 ARMCC::CondCodes CondCode =
5102 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5103 CondCode = ARMCC::getOppositeCondition(CondCode);
5104 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5105 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5107 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5108 OverflowCmp);
5111 return SDValue();
5114 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5115 SDValue Chain = Op.getOperand(0);
5116 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5117 SDValue LHS = Op.getOperand(2);
5118 SDValue RHS = Op.getOperand(3);
5119 SDValue Dest = Op.getOperand(4);
5120 SDLoc dl(Op);
5122 if (isUnsupportedFloatingType(LHS.getValueType())) {
5123 DAG.getTargetLoweringInfo().softenSetCCOperands(
5124 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5126 // If softenSetCCOperands only returned one value, we should compare it to
5127 // zero.
5128 if (!RHS.getNode()) {
5129 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5130 CC = ISD::SETNE;
5134 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5135 // instruction.
5136 unsigned Opc = LHS.getOpcode();
5137 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5138 !Subtarget->isThumb1Only();
5139 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5140 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5141 Opc == ISD::USUBO || OptimizeMul) &&
5142 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5143 // Only lower legal XALUO ops.
5144 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5145 return SDValue();
5147 // The actual operation with overflow check.
5148 SDValue Value, OverflowCmp;
5149 SDValue ARMcc;
5150 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5152 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5153 // Reverse the condition code.
5154 ARMCC::CondCodes CondCode =
5155 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5156 CondCode = ARMCC::getOppositeCondition(CondCode);
5157 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5159 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5161 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5162 OverflowCmp);
5165 if (LHS.getValueType() == MVT::i32) {
5166 SDValue ARMcc;
5167 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5168 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5169 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5170 Chain, Dest, ARMcc, CCR, Cmp);
5173 if (getTargetMachine().Options.UnsafeFPMath &&
5174 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5175 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5176 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5177 return Result;
5180 ARMCC::CondCodes CondCode, CondCode2;
5181 bool InvalidOnQNaN;
5182 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
5184 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5185 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
5186 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5187 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5188 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5189 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5190 if (CondCode2 != ARMCC::AL) {
5191 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5192 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5193 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5195 return Res;
5198 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5199 SDValue Chain = Op.getOperand(0);
5200 SDValue Table = Op.getOperand(1);
5201 SDValue Index = Op.getOperand(2);
5202 SDLoc dl(Op);
5204 EVT PTy = getPointerTy(DAG.getDataLayout());
5205 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5206 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5207 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5208 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5209 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5210 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5211 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5212 // which does another jump to the destination. This also makes it easier
5213 // to translate it to TBB / TBH later (Thumb2 only).
5214 // FIXME: This might not work if the function is extremely large.
5215 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5216 Addr, Op.getOperand(2), JTI);
5218 if (isPositionIndependent() || Subtarget->isROPI()) {
5219 Addr =
5220 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5221 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5222 Chain = Addr.getValue(1);
5223 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5224 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5225 } else {
5226 Addr =
5227 DAG.getLoad(PTy, dl, Chain, Addr,
5228 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5229 Chain = Addr.getValue(1);
5230 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5234 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5235 EVT VT = Op.getValueType();
5236 SDLoc dl(Op);
5238 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5239 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5240 return Op;
5241 return DAG.UnrollVectorOp(Op.getNode());
5244 const bool HasFullFP16 =
5245 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5247 EVT NewTy;
5248 const EVT OpTy = Op.getOperand(0).getValueType();
5249 if (OpTy == MVT::v4f32)
5250 NewTy = MVT::v4i32;
5251 else if (OpTy == MVT::v4f16 && HasFullFP16)
5252 NewTy = MVT::v4i16;
5253 else if (OpTy == MVT::v8f16 && HasFullFP16)
5254 NewTy = MVT::v8i16;
5255 else
5256 llvm_unreachable("Invalid type for custom lowering!");
5258 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5259 return DAG.UnrollVectorOp(Op.getNode());
5261 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5262 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5265 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5266 EVT VT = Op.getValueType();
5267 if (VT.isVector())
5268 return LowerVectorFP_TO_INT(Op, DAG);
5269 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5270 RTLIB::Libcall LC;
5271 if (Op.getOpcode() == ISD::FP_TO_SINT)
5272 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5273 Op.getValueType());
5274 else
5275 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5276 Op.getValueType());
5277 MakeLibCallOptions CallOptions;
5278 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5279 CallOptions, SDLoc(Op)).first;
5282 return Op;
5285 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5286 EVT VT = Op.getValueType();
5287 SDLoc dl(Op);
5289 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5290 if (VT.getVectorElementType() == MVT::f32)
5291 return Op;
5292 return DAG.UnrollVectorOp(Op.getNode());
5295 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5296 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5297 "Invalid type for custom lowering!");
5299 const bool HasFullFP16 =
5300 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5302 EVT DestVecType;
5303 if (VT == MVT::v4f32)
5304 DestVecType = MVT::v4i32;
5305 else if (VT == MVT::v4f16 && HasFullFP16)
5306 DestVecType = MVT::v4i16;
5307 else if (VT == MVT::v8f16 && HasFullFP16)
5308 DestVecType = MVT::v8i16;
5309 else
5310 return DAG.UnrollVectorOp(Op.getNode());
5312 unsigned CastOpc;
5313 unsigned Opc;
5314 switch (Op.getOpcode()) {
5315 default: llvm_unreachable("Invalid opcode!");
5316 case ISD::SINT_TO_FP:
5317 CastOpc = ISD::SIGN_EXTEND;
5318 Opc = ISD::SINT_TO_FP;
5319 break;
5320 case ISD::UINT_TO_FP:
5321 CastOpc = ISD::ZERO_EXTEND;
5322 Opc = ISD::UINT_TO_FP;
5323 break;
5326 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5327 return DAG.getNode(Opc, dl, VT, Op);
5330 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5331 EVT VT = Op.getValueType();
5332 if (VT.isVector())
5333 return LowerVectorINT_TO_FP(Op, DAG);
5334 if (isUnsupportedFloatingType(VT)) {
5335 RTLIB::Libcall LC;
5336 if (Op.getOpcode() == ISD::SINT_TO_FP)
5337 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5338 Op.getValueType());
5339 else
5340 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5341 Op.getValueType());
5342 MakeLibCallOptions CallOptions;
5343 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5344 CallOptions, SDLoc(Op)).first;
5347 return Op;
5350 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5351 // Implement fcopysign with a fabs and a conditional fneg.
5352 SDValue Tmp0 = Op.getOperand(0);
5353 SDValue Tmp1 = Op.getOperand(1);
5354 SDLoc dl(Op);
5355 EVT VT = Op.getValueType();
5356 EVT SrcVT = Tmp1.getValueType();
5357 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5358 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5359 bool UseNEON = !InGPR && Subtarget->hasNEON();
5361 if (UseNEON) {
5362 // Use VBSL to copy the sign bit.
5363 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5364 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5365 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5366 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5367 if (VT == MVT::f64)
5368 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5369 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5370 DAG.getConstant(32, dl, MVT::i32));
5371 else /*if (VT == MVT::f32)*/
5372 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5373 if (SrcVT == MVT::f32) {
5374 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5375 if (VT == MVT::f64)
5376 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5377 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5378 DAG.getConstant(32, dl, MVT::i32));
5379 } else if (VT == MVT::f32)
5380 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5381 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5382 DAG.getConstant(32, dl, MVT::i32));
5383 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5384 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5386 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5387 dl, MVT::i32);
5388 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5389 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5390 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5392 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5393 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5394 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5395 if (VT == MVT::f32) {
5396 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5397 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5398 DAG.getConstant(0, dl, MVT::i32));
5399 } else {
5400 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5403 return Res;
5406 // Bitcast operand 1 to i32.
5407 if (SrcVT == MVT::f64)
5408 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5409 Tmp1).getValue(1);
5410 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5412 // Or in the signbit with integer operations.
5413 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5414 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5415 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5416 if (VT == MVT::f32) {
5417 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5418 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5419 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5420 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5423 // f64: Or the high part with signbit and then combine two parts.
5424 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5425 Tmp0);
5426 SDValue Lo = Tmp0.getValue(0);
5427 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5428 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5429 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5432 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5433 MachineFunction &MF = DAG.getMachineFunction();
5434 MachineFrameInfo &MFI = MF.getFrameInfo();
5435 MFI.setReturnAddressIsTaken(true);
5437 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5438 return SDValue();
5440 EVT VT = Op.getValueType();
5441 SDLoc dl(Op);
5442 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5443 if (Depth) {
5444 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5445 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5446 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5447 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5448 MachinePointerInfo());
5451 // Return LR, which contains the return address. Mark it an implicit live-in.
5452 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5453 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5456 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5457 const ARMBaseRegisterInfo &ARI =
5458 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5459 MachineFunction &MF = DAG.getMachineFunction();
5460 MachineFrameInfo &MFI = MF.getFrameInfo();
5461 MFI.setFrameAddressIsTaken(true);
5463 EVT VT = Op.getValueType();
5464 SDLoc dl(Op); // FIXME probably not meaningful
5465 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5466 Register FrameReg = ARI.getFrameRegister(MF);
5467 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5468 while (Depth--)
5469 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5470 MachinePointerInfo());
5471 return FrameAddr;
5474 // FIXME? Maybe this could be a TableGen attribute on some registers and
5475 // this table could be generated automatically from RegInfo.
5476 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5477 SelectionDAG &DAG) const {
5478 unsigned Reg = StringSwitch<unsigned>(RegName)
5479 .Case("sp", ARM::SP)
5480 .Default(0);
5481 if (Reg)
5482 return Reg;
5483 report_fatal_error(Twine("Invalid register name \""
5484 + StringRef(RegName) + "\"."));
5487 // Result is 64 bit value so split into two 32 bit values and return as a
5488 // pair of values.
5489 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5490 SelectionDAG &DAG) {
5491 SDLoc DL(N);
5493 // This function is only supposed to be called for i64 type destination.
5494 assert(N->getValueType(0) == MVT::i64
5495 && "ExpandREAD_REGISTER called for non-i64 type result.");
5497 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5498 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5499 N->getOperand(0),
5500 N->getOperand(1));
5502 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5503 Read.getValue(1)));
5504 Results.push_back(Read.getOperand(0));
5507 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5508 /// When \p DstVT, the destination type of \p BC, is on the vector
5509 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5510 /// it might be possible to combine them, such that everything stays on the
5511 /// vector register bank.
5512 /// \p return The node that would replace \p BT, if the combine
5513 /// is possible.
5514 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5515 SelectionDAG &DAG) {
5516 SDValue Op = BC->getOperand(0);
5517 EVT DstVT = BC->getValueType(0);
5519 // The only vector instruction that can produce a scalar (remember,
5520 // since the bitcast was about to be turned into VMOVDRR, the source
5521 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5522 // Moreover, we can do this combine only if there is one use.
5523 // Finally, if the destination type is not a vector, there is not
5524 // much point on forcing everything on the vector bank.
5525 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5526 !Op.hasOneUse())
5527 return SDValue();
5529 // If the index is not constant, we will introduce an additional
5530 // multiply that will stick.
5531 // Give up in that case.
5532 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5533 if (!Index)
5534 return SDValue();
5535 unsigned DstNumElt = DstVT.getVectorNumElements();
5537 // Compute the new index.
5538 const APInt &APIntIndex = Index->getAPIntValue();
5539 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5540 NewIndex *= APIntIndex;
5541 // Check if the new constant index fits into i32.
5542 if (NewIndex.getBitWidth() > 32)
5543 return SDValue();
5545 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5546 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5547 SDLoc dl(Op);
5548 SDValue ExtractSrc = Op.getOperand(0);
5549 EVT VecVT = EVT::getVectorVT(
5550 *DAG.getContext(), DstVT.getScalarType(),
5551 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5552 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5553 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5554 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5557 /// ExpandBITCAST - If the target supports VFP, this function is called to
5558 /// expand a bit convert where either the source or destination type is i64 to
5559 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5560 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5561 /// vectors), since the legalizer won't know what to do with that.
5562 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5563 const ARMSubtarget *Subtarget) {
5564 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5565 SDLoc dl(N);
5566 SDValue Op = N->getOperand(0);
5568 // This function is only supposed to be called for i64 types, either as the
5569 // source or destination of the bit convert.
5570 EVT SrcVT = Op.getValueType();
5571 EVT DstVT = N->getValueType(0);
5572 const bool HasFullFP16 = Subtarget->hasFullFP16();
5574 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5575 // FullFP16: half values are passed in S-registers, and we don't
5576 // need any of the bitcast and moves:
5578 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5579 // t5: i32 = bitcast t2
5580 // t18: f16 = ARMISD::VMOVhr t5
5581 if (Op.getOpcode() != ISD::CopyFromReg ||
5582 Op.getValueType() != MVT::f32)
5583 return SDValue();
5585 auto Move = N->use_begin();
5586 if (Move->getOpcode() != ARMISD::VMOVhr)
5587 return SDValue();
5589 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5590 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5591 DAG.ReplaceAllUsesWith(*Move, &Copy);
5592 return Copy;
5595 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5596 if (!HasFullFP16)
5597 return SDValue();
5598 // SoftFP: read half-precision arguments:
5600 // t2: i32,ch = ...
5601 // t7: i16 = truncate t2 <~~~~ Op
5602 // t8: f16 = bitcast t7 <~~~~ N
5604 if (Op.getOperand(0).getValueType() == MVT::i32)
5605 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5606 MVT::f16, Op.getOperand(0));
5608 return SDValue();
5611 // Half-precision return values
5612 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5613 if (!HasFullFP16)
5614 return SDValue();
5616 // t11: f16 = fadd t8, t10
5617 // t12: i16 = bitcast t11 <~~~ SDNode N
5618 // t13: i32 = zero_extend t12
5619 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5620 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5622 // transform this into:
5624 // t20: i32 = ARMISD::VMOVrh t11
5625 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5627 auto ZeroExtend = N->use_begin();
5628 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5629 ZeroExtend->getValueType(0) != MVT::i32)
5630 return SDValue();
5632 auto Copy = ZeroExtend->use_begin();
5633 if (Copy->getOpcode() == ISD::CopyToReg &&
5634 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5635 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5636 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5637 return Cvt;
5639 return SDValue();
5642 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5643 return SDValue();
5645 // Turn i64->f64 into VMOVDRR.
5646 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5647 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5648 // if we can combine the bitcast with its source.
5649 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5650 return Val;
5652 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5653 DAG.getConstant(0, dl, MVT::i32));
5654 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5655 DAG.getConstant(1, dl, MVT::i32));
5656 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5657 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5660 // Turn f64->i64 into VMOVRRD.
5661 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5662 SDValue Cvt;
5663 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5664 SrcVT.getVectorNumElements() > 1)
5665 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5666 DAG.getVTList(MVT::i32, MVT::i32),
5667 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5668 else
5669 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5670 DAG.getVTList(MVT::i32, MVT::i32), Op);
5671 // Merge the pieces into a single i64 value.
5672 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5675 return SDValue();
5678 /// getZeroVector - Returns a vector of specified type with all zero elements.
5679 /// Zero vectors are used to represent vector negation and in those cases
5680 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5681 /// not support i64 elements, so sometimes the zero vectors will need to be
5682 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5683 /// zero vector.
5684 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5685 assert(VT.isVector() && "Expected a vector type");
5686 // The canonical modified immediate encoding of a zero vector is....0!
5687 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5688 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5689 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5690 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5693 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5694 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5695 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5696 SelectionDAG &DAG) const {
5697 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5698 EVT VT = Op.getValueType();
5699 unsigned VTBits = VT.getSizeInBits();
5700 SDLoc dl(Op);
5701 SDValue ShOpLo = Op.getOperand(0);
5702 SDValue ShOpHi = Op.getOperand(1);
5703 SDValue ShAmt = Op.getOperand(2);
5704 SDValue ARMcc;
5705 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5706 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5708 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5710 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5711 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5712 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5713 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5714 DAG.getConstant(VTBits, dl, MVT::i32));
5715 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5716 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5717 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5718 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5719 ISD::SETGE, ARMcc, DAG, dl);
5720 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5721 ARMcc, CCR, CmpLo);
5723 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5724 SDValue HiBigShift = Opc == ISD::SRA
5725 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5726 DAG.getConstant(VTBits - 1, dl, VT))
5727 : DAG.getConstant(0, dl, VT);
5728 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5729 ISD::SETGE, ARMcc, DAG, dl);
5730 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5731 ARMcc, CCR, CmpHi);
5733 SDValue Ops[2] = { Lo, Hi };
5734 return DAG.getMergeValues(Ops, dl);
5737 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5738 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5739 SDValue ARMTargetLowering::LowerShiftLeftParts(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);
5751 assert(Op.getOpcode() == ISD::SHL_PARTS);
5752 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5753 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5754 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5755 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5756 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5758 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5759 DAG.getConstant(VTBits, dl, MVT::i32));
5760 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5761 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5762 ISD::SETGE, ARMcc, DAG, dl);
5763 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5764 ARMcc, CCR, CmpHi);
5766 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5767 ISD::SETGE, ARMcc, DAG, dl);
5768 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5769 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5770 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5772 SDValue Ops[2] = { Lo, Hi };
5773 return DAG.getMergeValues(Ops, dl);
5776 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5777 SelectionDAG &DAG) const {
5778 // The rounding mode is in bits 23:22 of the FPSCR.
5779 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5780 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5781 // so that the shift + and get folded into a bitfield extract.
5782 SDLoc dl(Op);
5783 SDValue Ops[] = { DAG.getEntryNode(),
5784 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5786 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5787 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5788 DAG.getConstant(1U << 22, dl, MVT::i32));
5789 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5790 DAG.getConstant(22, dl, MVT::i32));
5791 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5792 DAG.getConstant(3, dl, MVT::i32));
5795 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5796 const ARMSubtarget *ST) {
5797 SDLoc dl(N);
5798 EVT VT = N->getValueType(0);
5799 if (VT.isVector()) {
5800 assert(ST->hasNEON());
5802 // Compute the least significant set bit: LSB = X & -X
5803 SDValue X = N->getOperand(0);
5804 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5805 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5807 EVT ElemTy = VT.getVectorElementType();
5809 if (ElemTy == MVT::i8) {
5810 // Compute with: cttz(x) = ctpop(lsb - 1)
5811 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5812 DAG.getTargetConstant(1, dl, ElemTy));
5813 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5814 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5817 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5818 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5819 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5820 unsigned NumBits = ElemTy.getSizeInBits();
5821 SDValue WidthMinus1 =
5822 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5823 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5824 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5825 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5828 // Compute with: cttz(x) = ctpop(lsb - 1)
5830 // Compute LSB - 1.
5831 SDValue Bits;
5832 if (ElemTy == MVT::i64) {
5833 // Load constant 0xffff'ffff'ffff'ffff to register.
5834 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5835 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5836 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5837 } else {
5838 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5839 DAG.getTargetConstant(1, dl, ElemTy));
5840 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5842 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5845 if (!ST->hasV6T2Ops())
5846 return SDValue();
5848 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5849 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5852 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5853 const ARMSubtarget *ST) {
5854 EVT VT = N->getValueType(0);
5855 SDLoc DL(N);
5857 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5858 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5859 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5860 "Unexpected type for custom ctpop lowering");
5862 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5863 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5864 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5865 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5867 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5868 unsigned EltSize = 8;
5869 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5870 while (EltSize != VT.getScalarSizeInBits()) {
5871 SmallVector<SDValue, 8> Ops;
5872 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5873 TLI.getPointerTy(DAG.getDataLayout())));
5874 Ops.push_back(Res);
5876 EltSize *= 2;
5877 NumElts /= 2;
5878 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5879 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5882 return Res;
5885 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5886 /// operand of a vector shift operation, where all the elements of the
5887 /// build_vector must have the same constant integer value.
5888 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5889 // Ignore bit_converts.
5890 while (Op.getOpcode() == ISD::BITCAST)
5891 Op = Op.getOperand(0);
5892 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5893 APInt SplatBits, SplatUndef;
5894 unsigned SplatBitSize;
5895 bool HasAnyUndefs;
5896 if (!BVN ||
5897 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5898 ElementBits) ||
5899 SplatBitSize > ElementBits)
5900 return false;
5901 Cnt = SplatBits.getSExtValue();
5902 return true;
5905 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5906 /// operand of a vector shift left operation. That value must be in the range:
5907 /// 0 <= Value < ElementBits for a left shift; or
5908 /// 0 <= Value <= ElementBits for a long left shift.
5909 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5910 assert(VT.isVector() && "vector shift count is not a vector type");
5911 int64_t ElementBits = VT.getScalarSizeInBits();
5912 if (!getVShiftImm(Op, ElementBits, Cnt))
5913 return false;
5914 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5917 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5918 /// operand of a vector shift right operation. For a shift opcode, the value
5919 /// is positive, but for an intrinsic the value count must be negative. The
5920 /// absolute value must be in the range:
5921 /// 1 <= |Value| <= ElementBits for a right shift; or
5922 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5923 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5924 int64_t &Cnt) {
5925 assert(VT.isVector() && "vector shift count is not a vector type");
5926 int64_t ElementBits = VT.getScalarSizeInBits();
5927 if (!getVShiftImm(Op, ElementBits, Cnt))
5928 return false;
5929 if (!isIntrinsic)
5930 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5931 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5932 Cnt = -Cnt;
5933 return true;
5935 return false;
5938 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5939 const ARMSubtarget *ST) {
5940 EVT VT = N->getValueType(0);
5941 SDLoc dl(N);
5942 int64_t Cnt;
5944 if (!VT.isVector())
5945 return SDValue();
5947 // We essentially have two forms here. Shift by an immediate and shift by a
5948 // vector register (there are also shift by a gpr, but that is just handled
5949 // with a tablegen pattern). We cannot easily match shift by an immediate in
5950 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5951 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5952 // signed or unsigned, and a negative shift indicates a shift right).
5953 if (N->getOpcode() == ISD::SHL) {
5954 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5955 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5956 DAG.getConstant(Cnt, dl, MVT::i32));
5957 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
5958 N->getOperand(1));
5961 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
5962 "unexpected vector shift opcode");
5964 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
5965 unsigned VShiftOpc =
5966 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
5967 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
5968 DAG.getConstant(Cnt, dl, MVT::i32));
5971 // Other right shifts we don't have operations for (we use a shift left by a
5972 // negative number).
5973 EVT ShiftVT = N->getOperand(1).getValueType();
5974 SDValue NegatedCount = DAG.getNode(
5975 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
5976 unsigned VShiftOpc =
5977 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
5978 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
5981 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5982 const ARMSubtarget *ST) {
5983 EVT VT = N->getValueType(0);
5984 SDLoc dl(N);
5986 // We can get here for a node like i32 = ISD::SHL i32, i64
5987 if (VT != MVT::i64)
5988 return SDValue();
5990 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
5991 N->getOpcode() == ISD::SHL) &&
5992 "Unknown shift to lower!");
5994 unsigned ShOpc = N->getOpcode();
5995 if (ST->hasMVEIntegerOps()) {
5996 SDValue ShAmt = N->getOperand(1);
5997 unsigned ShPartsOpc = ARMISD::LSLL;
5998 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6000 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6001 // then do the default optimisation
6002 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6003 (Con && Con->getZExtValue() >= 32))
6004 return SDValue();
6006 // Extract the lower 32 bits of the shift amount if it's not an i32
6007 if (ShAmt->getValueType(0) != MVT::i32)
6008 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6010 if (ShOpc == ISD::SRL) {
6011 if (!Con)
6012 // There is no t2LSRLr instruction so negate and perform an lsll if the
6013 // shift amount is in a register, emulating a right shift.
6014 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6015 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6016 else
6017 // Else generate an lsrl on the immediate shift amount
6018 ShPartsOpc = ARMISD::LSRL;
6019 } else if (ShOpc == ISD::SRA)
6020 ShPartsOpc = ARMISD::ASRL;
6022 // Lower 32 bits of the destination/source
6023 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6024 DAG.getConstant(0, dl, MVT::i32));
6025 // Upper 32 bits of the destination/source
6026 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6027 DAG.getConstant(1, dl, MVT::i32));
6029 // Generate the shift operation as computed above
6030 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6031 ShAmt);
6032 // The upper 32 bits come from the second return value of lsll
6033 Hi = SDValue(Lo.getNode(), 1);
6034 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6037 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6038 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6039 return SDValue();
6041 // If we are in thumb mode, we don't have RRX.
6042 if (ST->isThumb1Only())
6043 return SDValue();
6045 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6046 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6047 DAG.getConstant(0, dl, MVT::i32));
6048 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6049 DAG.getConstant(1, dl, MVT::i32));
6051 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6052 // captures the result into a carry flag.
6053 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6054 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6056 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6057 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6059 // Merge the pieces into a single i64 value.
6060 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6063 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6064 const ARMSubtarget *ST) {
6065 bool Invert = false;
6066 bool Swap = false;
6067 unsigned Opc = ARMCC::AL;
6069 SDValue Op0 = Op.getOperand(0);
6070 SDValue Op1 = Op.getOperand(1);
6071 SDValue CC = Op.getOperand(2);
6072 EVT VT = Op.getValueType();
6073 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6074 SDLoc dl(Op);
6076 EVT CmpVT;
6077 if (ST->hasNEON())
6078 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6079 else {
6080 assert(ST->hasMVEIntegerOps() &&
6081 "No hardware support for integer vector comparison!");
6083 if (Op.getValueType().getVectorElementType() != MVT::i1)
6084 return SDValue();
6086 // Make sure we expand floating point setcc to scalar if we do not have
6087 // mve.fp, so that we can handle them from there.
6088 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6089 return SDValue();
6091 CmpVT = VT;
6094 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6095 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6096 // Special-case integer 64-bit equality comparisons. They aren't legal,
6097 // but they can be lowered with a few vector instructions.
6098 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6099 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6100 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6101 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6102 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6103 DAG.getCondCode(ISD::SETEQ));
6104 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6105 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6106 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6107 if (SetCCOpcode == ISD::SETNE)
6108 Merged = DAG.getNOT(dl, Merged, CmpVT);
6109 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6110 return Merged;
6113 if (CmpVT.getVectorElementType() == MVT::i64)
6114 // 64-bit comparisons are not legal in general.
6115 return SDValue();
6117 if (Op1.getValueType().isFloatingPoint()) {
6118 switch (SetCCOpcode) {
6119 default: llvm_unreachable("Illegal FP comparison");
6120 case ISD::SETUNE:
6121 case ISD::SETNE:
6122 if (ST->hasMVEFloatOps()) {
6123 Opc = ARMCC::NE; break;
6124 } else {
6125 Invert = true; LLVM_FALLTHROUGH;
6127 case ISD::SETOEQ:
6128 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6129 case ISD::SETOLT:
6130 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6131 case ISD::SETOGT:
6132 case ISD::SETGT: Opc = ARMCC::GT; break;
6133 case ISD::SETOLE:
6134 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6135 case ISD::SETOGE:
6136 case ISD::SETGE: Opc = ARMCC::GE; break;
6137 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6138 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6139 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6140 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6141 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6142 case ISD::SETONE: {
6143 // Expand this to (OLT | OGT).
6144 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6145 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6146 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6147 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6148 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6149 if (Invert)
6150 Result = DAG.getNOT(dl, Result, VT);
6151 return Result;
6153 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6154 case ISD::SETO: {
6155 // Expand this to (OLT | OGE).
6156 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6157 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6158 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6159 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6160 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6161 if (Invert)
6162 Result = DAG.getNOT(dl, Result, VT);
6163 return Result;
6166 } else {
6167 // Integer comparisons.
6168 switch (SetCCOpcode) {
6169 default: llvm_unreachable("Illegal integer comparison");
6170 case ISD::SETNE:
6171 if (ST->hasMVEIntegerOps()) {
6172 Opc = ARMCC::NE; break;
6173 } else {
6174 Invert = true; LLVM_FALLTHROUGH;
6176 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6177 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6178 case ISD::SETGT: Opc = ARMCC::GT; break;
6179 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6180 case ISD::SETGE: Opc = ARMCC::GE; break;
6181 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6182 case ISD::SETUGT: Opc = ARMCC::HI; break;
6183 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6184 case ISD::SETUGE: Opc = ARMCC::HS; break;
6187 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6188 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6189 SDValue AndOp;
6190 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6191 AndOp = Op0;
6192 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6193 AndOp = Op1;
6195 // Ignore bitconvert.
6196 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6197 AndOp = AndOp.getOperand(0);
6199 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6200 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6201 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6202 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6203 if (!Invert)
6204 Result = DAG.getNOT(dl, Result, VT);
6205 return Result;
6210 if (Swap)
6211 std::swap(Op0, Op1);
6213 // If one of the operands is a constant vector zero, attempt to fold the
6214 // comparison to a specialized compare-against-zero form.
6215 SDValue SingleOp;
6216 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6217 SingleOp = Op0;
6218 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6219 if (Opc == ARMCC::GE)
6220 Opc = ARMCC::LE;
6221 else if (Opc == ARMCC::GT)
6222 Opc = ARMCC::LT;
6223 SingleOp = Op1;
6226 SDValue Result;
6227 if (SingleOp.getNode()) {
6228 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6229 DAG.getConstant(Opc, dl, MVT::i32));
6230 } else {
6231 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6232 DAG.getConstant(Opc, dl, MVT::i32));
6235 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6237 if (Invert)
6238 Result = DAG.getNOT(dl, Result, VT);
6240 return Result;
6243 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6244 SDValue LHS = Op.getOperand(0);
6245 SDValue RHS = Op.getOperand(1);
6246 SDValue Carry = Op.getOperand(2);
6247 SDValue Cond = Op.getOperand(3);
6248 SDLoc DL(Op);
6250 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6252 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6253 // have to invert the carry first.
6254 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6255 DAG.getConstant(1, DL, MVT::i32), Carry);
6256 // This converts the boolean value carry into the carry flag.
6257 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6259 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6260 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6262 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6263 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6264 SDValue ARMcc = DAG.getConstant(
6265 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6266 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6267 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6268 Cmp.getValue(1), SDValue());
6269 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6270 CCR, Chain.getValue(1));
6273 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6274 /// valid vector constant for a NEON or MVE instruction with a "modified
6275 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6276 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6277 unsigned SplatBitSize, SelectionDAG &DAG,
6278 const SDLoc &dl, EVT &VT, bool is128Bits,
6279 VMOVModImmType type) {
6280 unsigned OpCmode, Imm;
6282 // SplatBitSize is set to the smallest size that splats the vector, so a
6283 // zero vector will always have SplatBitSize == 8. However, NEON modified
6284 // immediate instructions others than VMOV do not support the 8-bit encoding
6285 // of a zero vector, and the default encoding of zero is supposed to be the
6286 // 32-bit version.
6287 if (SplatBits == 0)
6288 SplatBitSize = 32;
6290 switch (SplatBitSize) {
6291 case 8:
6292 if (type != VMOVModImm)
6293 return SDValue();
6294 // Any 1-byte value is OK. Op=0, Cmode=1110.
6295 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6296 OpCmode = 0xe;
6297 Imm = SplatBits;
6298 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6299 break;
6301 case 16:
6302 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6303 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6304 if ((SplatBits & ~0xff) == 0) {
6305 // Value = 0x00nn: Op=x, Cmode=100x.
6306 OpCmode = 0x8;
6307 Imm = SplatBits;
6308 break;
6310 if ((SplatBits & ~0xff00) == 0) {
6311 // Value = 0xnn00: Op=x, Cmode=101x.
6312 OpCmode = 0xa;
6313 Imm = SplatBits >> 8;
6314 break;
6316 return SDValue();
6318 case 32:
6319 // NEON's 32-bit VMOV supports splat values where:
6320 // * only one byte is nonzero, or
6321 // * the least significant byte is 0xff and the second byte is nonzero, or
6322 // * the least significant 2 bytes are 0xff and the third is nonzero.
6323 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6324 if ((SplatBits & ~0xff) == 0) {
6325 // Value = 0x000000nn: Op=x, Cmode=000x.
6326 OpCmode = 0;
6327 Imm = SplatBits;
6328 break;
6330 if ((SplatBits & ~0xff00) == 0) {
6331 // Value = 0x0000nn00: Op=x, Cmode=001x.
6332 OpCmode = 0x2;
6333 Imm = SplatBits >> 8;
6334 break;
6336 if ((SplatBits & ~0xff0000) == 0) {
6337 // Value = 0x00nn0000: Op=x, Cmode=010x.
6338 OpCmode = 0x4;
6339 Imm = SplatBits >> 16;
6340 break;
6342 if ((SplatBits & ~0xff000000) == 0) {
6343 // Value = 0xnn000000: Op=x, Cmode=011x.
6344 OpCmode = 0x6;
6345 Imm = SplatBits >> 24;
6346 break;
6349 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6350 if (type == OtherModImm) return SDValue();
6352 if ((SplatBits & ~0xffff) == 0 &&
6353 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6354 // Value = 0x0000nnff: Op=x, Cmode=1100.
6355 OpCmode = 0xc;
6356 Imm = SplatBits >> 8;
6357 break;
6360 // cmode == 0b1101 is not supported for MVE VMVN
6361 if (type == MVEVMVNModImm)
6362 return SDValue();
6364 if ((SplatBits & ~0xffffff) == 0 &&
6365 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6366 // Value = 0x00nnffff: Op=x, Cmode=1101.
6367 OpCmode = 0xd;
6368 Imm = SplatBits >> 16;
6369 break;
6372 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6373 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6374 // VMOV.I32. A (very) minor optimization would be to replicate the value
6375 // and fall through here to test for a valid 64-bit splat. But, then the
6376 // caller would also need to check and handle the change in size.
6377 return SDValue();
6379 case 64: {
6380 if (type != VMOVModImm)
6381 return SDValue();
6382 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6383 uint64_t BitMask = 0xff;
6384 uint64_t Val = 0;
6385 unsigned ImmMask = 1;
6386 Imm = 0;
6387 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6388 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6389 Val |= BitMask;
6390 Imm |= ImmMask;
6391 } else if ((SplatBits & BitMask) != 0) {
6392 return SDValue();
6394 BitMask <<= 8;
6395 ImmMask <<= 1;
6398 if (DAG.getDataLayout().isBigEndian())
6399 // swap higher and lower 32 bit word
6400 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6402 // Op=1, Cmode=1110.
6403 OpCmode = 0x1e;
6404 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6405 break;
6408 default:
6409 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6412 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6413 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6416 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6417 const ARMSubtarget *ST) const {
6418 EVT VT = Op.getValueType();
6419 bool IsDouble = (VT == MVT::f64);
6420 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6421 const APFloat &FPVal = CFP->getValueAPF();
6423 // Prevent floating-point constants from using literal loads
6424 // when execute-only is enabled.
6425 if (ST->genExecuteOnly()) {
6426 // If we can represent the constant as an immediate, don't lower it
6427 if (isFPImmLegal(FPVal, VT))
6428 return Op;
6429 // Otherwise, construct as integer, and move to float register
6430 APInt INTVal = FPVal.bitcastToAPInt();
6431 SDLoc DL(CFP);
6432 switch (VT.getSimpleVT().SimpleTy) {
6433 default:
6434 llvm_unreachable("Unknown floating point type!");
6435 break;
6436 case MVT::f64: {
6437 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6438 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6439 if (!ST->isLittle())
6440 std::swap(Lo, Hi);
6441 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6443 case MVT::f32:
6444 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6445 DAG.getConstant(INTVal, DL, MVT::i32));
6449 if (!ST->hasVFP3Base())
6450 return SDValue();
6452 // Use the default (constant pool) lowering for double constants when we have
6453 // an SP-only FPU
6454 if (IsDouble && !Subtarget->hasFP64())
6455 return SDValue();
6457 // Try splatting with a VMOV.f32...
6458 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6460 if (ImmVal != -1) {
6461 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6462 // We have code in place to select a valid ConstantFP already, no need to
6463 // do any mangling.
6464 return Op;
6467 // It's a float and we are trying to use NEON operations where
6468 // possible. Lower it to a splat followed by an extract.
6469 SDLoc DL(Op);
6470 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6471 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6472 NewVal);
6473 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6474 DAG.getConstant(0, DL, MVT::i32));
6477 // The rest of our options are NEON only, make sure that's allowed before
6478 // proceeding..
6479 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6480 return SDValue();
6482 EVT VMovVT;
6483 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6485 // It wouldn't really be worth bothering for doubles except for one very
6486 // important value, which does happen to match: 0.0. So make sure we don't do
6487 // anything stupid.
6488 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6489 return SDValue();
6491 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6492 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6493 VMovVT, false, VMOVModImm);
6494 if (NewVal != SDValue()) {
6495 SDLoc DL(Op);
6496 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6497 NewVal);
6498 if (IsDouble)
6499 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6501 // It's a float: cast and extract a vector element.
6502 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6503 VecConstant);
6504 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6505 DAG.getConstant(0, DL, MVT::i32));
6508 // Finally, try a VMVN.i32
6509 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6510 false, VMVNModImm);
6511 if (NewVal != SDValue()) {
6512 SDLoc DL(Op);
6513 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6515 if (IsDouble)
6516 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6518 // It's a float: cast and extract a vector element.
6519 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6520 VecConstant);
6521 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6522 DAG.getConstant(0, DL, MVT::i32));
6525 return SDValue();
6528 // check if an VEXT instruction can handle the shuffle mask when the
6529 // vector sources of the shuffle are the same.
6530 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6531 unsigned NumElts = VT.getVectorNumElements();
6533 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6534 if (M[0] < 0)
6535 return false;
6537 Imm = M[0];
6539 // If this is a VEXT shuffle, the immediate value is the index of the first
6540 // element. The other shuffle indices must be the successive elements after
6541 // the first one.
6542 unsigned ExpectedElt = Imm;
6543 for (unsigned i = 1; i < NumElts; ++i) {
6544 // Increment the expected index. If it wraps around, just follow it
6545 // back to index zero and keep going.
6546 ++ExpectedElt;
6547 if (ExpectedElt == NumElts)
6548 ExpectedElt = 0;
6550 if (M[i] < 0) continue; // ignore UNDEF indices
6551 if (ExpectedElt != static_cast<unsigned>(M[i]))
6552 return false;
6555 return true;
6558 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6559 bool &ReverseVEXT, unsigned &Imm) {
6560 unsigned NumElts = VT.getVectorNumElements();
6561 ReverseVEXT = false;
6563 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6564 if (M[0] < 0)
6565 return false;
6567 Imm = M[0];
6569 // If this is a VEXT shuffle, the immediate value is the index of the first
6570 // element. The other shuffle indices must be the successive elements after
6571 // the first one.
6572 unsigned ExpectedElt = Imm;
6573 for (unsigned i = 1; i < NumElts; ++i) {
6574 // Increment the expected index. If it wraps around, it may still be
6575 // a VEXT but the source vectors must be swapped.
6576 ExpectedElt += 1;
6577 if (ExpectedElt == NumElts * 2) {
6578 ExpectedElt = 0;
6579 ReverseVEXT = true;
6582 if (M[i] < 0) continue; // ignore UNDEF indices
6583 if (ExpectedElt != static_cast<unsigned>(M[i]))
6584 return false;
6587 // Adjust the index value if the source operands will be swapped.
6588 if (ReverseVEXT)
6589 Imm -= NumElts;
6591 return true;
6594 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6595 /// instruction with the specified blocksize. (The order of the elements
6596 /// within each block of the vector is reversed.)
6597 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6598 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6599 "Only possible block sizes for VREV are: 16, 32, 64");
6601 unsigned EltSz = VT.getScalarSizeInBits();
6602 if (EltSz == 64)
6603 return false;
6605 unsigned NumElts = VT.getVectorNumElements();
6606 unsigned BlockElts = M[0] + 1;
6607 // If the first shuffle index is UNDEF, be optimistic.
6608 if (M[0] < 0)
6609 BlockElts = BlockSize / EltSz;
6611 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6612 return false;
6614 for (unsigned i = 0; i < NumElts; ++i) {
6615 if (M[i] < 0) continue; // ignore UNDEF indices
6616 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6617 return false;
6620 return true;
6623 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6624 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6625 // range, then 0 is placed into the resulting vector. So pretty much any mask
6626 // of 8 elements can work here.
6627 return VT == MVT::v8i8 && M.size() == 8;
6630 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6631 unsigned Index) {
6632 if (Mask.size() == Elements * 2)
6633 return Index / Elements;
6634 return Mask[Index] == 0 ? 0 : 1;
6637 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6638 // checking that pairs of elements in the shuffle mask represent the same index
6639 // in each vector, incrementing the expected index by 2 at each step.
6640 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6641 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6642 // v2={e,f,g,h}
6643 // WhichResult gives the offset for each element in the mask based on which
6644 // of the two results it belongs to.
6646 // The transpose can be represented either as:
6647 // result1 = shufflevector v1, v2, result1_shuffle_mask
6648 // result2 = shufflevector v1, v2, result2_shuffle_mask
6649 // where v1/v2 and the shuffle masks have the same number of elements
6650 // (here WhichResult (see below) indicates which result is being checked)
6652 // or as:
6653 // results = shufflevector v1, v2, shuffle_mask
6654 // where both results are returned in one vector and the shuffle mask has twice
6655 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6656 // want to check the low half and high half of the shuffle mask as if it were
6657 // the other case
6658 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6659 unsigned EltSz = VT.getScalarSizeInBits();
6660 if (EltSz == 64)
6661 return false;
6663 unsigned NumElts = VT.getVectorNumElements();
6664 if (M.size() != NumElts && M.size() != NumElts*2)
6665 return false;
6667 // If the mask is twice as long as the input vector then we need to check the
6668 // upper and lower parts of the mask with a matching value for WhichResult
6669 // FIXME: A mask with only even values will be rejected in case the first
6670 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6671 // M[0] is used to determine WhichResult
6672 for (unsigned i = 0; i < M.size(); i += NumElts) {
6673 WhichResult = SelectPairHalf(NumElts, M, i);
6674 for (unsigned j = 0; j < NumElts; j += 2) {
6675 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6676 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6677 return false;
6681 if (M.size() == NumElts*2)
6682 WhichResult = 0;
6684 return true;
6687 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6688 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6689 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6690 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6691 unsigned EltSz = VT.getScalarSizeInBits();
6692 if (EltSz == 64)
6693 return false;
6695 unsigned NumElts = VT.getVectorNumElements();
6696 if (M.size() != NumElts && M.size() != NumElts*2)
6697 return false;
6699 for (unsigned i = 0; i < M.size(); i += NumElts) {
6700 WhichResult = SelectPairHalf(NumElts, M, i);
6701 for (unsigned j = 0; j < NumElts; j += 2) {
6702 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6703 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6704 return false;
6708 if (M.size() == NumElts*2)
6709 WhichResult = 0;
6711 return true;
6714 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6715 // that the mask elements are either all even and in steps of size 2 or all odd
6716 // and in steps of size 2.
6717 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6718 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6719 // v2={e,f,g,h}
6720 // Requires similar checks to that of isVTRNMask with
6721 // respect the how results are returned.
6722 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6723 unsigned EltSz = VT.getScalarSizeInBits();
6724 if (EltSz == 64)
6725 return false;
6727 unsigned NumElts = VT.getVectorNumElements();
6728 if (M.size() != NumElts && M.size() != NumElts*2)
6729 return false;
6731 for (unsigned i = 0; i < M.size(); i += NumElts) {
6732 WhichResult = SelectPairHalf(NumElts, M, i);
6733 for (unsigned j = 0; j < NumElts; ++j) {
6734 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6735 return false;
6739 if (M.size() == NumElts*2)
6740 WhichResult = 0;
6742 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6743 if (VT.is64BitVector() && EltSz == 32)
6744 return false;
6746 return true;
6749 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6750 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6751 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6752 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6753 unsigned EltSz = VT.getScalarSizeInBits();
6754 if (EltSz == 64)
6755 return false;
6757 unsigned NumElts = VT.getVectorNumElements();
6758 if (M.size() != NumElts && M.size() != NumElts*2)
6759 return false;
6761 unsigned Half = NumElts / 2;
6762 for (unsigned i = 0; i < M.size(); i += NumElts) {
6763 WhichResult = SelectPairHalf(NumElts, M, i);
6764 for (unsigned j = 0; j < NumElts; j += Half) {
6765 unsigned Idx = WhichResult;
6766 for (unsigned k = 0; k < Half; ++k) {
6767 int MIdx = M[i + j + k];
6768 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6769 return false;
6770 Idx += 2;
6775 if (M.size() == NumElts*2)
6776 WhichResult = 0;
6778 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6779 if (VT.is64BitVector() && EltSz == 32)
6780 return false;
6782 return true;
6785 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6786 // that pairs of elements of the shufflemask represent the same index in each
6787 // vector incrementing sequentially through the vectors.
6788 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6789 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6790 // v2={e,f,g,h}
6791 // Requires similar checks to that of isVTRNMask with respect the how results
6792 // are returned.
6793 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6794 unsigned EltSz = VT.getScalarSizeInBits();
6795 if (EltSz == 64)
6796 return false;
6798 unsigned NumElts = VT.getVectorNumElements();
6799 if (M.size() != NumElts && M.size() != NumElts*2)
6800 return false;
6802 for (unsigned i = 0; i < M.size(); i += NumElts) {
6803 WhichResult = SelectPairHalf(NumElts, M, i);
6804 unsigned Idx = WhichResult * NumElts / 2;
6805 for (unsigned j = 0; j < NumElts; j += 2) {
6806 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6807 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6808 return false;
6809 Idx += 1;
6813 if (M.size() == NumElts*2)
6814 WhichResult = 0;
6816 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6817 if (VT.is64BitVector() && EltSz == 32)
6818 return false;
6820 return true;
6823 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6824 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6825 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6826 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6827 unsigned EltSz = VT.getScalarSizeInBits();
6828 if (EltSz == 64)
6829 return false;
6831 unsigned NumElts = VT.getVectorNumElements();
6832 if (M.size() != NumElts && M.size() != NumElts*2)
6833 return false;
6835 for (unsigned i = 0; i < M.size(); i += NumElts) {
6836 WhichResult = SelectPairHalf(NumElts, M, i);
6837 unsigned Idx = WhichResult * NumElts / 2;
6838 for (unsigned j = 0; j < NumElts; j += 2) {
6839 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6840 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6841 return false;
6842 Idx += 1;
6846 if (M.size() == NumElts*2)
6847 WhichResult = 0;
6849 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6850 if (VT.is64BitVector() && EltSz == 32)
6851 return false;
6853 return true;
6856 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6857 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6858 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6859 unsigned &WhichResult,
6860 bool &isV_UNDEF) {
6861 isV_UNDEF = false;
6862 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6863 return ARMISD::VTRN;
6864 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6865 return ARMISD::VUZP;
6866 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6867 return ARMISD::VZIP;
6869 isV_UNDEF = true;
6870 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6871 return ARMISD::VTRN;
6872 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6873 return ARMISD::VUZP;
6874 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6875 return ARMISD::VZIP;
6877 return 0;
6880 /// \return true if this is a reverse operation on an vector.
6881 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6882 unsigned NumElts = VT.getVectorNumElements();
6883 // Make sure the mask has the right size.
6884 if (NumElts != M.size())
6885 return false;
6887 // Look for <15, ..., 3, -1, 1, 0>.
6888 for (unsigned i = 0; i != NumElts; ++i)
6889 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6890 return false;
6892 return true;
6895 // If N is an integer constant that can be moved into a register in one
6896 // instruction, return an SDValue of such a constant (will become a MOV
6897 // instruction). Otherwise return null.
6898 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6899 const ARMSubtarget *ST, const SDLoc &dl) {
6900 uint64_t Val;
6901 if (!isa<ConstantSDNode>(N))
6902 return SDValue();
6903 Val = cast<ConstantSDNode>(N)->getZExtValue();
6905 if (ST->isThumb1Only()) {
6906 if (Val <= 255 || ~Val <= 255)
6907 return DAG.getConstant(Val, dl, MVT::i32);
6908 } else {
6909 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6910 return DAG.getConstant(Val, dl, MVT::i32);
6912 return SDValue();
6915 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6916 const ARMSubtarget *ST) {
6917 SDLoc dl(Op);
6918 EVT VT = Op.getValueType();
6920 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6922 unsigned NumElts = VT.getVectorNumElements();
6923 unsigned BoolMask;
6924 unsigned BitsPerBool;
6925 if (NumElts == 4) {
6926 BitsPerBool = 4;
6927 BoolMask = 0xf;
6928 } else if (NumElts == 8) {
6929 BitsPerBool = 2;
6930 BoolMask = 0x3;
6931 } else if (NumElts == 16) {
6932 BitsPerBool = 1;
6933 BoolMask = 0x1;
6934 } else
6935 return SDValue();
6937 // First create base with bits set where known
6938 unsigned Bits32 = 0;
6939 for (unsigned i = 0; i < NumElts; ++i) {
6940 SDValue V = Op.getOperand(i);
6941 if (!isa<ConstantSDNode>(V) && !V.isUndef())
6942 continue;
6943 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
6944 if (BitSet)
6945 Bits32 |= BoolMask << (i * BitsPerBool);
6948 // Add in unknown nodes
6949 // FIXME: Handle splats of the same value better.
6950 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
6951 DAG.getConstant(Bits32, dl, MVT::i32));
6952 for (unsigned i = 0; i < NumElts; ++i) {
6953 SDValue V = Op.getOperand(i);
6954 if (isa<ConstantSDNode>(V) || V.isUndef())
6955 continue;
6956 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
6957 DAG.getConstant(i, dl, MVT::i32));
6960 return Base;
6963 // If this is a case we can't handle, return null and let the default
6964 // expansion code take care of it.
6965 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6966 const ARMSubtarget *ST) const {
6967 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6968 SDLoc dl(Op);
6969 EVT VT = Op.getValueType();
6971 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
6972 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
6974 APInt SplatBits, SplatUndef;
6975 unsigned SplatBitSize;
6976 bool HasAnyUndefs;
6977 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6978 if (SplatUndef.isAllOnesValue())
6979 return DAG.getUNDEF(VT);
6981 if ((ST->hasNEON() && SplatBitSize <= 64) ||
6982 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
6983 // Check if an immediate VMOV works.
6984 EVT VmovVT;
6985 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
6986 SplatUndef.getZExtValue(), SplatBitSize,
6987 DAG, dl, VmovVT, VT.is128BitVector(),
6988 VMOVModImm);
6990 if (Val.getNode()) {
6991 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6992 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6995 // Try an immediate VMVN.
6996 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6997 Val = isVMOVModifiedImm(
6998 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
6999 DAG, dl, VmovVT, VT.is128BitVector(),
7000 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7001 if (Val.getNode()) {
7002 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7003 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7006 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7007 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7008 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7009 if (ImmVal != -1) {
7010 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7011 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7017 // Scan through the operands to see if only one value is used.
7019 // As an optimisation, even if more than one value is used it may be more
7020 // profitable to splat with one value then change some lanes.
7022 // Heuristically we decide to do this if the vector has a "dominant" value,
7023 // defined as splatted to more than half of the lanes.
7024 unsigned NumElts = VT.getVectorNumElements();
7025 bool isOnlyLowElement = true;
7026 bool usesOnlyOneValue = true;
7027 bool hasDominantValue = false;
7028 bool isConstant = true;
7030 // Map of the number of times a particular SDValue appears in the
7031 // element list.
7032 DenseMap<SDValue, unsigned> ValueCounts;
7033 SDValue Value;
7034 for (unsigned i = 0; i < NumElts; ++i) {
7035 SDValue V = Op.getOperand(i);
7036 if (V.isUndef())
7037 continue;
7038 if (i > 0)
7039 isOnlyLowElement = false;
7040 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7041 isConstant = false;
7043 ValueCounts.insert(std::make_pair(V, 0));
7044 unsigned &Count = ValueCounts[V];
7046 // Is this value dominant? (takes up more than half of the lanes)
7047 if (++Count > (NumElts / 2)) {
7048 hasDominantValue = true;
7049 Value = V;
7052 if (ValueCounts.size() != 1)
7053 usesOnlyOneValue = false;
7054 if (!Value.getNode() && !ValueCounts.empty())
7055 Value = ValueCounts.begin()->first;
7057 if (ValueCounts.empty())
7058 return DAG.getUNDEF(VT);
7060 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7061 // Keep going if we are hitting this case.
7062 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7063 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7065 unsigned EltSize = VT.getScalarSizeInBits();
7067 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7068 // i32 and try again.
7069 if (hasDominantValue && EltSize <= 32) {
7070 if (!isConstant) {
7071 SDValue N;
7073 // If we are VDUPing a value that comes directly from a vector, that will
7074 // cause an unnecessary move to and from a GPR, where instead we could
7075 // just use VDUPLANE. We can only do this if the lane being extracted
7076 // is at a constant index, as the VDUP from lane instructions only have
7077 // constant-index forms.
7078 ConstantSDNode *constIndex;
7079 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7080 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7081 // We need to create a new undef vector to use for the VDUPLANE if the
7082 // size of the vector from which we get the value is different than the
7083 // size of the vector that we need to create. We will insert the element
7084 // such that the register coalescer will remove unnecessary copies.
7085 if (VT != Value->getOperand(0).getValueType()) {
7086 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7087 VT.getVectorNumElements();
7088 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7089 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7090 Value, DAG.getConstant(index, dl, MVT::i32)),
7091 DAG.getConstant(index, dl, MVT::i32));
7092 } else
7093 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7094 Value->getOperand(0), Value->getOperand(1));
7095 } else
7096 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7098 if (!usesOnlyOneValue) {
7099 // The dominant value was splatted as 'N', but we now have to insert
7100 // all differing elements.
7101 for (unsigned I = 0; I < NumElts; ++I) {
7102 if (Op.getOperand(I) == Value)
7103 continue;
7104 SmallVector<SDValue, 3> Ops;
7105 Ops.push_back(N);
7106 Ops.push_back(Op.getOperand(I));
7107 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7108 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7111 return N;
7113 if (VT.getVectorElementType().isFloatingPoint()) {
7114 SmallVector<SDValue, 8> Ops;
7115 MVT FVT = VT.getVectorElementType().getSimpleVT();
7116 assert(FVT == MVT::f32 || FVT == MVT::f16);
7117 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7118 for (unsigned i = 0; i < NumElts; ++i)
7119 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7120 Op.getOperand(i)));
7121 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7122 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7123 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7124 if (Val.getNode())
7125 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7127 if (usesOnlyOneValue) {
7128 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7129 if (isConstant && Val.getNode())
7130 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7134 // If all elements are constants and the case above didn't get hit, fall back
7135 // to the default expansion, which will generate a load from the constant
7136 // pool.
7137 if (isConstant)
7138 return SDValue();
7140 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7141 if (NumElts >= 4) {
7142 SDValue shuffle = ReconstructShuffle(Op, DAG);
7143 if (shuffle != SDValue())
7144 return shuffle;
7147 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7148 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7149 // into two 64-bit vectors; we might discover a better way to lower it.
7150 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7151 EVT ExtVT = VT.getVectorElementType();
7152 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7153 SDValue Lower =
7154 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7155 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7156 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7157 SDValue Upper = DAG.getBuildVector(
7158 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7159 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7160 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7161 if (Lower && Upper)
7162 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7165 // Vectors with 32- or 64-bit elements can be built by directly assigning
7166 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7167 // will be legalized.
7168 if (EltSize >= 32) {
7169 // Do the expansion with floating-point types, since that is what the VFP
7170 // registers are defined to use, and since i64 is not legal.
7171 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7172 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7173 SmallVector<SDValue, 8> Ops;
7174 for (unsigned i = 0; i < NumElts; ++i)
7175 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7176 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7177 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7180 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7181 // know the default expansion would otherwise fall back on something even
7182 // worse. For a vector with one or two non-undef values, that's
7183 // scalar_to_vector for the elements followed by a shuffle (provided the
7184 // shuffle is valid for the target) and materialization element by element
7185 // on the stack followed by a load for everything else.
7186 if (!isConstant && !usesOnlyOneValue) {
7187 SDValue Vec = DAG.getUNDEF(VT);
7188 for (unsigned i = 0 ; i < NumElts; ++i) {
7189 SDValue V = Op.getOperand(i);
7190 if (V.isUndef())
7191 continue;
7192 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7193 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7195 return Vec;
7198 return SDValue();
7201 // Gather data to see if the operation can be modelled as a
7202 // shuffle in combination with VEXTs.
7203 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7204 SelectionDAG &DAG) const {
7205 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7206 SDLoc dl(Op);
7207 EVT VT = Op.getValueType();
7208 unsigned NumElts = VT.getVectorNumElements();
7210 struct ShuffleSourceInfo {
7211 SDValue Vec;
7212 unsigned MinElt = std::numeric_limits<unsigned>::max();
7213 unsigned MaxElt = 0;
7215 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7216 // be compatible with the shuffle we intend to construct. As a result
7217 // ShuffleVec will be some sliding window into the original Vec.
7218 SDValue ShuffleVec;
7220 // Code should guarantee that element i in Vec starts at element "WindowBase
7221 // + i * WindowScale in ShuffleVec".
7222 int WindowBase = 0;
7223 int WindowScale = 1;
7225 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7227 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7230 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7231 // node.
7232 SmallVector<ShuffleSourceInfo, 2> Sources;
7233 for (unsigned i = 0; i < NumElts; ++i) {
7234 SDValue V = Op.getOperand(i);
7235 if (V.isUndef())
7236 continue;
7237 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7238 // A shuffle can only come from building a vector from various
7239 // elements of other vectors.
7240 return SDValue();
7241 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7242 // Furthermore, shuffles require a constant mask, whereas extractelts
7243 // accept variable indices.
7244 return SDValue();
7247 // Add this element source to the list if it's not already there.
7248 SDValue SourceVec = V.getOperand(0);
7249 auto Source = llvm::find(Sources, SourceVec);
7250 if (Source == Sources.end())
7251 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7253 // Update the minimum and maximum lane number seen.
7254 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7255 Source->MinElt = std::min(Source->MinElt, EltNo);
7256 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7259 // Currently only do something sane when at most two source vectors
7260 // are involved.
7261 if (Sources.size() > 2)
7262 return SDValue();
7264 // Find out the smallest element size among result and two sources, and use
7265 // it as element size to build the shuffle_vector.
7266 EVT SmallestEltTy = VT.getVectorElementType();
7267 for (auto &Source : Sources) {
7268 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7269 if (SrcEltTy.bitsLT(SmallestEltTy))
7270 SmallestEltTy = SrcEltTy;
7272 unsigned ResMultiplier =
7273 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7274 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7275 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7277 // If the source vector is too wide or too narrow, we may nevertheless be able
7278 // to construct a compatible shuffle either by concatenating it with UNDEF or
7279 // extracting a suitable range of elements.
7280 for (auto &Src : Sources) {
7281 EVT SrcVT = Src.ShuffleVec.getValueType();
7283 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7284 continue;
7286 // This stage of the search produces a source with the same element type as
7287 // the original, but with a total width matching the BUILD_VECTOR output.
7288 EVT EltVT = SrcVT.getVectorElementType();
7289 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7290 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7292 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7293 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7294 return SDValue();
7295 // We can pad out the smaller vector for free, so if it's part of a
7296 // shuffle...
7297 Src.ShuffleVec =
7298 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7299 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7300 continue;
7303 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7304 return SDValue();
7306 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7307 // Span too large for a VEXT to cope
7308 return SDValue();
7311 if (Src.MinElt >= NumSrcElts) {
7312 // The extraction can just take the second half
7313 Src.ShuffleVec =
7314 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7315 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7316 Src.WindowBase = -NumSrcElts;
7317 } else if (Src.MaxElt < NumSrcElts) {
7318 // The extraction can just take the first half
7319 Src.ShuffleVec =
7320 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7321 DAG.getConstant(0, dl, MVT::i32));
7322 } else {
7323 // An actual VEXT is needed
7324 SDValue VEXTSrc1 =
7325 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7326 DAG.getConstant(0, dl, MVT::i32));
7327 SDValue VEXTSrc2 =
7328 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7329 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7331 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7332 VEXTSrc2,
7333 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7334 Src.WindowBase = -Src.MinElt;
7338 // Another possible incompatibility occurs from the vector element types. We
7339 // can fix this by bitcasting the source vectors to the same type we intend
7340 // for the shuffle.
7341 for (auto &Src : Sources) {
7342 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7343 if (SrcEltTy == SmallestEltTy)
7344 continue;
7345 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7346 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7347 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7348 Src.WindowBase *= Src.WindowScale;
7351 // Final sanity check before we try to actually produce a shuffle.
7352 LLVM_DEBUG(for (auto Src
7353 : Sources)
7354 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7356 // The stars all align, our next step is to produce the mask for the shuffle.
7357 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7358 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7359 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7360 SDValue Entry = Op.getOperand(i);
7361 if (Entry.isUndef())
7362 continue;
7364 auto Src = llvm::find(Sources, Entry.getOperand(0));
7365 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7367 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7368 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7369 // segment.
7370 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7371 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7372 VT.getScalarSizeInBits());
7373 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7375 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7376 // starting at the appropriate offset.
7377 int *LaneMask = &Mask[i * ResMultiplier];
7379 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7380 ExtractBase += NumElts * (Src - Sources.begin());
7381 for (int j = 0; j < LanesDefined; ++j)
7382 LaneMask[j] = ExtractBase + j;
7386 // We can't handle more than two sources. This should have already
7387 // been checked before this point.
7388 assert(Sources.size() <= 2 && "Too many sources!");
7390 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7391 for (unsigned i = 0; i < Sources.size(); ++i)
7392 ShuffleOps[i] = Sources[i].ShuffleVec;
7394 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7395 ShuffleOps[1], Mask, DAG);
7396 if (!Shuffle)
7397 return SDValue();
7398 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7401 enum ShuffleOpCodes {
7402 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7403 OP_VREV,
7404 OP_VDUP0,
7405 OP_VDUP1,
7406 OP_VDUP2,
7407 OP_VDUP3,
7408 OP_VEXT1,
7409 OP_VEXT2,
7410 OP_VEXT3,
7411 OP_VUZPL, // VUZP, left result
7412 OP_VUZPR, // VUZP, right result
7413 OP_VZIPL, // VZIP, left result
7414 OP_VZIPR, // VZIP, right result
7415 OP_VTRNL, // VTRN, left result
7416 OP_VTRNR // VTRN, right result
7419 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7420 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7421 switch (OpNum) {
7422 case OP_COPY:
7423 case OP_VREV:
7424 case OP_VDUP0:
7425 case OP_VDUP1:
7426 case OP_VDUP2:
7427 case OP_VDUP3:
7428 return true;
7430 return false;
7433 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7434 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7435 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7436 /// are assumed to be legal.
7437 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7438 if (VT.getVectorNumElements() == 4 &&
7439 (VT.is128BitVector() || VT.is64BitVector())) {
7440 unsigned PFIndexes[4];
7441 for (unsigned i = 0; i != 4; ++i) {
7442 if (M[i] < 0)
7443 PFIndexes[i] = 8;
7444 else
7445 PFIndexes[i] = M[i];
7448 // Compute the index in the perfect shuffle table.
7449 unsigned PFTableIndex =
7450 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7451 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7452 unsigned Cost = (PFEntry >> 30);
7454 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7455 return true;
7458 bool ReverseVEXT, isV_UNDEF;
7459 unsigned Imm, WhichResult;
7461 unsigned EltSize = VT.getScalarSizeInBits();
7462 if (EltSize >= 32 ||
7463 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7464 isVREVMask(M, VT, 64) ||
7465 isVREVMask(M, VT, 32) ||
7466 isVREVMask(M, VT, 16))
7467 return true;
7468 else if (Subtarget->hasNEON() &&
7469 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7470 isVTBLMask(M, VT) ||
7471 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7472 return true;
7473 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7474 isReverseMask(M, VT))
7475 return true;
7476 else
7477 return false;
7480 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7481 /// the specified operations to build the shuffle.
7482 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7483 SDValue RHS, SelectionDAG &DAG,
7484 const SDLoc &dl) {
7485 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7486 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7487 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7489 if (OpNum == OP_COPY) {
7490 if (LHSID == (1*9+2)*9+3) return LHS;
7491 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7492 return RHS;
7495 SDValue OpLHS, OpRHS;
7496 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7497 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7498 EVT VT = OpLHS.getValueType();
7500 switch (OpNum) {
7501 default: llvm_unreachable("Unknown shuffle opcode!");
7502 case OP_VREV:
7503 // VREV divides the vector in half and swaps within the half.
7504 if (VT.getVectorElementType() == MVT::i32 ||
7505 VT.getVectorElementType() == MVT::f32)
7506 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7507 // vrev <4 x i16> -> VREV32
7508 if (VT.getVectorElementType() == MVT::i16)
7509 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7510 // vrev <4 x i8> -> VREV16
7511 assert(VT.getVectorElementType() == MVT::i8);
7512 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7513 case OP_VDUP0:
7514 case OP_VDUP1:
7515 case OP_VDUP2:
7516 case OP_VDUP3:
7517 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7518 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7519 case OP_VEXT1:
7520 case OP_VEXT2:
7521 case OP_VEXT3:
7522 return DAG.getNode(ARMISD::VEXT, dl, VT,
7523 OpLHS, OpRHS,
7524 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7525 case OP_VUZPL:
7526 case OP_VUZPR:
7527 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7528 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7529 case OP_VZIPL:
7530 case OP_VZIPR:
7531 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7532 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7533 case OP_VTRNL:
7534 case OP_VTRNR:
7535 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7536 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7540 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7541 ArrayRef<int> ShuffleMask,
7542 SelectionDAG &DAG) {
7543 // Check to see if we can use the VTBL instruction.
7544 SDValue V1 = Op.getOperand(0);
7545 SDValue V2 = Op.getOperand(1);
7546 SDLoc DL(Op);
7548 SmallVector<SDValue, 8> VTBLMask;
7549 for (ArrayRef<int>::iterator
7550 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7551 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7553 if (V2.getNode()->isUndef())
7554 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7555 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7557 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7558 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7561 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7562 SelectionDAG &DAG) {
7563 SDLoc DL(Op);
7564 SDValue OpLHS = Op.getOperand(0);
7565 EVT VT = OpLHS.getValueType();
7567 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7568 "Expect an v8i16/v16i8 type");
7569 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7570 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7571 // extract the first 8 bytes into the top double word and the last 8 bytes
7572 // into the bottom double word. The v8i16 case is similar.
7573 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7574 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7575 DAG.getConstant(ExtractNum, DL, MVT::i32));
7578 static EVT getVectorTyFromPredicateVector(EVT VT) {
7579 switch (VT.getSimpleVT().SimpleTy) {
7580 case MVT::v4i1:
7581 return MVT::v4i32;
7582 case MVT::v8i1:
7583 return MVT::v8i16;
7584 case MVT::v16i1:
7585 return MVT::v16i8;
7586 default:
7587 llvm_unreachable("Unexpected vector predicate type");
7591 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7592 SelectionDAG &DAG) {
7593 // Converting from boolean predicates to integers involves creating a vector
7594 // of all ones or all zeroes and selecting the lanes based upon the real
7595 // predicate.
7596 SDValue AllOnes =
7597 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7598 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7600 SDValue AllZeroes =
7601 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7602 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7604 // Get full vector type from predicate type
7605 EVT NewVT = getVectorTyFromPredicateVector(VT);
7607 SDValue RecastV1;
7608 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7609 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7610 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7611 // since we know in hardware the sizes are really the same.
7612 if (VT != MVT::v16i1)
7613 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7614 else
7615 RecastV1 = Pred;
7617 // Select either all ones or zeroes depending upon the real predicate bits.
7618 SDValue PredAsVector =
7619 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7621 // Recast our new predicate-as-integer v16i8 vector into something
7622 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7623 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7626 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7627 const ARMSubtarget *ST) {
7628 EVT VT = Op.getValueType();
7629 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7630 ArrayRef<int> ShuffleMask = SVN->getMask();
7632 assert(ST->hasMVEIntegerOps() &&
7633 "No support for vector shuffle of boolean predicates");
7635 SDValue V1 = Op.getOperand(0);
7636 SDLoc dl(Op);
7637 if (isReverseMask(ShuffleMask, VT)) {
7638 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7639 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7640 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7641 DAG.getConstant(16, dl, MVT::i32));
7642 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7645 // Until we can come up with optimised cases for every single vector
7646 // shuffle in existence we have chosen the least painful strategy. This is
7647 // to essentially promote the boolean predicate to a 8-bit integer, where
7648 // each predicate represents a byte. Then we fall back on a normal integer
7649 // vector shuffle and convert the result back into a predicate vector. In
7650 // many cases the generated code might be even better than scalar code
7651 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7652 // fields in a register into 8 other arbitrary 2-bit fields!
7653 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7654 EVT NewVT = PredAsVector.getValueType();
7656 // Do the shuffle!
7657 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7658 DAG.getUNDEF(NewVT), ShuffleMask);
7660 // Now return the result of comparing the shuffled vector with zero,
7661 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7662 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7663 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7666 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7667 const ARMSubtarget *ST) {
7668 SDValue V1 = Op.getOperand(0);
7669 SDValue V2 = Op.getOperand(1);
7670 SDLoc dl(Op);
7671 EVT VT = Op.getValueType();
7672 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7673 unsigned EltSize = VT.getScalarSizeInBits();
7675 if (ST->hasMVEIntegerOps() && EltSize == 1)
7676 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7678 // Convert shuffles that are directly supported on NEON to target-specific
7679 // DAG nodes, instead of keeping them as shuffles and matching them again
7680 // during code selection. This is more efficient and avoids the possibility
7681 // of inconsistencies between legalization and selection.
7682 // FIXME: floating-point vectors should be canonicalized to integer vectors
7683 // of the same time so that they get CSEd properly.
7684 ArrayRef<int> ShuffleMask = SVN->getMask();
7686 if (EltSize <= 32) {
7687 if (SVN->isSplat()) {
7688 int Lane = SVN->getSplatIndex();
7689 // If this is undef splat, generate it via "just" vdup, if possible.
7690 if (Lane == -1) Lane = 0;
7692 // Test if V1 is a SCALAR_TO_VECTOR.
7693 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7694 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7696 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7697 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7698 // reaches it).
7699 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7700 !isa<ConstantSDNode>(V1.getOperand(0))) {
7701 bool IsScalarToVector = true;
7702 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7703 if (!V1.getOperand(i).isUndef()) {
7704 IsScalarToVector = false;
7705 break;
7707 if (IsScalarToVector)
7708 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7710 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7711 DAG.getConstant(Lane, dl, MVT::i32));
7714 bool ReverseVEXT = false;
7715 unsigned Imm = 0;
7716 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7717 if (ReverseVEXT)
7718 std::swap(V1, V2);
7719 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7720 DAG.getConstant(Imm, dl, MVT::i32));
7723 if (isVREVMask(ShuffleMask, VT, 64))
7724 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7725 if (isVREVMask(ShuffleMask, VT, 32))
7726 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7727 if (isVREVMask(ShuffleMask, VT, 16))
7728 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7730 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7731 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7732 DAG.getConstant(Imm, dl, MVT::i32));
7735 // Check for Neon shuffles that modify both input vectors in place.
7736 // If both results are used, i.e., if there are two shuffles with the same
7737 // source operands and with masks corresponding to both results of one of
7738 // these operations, DAG memoization will ensure that a single node is
7739 // used for both shuffles.
7740 unsigned WhichResult = 0;
7741 bool isV_UNDEF = false;
7742 if (ST->hasNEON()) {
7743 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7744 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7745 if (isV_UNDEF)
7746 V2 = V1;
7747 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7748 .getValue(WhichResult);
7752 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7753 // shuffles that produce a result larger than their operands with:
7754 // shuffle(concat(v1, undef), concat(v2, undef))
7755 // ->
7756 // shuffle(concat(v1, v2), undef)
7757 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7759 // This is useful in the general case, but there are special cases where
7760 // native shuffles produce larger results: the two-result ops.
7762 // Look through the concat when lowering them:
7763 // shuffle(concat(v1, v2), undef)
7764 // ->
7765 // concat(VZIP(v1, v2):0, :1)
7767 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7768 SDValue SubV1 = V1->getOperand(0);
7769 SDValue SubV2 = V1->getOperand(1);
7770 EVT SubVT = SubV1.getValueType();
7772 // We expect these to have been canonicalized to -1.
7773 assert(llvm::all_of(ShuffleMask, [&](int i) {
7774 return i < (int)VT.getVectorNumElements();
7775 }) && "Unexpected shuffle index into UNDEF operand!");
7777 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7778 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7779 if (isV_UNDEF)
7780 SubV2 = SubV1;
7781 assert((WhichResult == 0) &&
7782 "In-place shuffle of concat can only have one result!");
7783 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7784 SubV1, SubV2);
7785 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7786 Res.getValue(1));
7791 // If the shuffle is not directly supported and it has 4 elements, use
7792 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7793 unsigned NumElts = VT.getVectorNumElements();
7794 if (NumElts == 4) {
7795 unsigned PFIndexes[4];
7796 for (unsigned i = 0; i != 4; ++i) {
7797 if (ShuffleMask[i] < 0)
7798 PFIndexes[i] = 8;
7799 else
7800 PFIndexes[i] = ShuffleMask[i];
7803 // Compute the index in the perfect shuffle table.
7804 unsigned PFTableIndex =
7805 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7806 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7807 unsigned Cost = (PFEntry >> 30);
7809 if (Cost <= 4) {
7810 if (ST->hasNEON())
7811 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7812 else if (isLegalMVEShuffleOp(PFEntry)) {
7813 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7814 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7815 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7816 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7817 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7818 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7823 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7824 if (EltSize >= 32) {
7825 // Do the expansion with floating-point types, since that is what the VFP
7826 // registers are defined to use, and since i64 is not legal.
7827 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7828 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7829 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7830 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7831 SmallVector<SDValue, 8> Ops;
7832 for (unsigned i = 0; i < NumElts; ++i) {
7833 if (ShuffleMask[i] < 0)
7834 Ops.push_back(DAG.getUNDEF(EltVT));
7835 else
7836 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7837 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7838 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7839 dl, MVT::i32)));
7841 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7842 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7845 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7846 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7848 if (ST->hasNEON() && VT == MVT::v8i8)
7849 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7850 return NewOp;
7852 return SDValue();
7855 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7856 const ARMSubtarget *ST) {
7857 EVT VecVT = Op.getOperand(0).getValueType();
7858 SDLoc dl(Op);
7860 assert(ST->hasMVEIntegerOps() &&
7861 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7863 SDValue Conv =
7864 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7865 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7866 unsigned LaneWidth =
7867 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7868 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7869 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7870 Op.getOperand(1), DAG.getValueType(MVT::i1));
7871 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7872 DAG.getConstant(~Mask, dl, MVT::i32));
7873 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7876 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7877 SelectionDAG &DAG) const {
7878 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7879 SDValue Lane = Op.getOperand(2);
7880 if (!isa<ConstantSDNode>(Lane))
7881 return SDValue();
7883 SDValue Elt = Op.getOperand(1);
7884 EVT EltVT = Elt.getValueType();
7886 if (Subtarget->hasMVEIntegerOps() &&
7887 Op.getValueType().getScalarSizeInBits() == 1)
7888 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7890 if (getTypeAction(*DAG.getContext(), EltVT) ==
7891 TargetLowering::TypePromoteFloat) {
7892 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7893 // but the type system will try to do that if we don't intervene.
7894 // Reinterpret any such vector-element insertion as one with the
7895 // corresponding integer types.
7897 SDLoc dl(Op);
7899 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7900 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7901 TargetLowering::TypePromoteFloat);
7903 SDValue VecIn = Op.getOperand(0);
7904 EVT VecVT = VecIn.getValueType();
7905 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7906 VecVT.getVectorNumElements());
7908 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7909 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7910 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7911 IVecIn, IElt, Lane);
7912 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
7915 return Op;
7918 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7919 const ARMSubtarget *ST) {
7920 EVT VecVT = Op.getOperand(0).getValueType();
7921 SDLoc dl(Op);
7923 assert(ST->hasMVEIntegerOps() &&
7924 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7926 SDValue Conv =
7927 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7928 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7929 unsigned LaneWidth =
7930 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7931 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
7932 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
7933 return Shift;
7936 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
7937 const ARMSubtarget *ST) {
7938 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7939 SDValue Lane = Op.getOperand(1);
7940 if (!isa<ConstantSDNode>(Lane))
7941 return SDValue();
7943 SDValue Vec = Op.getOperand(0);
7944 EVT VT = Vec.getValueType();
7946 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7947 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
7949 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7950 SDLoc dl(Op);
7951 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7954 return Op;
7957 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
7958 const ARMSubtarget *ST) {
7959 SDValue V1 = Op.getOperand(0);
7960 SDValue V2 = Op.getOperand(1);
7961 SDLoc dl(Op);
7962 EVT VT = Op.getValueType();
7963 EVT Op1VT = V1.getValueType();
7964 EVT Op2VT = V2.getValueType();
7965 unsigned NumElts = VT.getVectorNumElements();
7967 assert(Op1VT == Op2VT && "Operand types don't match!");
7968 assert(VT.getScalarSizeInBits() == 1 &&
7969 "Unexpected custom CONCAT_VECTORS lowering");
7970 assert(ST->hasMVEIntegerOps() &&
7971 "CONCAT_VECTORS lowering only supported for MVE");
7973 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7974 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
7976 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
7977 // promoted to v8i16, etc.
7979 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7981 // Extract the vector elements from Op1 and Op2 one by one and truncate them
7982 // to be the right size for the destination. For example, if Op1 is v4i1 then
7983 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
7984 // which when promoted is v8i16. That means each i32 element from Op1 needs
7985 // truncating to i16 and inserting in the result.
7986 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
7987 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
7988 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
7989 EVT NewVT = NewV.getValueType();
7990 EVT ConcatVT = ConVec.getValueType();
7991 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
7992 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
7993 DAG.getIntPtrConstant(i, dl));
7994 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
7995 DAG.getConstant(j, dl, MVT::i32));
7997 return ConVec;
7999 unsigned j = 0;
8000 ConVec = ExractInto(NewV1, ConVec, j);
8001 ConVec = ExractInto(NewV2, ConVec, j);
8003 // Now return the result of comparing the subvector with zero,
8004 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8005 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8006 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8009 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8010 const ARMSubtarget *ST) {
8011 EVT VT = Op->getValueType(0);
8012 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8013 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8015 // The only time a CONCAT_VECTORS operation can have legal types is when
8016 // two 64-bit vectors are concatenated to a 128-bit vector.
8017 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8018 "unexpected CONCAT_VECTORS");
8019 SDLoc dl(Op);
8020 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8021 SDValue Op0 = Op.getOperand(0);
8022 SDValue Op1 = Op.getOperand(1);
8023 if (!Op0.isUndef())
8024 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8025 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8026 DAG.getIntPtrConstant(0, dl));
8027 if (!Op1.isUndef())
8028 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8029 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8030 DAG.getIntPtrConstant(1, dl));
8031 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8034 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8035 const ARMSubtarget *ST) {
8036 SDValue V1 = Op.getOperand(0);
8037 SDValue V2 = Op.getOperand(1);
8038 SDLoc dl(Op);
8039 EVT VT = Op.getValueType();
8040 EVT Op1VT = V1.getValueType();
8041 unsigned NumElts = VT.getVectorNumElements();
8042 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8044 assert(VT.getScalarSizeInBits() == 1 &&
8045 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8046 assert(ST->hasMVEIntegerOps() &&
8047 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8049 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8051 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8052 // promoted to v8i16, etc.
8054 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8056 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8057 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8058 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8059 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8060 DAG.getIntPtrConstant(i, dl));
8061 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8062 DAG.getConstant(j, dl, MVT::i32));
8065 // Now return the result of comparing the subvector with zero,
8066 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8067 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8068 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8071 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8072 /// element has been zero/sign-extended, depending on the isSigned parameter,
8073 /// from an integer type half its size.
8074 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8075 bool isSigned) {
8076 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8077 EVT VT = N->getValueType(0);
8078 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8079 SDNode *BVN = N->getOperand(0).getNode();
8080 if (BVN->getValueType(0) != MVT::v4i32 ||
8081 BVN->getOpcode() != ISD::BUILD_VECTOR)
8082 return false;
8083 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8084 unsigned HiElt = 1 - LoElt;
8085 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8086 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8087 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8088 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8089 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8090 return false;
8091 if (isSigned) {
8092 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8093 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8094 return true;
8095 } else {
8096 if (Hi0->isNullValue() && Hi1->isNullValue())
8097 return true;
8099 return false;
8102 if (N->getOpcode() != ISD::BUILD_VECTOR)
8103 return false;
8105 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8106 SDNode *Elt = N->getOperand(i).getNode();
8107 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8108 unsigned EltSize = VT.getScalarSizeInBits();
8109 unsigned HalfSize = EltSize / 2;
8110 if (isSigned) {
8111 if (!isIntN(HalfSize, C->getSExtValue()))
8112 return false;
8113 } else {
8114 if (!isUIntN(HalfSize, C->getZExtValue()))
8115 return false;
8117 continue;
8119 return false;
8122 return true;
8125 /// isSignExtended - Check if a node is a vector value that is sign-extended
8126 /// or a constant BUILD_VECTOR with sign-extended elements.
8127 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8128 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8129 return true;
8130 if (isExtendedBUILD_VECTOR(N, DAG, true))
8131 return true;
8132 return false;
8135 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8136 /// or a constant BUILD_VECTOR with zero-extended elements.
8137 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8138 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8139 return true;
8140 if (isExtendedBUILD_VECTOR(N, DAG, false))
8141 return true;
8142 return false;
8145 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8146 if (OrigVT.getSizeInBits() >= 64)
8147 return OrigVT;
8149 assert(OrigVT.isSimple() && "Expecting a simple value type");
8151 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8152 switch (OrigSimpleTy) {
8153 default: llvm_unreachable("Unexpected Vector Type");
8154 case MVT::v2i8:
8155 case MVT::v2i16:
8156 return MVT::v2i32;
8157 case MVT::v4i8:
8158 return MVT::v4i16;
8162 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8163 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8164 /// We insert the required extension here to get the vector to fill a D register.
8165 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8166 const EVT &OrigTy,
8167 const EVT &ExtTy,
8168 unsigned ExtOpcode) {
8169 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8170 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8171 // 64-bits we need to insert a new extension so that it will be 64-bits.
8172 assert(ExtTy.is128BitVector() && "Unexpected extension size");
8173 if (OrigTy.getSizeInBits() >= 64)
8174 return N;
8176 // Must extend size to at least 64 bits to be used as an operand for VMULL.
8177 EVT NewVT = getExtensionTo64Bits(OrigTy);
8179 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8182 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8183 /// does not do any sign/zero extension. If the original vector is less
8184 /// than 64 bits, an appropriate extension will be added after the load to
8185 /// reach a total size of 64 bits. We have to add the extension separately
8186 /// because ARM does not have a sign/zero extending load for vectors.
8187 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8188 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8190 // The load already has the right type.
8191 if (ExtendedTy == LD->getMemoryVT())
8192 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8193 LD->getBasePtr(), LD->getPointerInfo(),
8194 LD->getAlignment(), LD->getMemOperand()->getFlags());
8196 // We need to create a zextload/sextload. We cannot just create a load
8197 // followed by a zext/zext node because LowerMUL is also run during normal
8198 // operation legalization where we can't create illegal types.
8199 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8200 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8201 LD->getMemoryVT(), LD->getAlignment(),
8202 LD->getMemOperand()->getFlags());
8205 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8206 /// extending load, or BUILD_VECTOR with extended elements, return the
8207 /// unextended value. The unextended vector should be 64 bits so that it can
8208 /// be used as an operand to a VMULL instruction. If the original vector size
8209 /// before extension is less than 64 bits we add a an extension to resize
8210 /// the vector to 64 bits.
8211 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8212 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8213 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8214 N->getOperand(0)->getValueType(0),
8215 N->getValueType(0),
8216 N->getOpcode());
8218 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8219 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8220 "Expected extending load");
8222 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8223 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8224 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8225 SDValue extLoad =
8226 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8227 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8229 return newLoad;
8232 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8233 // have been legalized as a BITCAST from v4i32.
8234 if (N->getOpcode() == ISD::BITCAST) {
8235 SDNode *BVN = N->getOperand(0).getNode();
8236 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8237 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8238 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8239 return DAG.getBuildVector(
8240 MVT::v2i32, SDLoc(N),
8241 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8243 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8244 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8245 EVT VT = N->getValueType(0);
8246 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8247 unsigned NumElts = VT.getVectorNumElements();
8248 MVT TruncVT = MVT::getIntegerVT(EltSize);
8249 SmallVector<SDValue, 8> Ops;
8250 SDLoc dl(N);
8251 for (unsigned i = 0; i != NumElts; ++i) {
8252 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8253 const APInt &CInt = C->getAPIntValue();
8254 // Element types smaller than 32 bits are not legal, so use i32 elements.
8255 // The values are implicitly truncated so sext vs. zext doesn't matter.
8256 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8258 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8261 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8262 unsigned Opcode = N->getOpcode();
8263 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8264 SDNode *N0 = N->getOperand(0).getNode();
8265 SDNode *N1 = N->getOperand(1).getNode();
8266 return N0->hasOneUse() && N1->hasOneUse() &&
8267 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8269 return false;
8272 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8273 unsigned Opcode = N->getOpcode();
8274 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8275 SDNode *N0 = N->getOperand(0).getNode();
8276 SDNode *N1 = N->getOperand(1).getNode();
8277 return N0->hasOneUse() && N1->hasOneUse() &&
8278 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8280 return false;
8283 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8284 // Multiplications are only custom-lowered for 128-bit vectors so that
8285 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8286 EVT VT = Op.getValueType();
8287 assert(VT.is128BitVector() && VT.isInteger() &&
8288 "unexpected type for custom-lowering ISD::MUL");
8289 SDNode *N0 = Op.getOperand(0).getNode();
8290 SDNode *N1 = Op.getOperand(1).getNode();
8291 unsigned NewOpc = 0;
8292 bool isMLA = false;
8293 bool isN0SExt = isSignExtended(N0, DAG);
8294 bool isN1SExt = isSignExtended(N1, DAG);
8295 if (isN0SExt && isN1SExt)
8296 NewOpc = ARMISD::VMULLs;
8297 else {
8298 bool isN0ZExt = isZeroExtended(N0, DAG);
8299 bool isN1ZExt = isZeroExtended(N1, DAG);
8300 if (isN0ZExt && isN1ZExt)
8301 NewOpc = ARMISD::VMULLu;
8302 else if (isN1SExt || isN1ZExt) {
8303 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8304 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8305 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8306 NewOpc = ARMISD::VMULLs;
8307 isMLA = true;
8308 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8309 NewOpc = ARMISD::VMULLu;
8310 isMLA = true;
8311 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8312 std::swap(N0, N1);
8313 NewOpc = ARMISD::VMULLu;
8314 isMLA = true;
8318 if (!NewOpc) {
8319 if (VT == MVT::v2i64)
8320 // Fall through to expand this. It is not legal.
8321 return SDValue();
8322 else
8323 // Other vector multiplications are legal.
8324 return Op;
8328 // Legalize to a VMULL instruction.
8329 SDLoc DL(Op);
8330 SDValue Op0;
8331 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8332 if (!isMLA) {
8333 Op0 = SkipExtensionForVMULL(N0, DAG);
8334 assert(Op0.getValueType().is64BitVector() &&
8335 Op1.getValueType().is64BitVector() &&
8336 "unexpected types for extended operands to VMULL");
8337 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8340 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8341 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8342 // vmull q0, d4, d6
8343 // vmlal q0, d5, d6
8344 // is faster than
8345 // vaddl q0, d4, d5
8346 // vmovl q1, d6
8347 // vmul q0, q0, q1
8348 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8349 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8350 EVT Op1VT = Op1.getValueType();
8351 return DAG.getNode(N0->getOpcode(), DL, VT,
8352 DAG.getNode(NewOpc, DL, VT,
8353 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8354 DAG.getNode(NewOpc, DL, VT,
8355 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8358 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8359 SelectionDAG &DAG) {
8360 // TODO: Should this propagate fast-math-flags?
8362 // Convert to float
8363 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8364 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8365 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8366 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8367 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8368 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8369 // Get reciprocal estimate.
8370 // float4 recip = vrecpeq_f32(yf);
8371 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8372 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8374 // Because char has a smaller range than uchar, we can actually get away
8375 // without any newton steps. This requires that we use a weird bias
8376 // of 0xb000, however (again, this has been exhaustively tested).
8377 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8378 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8379 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8380 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8381 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8382 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8383 // Convert back to short.
8384 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8385 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8386 return X;
8389 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8390 SelectionDAG &DAG) {
8391 // TODO: Should this propagate fast-math-flags?
8393 SDValue N2;
8394 // Convert to float.
8395 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8396 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8397 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8398 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8399 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8400 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8402 // Use reciprocal estimate and one refinement step.
8403 // float4 recip = vrecpeq_f32(yf);
8404 // recip *= vrecpsq_f32(yf, recip);
8405 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8406 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8407 N1);
8408 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8409 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8410 N1, N2);
8411 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8412 // Because short has a smaller range than ushort, we can actually get away
8413 // with only a single newton step. This requires that we use a weird bias
8414 // of 89, however (again, this has been exhaustively tested).
8415 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8416 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8417 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8418 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8419 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8420 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8421 // Convert back to integer and return.
8422 // return vmovn_s32(vcvt_s32_f32(result));
8423 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8424 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8425 return N0;
8428 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8429 const ARMSubtarget *ST) {
8430 EVT VT = Op.getValueType();
8431 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8432 "unexpected type for custom-lowering ISD::SDIV");
8434 SDLoc dl(Op);
8435 SDValue N0 = Op.getOperand(0);
8436 SDValue N1 = Op.getOperand(1);
8437 SDValue N2, N3;
8439 if (VT == MVT::v8i8) {
8440 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8441 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8443 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8444 DAG.getIntPtrConstant(4, dl));
8445 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8446 DAG.getIntPtrConstant(4, dl));
8447 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8448 DAG.getIntPtrConstant(0, dl));
8449 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8450 DAG.getIntPtrConstant(0, dl));
8452 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8453 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8455 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8456 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8458 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8459 return N0;
8461 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8464 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8465 const ARMSubtarget *ST) {
8466 // TODO: Should this propagate fast-math-flags?
8467 EVT VT = Op.getValueType();
8468 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8469 "unexpected type for custom-lowering ISD::UDIV");
8471 SDLoc dl(Op);
8472 SDValue N0 = Op.getOperand(0);
8473 SDValue N1 = Op.getOperand(1);
8474 SDValue N2, N3;
8476 if (VT == MVT::v8i8) {
8477 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8478 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8480 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8481 DAG.getIntPtrConstant(4, dl));
8482 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8483 DAG.getIntPtrConstant(4, dl));
8484 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8485 DAG.getIntPtrConstant(0, dl));
8486 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8487 DAG.getIntPtrConstant(0, dl));
8489 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8490 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8492 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8493 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8495 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8496 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8497 MVT::i32),
8498 N0);
8499 return N0;
8502 // v4i16 sdiv ... Convert to float.
8503 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8504 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8505 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8506 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8507 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8508 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8510 // Use reciprocal estimate and two refinement steps.
8511 // float4 recip = vrecpeq_f32(yf);
8512 // recip *= vrecpsq_f32(yf, recip);
8513 // recip *= vrecpsq_f32(yf, recip);
8514 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8515 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8516 BN1);
8517 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8518 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8519 BN1, N2);
8520 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8521 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8522 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8523 BN1, N2);
8524 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8525 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8526 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8527 // and that it will never cause us to return an answer too large).
8528 // float4 result = as_float4(as_int4(xf*recip) + 2);
8529 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8530 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8531 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8532 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8533 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8534 // Convert back to integer and return.
8535 // return vmovn_u32(vcvt_s32_f32(result));
8536 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8537 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8538 return N0;
8541 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8542 SDNode *N = Op.getNode();
8543 EVT VT = N->getValueType(0);
8544 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8546 SDValue Carry = Op.getOperand(2);
8548 SDLoc DL(Op);
8550 SDValue Result;
8551 if (Op.getOpcode() == ISD::ADDCARRY) {
8552 // This converts the boolean value carry into the carry flag.
8553 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8555 // Do the addition proper using the carry flag we wanted.
8556 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8557 Op.getOperand(1), Carry);
8559 // Now convert the carry flag into a boolean value.
8560 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8561 } else {
8562 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8563 // have to invert the carry first.
8564 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8565 DAG.getConstant(1, DL, MVT::i32), Carry);
8566 // This converts the boolean value carry into the carry flag.
8567 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8569 // Do the subtraction proper using the carry flag we wanted.
8570 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8571 Op.getOperand(1), Carry);
8573 // Now convert the carry flag into a boolean value.
8574 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8575 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8576 // by ISD::SUBCARRY, so compute 1 - C.
8577 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8578 DAG.getConstant(1, DL, MVT::i32), Carry);
8581 // Return both values.
8582 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8585 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8586 assert(Subtarget->isTargetDarwin());
8588 // For iOS, we want to call an alternative entry point: __sincos_stret,
8589 // return values are passed via sret.
8590 SDLoc dl(Op);
8591 SDValue Arg = Op.getOperand(0);
8592 EVT ArgVT = Arg.getValueType();
8593 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8594 auto PtrVT = getPointerTy(DAG.getDataLayout());
8596 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8597 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8599 // Pair of floats / doubles used to pass the result.
8600 Type *RetTy = StructType::get(ArgTy, ArgTy);
8601 auto &DL = DAG.getDataLayout();
8603 ArgListTy Args;
8604 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8605 SDValue SRet;
8606 if (ShouldUseSRet) {
8607 // Create stack object for sret.
8608 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8609 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8610 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8611 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8613 ArgListEntry Entry;
8614 Entry.Node = SRet;
8615 Entry.Ty = RetTy->getPointerTo();
8616 Entry.IsSExt = false;
8617 Entry.IsZExt = false;
8618 Entry.IsSRet = true;
8619 Args.push_back(Entry);
8620 RetTy = Type::getVoidTy(*DAG.getContext());
8623 ArgListEntry Entry;
8624 Entry.Node = Arg;
8625 Entry.Ty = ArgTy;
8626 Entry.IsSExt = false;
8627 Entry.IsZExt = false;
8628 Args.push_back(Entry);
8630 RTLIB::Libcall LC =
8631 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8632 const char *LibcallName = getLibcallName(LC);
8633 CallingConv::ID CC = getLibcallCallingConv(LC);
8634 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8636 TargetLowering::CallLoweringInfo CLI(DAG);
8637 CLI.setDebugLoc(dl)
8638 .setChain(DAG.getEntryNode())
8639 .setCallee(CC, RetTy, Callee, std::move(Args))
8640 .setDiscardResult(ShouldUseSRet);
8641 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8643 if (!ShouldUseSRet)
8644 return CallResult.first;
8646 SDValue LoadSin =
8647 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8649 // Address of cos field.
8650 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8651 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8652 SDValue LoadCos =
8653 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8655 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8656 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8657 LoadSin.getValue(0), LoadCos.getValue(0));
8660 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8661 bool Signed,
8662 SDValue &Chain) const {
8663 EVT VT = Op.getValueType();
8664 assert((VT == MVT::i32 || VT == MVT::i64) &&
8665 "unexpected type for custom lowering DIV");
8666 SDLoc dl(Op);
8668 const auto &DL = DAG.getDataLayout();
8669 const auto &TLI = DAG.getTargetLoweringInfo();
8671 const char *Name = nullptr;
8672 if (Signed)
8673 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8674 else
8675 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8677 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8679 ARMTargetLowering::ArgListTy Args;
8681 for (auto AI : {1, 0}) {
8682 ArgListEntry Arg;
8683 Arg.Node = Op.getOperand(AI);
8684 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8685 Args.push_back(Arg);
8688 CallLoweringInfo CLI(DAG);
8689 CLI.setDebugLoc(dl)
8690 .setChain(Chain)
8691 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8692 ES, std::move(Args));
8694 return LowerCallTo(CLI).first;
8697 // This is a code size optimisation: return the original SDIV node to
8698 // DAGCombiner when we don't want to expand SDIV into a sequence of
8699 // instructions, and an empty node otherwise which will cause the
8700 // SDIV to be expanded in DAGCombine.
8701 SDValue
8702 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8703 SelectionDAG &DAG,
8704 SmallVectorImpl<SDNode *> &Created) const {
8705 // TODO: Support SREM
8706 if (N->getOpcode() != ISD::SDIV)
8707 return SDValue();
8709 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8710 const bool MinSize = ST.hasMinSize();
8711 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8712 : ST.hasDivideInARMMode();
8714 // Don't touch vector types; rewriting this may lead to scalarizing
8715 // the int divs.
8716 if (N->getOperand(0).getValueType().isVector())
8717 return SDValue();
8719 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8720 // hwdiv support for this to be really profitable.
8721 if (!(MinSize && HasDivide))
8722 return SDValue();
8724 // ARM mode is a bit simpler than Thumb: we can handle large power
8725 // of 2 immediates with 1 mov instruction; no further checks required,
8726 // just return the sdiv node.
8727 if (!ST.isThumb())
8728 return SDValue(N, 0);
8730 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8731 // and thus lose the code size benefits of a MOVS that requires only 2.
8732 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8733 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8734 if (Divisor.sgt(128))
8735 return SDValue();
8737 return SDValue(N, 0);
8740 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8741 bool Signed) const {
8742 assert(Op.getValueType() == MVT::i32 &&
8743 "unexpected type for custom lowering DIV");
8744 SDLoc dl(Op);
8746 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8747 DAG.getEntryNode(), Op.getOperand(1));
8749 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8752 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8753 SDLoc DL(N);
8754 SDValue Op = N->getOperand(1);
8755 if (N->getValueType(0) == MVT::i32)
8756 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8757 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8758 DAG.getConstant(0, DL, MVT::i32));
8759 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8760 DAG.getConstant(1, DL, MVT::i32));
8761 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8762 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8765 void ARMTargetLowering::ExpandDIV_Windows(
8766 SDValue Op, SelectionDAG &DAG, bool Signed,
8767 SmallVectorImpl<SDValue> &Results) const {
8768 const auto &DL = DAG.getDataLayout();
8769 const auto &TLI = DAG.getTargetLoweringInfo();
8771 assert(Op.getValueType() == MVT::i64 &&
8772 "unexpected type for custom lowering DIV");
8773 SDLoc dl(Op);
8775 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8777 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8779 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8780 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8781 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8782 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8784 Results.push_back(Lower);
8785 Results.push_back(Upper);
8788 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
8789 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
8790 EVT MemVT = LD->getMemoryVT();
8791 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
8792 "Expected a predicate type!");
8793 assert(MemVT == Op.getValueType());
8794 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
8795 "Expected a non-extending load");
8796 assert(LD->isUnindexed() && "Expected a unindexed load");
8798 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
8799 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
8800 // need to make sure that 8/4 bits are actually loaded into the correct
8801 // place, which means loading the value and then shuffling the values into
8802 // the bottom bits of the predicate.
8803 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
8804 // for BE).
8806 SDLoc dl(Op);
8807 SDValue Load = DAG.getExtLoad(
8808 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
8809 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
8810 LD->getMemOperand());
8811 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
8812 if (MemVT != MVT::v16i1)
8813 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
8814 DAG.getConstant(0, dl, MVT::i32));
8815 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
8818 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
8819 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
8820 EVT MemVT = ST->getMemoryVT();
8821 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
8822 "Expected a predicate type!");
8823 assert(MemVT == ST->getValue().getValueType());
8824 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
8825 assert(ST->isUnindexed() && "Expected a unindexed store");
8827 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
8828 // unset and a scalar store.
8829 SDLoc dl(Op);
8830 SDValue Build = ST->getValue();
8831 if (MemVT != MVT::v16i1) {
8832 SmallVector<SDValue, 16> Ops;
8833 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
8834 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
8835 DAG.getConstant(I, dl, MVT::i32)));
8836 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
8837 Ops.push_back(DAG.getUNDEF(MVT::i32));
8838 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
8840 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
8841 return DAG.getTruncStore(
8842 ST->getChain(), dl, GRP, ST->getBasePtr(),
8843 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
8844 ST->getMemOperand());
8847 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8848 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8849 // Acquire/Release load/store is not legal for targets without a dmb or
8850 // equivalent available.
8851 return SDValue();
8853 // Monotonic load/store is legal for all targets.
8854 return Op;
8857 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8858 SmallVectorImpl<SDValue> &Results,
8859 SelectionDAG &DAG,
8860 const ARMSubtarget *Subtarget) {
8861 SDLoc DL(N);
8862 // Under Power Management extensions, the cycle-count is:
8863 // mrc p15, #0, <Rt>, c9, c13, #0
8864 SDValue Ops[] = { N->getOperand(0), // Chain
8865 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8866 DAG.getConstant(15, DL, MVT::i32),
8867 DAG.getConstant(0, DL, MVT::i32),
8868 DAG.getConstant(9, DL, MVT::i32),
8869 DAG.getConstant(13, DL, MVT::i32),
8870 DAG.getConstant(0, DL, MVT::i32)
8873 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8874 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8875 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8876 DAG.getConstant(0, DL, MVT::i32)));
8877 Results.push_back(Cycles32.getValue(1));
8880 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8881 SDLoc dl(V.getNode());
8882 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
8883 SDValue VHi = DAG.getAnyExtOrTrunc(
8884 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
8885 dl, MVT::i32);
8886 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8887 if (isBigEndian)
8888 std::swap (VLo, VHi);
8889 SDValue RegClass =
8890 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
8891 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
8892 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
8893 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
8894 return SDValue(
8895 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
8898 static void ReplaceCMP_SWAP_64Results(SDNode *N,
8899 SmallVectorImpl<SDValue> & Results,
8900 SelectionDAG &DAG) {
8901 assert(N->getValueType(0) == MVT::i64 &&
8902 "AtomicCmpSwap on types less than 64 should be legal");
8903 SDValue Ops[] = {N->getOperand(1),
8904 createGPRPairNode(DAG, N->getOperand(2)),
8905 createGPRPairNode(DAG, N->getOperand(3)),
8906 N->getOperand(0)};
8907 SDNode *CmpSwap = DAG.getMachineNode(
8908 ARM::CMP_SWAP_64, SDLoc(N),
8909 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
8911 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
8912 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8914 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8916 Results.push_back(
8917 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8918 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8919 Results.push_back(
8920 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8921 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8922 Results.push_back(SDValue(CmpSwap, 2));
8925 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8926 SelectionDAG &DAG) {
8927 const auto &TLI = DAG.getTargetLoweringInfo();
8929 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8930 "Custom lowering is MSVCRT specific!");
8932 SDLoc dl(Op);
8933 SDValue Val = Op.getOperand(0);
8934 MVT Ty = Val->getSimpleValueType(0);
8935 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8936 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8937 TLI.getPointerTy(DAG.getDataLayout()));
8939 TargetLowering::ArgListTy Args;
8940 TargetLowering::ArgListEntry Entry;
8942 Entry.Node = Val;
8943 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8944 Entry.IsZExt = true;
8945 Args.push_back(Entry);
8947 Entry.Node = Exponent;
8948 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8949 Entry.IsZExt = true;
8950 Args.push_back(Entry);
8952 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8954 // In the in-chain to the call is the entry node If we are emitting a
8955 // tailcall, the chain will be mutated if the node has a non-entry input
8956 // chain.
8957 SDValue InChain = DAG.getEntryNode();
8958 SDValue TCChain = InChain;
8960 const Function &F = DAG.getMachineFunction().getFunction();
8961 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8962 F.getReturnType() == LCRTy;
8963 if (IsTC)
8964 InChain = TCChain;
8966 TargetLowering::CallLoweringInfo CLI(DAG);
8967 CLI.setDebugLoc(dl)
8968 .setChain(InChain)
8969 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8970 .setTailCall(IsTC);
8971 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8973 // Return the chain (the DAG root) if it is a tail call
8974 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8977 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8978 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8979 switch (Op.getOpcode()) {
8980 default: llvm_unreachable("Don't know how to custom lower this!");
8981 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8982 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8983 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8984 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8985 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8986 case ISD::SELECT: return LowerSELECT(Op, DAG);
8987 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8988 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8989 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
8990 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
8991 case ISD::VASTART: return LowerVASTART(Op, DAG);
8992 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8993 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
8994 case ISD::SINT_TO_FP:
8995 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8996 case ISD::FP_TO_SINT:
8997 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
8998 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8999 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9000 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9001 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9002 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9003 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9004 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9005 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9006 Subtarget);
9007 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9008 case ISD::SHL:
9009 case ISD::SRL:
9010 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
9011 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
9012 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
9013 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
9014 case ISD::SRL_PARTS:
9015 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
9016 case ISD::CTTZ:
9017 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9018 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9019 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
9020 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
9021 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
9022 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9023 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9024 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9025 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9026 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9027 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9028 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9029 case ISD::MUL: return LowerMUL(Op, DAG);
9030 case ISD::SDIV:
9031 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9032 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9033 return LowerSDIV(Op, DAG, Subtarget);
9034 case ISD::UDIV:
9035 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9036 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9037 return LowerUDIV(Op, DAG, Subtarget);
9038 case ISD::ADDCARRY:
9039 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
9040 case ISD::SADDO:
9041 case ISD::SSUBO:
9042 return LowerSignedALUO(Op, DAG);
9043 case ISD::UADDO:
9044 case ISD::USUBO:
9045 return LowerUnsignedALUO(Op, DAG);
9046 case ISD::LOAD:
9047 return LowerPredicateLoad(Op, DAG);
9048 case ISD::STORE:
9049 return LowerPredicateStore(Op, DAG);
9050 case ISD::ATOMIC_LOAD:
9051 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
9052 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
9053 case ISD::SDIVREM:
9054 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
9055 case ISD::DYNAMIC_STACKALLOC:
9056 if (Subtarget->isTargetWindows())
9057 return LowerDYNAMIC_STACKALLOC(Op, DAG);
9058 llvm_unreachable("Don't know how to custom lower this!");
9059 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9060 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9061 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
9062 case ARMISD::WIN__DBZCHK: return SDValue();
9066 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9067 SelectionDAG &DAG) {
9068 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9069 unsigned Opc = 0;
9070 if (IntNo == Intrinsic::arm_smlald)
9071 Opc = ARMISD::SMLALD;
9072 else if (IntNo == Intrinsic::arm_smlaldx)
9073 Opc = ARMISD::SMLALDX;
9074 else if (IntNo == Intrinsic::arm_smlsld)
9075 Opc = ARMISD::SMLSLD;
9076 else if (IntNo == Intrinsic::arm_smlsldx)
9077 Opc = ARMISD::SMLSLDX;
9078 else
9079 return;
9081 SDLoc dl(N);
9082 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9083 N->getOperand(3),
9084 DAG.getConstant(0, dl, MVT::i32));
9085 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9086 N->getOperand(3),
9087 DAG.getConstant(1, dl, MVT::i32));
9089 SDValue LongMul = DAG.getNode(Opc, dl,
9090 DAG.getVTList(MVT::i32, MVT::i32),
9091 N->getOperand(1), N->getOperand(2),
9092 Lo, Hi);
9093 Results.push_back(LongMul.getValue(0));
9094 Results.push_back(LongMul.getValue(1));
9097 /// ReplaceNodeResults - Replace the results of node with an illegal result
9098 /// type with new values built out of custom code.
9099 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9100 SmallVectorImpl<SDValue> &Results,
9101 SelectionDAG &DAG) const {
9102 SDValue Res;
9103 switch (N->getOpcode()) {
9104 default:
9105 llvm_unreachable("Don't know how to custom expand this!");
9106 case ISD::READ_REGISTER:
9107 ExpandREAD_REGISTER(N, Results, DAG);
9108 break;
9109 case ISD::BITCAST:
9110 Res = ExpandBITCAST(N, DAG, Subtarget);
9111 break;
9112 case ISD::SRL:
9113 case ISD::SRA:
9114 case ISD::SHL:
9115 Res = Expand64BitShift(N, DAG, Subtarget);
9116 break;
9117 case ISD::SREM:
9118 case ISD::UREM:
9119 Res = LowerREM(N, DAG);
9120 break;
9121 case ISD::SDIVREM:
9122 case ISD::UDIVREM:
9123 Res = LowerDivRem(SDValue(N, 0), DAG);
9124 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9125 Results.push_back(Res.getValue(0));
9126 Results.push_back(Res.getValue(1));
9127 return;
9128 case ISD::READCYCLECOUNTER:
9129 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9130 return;
9131 case ISD::UDIV:
9132 case ISD::SDIV:
9133 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9134 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9135 Results);
9136 case ISD::ATOMIC_CMP_SWAP:
9137 ReplaceCMP_SWAP_64Results(N, Results, DAG);
9138 return;
9139 case ISD::INTRINSIC_WO_CHAIN:
9140 return ReplaceLongIntrinsic(N, Results, DAG);
9141 case ISD::ABS:
9142 lowerABS(N, Results, DAG);
9143 return ;
9146 if (Res.getNode())
9147 Results.push_back(Res);
9150 //===----------------------------------------------------------------------===//
9151 // ARM Scheduler Hooks
9152 //===----------------------------------------------------------------------===//
9154 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9155 /// registers the function context.
9156 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9157 MachineBasicBlock *MBB,
9158 MachineBasicBlock *DispatchBB,
9159 int FI) const {
9160 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9161 "ROPI/RWPI not currently supported with SjLj");
9162 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9163 DebugLoc dl = MI.getDebugLoc();
9164 MachineFunction *MF = MBB->getParent();
9165 MachineRegisterInfo *MRI = &MF->getRegInfo();
9166 MachineConstantPool *MCP = MF->getConstantPool();
9167 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9168 const Function &F = MF->getFunction();
9170 bool isThumb = Subtarget->isThumb();
9171 bool isThumb2 = Subtarget->isThumb2();
9173 unsigned PCLabelId = AFI->createPICLabelUId();
9174 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9175 ARMConstantPoolValue *CPV =
9176 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9177 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9179 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9180 : &ARM::GPRRegClass;
9182 // Grab constant pool and fixed stack memory operands.
9183 MachineMemOperand *CPMMO =
9184 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9185 MachineMemOperand::MOLoad, 4, 4);
9187 MachineMemOperand *FIMMOSt =
9188 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9189 MachineMemOperand::MOStore, 4, 4);
9191 // Load the address of the dispatch MBB into the jump buffer.
9192 if (isThumb2) {
9193 // Incoming value: jbuf
9194 // ldr.n r5, LCPI1_1
9195 // orr r5, r5, #1
9196 // add r5, pc
9197 // str r5, [$jbuf, #+4] ; &jbuf[1]
9198 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9199 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9200 .addConstantPoolIndex(CPI)
9201 .addMemOperand(CPMMO)
9202 .add(predOps(ARMCC::AL));
9203 // Set the low bit because of thumb mode.
9204 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9205 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9206 .addReg(NewVReg1, RegState::Kill)
9207 .addImm(0x01)
9208 .add(predOps(ARMCC::AL))
9209 .add(condCodeOp());
9210 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9211 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9212 .addReg(NewVReg2, RegState::Kill)
9213 .addImm(PCLabelId);
9214 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9215 .addReg(NewVReg3, RegState::Kill)
9216 .addFrameIndex(FI)
9217 .addImm(36) // &jbuf[1] :: pc
9218 .addMemOperand(FIMMOSt)
9219 .add(predOps(ARMCC::AL));
9220 } else if (isThumb) {
9221 // Incoming value: jbuf
9222 // ldr.n r1, LCPI1_4
9223 // add r1, pc
9224 // mov r2, #1
9225 // orrs r1, r2
9226 // add r2, $jbuf, #+4 ; &jbuf[1]
9227 // str r1, [r2]
9228 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9229 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9230 .addConstantPoolIndex(CPI)
9231 .addMemOperand(CPMMO)
9232 .add(predOps(ARMCC::AL));
9233 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9234 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9235 .addReg(NewVReg1, RegState::Kill)
9236 .addImm(PCLabelId);
9237 // Set the low bit because of thumb mode.
9238 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9239 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9240 .addReg(ARM::CPSR, RegState::Define)
9241 .addImm(1)
9242 .add(predOps(ARMCC::AL));
9243 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9244 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9245 .addReg(ARM::CPSR, RegState::Define)
9246 .addReg(NewVReg2, RegState::Kill)
9247 .addReg(NewVReg3, RegState::Kill)
9248 .add(predOps(ARMCC::AL));
9249 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9250 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9251 .addFrameIndex(FI)
9252 .addImm(36); // &jbuf[1] :: pc
9253 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9254 .addReg(NewVReg4, RegState::Kill)
9255 .addReg(NewVReg5, RegState::Kill)
9256 .addImm(0)
9257 .addMemOperand(FIMMOSt)
9258 .add(predOps(ARMCC::AL));
9259 } else {
9260 // Incoming value: jbuf
9261 // ldr r1, LCPI1_1
9262 // add r1, pc, r1
9263 // str r1, [$jbuf, #+4] ; &jbuf[1]
9264 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9265 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9266 .addConstantPoolIndex(CPI)
9267 .addImm(0)
9268 .addMemOperand(CPMMO)
9269 .add(predOps(ARMCC::AL));
9270 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9271 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9272 .addReg(NewVReg1, RegState::Kill)
9273 .addImm(PCLabelId)
9274 .add(predOps(ARMCC::AL));
9275 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9276 .addReg(NewVReg2, RegState::Kill)
9277 .addFrameIndex(FI)
9278 .addImm(36) // &jbuf[1] :: pc
9279 .addMemOperand(FIMMOSt)
9280 .add(predOps(ARMCC::AL));
9284 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9285 MachineBasicBlock *MBB) const {
9286 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9287 DebugLoc dl = MI.getDebugLoc();
9288 MachineFunction *MF = MBB->getParent();
9289 MachineRegisterInfo *MRI = &MF->getRegInfo();
9290 MachineFrameInfo &MFI = MF->getFrameInfo();
9291 int FI = MFI.getFunctionContextIndex();
9293 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9294 : &ARM::GPRnopcRegClass;
9296 // Get a mapping of the call site numbers to all of the landing pads they're
9297 // associated with.
9298 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9299 unsigned MaxCSNum = 0;
9300 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9301 ++BB) {
9302 if (!BB->isEHPad()) continue;
9304 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9305 // pad.
9306 for (MachineBasicBlock::iterator
9307 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9308 if (!II->isEHLabel()) continue;
9310 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9311 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9313 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9314 for (SmallVectorImpl<unsigned>::iterator
9315 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9316 CSI != CSE; ++CSI) {
9317 CallSiteNumToLPad[*CSI].push_back(&*BB);
9318 MaxCSNum = std::max(MaxCSNum, *CSI);
9320 break;
9324 // Get an ordered list of the machine basic blocks for the jump table.
9325 std::vector<MachineBasicBlock*> LPadList;
9326 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9327 LPadList.reserve(CallSiteNumToLPad.size());
9328 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9329 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9330 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9331 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9332 LPadList.push_back(*II);
9333 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9337 assert(!LPadList.empty() &&
9338 "No landing pad destinations for the dispatch jump table!");
9340 // Create the jump table and associated information.
9341 MachineJumpTableInfo *JTI =
9342 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9343 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9345 // Create the MBBs for the dispatch code.
9347 // Shove the dispatch's address into the return slot in the function context.
9348 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9349 DispatchBB->setIsEHPad();
9351 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9352 unsigned trap_opcode;
9353 if (Subtarget->isThumb())
9354 trap_opcode = ARM::tTRAP;
9355 else
9356 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9358 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9359 DispatchBB->addSuccessor(TrapBB);
9361 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9362 DispatchBB->addSuccessor(DispContBB);
9364 // Insert and MBBs.
9365 MF->insert(MF->end(), DispatchBB);
9366 MF->insert(MF->end(), DispContBB);
9367 MF->insert(MF->end(), TrapBB);
9369 // Insert code into the entry block that creates and registers the function
9370 // context.
9371 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9373 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9374 MachinePointerInfo::getFixedStack(*MF, FI),
9375 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9377 MachineInstrBuilder MIB;
9378 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9380 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9381 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9383 // Add a register mask with no preserved registers. This results in all
9384 // registers being marked as clobbered. This can't work if the dispatch block
9385 // is in a Thumb1 function and is linked with ARM code which uses the FP
9386 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9387 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9389 bool IsPositionIndependent = isPositionIndependent();
9390 unsigned NumLPads = LPadList.size();
9391 if (Subtarget->isThumb2()) {
9392 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9393 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9394 .addFrameIndex(FI)
9395 .addImm(4)
9396 .addMemOperand(FIMMOLd)
9397 .add(predOps(ARMCC::AL));
9399 if (NumLPads < 256) {
9400 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9401 .addReg(NewVReg1)
9402 .addImm(LPadList.size())
9403 .add(predOps(ARMCC::AL));
9404 } else {
9405 Register VReg1 = MRI->createVirtualRegister(TRC);
9406 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9407 .addImm(NumLPads & 0xFFFF)
9408 .add(predOps(ARMCC::AL));
9410 unsigned VReg2 = VReg1;
9411 if ((NumLPads & 0xFFFF0000) != 0) {
9412 VReg2 = MRI->createVirtualRegister(TRC);
9413 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9414 .addReg(VReg1)
9415 .addImm(NumLPads >> 16)
9416 .add(predOps(ARMCC::AL));
9419 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9420 .addReg(NewVReg1)
9421 .addReg(VReg2)
9422 .add(predOps(ARMCC::AL));
9425 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9426 .addMBB(TrapBB)
9427 .addImm(ARMCC::HI)
9428 .addReg(ARM::CPSR);
9430 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9431 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9432 .addJumpTableIndex(MJTI)
9433 .add(predOps(ARMCC::AL));
9435 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9436 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9437 .addReg(NewVReg3, RegState::Kill)
9438 .addReg(NewVReg1)
9439 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9440 .add(predOps(ARMCC::AL))
9441 .add(condCodeOp());
9443 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9444 .addReg(NewVReg4, RegState::Kill)
9445 .addReg(NewVReg1)
9446 .addJumpTableIndex(MJTI);
9447 } else if (Subtarget->isThumb()) {
9448 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9449 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9450 .addFrameIndex(FI)
9451 .addImm(1)
9452 .addMemOperand(FIMMOLd)
9453 .add(predOps(ARMCC::AL));
9455 if (NumLPads < 256) {
9456 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9457 .addReg(NewVReg1)
9458 .addImm(NumLPads)
9459 .add(predOps(ARMCC::AL));
9460 } else {
9461 MachineConstantPool *ConstantPool = MF->getConstantPool();
9462 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9463 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9465 // MachineConstantPool wants an explicit alignment.
9466 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9467 if (Align == 0)
9468 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9469 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9471 Register VReg1 = MRI->createVirtualRegister(TRC);
9472 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9473 .addReg(VReg1, RegState::Define)
9474 .addConstantPoolIndex(Idx)
9475 .add(predOps(ARMCC::AL));
9476 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9477 .addReg(NewVReg1)
9478 .addReg(VReg1)
9479 .add(predOps(ARMCC::AL));
9482 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9483 .addMBB(TrapBB)
9484 .addImm(ARMCC::HI)
9485 .addReg(ARM::CPSR);
9487 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9488 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9489 .addReg(ARM::CPSR, RegState::Define)
9490 .addReg(NewVReg1)
9491 .addImm(2)
9492 .add(predOps(ARMCC::AL));
9494 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9495 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9496 .addJumpTableIndex(MJTI)
9497 .add(predOps(ARMCC::AL));
9499 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9500 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9501 .addReg(ARM::CPSR, RegState::Define)
9502 .addReg(NewVReg2, RegState::Kill)
9503 .addReg(NewVReg3)
9504 .add(predOps(ARMCC::AL));
9506 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9507 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9509 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9510 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9511 .addReg(NewVReg4, RegState::Kill)
9512 .addImm(0)
9513 .addMemOperand(JTMMOLd)
9514 .add(predOps(ARMCC::AL));
9516 unsigned NewVReg6 = NewVReg5;
9517 if (IsPositionIndependent) {
9518 NewVReg6 = MRI->createVirtualRegister(TRC);
9519 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9520 .addReg(ARM::CPSR, RegState::Define)
9521 .addReg(NewVReg5, RegState::Kill)
9522 .addReg(NewVReg3)
9523 .add(predOps(ARMCC::AL));
9526 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9527 .addReg(NewVReg6, RegState::Kill)
9528 .addJumpTableIndex(MJTI);
9529 } else {
9530 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9531 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9532 .addFrameIndex(FI)
9533 .addImm(4)
9534 .addMemOperand(FIMMOLd)
9535 .add(predOps(ARMCC::AL));
9537 if (NumLPads < 256) {
9538 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9539 .addReg(NewVReg1)
9540 .addImm(NumLPads)
9541 .add(predOps(ARMCC::AL));
9542 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9543 Register VReg1 = MRI->createVirtualRegister(TRC);
9544 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9545 .addImm(NumLPads & 0xFFFF)
9546 .add(predOps(ARMCC::AL));
9548 unsigned VReg2 = VReg1;
9549 if ((NumLPads & 0xFFFF0000) != 0) {
9550 VReg2 = MRI->createVirtualRegister(TRC);
9551 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9552 .addReg(VReg1)
9553 .addImm(NumLPads >> 16)
9554 .add(predOps(ARMCC::AL));
9557 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9558 .addReg(NewVReg1)
9559 .addReg(VReg2)
9560 .add(predOps(ARMCC::AL));
9561 } else {
9562 MachineConstantPool *ConstantPool = MF->getConstantPool();
9563 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9564 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9566 // MachineConstantPool wants an explicit alignment.
9567 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9568 if (Align == 0)
9569 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9570 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9572 Register VReg1 = MRI->createVirtualRegister(TRC);
9573 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9574 .addReg(VReg1, RegState::Define)
9575 .addConstantPoolIndex(Idx)
9576 .addImm(0)
9577 .add(predOps(ARMCC::AL));
9578 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9579 .addReg(NewVReg1)
9580 .addReg(VReg1, RegState::Kill)
9581 .add(predOps(ARMCC::AL));
9584 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9585 .addMBB(TrapBB)
9586 .addImm(ARMCC::HI)
9587 .addReg(ARM::CPSR);
9589 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9590 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9591 .addReg(NewVReg1)
9592 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9593 .add(predOps(ARMCC::AL))
9594 .add(condCodeOp());
9595 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9596 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9597 .addJumpTableIndex(MJTI)
9598 .add(predOps(ARMCC::AL));
9600 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9601 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9602 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9603 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9604 .addReg(NewVReg3, RegState::Kill)
9605 .addReg(NewVReg4)
9606 .addImm(0)
9607 .addMemOperand(JTMMOLd)
9608 .add(predOps(ARMCC::AL));
9610 if (IsPositionIndependent) {
9611 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9612 .addReg(NewVReg5, RegState::Kill)
9613 .addReg(NewVReg4)
9614 .addJumpTableIndex(MJTI);
9615 } else {
9616 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9617 .addReg(NewVReg5, RegState::Kill)
9618 .addJumpTableIndex(MJTI);
9622 // Add the jump table entries as successors to the MBB.
9623 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9624 for (std::vector<MachineBasicBlock*>::iterator
9625 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9626 MachineBasicBlock *CurMBB = *I;
9627 if (SeenMBBs.insert(CurMBB).second)
9628 DispContBB->addSuccessor(CurMBB);
9631 // N.B. the order the invoke BBs are processed in doesn't matter here.
9632 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9633 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9634 for (MachineBasicBlock *BB : InvokeBBs) {
9636 // Remove the landing pad successor from the invoke block and replace it
9637 // with the new dispatch block.
9638 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9639 BB->succ_end());
9640 while (!Successors.empty()) {
9641 MachineBasicBlock *SMBB = Successors.pop_back_val();
9642 if (SMBB->isEHPad()) {
9643 BB->removeSuccessor(SMBB);
9644 MBBLPads.push_back(SMBB);
9648 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9649 BB->normalizeSuccProbs();
9651 // Find the invoke call and mark all of the callee-saved registers as
9652 // 'implicit defined' so that they're spilled. This prevents code from
9653 // moving instructions to before the EH block, where they will never be
9654 // executed.
9655 for (MachineBasicBlock::reverse_iterator
9656 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9657 if (!II->isCall()) continue;
9659 DenseMap<unsigned, bool> DefRegs;
9660 for (MachineInstr::mop_iterator
9661 OI = II->operands_begin(), OE = II->operands_end();
9662 OI != OE; ++OI) {
9663 if (!OI->isReg()) continue;
9664 DefRegs[OI->getReg()] = true;
9667 MachineInstrBuilder MIB(*MF, &*II);
9669 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9670 unsigned Reg = SavedRegs[i];
9671 if (Subtarget->isThumb2() &&
9672 !ARM::tGPRRegClass.contains(Reg) &&
9673 !ARM::hGPRRegClass.contains(Reg))
9674 continue;
9675 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9676 continue;
9677 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9678 continue;
9679 if (!DefRegs[Reg])
9680 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9683 break;
9687 // Mark all former landing pads as non-landing pads. The dispatch is the only
9688 // landing pad now.
9689 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9690 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9691 (*I)->setIsEHPad(false);
9693 // The instruction is gone now.
9694 MI.eraseFromParent();
9697 static
9698 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9699 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9700 E = MBB->succ_end(); I != E; ++I)
9701 if (*I != Succ)
9702 return *I;
9703 llvm_unreachable("Expecting a BB with two successors!");
9706 /// Return the load opcode for a given load size. If load size >= 8,
9707 /// neon opcode will be returned.
9708 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9709 if (LdSize >= 8)
9710 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9711 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9712 if (IsThumb1)
9713 return LdSize == 4 ? ARM::tLDRi
9714 : LdSize == 2 ? ARM::tLDRHi
9715 : LdSize == 1 ? ARM::tLDRBi : 0;
9716 if (IsThumb2)
9717 return LdSize == 4 ? ARM::t2LDR_POST
9718 : LdSize == 2 ? ARM::t2LDRH_POST
9719 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9720 return LdSize == 4 ? ARM::LDR_POST_IMM
9721 : LdSize == 2 ? ARM::LDRH_POST
9722 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9725 /// Return the store opcode for a given store size. If store size >= 8,
9726 /// neon opcode will be returned.
9727 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9728 if (StSize >= 8)
9729 return StSize == 16 ? ARM::VST1q32wb_fixed
9730 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9731 if (IsThumb1)
9732 return StSize == 4 ? ARM::tSTRi
9733 : StSize == 2 ? ARM::tSTRHi
9734 : StSize == 1 ? ARM::tSTRBi : 0;
9735 if (IsThumb2)
9736 return StSize == 4 ? ARM::t2STR_POST
9737 : StSize == 2 ? ARM::t2STRH_POST
9738 : StSize == 1 ? ARM::t2STRB_POST : 0;
9739 return StSize == 4 ? ARM::STR_POST_IMM
9740 : StSize == 2 ? ARM::STRH_POST
9741 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9744 /// Emit a post-increment load operation with given size. The instructions
9745 /// will be added to BB at Pos.
9746 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9747 const TargetInstrInfo *TII, const DebugLoc &dl,
9748 unsigned LdSize, unsigned Data, unsigned AddrIn,
9749 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9750 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9751 assert(LdOpc != 0 && "Should have a load opcode");
9752 if (LdSize >= 8) {
9753 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9754 .addReg(AddrOut, RegState::Define)
9755 .addReg(AddrIn)
9756 .addImm(0)
9757 .add(predOps(ARMCC::AL));
9758 } else if (IsThumb1) {
9759 // load + update AddrIn
9760 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9761 .addReg(AddrIn)
9762 .addImm(0)
9763 .add(predOps(ARMCC::AL));
9764 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9765 .add(t1CondCodeOp())
9766 .addReg(AddrIn)
9767 .addImm(LdSize)
9768 .add(predOps(ARMCC::AL));
9769 } else if (IsThumb2) {
9770 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9771 .addReg(AddrOut, RegState::Define)
9772 .addReg(AddrIn)
9773 .addImm(LdSize)
9774 .add(predOps(ARMCC::AL));
9775 } else { // arm
9776 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9777 .addReg(AddrOut, RegState::Define)
9778 .addReg(AddrIn)
9779 .addReg(0)
9780 .addImm(LdSize)
9781 .add(predOps(ARMCC::AL));
9785 /// Emit a post-increment store operation with given size. The instructions
9786 /// will be added to BB at Pos.
9787 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9788 const TargetInstrInfo *TII, const DebugLoc &dl,
9789 unsigned StSize, unsigned Data, unsigned AddrIn,
9790 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9791 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9792 assert(StOpc != 0 && "Should have a store opcode");
9793 if (StSize >= 8) {
9794 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9795 .addReg(AddrIn)
9796 .addImm(0)
9797 .addReg(Data)
9798 .add(predOps(ARMCC::AL));
9799 } else if (IsThumb1) {
9800 // store + update AddrIn
9801 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9802 .addReg(Data)
9803 .addReg(AddrIn)
9804 .addImm(0)
9805 .add(predOps(ARMCC::AL));
9806 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9807 .add(t1CondCodeOp())
9808 .addReg(AddrIn)
9809 .addImm(StSize)
9810 .add(predOps(ARMCC::AL));
9811 } else if (IsThumb2) {
9812 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9813 .addReg(Data)
9814 .addReg(AddrIn)
9815 .addImm(StSize)
9816 .add(predOps(ARMCC::AL));
9817 } else { // arm
9818 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9819 .addReg(Data)
9820 .addReg(AddrIn)
9821 .addReg(0)
9822 .addImm(StSize)
9823 .add(predOps(ARMCC::AL));
9827 MachineBasicBlock *
9828 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9829 MachineBasicBlock *BB) const {
9830 // This pseudo instruction has 3 operands: dst, src, size
9831 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9832 // Otherwise, we will generate unrolled scalar copies.
9833 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9834 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9835 MachineFunction::iterator It = ++BB->getIterator();
9837 Register dest = MI.getOperand(0).getReg();
9838 Register src = MI.getOperand(1).getReg();
9839 unsigned SizeVal = MI.getOperand(2).getImm();
9840 unsigned Align = MI.getOperand(3).getImm();
9841 DebugLoc dl = MI.getDebugLoc();
9843 MachineFunction *MF = BB->getParent();
9844 MachineRegisterInfo &MRI = MF->getRegInfo();
9845 unsigned UnitSize = 0;
9846 const TargetRegisterClass *TRC = nullptr;
9847 const TargetRegisterClass *VecTRC = nullptr;
9849 bool IsThumb1 = Subtarget->isThumb1Only();
9850 bool IsThumb2 = Subtarget->isThumb2();
9851 bool IsThumb = Subtarget->isThumb();
9853 if (Align & 1) {
9854 UnitSize = 1;
9855 } else if (Align & 2) {
9856 UnitSize = 2;
9857 } else {
9858 // Check whether we can use NEON instructions.
9859 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9860 Subtarget->hasNEON()) {
9861 if ((Align % 16 == 0) && SizeVal >= 16)
9862 UnitSize = 16;
9863 else if ((Align % 8 == 0) && SizeVal >= 8)
9864 UnitSize = 8;
9866 // Can't use NEON instructions.
9867 if (UnitSize == 0)
9868 UnitSize = 4;
9871 // Select the correct opcode and register class for unit size load/store
9872 bool IsNeon = UnitSize >= 8;
9873 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
9874 if (IsNeon)
9875 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
9876 : UnitSize == 8 ? &ARM::DPRRegClass
9877 : nullptr;
9879 unsigned BytesLeft = SizeVal % UnitSize;
9880 unsigned LoopSize = SizeVal - BytesLeft;
9882 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
9883 // Use LDR and STR to copy.
9884 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
9885 // [destOut] = STR_POST(scratch, destIn, UnitSize)
9886 unsigned srcIn = src;
9887 unsigned destIn = dest;
9888 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
9889 Register srcOut = MRI.createVirtualRegister(TRC);
9890 Register destOut = MRI.createVirtualRegister(TRC);
9891 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9892 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
9893 IsThumb1, IsThumb2);
9894 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
9895 IsThumb1, IsThumb2);
9896 srcIn = srcOut;
9897 destIn = destOut;
9900 // Handle the leftover bytes with LDRB and STRB.
9901 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
9902 // [destOut] = STRB_POST(scratch, destIn, 1)
9903 for (unsigned i = 0; i < BytesLeft; i++) {
9904 Register srcOut = MRI.createVirtualRegister(TRC);
9905 Register destOut = MRI.createVirtualRegister(TRC);
9906 Register scratch = MRI.createVirtualRegister(TRC);
9907 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
9908 IsThumb1, IsThumb2);
9909 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
9910 IsThumb1, IsThumb2);
9911 srcIn = srcOut;
9912 destIn = destOut;
9914 MI.eraseFromParent(); // The instruction is gone now.
9915 return BB;
9918 // Expand the pseudo op to a loop.
9919 // thisMBB:
9920 // ...
9921 // movw varEnd, # --> with thumb2
9922 // movt varEnd, #
9923 // ldrcp varEnd, idx --> without thumb2
9924 // fallthrough --> loopMBB
9925 // loopMBB:
9926 // PHI varPhi, varEnd, varLoop
9927 // PHI srcPhi, src, srcLoop
9928 // PHI destPhi, dst, destLoop
9929 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9930 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9931 // subs varLoop, varPhi, #UnitSize
9932 // bne loopMBB
9933 // fallthrough --> exitMBB
9934 // exitMBB:
9935 // epilogue to handle left-over bytes
9936 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9937 // [destOut] = STRB_POST(scratch, destLoop, 1)
9938 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9939 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9940 MF->insert(It, loopMBB);
9941 MF->insert(It, exitMBB);
9943 // Transfer the remainder of BB and its successor edges to exitMBB.
9944 exitMBB->splice(exitMBB->begin(), BB,
9945 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9946 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9948 // Load an immediate to varEnd.
9949 Register varEnd = MRI.createVirtualRegister(TRC);
9950 if (Subtarget->useMovt()) {
9951 unsigned Vtmp = varEnd;
9952 if ((LoopSize & 0xFFFF0000) != 0)
9953 Vtmp = MRI.createVirtualRegister(TRC);
9954 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9955 .addImm(LoopSize & 0xFFFF)
9956 .add(predOps(ARMCC::AL));
9958 if ((LoopSize & 0xFFFF0000) != 0)
9959 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9960 .addReg(Vtmp)
9961 .addImm(LoopSize >> 16)
9962 .add(predOps(ARMCC::AL));
9963 } else {
9964 MachineConstantPool *ConstantPool = MF->getConstantPool();
9965 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9966 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9968 // MachineConstantPool wants an explicit alignment.
9969 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9970 if (Align == 0)
9971 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9972 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9973 MachineMemOperand *CPMMO =
9974 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9975 MachineMemOperand::MOLoad, 4, 4);
9977 if (IsThumb)
9978 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9979 .addReg(varEnd, RegState::Define)
9980 .addConstantPoolIndex(Idx)
9981 .add(predOps(ARMCC::AL))
9982 .addMemOperand(CPMMO);
9983 else
9984 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9985 .addReg(varEnd, RegState::Define)
9986 .addConstantPoolIndex(Idx)
9987 .addImm(0)
9988 .add(predOps(ARMCC::AL))
9989 .addMemOperand(CPMMO);
9991 BB->addSuccessor(loopMBB);
9993 // Generate the loop body:
9994 // varPhi = PHI(varLoop, varEnd)
9995 // srcPhi = PHI(srcLoop, src)
9996 // destPhi = PHI(destLoop, dst)
9997 MachineBasicBlock *entryBB = BB;
9998 BB = loopMBB;
9999 Register varLoop = MRI.createVirtualRegister(TRC);
10000 Register varPhi = MRI.createVirtualRegister(TRC);
10001 Register srcLoop = MRI.createVirtualRegister(TRC);
10002 Register srcPhi = MRI.createVirtualRegister(TRC);
10003 Register destLoop = MRI.createVirtualRegister(TRC);
10004 Register destPhi = MRI.createVirtualRegister(TRC);
10006 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10007 .addReg(varLoop).addMBB(loopMBB)
10008 .addReg(varEnd).addMBB(entryBB);
10009 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10010 .addReg(srcLoop).addMBB(loopMBB)
10011 .addReg(src).addMBB(entryBB);
10012 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10013 .addReg(destLoop).addMBB(loopMBB)
10014 .addReg(dest).addMBB(entryBB);
10016 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10017 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10018 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10019 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10020 IsThumb1, IsThumb2);
10021 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10022 IsThumb1, IsThumb2);
10024 // Decrement loop variable by UnitSize.
10025 if (IsThumb1) {
10026 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10027 .add(t1CondCodeOp())
10028 .addReg(varPhi)
10029 .addImm(UnitSize)
10030 .add(predOps(ARMCC::AL));
10031 } else {
10032 MachineInstrBuilder MIB =
10033 BuildMI(*BB, BB->end(), dl,
10034 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10035 MIB.addReg(varPhi)
10036 .addImm(UnitSize)
10037 .add(predOps(ARMCC::AL))
10038 .add(condCodeOp());
10039 MIB->getOperand(5).setReg(ARM::CPSR);
10040 MIB->getOperand(5).setIsDef(true);
10042 BuildMI(*BB, BB->end(), dl,
10043 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10044 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10046 // loopMBB can loop back to loopMBB or fall through to exitMBB.
10047 BB->addSuccessor(loopMBB);
10048 BB->addSuccessor(exitMBB);
10050 // Add epilogue to handle BytesLeft.
10051 BB = exitMBB;
10052 auto StartOfExit = exitMBB->begin();
10054 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10055 // [destOut] = STRB_POST(scratch, destLoop, 1)
10056 unsigned srcIn = srcLoop;
10057 unsigned destIn = destLoop;
10058 for (unsigned i = 0; i < BytesLeft; i++) {
10059 Register srcOut = MRI.createVirtualRegister(TRC);
10060 Register destOut = MRI.createVirtualRegister(TRC);
10061 Register scratch = MRI.createVirtualRegister(TRC);
10062 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10063 IsThumb1, IsThumb2);
10064 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10065 IsThumb1, IsThumb2);
10066 srcIn = srcOut;
10067 destIn = destOut;
10070 MI.eraseFromParent(); // The instruction is gone now.
10071 return BB;
10074 MachineBasicBlock *
10075 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10076 MachineBasicBlock *MBB) const {
10077 const TargetMachine &TM = getTargetMachine();
10078 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10079 DebugLoc DL = MI.getDebugLoc();
10081 assert(Subtarget->isTargetWindows() &&
10082 "__chkstk is only supported on Windows");
10083 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10085 // __chkstk takes the number of words to allocate on the stack in R4, and
10086 // returns the stack adjustment in number of bytes in R4. This will not
10087 // clober any other registers (other than the obvious lr).
10089 // Although, technically, IP should be considered a register which may be
10090 // clobbered, the call itself will not touch it. Windows on ARM is a pure
10091 // thumb-2 environment, so there is no interworking required. As a result, we
10092 // do not expect a veneer to be emitted by the linker, clobbering IP.
10094 // Each module receives its own copy of __chkstk, so no import thunk is
10095 // required, again, ensuring that IP is not clobbered.
10097 // Finally, although some linkers may theoretically provide a trampoline for
10098 // out of range calls (which is quite common due to a 32M range limitation of
10099 // branches for Thumb), we can generate the long-call version via
10100 // -mcmodel=large, alleviating the need for the trampoline which may clobber
10101 // IP.
10103 switch (TM.getCodeModel()) {
10104 case CodeModel::Tiny:
10105 llvm_unreachable("Tiny code model not available on ARM.");
10106 case CodeModel::Small:
10107 case CodeModel::Medium:
10108 case CodeModel::Kernel:
10109 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10110 .add(predOps(ARMCC::AL))
10111 .addExternalSymbol("__chkstk")
10112 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10113 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10114 .addReg(ARM::R12,
10115 RegState::Implicit | RegState::Define | RegState::Dead)
10116 .addReg(ARM::CPSR,
10117 RegState::Implicit | RegState::Define | RegState::Dead);
10118 break;
10119 case CodeModel::Large: {
10120 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10121 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10123 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10124 .addExternalSymbol("__chkstk");
10125 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10126 .add(predOps(ARMCC::AL))
10127 .addReg(Reg, RegState::Kill)
10128 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10129 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10130 .addReg(ARM::R12,
10131 RegState::Implicit | RegState::Define | RegState::Dead)
10132 .addReg(ARM::CPSR,
10133 RegState::Implicit | RegState::Define | RegState::Dead);
10134 break;
10138 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10139 .addReg(ARM::SP, RegState::Kill)
10140 .addReg(ARM::R4, RegState::Kill)
10141 .setMIFlags(MachineInstr::FrameSetup)
10142 .add(predOps(ARMCC::AL))
10143 .add(condCodeOp());
10145 MI.eraseFromParent();
10146 return MBB;
10149 MachineBasicBlock *
10150 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10151 MachineBasicBlock *MBB) const {
10152 DebugLoc DL = MI.getDebugLoc();
10153 MachineFunction *MF = MBB->getParent();
10154 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10156 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10157 MF->insert(++MBB->getIterator(), ContBB);
10158 ContBB->splice(ContBB->begin(), MBB,
10159 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10160 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10161 MBB->addSuccessor(ContBB);
10163 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10164 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10165 MF->push_back(TrapBB);
10166 MBB->addSuccessor(TrapBB);
10168 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10169 .addReg(MI.getOperand(0).getReg())
10170 .addImm(0)
10171 .add(predOps(ARMCC::AL));
10172 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10173 .addMBB(TrapBB)
10174 .addImm(ARMCC::EQ)
10175 .addReg(ARM::CPSR);
10177 MI.eraseFromParent();
10178 return ContBB;
10181 // The CPSR operand of SelectItr might be missing a kill marker
10182 // because there were multiple uses of CPSR, and ISel didn't know
10183 // which to mark. Figure out whether SelectItr should have had a
10184 // kill marker, and set it if it should. Returns the correct kill
10185 // marker value.
10186 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10187 MachineBasicBlock* BB,
10188 const TargetRegisterInfo* TRI) {
10189 // Scan forward through BB for a use/def of CPSR.
10190 MachineBasicBlock::iterator miI(std::next(SelectItr));
10191 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10192 const MachineInstr& mi = *miI;
10193 if (mi.readsRegister(ARM::CPSR))
10194 return false;
10195 if (mi.definesRegister(ARM::CPSR))
10196 break; // Should have kill-flag - update below.
10199 // If we hit the end of the block, check whether CPSR is live into a
10200 // successor.
10201 if (miI == BB->end()) {
10202 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10203 sEnd = BB->succ_end();
10204 sItr != sEnd; ++sItr) {
10205 MachineBasicBlock* succ = *sItr;
10206 if (succ->isLiveIn(ARM::CPSR))
10207 return false;
10211 // We found a def, or hit the end of the basic block and CPSR wasn't live
10212 // out. SelectMI should have a kill flag on CPSR.
10213 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10214 return true;
10217 MachineBasicBlock *
10218 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10219 MachineBasicBlock *BB) const {
10220 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10221 DebugLoc dl = MI.getDebugLoc();
10222 bool isThumb2 = Subtarget->isThumb2();
10223 switch (MI.getOpcode()) {
10224 default: {
10225 MI.print(errs());
10226 llvm_unreachable("Unexpected instr type to insert");
10229 // Thumb1 post-indexed loads are really just single-register LDMs.
10230 case ARM::tLDR_postidx: {
10231 MachineOperand Def(MI.getOperand(1));
10232 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10233 .add(Def) // Rn_wb
10234 .add(MI.getOperand(2)) // Rn
10235 .add(MI.getOperand(3)) // PredImm
10236 .add(MI.getOperand(4)) // PredReg
10237 .add(MI.getOperand(0)) // Rt
10238 .cloneMemRefs(MI);
10239 MI.eraseFromParent();
10240 return BB;
10243 // The Thumb2 pre-indexed stores have the same MI operands, they just
10244 // define them differently in the .td files from the isel patterns, so
10245 // they need pseudos.
10246 case ARM::t2STR_preidx:
10247 MI.setDesc(TII->get(ARM::t2STR_PRE));
10248 return BB;
10249 case ARM::t2STRB_preidx:
10250 MI.setDesc(TII->get(ARM::t2STRB_PRE));
10251 return BB;
10252 case ARM::t2STRH_preidx:
10253 MI.setDesc(TII->get(ARM::t2STRH_PRE));
10254 return BB;
10256 case ARM::STRi_preidx:
10257 case ARM::STRBi_preidx: {
10258 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10259 : ARM::STRB_PRE_IMM;
10260 // Decode the offset.
10261 unsigned Offset = MI.getOperand(4).getImm();
10262 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10263 Offset = ARM_AM::getAM2Offset(Offset);
10264 if (isSub)
10265 Offset = -Offset;
10267 MachineMemOperand *MMO = *MI.memoperands_begin();
10268 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10269 .add(MI.getOperand(0)) // Rn_wb
10270 .add(MI.getOperand(1)) // Rt
10271 .add(MI.getOperand(2)) // Rn
10272 .addImm(Offset) // offset (skip GPR==zero_reg)
10273 .add(MI.getOperand(5)) // pred
10274 .add(MI.getOperand(6))
10275 .addMemOperand(MMO);
10276 MI.eraseFromParent();
10277 return BB;
10279 case ARM::STRr_preidx:
10280 case ARM::STRBr_preidx:
10281 case ARM::STRH_preidx: {
10282 unsigned NewOpc;
10283 switch (MI.getOpcode()) {
10284 default: llvm_unreachable("unexpected opcode!");
10285 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10286 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10287 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10289 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10290 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10291 MIB.add(MI.getOperand(i));
10292 MI.eraseFromParent();
10293 return BB;
10296 case ARM::tMOVCCr_pseudo: {
10297 // To "insert" a SELECT_CC instruction, we actually have to insert the
10298 // diamond control-flow pattern. The incoming instruction knows the
10299 // destination vreg to set, the condition code register to branch on, the
10300 // true/false values to select between, and a branch opcode to use.
10301 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10302 MachineFunction::iterator It = ++BB->getIterator();
10304 // thisMBB:
10305 // ...
10306 // TrueVal = ...
10307 // cmpTY ccX, r1, r2
10308 // bCC copy1MBB
10309 // fallthrough --> copy0MBB
10310 MachineBasicBlock *thisMBB = BB;
10311 MachineFunction *F = BB->getParent();
10312 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10313 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10314 F->insert(It, copy0MBB);
10315 F->insert(It, sinkMBB);
10317 // Check whether CPSR is live past the tMOVCCr_pseudo.
10318 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10319 if (!MI.killsRegister(ARM::CPSR) &&
10320 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10321 copy0MBB->addLiveIn(ARM::CPSR);
10322 sinkMBB->addLiveIn(ARM::CPSR);
10325 // Transfer the remainder of BB and its successor edges to sinkMBB.
10326 sinkMBB->splice(sinkMBB->begin(), BB,
10327 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10328 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10330 BB->addSuccessor(copy0MBB);
10331 BB->addSuccessor(sinkMBB);
10333 BuildMI(BB, dl, TII->get(ARM::tBcc))
10334 .addMBB(sinkMBB)
10335 .addImm(MI.getOperand(3).getImm())
10336 .addReg(MI.getOperand(4).getReg());
10338 // copy0MBB:
10339 // %FalseValue = ...
10340 // # fallthrough to sinkMBB
10341 BB = copy0MBB;
10343 // Update machine-CFG edges
10344 BB->addSuccessor(sinkMBB);
10346 // sinkMBB:
10347 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10348 // ...
10349 BB = sinkMBB;
10350 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10351 .addReg(MI.getOperand(1).getReg())
10352 .addMBB(copy0MBB)
10353 .addReg(MI.getOperand(2).getReg())
10354 .addMBB(thisMBB);
10356 MI.eraseFromParent(); // The pseudo instruction is gone now.
10357 return BB;
10360 case ARM::BCCi64:
10361 case ARM::BCCZi64: {
10362 // If there is an unconditional branch to the other successor, remove it.
10363 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10365 // Compare both parts that make up the double comparison separately for
10366 // equality.
10367 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10369 Register LHS1 = MI.getOperand(1).getReg();
10370 Register LHS2 = MI.getOperand(2).getReg();
10371 if (RHSisZero) {
10372 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10373 .addReg(LHS1)
10374 .addImm(0)
10375 .add(predOps(ARMCC::AL));
10376 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10377 .addReg(LHS2).addImm(0)
10378 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10379 } else {
10380 Register RHS1 = MI.getOperand(3).getReg();
10381 Register RHS2 = MI.getOperand(4).getReg();
10382 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10383 .addReg(LHS1)
10384 .addReg(RHS1)
10385 .add(predOps(ARMCC::AL));
10386 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10387 .addReg(LHS2).addReg(RHS2)
10388 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10391 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10392 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10393 if (MI.getOperand(0).getImm() == ARMCC::NE)
10394 std::swap(destMBB, exitMBB);
10396 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10397 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10398 if (isThumb2)
10399 BuildMI(BB, dl, TII->get(ARM::t2B))
10400 .addMBB(exitMBB)
10401 .add(predOps(ARMCC::AL));
10402 else
10403 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10405 MI.eraseFromParent(); // The pseudo instruction is gone now.
10406 return BB;
10409 case ARM::Int_eh_sjlj_setjmp:
10410 case ARM::Int_eh_sjlj_setjmp_nofp:
10411 case ARM::tInt_eh_sjlj_setjmp:
10412 case ARM::t2Int_eh_sjlj_setjmp:
10413 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10414 return BB;
10416 case ARM::Int_eh_sjlj_setup_dispatch:
10417 EmitSjLjDispatchBlock(MI, BB);
10418 return BB;
10420 case ARM::ABS:
10421 case ARM::t2ABS: {
10422 // To insert an ABS instruction, we have to insert the
10423 // diamond control-flow pattern. The incoming instruction knows the
10424 // source vreg to test against 0, the destination vreg to set,
10425 // the condition code register to branch on, the
10426 // true/false values to select between, and a branch opcode to use.
10427 // It transforms
10428 // V1 = ABS V0
10429 // into
10430 // V2 = MOVS V0
10431 // BCC (branch to SinkBB if V0 >= 0)
10432 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10433 // SinkBB: V1 = PHI(V2, V3)
10434 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10435 MachineFunction::iterator BBI = ++BB->getIterator();
10436 MachineFunction *Fn = BB->getParent();
10437 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10438 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10439 Fn->insert(BBI, RSBBB);
10440 Fn->insert(BBI, SinkBB);
10442 Register ABSSrcReg = MI.getOperand(1).getReg();
10443 Register ABSDstReg = MI.getOperand(0).getReg();
10444 bool ABSSrcKIll = MI.getOperand(1).isKill();
10445 bool isThumb2 = Subtarget->isThumb2();
10446 MachineRegisterInfo &MRI = Fn->getRegInfo();
10447 // In Thumb mode S must not be specified if source register is the SP or
10448 // PC and if destination register is the SP, so restrict register class
10449 Register NewRsbDstReg = MRI.createVirtualRegister(
10450 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10452 // Transfer the remainder of BB and its successor edges to sinkMBB.
10453 SinkBB->splice(SinkBB->begin(), BB,
10454 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10455 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10457 BB->addSuccessor(RSBBB);
10458 BB->addSuccessor(SinkBB);
10460 // fall through to SinkMBB
10461 RSBBB->addSuccessor(SinkBB);
10463 // insert a cmp at the end of BB
10464 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10465 .addReg(ABSSrcReg)
10466 .addImm(0)
10467 .add(predOps(ARMCC::AL));
10469 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10470 BuildMI(BB, dl,
10471 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10472 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10474 // insert rsbri in RSBBB
10475 // Note: BCC and rsbri will be converted into predicated rsbmi
10476 // by if-conversion pass
10477 BuildMI(*RSBBB, RSBBB->begin(), dl,
10478 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10479 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10480 .addImm(0)
10481 .add(predOps(ARMCC::AL))
10482 .add(condCodeOp());
10484 // insert PHI in SinkBB,
10485 // reuse ABSDstReg to not change uses of ABS instruction
10486 BuildMI(*SinkBB, SinkBB->begin(), dl,
10487 TII->get(ARM::PHI), ABSDstReg)
10488 .addReg(NewRsbDstReg).addMBB(RSBBB)
10489 .addReg(ABSSrcReg).addMBB(BB);
10491 // remove ABS instruction
10492 MI.eraseFromParent();
10494 // return last added BB
10495 return SinkBB;
10497 case ARM::COPY_STRUCT_BYVAL_I32:
10498 ++NumLoopByVals;
10499 return EmitStructByval(MI, BB);
10500 case ARM::WIN__CHKSTK:
10501 return EmitLowered__chkstk(MI, BB);
10502 case ARM::WIN__DBZCHK:
10503 return EmitLowered__dbzchk(MI, BB);
10507 /// Attaches vregs to MEMCPY that it will use as scratch registers
10508 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10509 /// instead of as a custom inserter because we need the use list from the SDNode.
10510 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10511 MachineInstr &MI, const SDNode *Node) {
10512 bool isThumb1 = Subtarget->isThumb1Only();
10514 DebugLoc DL = MI.getDebugLoc();
10515 MachineFunction *MF = MI.getParent()->getParent();
10516 MachineRegisterInfo &MRI = MF->getRegInfo();
10517 MachineInstrBuilder MIB(*MF, MI);
10519 // If the new dst/src is unused mark it as dead.
10520 if (!Node->hasAnyUseOfValue(0)) {
10521 MI.getOperand(0).setIsDead(true);
10523 if (!Node->hasAnyUseOfValue(1)) {
10524 MI.getOperand(1).setIsDead(true);
10527 // The MEMCPY both defines and kills the scratch registers.
10528 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10529 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10530 : &ARM::GPRRegClass);
10531 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10535 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10536 SDNode *Node) const {
10537 if (MI.getOpcode() == ARM::MEMCPY) {
10538 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10539 return;
10542 const MCInstrDesc *MCID = &MI.getDesc();
10543 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10544 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10545 // operand is still set to noreg. If needed, set the optional operand's
10546 // register to CPSR, and remove the redundant implicit def.
10548 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10550 // Rename pseudo opcodes.
10551 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10552 unsigned ccOutIdx;
10553 if (NewOpc) {
10554 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10555 MCID = &TII->get(NewOpc);
10557 assert(MCID->getNumOperands() ==
10558 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10559 && "converted opcode should be the same except for cc_out"
10560 " (and, on Thumb1, pred)");
10562 MI.setDesc(*MCID);
10564 // Add the optional cc_out operand
10565 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10567 // On Thumb1, move all input operands to the end, then add the predicate
10568 if (Subtarget->isThumb1Only()) {
10569 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10570 MI.addOperand(MI.getOperand(1));
10571 MI.RemoveOperand(1);
10574 // Restore the ties
10575 for (unsigned i = MI.getNumOperands(); i--;) {
10576 const MachineOperand& op = MI.getOperand(i);
10577 if (op.isReg() && op.isUse()) {
10578 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10579 if (DefIdx != -1)
10580 MI.tieOperands(DefIdx, i);
10584 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10585 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10586 ccOutIdx = 1;
10587 } else
10588 ccOutIdx = MCID->getNumOperands() - 1;
10589 } else
10590 ccOutIdx = MCID->getNumOperands() - 1;
10592 // Any ARM instruction that sets the 's' bit should specify an optional
10593 // "cc_out" operand in the last operand position.
10594 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10595 assert(!NewOpc && "Optional cc_out operand required");
10596 return;
10598 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10599 // since we already have an optional CPSR def.
10600 bool definesCPSR = false;
10601 bool deadCPSR = false;
10602 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10603 ++i) {
10604 const MachineOperand &MO = MI.getOperand(i);
10605 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10606 definesCPSR = true;
10607 if (MO.isDead())
10608 deadCPSR = true;
10609 MI.RemoveOperand(i);
10610 break;
10613 if (!definesCPSR) {
10614 assert(!NewOpc && "Optional cc_out operand required");
10615 return;
10617 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10618 if (deadCPSR) {
10619 assert(!MI.getOperand(ccOutIdx).getReg() &&
10620 "expect uninitialized optional cc_out operand");
10621 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10622 if (!Subtarget->isThumb1Only())
10623 return;
10626 // If this instruction was defined with an optional CPSR def and its dag node
10627 // had a live implicit CPSR def, then activate the optional CPSR def.
10628 MachineOperand &MO = MI.getOperand(ccOutIdx);
10629 MO.setReg(ARM::CPSR);
10630 MO.setIsDef(true);
10633 //===----------------------------------------------------------------------===//
10634 // ARM Optimization Hooks
10635 //===----------------------------------------------------------------------===//
10637 // Helper function that checks if N is a null or all ones constant.
10638 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10639 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10642 // Return true if N is conditionally 0 or all ones.
10643 // Detects these expressions where cc is an i1 value:
10645 // (select cc 0, y) [AllOnes=0]
10646 // (select cc y, 0) [AllOnes=0]
10647 // (zext cc) [AllOnes=0]
10648 // (sext cc) [AllOnes=0/1]
10649 // (select cc -1, y) [AllOnes=1]
10650 // (select cc y, -1) [AllOnes=1]
10652 // Invert is set when N is the null/all ones constant when CC is false.
10653 // OtherOp is set to the alternative value of N.
10654 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10655 SDValue &CC, bool &Invert,
10656 SDValue &OtherOp,
10657 SelectionDAG &DAG) {
10658 switch (N->getOpcode()) {
10659 default: return false;
10660 case ISD::SELECT: {
10661 CC = N->getOperand(0);
10662 SDValue N1 = N->getOperand(1);
10663 SDValue N2 = N->getOperand(2);
10664 if (isZeroOrAllOnes(N1, AllOnes)) {
10665 Invert = false;
10666 OtherOp = N2;
10667 return true;
10669 if (isZeroOrAllOnes(N2, AllOnes)) {
10670 Invert = true;
10671 OtherOp = N1;
10672 return true;
10674 return false;
10676 case ISD::ZERO_EXTEND:
10677 // (zext cc) can never be the all ones value.
10678 if (AllOnes)
10679 return false;
10680 LLVM_FALLTHROUGH;
10681 case ISD::SIGN_EXTEND: {
10682 SDLoc dl(N);
10683 EVT VT = N->getValueType(0);
10684 CC = N->getOperand(0);
10685 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10686 return false;
10687 Invert = !AllOnes;
10688 if (AllOnes)
10689 // When looking for an AllOnes constant, N is an sext, and the 'other'
10690 // value is 0.
10691 OtherOp = DAG.getConstant(0, dl, VT);
10692 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10693 // When looking for a 0 constant, N can be zext or sext.
10694 OtherOp = DAG.getConstant(1, dl, VT);
10695 else
10696 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10697 VT);
10698 return true;
10703 // Combine a constant select operand into its use:
10705 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10706 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10707 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10708 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10709 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10711 // The transform is rejected if the select doesn't have a constant operand that
10712 // is null, or all ones when AllOnes is set.
10714 // Also recognize sext/zext from i1:
10716 // (add (zext cc), x) -> (select cc (add x, 1), x)
10717 // (add (sext cc), x) -> (select cc (add x, -1), x)
10719 // These transformations eventually create predicated instructions.
10721 // @param N The node to transform.
10722 // @param Slct The N operand that is a select.
10723 // @param OtherOp The other N operand (x above).
10724 // @param DCI Context.
10725 // @param AllOnes Require the select constant to be all ones instead of null.
10726 // @returns The new node, or SDValue() on failure.
10727 static
10728 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10729 TargetLowering::DAGCombinerInfo &DCI,
10730 bool AllOnes = false) {
10731 SelectionDAG &DAG = DCI.DAG;
10732 EVT VT = N->getValueType(0);
10733 SDValue NonConstantVal;
10734 SDValue CCOp;
10735 bool SwapSelectOps;
10736 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10737 NonConstantVal, DAG))
10738 return SDValue();
10740 // Slct is now know to be the desired identity constant when CC is true.
10741 SDValue TrueVal = OtherOp;
10742 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10743 OtherOp, NonConstantVal);
10744 // Unless SwapSelectOps says CC should be false.
10745 if (SwapSelectOps)
10746 std::swap(TrueVal, FalseVal);
10748 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10749 CCOp, TrueVal, FalseVal);
10752 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10753 static
10754 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10755 TargetLowering::DAGCombinerInfo &DCI) {
10756 SDValue N0 = N->getOperand(0);
10757 SDValue N1 = N->getOperand(1);
10758 if (N0.getNode()->hasOneUse())
10759 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10760 return Result;
10761 if (N1.getNode()->hasOneUse())
10762 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10763 return Result;
10764 return SDValue();
10767 static bool IsVUZPShuffleNode(SDNode *N) {
10768 // VUZP shuffle node.
10769 if (N->getOpcode() == ARMISD::VUZP)
10770 return true;
10772 // "VUZP" on i32 is an alias for VTRN.
10773 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10774 return true;
10776 return false;
10779 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10780 TargetLowering::DAGCombinerInfo &DCI,
10781 const ARMSubtarget *Subtarget) {
10782 // Look for ADD(VUZP.0, VUZP.1).
10783 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10784 N0 == N1)
10785 return SDValue();
10787 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10788 if (!N->getValueType(0).is64BitVector())
10789 return SDValue();
10791 // Generate vpadd.
10792 SelectionDAG &DAG = DCI.DAG;
10793 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10794 SDLoc dl(N);
10795 SDNode *Unzip = N0.getNode();
10796 EVT VT = N->getValueType(0);
10798 SmallVector<SDValue, 8> Ops;
10799 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10800 TLI.getPointerTy(DAG.getDataLayout())));
10801 Ops.push_back(Unzip->getOperand(0));
10802 Ops.push_back(Unzip->getOperand(1));
10804 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10807 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10808 TargetLowering::DAGCombinerInfo &DCI,
10809 const ARMSubtarget *Subtarget) {
10810 // Check for two extended operands.
10811 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10812 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10813 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10814 N1.getOpcode() == ISD::ZERO_EXTEND))
10815 return SDValue();
10817 SDValue N00 = N0.getOperand(0);
10818 SDValue N10 = N1.getOperand(0);
10820 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10821 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10822 N00 == N10)
10823 return SDValue();
10825 // We only recognize Q register paddl here; this can't be reached until
10826 // after type legalization.
10827 if (!N00.getValueType().is64BitVector() ||
10828 !N0.getValueType().is128BitVector())
10829 return SDValue();
10831 // Generate vpaddl.
10832 SelectionDAG &DAG = DCI.DAG;
10833 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10834 SDLoc dl(N);
10835 EVT VT = N->getValueType(0);
10837 SmallVector<SDValue, 8> Ops;
10838 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10839 unsigned Opcode;
10840 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10841 Opcode = Intrinsic::arm_neon_vpaddls;
10842 else
10843 Opcode = Intrinsic::arm_neon_vpaddlu;
10844 Ops.push_back(DAG.getConstant(Opcode, dl,
10845 TLI.getPointerTy(DAG.getDataLayout())));
10846 EVT ElemTy = N00.getValueType().getVectorElementType();
10847 unsigned NumElts = VT.getVectorNumElements();
10848 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10849 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10850 N00.getOperand(0), N00.getOperand(1));
10851 Ops.push_back(Concat);
10853 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10856 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10857 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10858 // much easier to match.
10859 static SDValue
10860 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10861 TargetLowering::DAGCombinerInfo &DCI,
10862 const ARMSubtarget *Subtarget) {
10863 // Only perform optimization if after legalize, and if NEON is available. We
10864 // also expected both operands to be BUILD_VECTORs.
10865 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10866 || N0.getOpcode() != ISD::BUILD_VECTOR
10867 || N1.getOpcode() != ISD::BUILD_VECTOR)
10868 return SDValue();
10870 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10871 EVT VT = N->getValueType(0);
10872 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10873 return SDValue();
10875 // Check that the vector operands are of the right form.
10876 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
10877 // operands, where N is the size of the formed vector.
10878 // Each EXTRACT_VECTOR should have the same input vector and odd or even
10879 // index such that we have a pair wise add pattern.
10881 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
10882 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10883 return SDValue();
10884 SDValue Vec = N0->getOperand(0)->getOperand(0);
10885 SDNode *V = Vec.getNode();
10886 unsigned nextIndex = 0;
10888 // For each operands to the ADD which are BUILD_VECTORs,
10889 // check to see if each of their operands are an EXTRACT_VECTOR with
10890 // the same vector and appropriate index.
10891 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
10892 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
10893 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10895 SDValue ExtVec0 = N0->getOperand(i);
10896 SDValue ExtVec1 = N1->getOperand(i);
10898 // First operand is the vector, verify its the same.
10899 if (V != ExtVec0->getOperand(0).getNode() ||
10900 V != ExtVec1->getOperand(0).getNode())
10901 return SDValue();
10903 // Second is the constant, verify its correct.
10904 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
10905 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
10907 // For the constant, we want to see all the even or all the odd.
10908 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
10909 || C1->getZExtValue() != nextIndex+1)
10910 return SDValue();
10912 // Increment index.
10913 nextIndex+=2;
10914 } else
10915 return SDValue();
10918 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
10919 // we're using the entire input vector, otherwise there's a size/legality
10920 // mismatch somewhere.
10921 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10922 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10923 return SDValue();
10925 // Create VPADDL node.
10926 SelectionDAG &DAG = DCI.DAG;
10927 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10929 SDLoc dl(N);
10931 // Build operand list.
10932 SmallVector<SDValue, 8> Ops;
10933 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10934 TLI.getPointerTy(DAG.getDataLayout())));
10936 // Input is the vector.
10937 Ops.push_back(Vec);
10939 // Get widened type and narrowed type.
10940 MVT widenType;
10941 unsigned numElem = VT.getVectorNumElements();
10943 EVT inputLaneType = Vec.getValueType().getVectorElementType();
10944 switch (inputLaneType.getSimpleVT().SimpleTy) {
10945 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10946 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10947 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10948 default:
10949 llvm_unreachable("Invalid vector element type for padd optimization.");
10952 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
10953 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
10954 return DAG.getNode(ExtOp, dl, VT, tmp);
10957 static SDValue findMUL_LOHI(SDValue V) {
10958 if (V->getOpcode() == ISD::UMUL_LOHI ||
10959 V->getOpcode() == ISD::SMUL_LOHI)
10960 return V;
10961 return SDValue();
10964 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
10965 TargetLowering::DAGCombinerInfo &DCI,
10966 const ARMSubtarget *Subtarget) {
10967 if (Subtarget->isThumb()) {
10968 if (!Subtarget->hasDSP())
10969 return SDValue();
10970 } else if (!Subtarget->hasV5TEOps())
10971 return SDValue();
10973 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10974 // accumulates the product into a 64-bit value. The 16-bit values will
10975 // be sign extended somehow or SRA'd into 32-bit values
10976 // (addc (adde (mul 16bit, 16bit), lo), hi)
10977 SDValue Mul = AddcNode->getOperand(0);
10978 SDValue Lo = AddcNode->getOperand(1);
10979 if (Mul.getOpcode() != ISD::MUL) {
10980 Lo = AddcNode->getOperand(0);
10981 Mul = AddcNode->getOperand(1);
10982 if (Mul.getOpcode() != ISD::MUL)
10983 return SDValue();
10986 SDValue SRA = AddeNode->getOperand(0);
10987 SDValue Hi = AddeNode->getOperand(1);
10988 if (SRA.getOpcode() != ISD::SRA) {
10989 SRA = AddeNode->getOperand(1);
10990 Hi = AddeNode->getOperand(0);
10991 if (SRA.getOpcode() != ISD::SRA)
10992 return SDValue();
10994 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10995 if (Const->getZExtValue() != 31)
10996 return SDValue();
10997 } else
10998 return SDValue();
11000 if (SRA.getOperand(0) != Mul)
11001 return SDValue();
11003 SelectionDAG &DAG = DCI.DAG;
11004 SDLoc dl(AddcNode);
11005 unsigned Opcode = 0;
11006 SDValue Op0;
11007 SDValue Op1;
11009 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11010 Opcode = ARMISD::SMLALBB;
11011 Op0 = Mul.getOperand(0);
11012 Op1 = Mul.getOperand(1);
11013 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11014 Opcode = ARMISD::SMLALBT;
11015 Op0 = Mul.getOperand(0);
11016 Op1 = Mul.getOperand(1).getOperand(0);
11017 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11018 Opcode = ARMISD::SMLALTB;
11019 Op0 = Mul.getOperand(0).getOperand(0);
11020 Op1 = Mul.getOperand(1);
11021 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11022 Opcode = ARMISD::SMLALTT;
11023 Op0 = Mul->getOperand(0).getOperand(0);
11024 Op1 = Mul->getOperand(1).getOperand(0);
11027 if (!Op0 || !Op1)
11028 return SDValue();
11030 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11031 Op0, Op1, Lo, Hi);
11032 // Replace the ADDs' nodes uses by the MLA node's values.
11033 SDValue HiMLALResult(SMLAL.getNode(), 1);
11034 SDValue LoMLALResult(SMLAL.getNode(), 0);
11036 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11037 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11039 // Return original node to notify the driver to stop replacing.
11040 SDValue resNode(AddcNode, 0);
11041 return resNode;
11044 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11045 TargetLowering::DAGCombinerInfo &DCI,
11046 const ARMSubtarget *Subtarget) {
11047 // Look for multiply add opportunities.
11048 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11049 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11050 // a glue link from the first add to the second add.
11051 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11052 // a S/UMLAL instruction.
11053 // UMUL_LOHI
11054 // / :lo \ :hi
11055 // V \ [no multiline comment]
11056 // loAdd -> ADDC |
11057 // \ :carry /
11058 // V V
11059 // ADDE <- hiAdd
11061 // In the special case where only the higher part of a signed result is used
11062 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11063 // a constant with the exact value of 0x80000000, we recognize we are dealing
11064 // with a "rounded multiply and add" (or subtract) and transform it into
11065 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11067 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11068 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11069 "Expect an ADDE or SUBE");
11071 assert(AddeSubeNode->getNumOperands() == 3 &&
11072 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11073 "ADDE node has the wrong inputs");
11075 // Check that we are chained to the right ADDC or SUBC node.
11076 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11077 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11078 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11079 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11080 AddcSubcNode->getOpcode() != ARMISD::SUBC))
11081 return SDValue();
11083 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11084 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11086 // Check if the two operands are from the same mul_lohi node.
11087 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11088 return SDValue();
11090 assert(AddcSubcNode->getNumValues() == 2 &&
11091 AddcSubcNode->getValueType(0) == MVT::i32 &&
11092 "Expect ADDC with two result values. First: i32");
11094 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11095 // maybe a SMLAL which multiplies two 16-bit values.
11096 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11097 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11098 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11099 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11100 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11101 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11103 // Check for the triangle shape.
11104 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11105 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11107 // Make sure that the ADDE/SUBE operands are not coming from the same node.
11108 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11109 return SDValue();
11111 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11112 bool IsLeftOperandMUL = false;
11113 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11114 if (MULOp == SDValue())
11115 MULOp = findMUL_LOHI(AddeSubeOp1);
11116 else
11117 IsLeftOperandMUL = true;
11118 if (MULOp == SDValue())
11119 return SDValue();
11121 // Figure out the right opcode.
11122 unsigned Opc = MULOp->getOpcode();
11123 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11125 // Figure out the high and low input values to the MLAL node.
11126 SDValue *HiAddSub = nullptr;
11127 SDValue *LoMul = nullptr;
11128 SDValue *LowAddSub = nullptr;
11130 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11131 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11132 return SDValue();
11134 if (IsLeftOperandMUL)
11135 HiAddSub = &AddeSubeOp1;
11136 else
11137 HiAddSub = &AddeSubeOp0;
11139 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11140 // whose low result is fed to the ADDC/SUBC we are checking.
11142 if (AddcSubcOp0 == MULOp.getValue(0)) {
11143 LoMul = &AddcSubcOp0;
11144 LowAddSub = &AddcSubcOp1;
11146 if (AddcSubcOp1 == MULOp.getValue(0)) {
11147 LoMul = &AddcSubcOp1;
11148 LowAddSub = &AddcSubcOp0;
11151 if (!LoMul)
11152 return SDValue();
11154 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11155 // the replacement below will create a cycle.
11156 if (AddcSubcNode == HiAddSub->getNode() ||
11157 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11158 return SDValue();
11160 // Create the merged node.
11161 SelectionDAG &DAG = DCI.DAG;
11163 // Start building operand list.
11164 SmallVector<SDValue, 8> Ops;
11165 Ops.push_back(LoMul->getOperand(0));
11166 Ops.push_back(LoMul->getOperand(1));
11168 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
11169 // the case, we must be doing signed multiplication and only use the higher
11170 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11171 // addition or subtraction with the value of 0x800000.
11172 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11173 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11174 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11175 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11176 0x80000000) {
11177 Ops.push_back(*HiAddSub);
11178 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11179 FinalOpc = ARMISD::SMMLSR;
11180 } else {
11181 FinalOpc = ARMISD::SMMLAR;
11183 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11184 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11186 return SDValue(AddeSubeNode, 0);
11187 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11188 // SMMLS is generated during instruction selection and the rest of this
11189 // function can not handle the case where AddcSubcNode is a SUBC.
11190 return SDValue();
11192 // Finish building the operand list for {U/S}MLAL
11193 Ops.push_back(*LowAddSub);
11194 Ops.push_back(*HiAddSub);
11196 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11197 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11199 // Replace the ADDs' nodes uses by the MLA node's values.
11200 SDValue HiMLALResult(MLALNode.getNode(), 1);
11201 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11203 SDValue LoMLALResult(MLALNode.getNode(), 0);
11204 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11206 // Return original node to notify the driver to stop replacing.
11207 return SDValue(AddeSubeNode, 0);
11210 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11211 TargetLowering::DAGCombinerInfo &DCI,
11212 const ARMSubtarget *Subtarget) {
11213 // UMAAL is similar to UMLAL except that it adds two unsigned values.
11214 // While trying to combine for the other MLAL nodes, first search for the
11215 // chance to use UMAAL. Check if Addc uses a node which has already
11216 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11217 // as the addend, and it's handled in PerformUMLALCombine.
11219 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11220 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11222 // Check that we have a glued ADDC node.
11223 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11224 if (AddcNode->getOpcode() != ARMISD::ADDC)
11225 return SDValue();
11227 // Find the converted UMAAL or quit if it doesn't exist.
11228 SDNode *UmlalNode = nullptr;
11229 SDValue AddHi;
11230 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11231 UmlalNode = AddcNode->getOperand(0).getNode();
11232 AddHi = AddcNode->getOperand(1);
11233 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11234 UmlalNode = AddcNode->getOperand(1).getNode();
11235 AddHi = AddcNode->getOperand(0);
11236 } else {
11237 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11240 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11241 // the ADDC as well as Zero.
11242 if (!isNullConstant(UmlalNode->getOperand(3)))
11243 return SDValue();
11245 if ((isNullConstant(AddeNode->getOperand(0)) &&
11246 AddeNode->getOperand(1).getNode() == UmlalNode) ||
11247 (AddeNode->getOperand(0).getNode() == UmlalNode &&
11248 isNullConstant(AddeNode->getOperand(1)))) {
11249 SelectionDAG &DAG = DCI.DAG;
11250 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11251 UmlalNode->getOperand(2), AddHi };
11252 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11253 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11255 // Replace the ADDs' nodes uses by the UMAAL node's values.
11256 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11257 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11259 // Return original node to notify the driver to stop replacing.
11260 return SDValue(AddeNode, 0);
11262 return SDValue();
11265 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11266 const ARMSubtarget *Subtarget) {
11267 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11268 return SDValue();
11270 // Check that we have a pair of ADDC and ADDE as operands.
11271 // Both addends of the ADDE must be zero.
11272 SDNode* AddcNode = N->getOperand(2).getNode();
11273 SDNode* AddeNode = N->getOperand(3).getNode();
11274 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11275 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11276 isNullConstant(AddeNode->getOperand(0)) &&
11277 isNullConstant(AddeNode->getOperand(1)) &&
11278 (AddeNode->getOperand(2).getNode() == AddcNode))
11279 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11280 DAG.getVTList(MVT::i32, MVT::i32),
11281 {N->getOperand(0), N->getOperand(1),
11282 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11283 else
11284 return SDValue();
11287 static SDValue PerformAddcSubcCombine(SDNode *N,
11288 TargetLowering::DAGCombinerInfo &DCI,
11289 const ARMSubtarget *Subtarget) {
11290 SelectionDAG &DAG(DCI.DAG);
11292 if (N->getOpcode() == ARMISD::SUBC) {
11293 // (SUBC (ADDE 0, 0, C), 1) -> C
11294 SDValue LHS = N->getOperand(0);
11295 SDValue RHS = N->getOperand(1);
11296 if (LHS->getOpcode() == ARMISD::ADDE &&
11297 isNullConstant(LHS->getOperand(0)) &&
11298 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11299 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11303 if (Subtarget->isThumb1Only()) {
11304 SDValue RHS = N->getOperand(1);
11305 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11306 int32_t imm = C->getSExtValue();
11307 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11308 SDLoc DL(N);
11309 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11310 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11311 : ARMISD::ADDC;
11312 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11317 return SDValue();
11320 static SDValue PerformAddeSubeCombine(SDNode *N,
11321 TargetLowering::DAGCombinerInfo &DCI,
11322 const ARMSubtarget *Subtarget) {
11323 if (Subtarget->isThumb1Only()) {
11324 SelectionDAG &DAG = DCI.DAG;
11325 SDValue RHS = N->getOperand(1);
11326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11327 int64_t imm = C->getSExtValue();
11328 if (imm < 0) {
11329 SDLoc DL(N);
11331 // The with-carry-in form matches bitwise not instead of the negation.
11332 // Effectively, the inverse interpretation of the carry flag already
11333 // accounts for part of the negation.
11334 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11336 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11337 : ARMISD::ADDE;
11338 return DAG.getNode(Opcode, DL, N->getVTList(),
11339 N->getOperand(0), RHS, N->getOperand(2));
11342 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11343 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11345 return SDValue();
11348 static SDValue PerformABSCombine(SDNode *N,
11349 TargetLowering::DAGCombinerInfo &DCI,
11350 const ARMSubtarget *Subtarget) {
11351 SDValue res;
11352 SelectionDAG &DAG = DCI.DAG;
11353 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11355 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11356 return SDValue();
11358 if (!TLI.expandABS(N, res, DAG))
11359 return SDValue();
11361 return res;
11364 /// PerformADDECombine - Target-specific dag combine transform from
11365 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11366 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11367 static SDValue PerformADDECombine(SDNode *N,
11368 TargetLowering::DAGCombinerInfo &DCI,
11369 const ARMSubtarget *Subtarget) {
11370 // Only ARM and Thumb2 support UMLAL/SMLAL.
11371 if (Subtarget->isThumb1Only())
11372 return PerformAddeSubeCombine(N, DCI, Subtarget);
11374 // Only perform the checks after legalize when the pattern is available.
11375 if (DCI.isBeforeLegalize()) return SDValue();
11377 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11380 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11381 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11382 /// called with the default operands, and if that fails, with commuted
11383 /// operands.
11384 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11385 TargetLowering::DAGCombinerInfo &DCI,
11386 const ARMSubtarget *Subtarget){
11387 // Attempt to create vpadd for this add.
11388 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11389 return Result;
11391 // Attempt to create vpaddl for this add.
11392 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11393 return Result;
11394 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11395 Subtarget))
11396 return Result;
11398 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11399 if (N0.getNode()->hasOneUse())
11400 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11401 return Result;
11402 return SDValue();
11405 bool
11406 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11407 CombineLevel Level) const {
11408 if (Level == BeforeLegalizeTypes)
11409 return true;
11411 if (N->getOpcode() != ISD::SHL)
11412 return true;
11414 if (Subtarget->isThumb1Only()) {
11415 // Avoid making expensive immediates by commuting shifts. (This logic
11416 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11417 // for free.)
11418 if (N->getOpcode() != ISD::SHL)
11419 return true;
11420 SDValue N1 = N->getOperand(0);
11421 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11422 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11423 return true;
11424 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11425 if (Const->getAPIntValue().ult(256))
11426 return false;
11427 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11428 Const->getAPIntValue().sgt(-256))
11429 return false;
11431 return true;
11434 // Turn off commute-with-shift transform after legalization, so it doesn't
11435 // conflict with PerformSHLSimplify. (We could try to detect when
11436 // PerformSHLSimplify would trigger more precisely, but it isn't
11437 // really necessary.)
11438 return false;
11441 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11442 const SDNode *N, CombineLevel Level) const {
11443 if (!Subtarget->isThumb1Only())
11444 return true;
11446 if (Level == BeforeLegalizeTypes)
11447 return true;
11449 return false;
11452 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11453 if (!Subtarget->hasNEON()) {
11454 if (Subtarget->isThumb1Only())
11455 return VT.getScalarSizeInBits() <= 32;
11456 return true;
11458 return VT.isScalarInteger();
11461 static SDValue PerformSHLSimplify(SDNode *N,
11462 TargetLowering::DAGCombinerInfo &DCI,
11463 const ARMSubtarget *ST) {
11464 // Allow the generic combiner to identify potential bswaps.
11465 if (DCI.isBeforeLegalize())
11466 return SDValue();
11468 // DAG combiner will fold:
11469 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11470 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11471 // Other code patterns that can be also be modified have the following form:
11472 // b + ((a << 1) | 510)
11473 // b + ((a << 1) & 510)
11474 // b + ((a << 1) ^ 510)
11475 // b + ((a << 1) + 510)
11477 // Many instructions can perform the shift for free, but it requires both
11478 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11479 // instruction will needed. So, unfold back to the original pattern if:
11480 // - if c1 and c2 are small enough that they don't require mov imms.
11481 // - the user(s) of the node can perform an shl
11483 // No shifted operands for 16-bit instructions.
11484 if (ST->isThumb() && ST->isThumb1Only())
11485 return SDValue();
11487 // Check that all the users could perform the shl themselves.
11488 for (auto U : N->uses()) {
11489 switch(U->getOpcode()) {
11490 default:
11491 return SDValue();
11492 case ISD::SUB:
11493 case ISD::ADD:
11494 case ISD::AND:
11495 case ISD::OR:
11496 case ISD::XOR:
11497 case ISD::SETCC:
11498 case ARMISD::CMP:
11499 // Check that the user isn't already using a constant because there
11500 // aren't any instructions that support an immediate operand and a
11501 // shifted operand.
11502 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11503 isa<ConstantSDNode>(U->getOperand(1)))
11504 return SDValue();
11506 // Check that it's not already using a shift.
11507 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11508 U->getOperand(1).getOpcode() == ISD::SHL)
11509 return SDValue();
11510 break;
11514 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11515 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11516 return SDValue();
11518 if (N->getOperand(0).getOpcode() != ISD::SHL)
11519 return SDValue();
11521 SDValue SHL = N->getOperand(0);
11523 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11524 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11525 if (!C1ShlC2 || !C2)
11526 return SDValue();
11528 APInt C2Int = C2->getAPIntValue();
11529 APInt C1Int = C1ShlC2->getAPIntValue();
11531 // Check that performing a lshr will not lose any information.
11532 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11533 C2Int.getBitWidth() - C2->getZExtValue());
11534 if ((C1Int & Mask) != C1Int)
11535 return SDValue();
11537 // Shift the first constant.
11538 C1Int.lshrInPlace(C2Int);
11540 // The immediates are encoded as an 8-bit value that can be rotated.
11541 auto LargeImm = [](const APInt &Imm) {
11542 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11543 return Imm.getBitWidth() - Zeros > 8;
11546 if (LargeImm(C1Int) || LargeImm(C2Int))
11547 return SDValue();
11549 SelectionDAG &DAG = DCI.DAG;
11550 SDLoc dl(N);
11551 SDValue X = SHL.getOperand(0);
11552 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11553 DAG.getConstant(C1Int, dl, MVT::i32));
11554 // Shift left to compensate for the lshr of C1Int.
11555 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11557 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11558 SHL.dump(); N->dump());
11559 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11560 return Res;
11564 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11566 static SDValue PerformADDCombine(SDNode *N,
11567 TargetLowering::DAGCombinerInfo &DCI,
11568 const ARMSubtarget *Subtarget) {
11569 SDValue N0 = N->getOperand(0);
11570 SDValue N1 = N->getOperand(1);
11572 // Only works one way, because it needs an immediate operand.
11573 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11574 return Result;
11576 // First try with the default operand order.
11577 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11578 return Result;
11580 // If that didn't work, try again with the operands commuted.
11581 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11584 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11586 static SDValue PerformSUBCombine(SDNode *N,
11587 TargetLowering::DAGCombinerInfo &DCI) {
11588 SDValue N0 = N->getOperand(0);
11589 SDValue N1 = N->getOperand(1);
11591 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11592 if (N1.getNode()->hasOneUse())
11593 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11594 return Result;
11596 return SDValue();
11599 /// PerformVMULCombine
11600 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11601 /// special multiplier accumulator forwarding.
11602 /// vmul d3, d0, d2
11603 /// vmla d3, d1, d2
11604 /// is faster than
11605 /// vadd d3, d0, d1
11606 /// vmul d3, d3, d2
11607 // However, for (A + B) * (A + B),
11608 // vadd d2, d0, d1
11609 // vmul d3, d0, d2
11610 // vmla d3, d1, d2
11611 // is slower than
11612 // vadd d2, d0, d1
11613 // vmul d3, d2, d2
11614 static SDValue PerformVMULCombine(SDNode *N,
11615 TargetLowering::DAGCombinerInfo &DCI,
11616 const ARMSubtarget *Subtarget) {
11617 if (!Subtarget->hasVMLxForwarding())
11618 return SDValue();
11620 SelectionDAG &DAG = DCI.DAG;
11621 SDValue N0 = N->getOperand(0);
11622 SDValue N1 = N->getOperand(1);
11623 unsigned Opcode = N0.getOpcode();
11624 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11625 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11626 Opcode = N1.getOpcode();
11627 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11628 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11629 return SDValue();
11630 std::swap(N0, N1);
11633 if (N0 == N1)
11634 return SDValue();
11636 EVT VT = N->getValueType(0);
11637 SDLoc DL(N);
11638 SDValue N00 = N0->getOperand(0);
11639 SDValue N01 = N0->getOperand(1);
11640 return DAG.getNode(Opcode, DL, VT,
11641 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11642 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11645 static SDValue PerformMULCombine(SDNode *N,
11646 TargetLowering::DAGCombinerInfo &DCI,
11647 const ARMSubtarget *Subtarget) {
11648 SelectionDAG &DAG = DCI.DAG;
11650 if (Subtarget->isThumb1Only())
11651 return SDValue();
11653 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11654 return SDValue();
11656 EVT VT = N->getValueType(0);
11657 if (VT.is64BitVector() || VT.is128BitVector())
11658 return PerformVMULCombine(N, DCI, Subtarget);
11659 if (VT != MVT::i32)
11660 return SDValue();
11662 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11663 if (!C)
11664 return SDValue();
11666 int64_t MulAmt = C->getSExtValue();
11667 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11669 ShiftAmt = ShiftAmt & (32 - 1);
11670 SDValue V = N->getOperand(0);
11671 SDLoc DL(N);
11673 SDValue Res;
11674 MulAmt >>= ShiftAmt;
11676 if (MulAmt >= 0) {
11677 if (isPowerOf2_32(MulAmt - 1)) {
11678 // (mul x, 2^N + 1) => (add (shl x, N), x)
11679 Res = DAG.getNode(ISD::ADD, DL, VT,
11681 DAG.getNode(ISD::SHL, DL, VT,
11683 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11684 MVT::i32)));
11685 } else if (isPowerOf2_32(MulAmt + 1)) {
11686 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11687 Res = DAG.getNode(ISD::SUB, DL, VT,
11688 DAG.getNode(ISD::SHL, DL, VT,
11690 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11691 MVT::i32)),
11693 } else
11694 return SDValue();
11695 } else {
11696 uint64_t MulAmtAbs = -MulAmt;
11697 if (isPowerOf2_32(MulAmtAbs + 1)) {
11698 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11699 Res = DAG.getNode(ISD::SUB, DL, VT,
11701 DAG.getNode(ISD::SHL, DL, VT,
11703 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11704 MVT::i32)));
11705 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11706 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11707 Res = DAG.getNode(ISD::ADD, DL, VT,
11709 DAG.getNode(ISD::SHL, DL, VT,
11711 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11712 MVT::i32)));
11713 Res = DAG.getNode(ISD::SUB, DL, VT,
11714 DAG.getConstant(0, DL, MVT::i32), Res);
11715 } else
11716 return SDValue();
11719 if (ShiftAmt != 0)
11720 Res = DAG.getNode(ISD::SHL, DL, VT,
11721 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11723 // Do not add new nodes to DAG combiner worklist.
11724 DCI.CombineTo(N, Res, false);
11725 return SDValue();
11728 static SDValue CombineANDShift(SDNode *N,
11729 TargetLowering::DAGCombinerInfo &DCI,
11730 const ARMSubtarget *Subtarget) {
11731 // Allow DAGCombine to pattern-match before we touch the canonical form.
11732 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11733 return SDValue();
11735 if (N->getValueType(0) != MVT::i32)
11736 return SDValue();
11738 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11739 if (!N1C)
11740 return SDValue();
11742 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11743 // Don't transform uxtb/uxth.
11744 if (C1 == 255 || C1 == 65535)
11745 return SDValue();
11747 SDNode *N0 = N->getOperand(0).getNode();
11748 if (!N0->hasOneUse())
11749 return SDValue();
11751 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11752 return SDValue();
11754 bool LeftShift = N0->getOpcode() == ISD::SHL;
11756 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11757 if (!N01C)
11758 return SDValue();
11760 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11761 if (!C2 || C2 >= 32)
11762 return SDValue();
11764 // Clear irrelevant bits in the mask.
11765 if (LeftShift)
11766 C1 &= (-1U << C2);
11767 else
11768 C1 &= (-1U >> C2);
11770 SelectionDAG &DAG = DCI.DAG;
11771 SDLoc DL(N);
11773 // We have a pattern of the form "(and (shl x, c2) c1)" or
11774 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11775 // transform to a pair of shifts, to save materializing c1.
11777 // First pattern: right shift, then mask off leading bits.
11778 // FIXME: Use demanded bits?
11779 if (!LeftShift && isMask_32(C1)) {
11780 uint32_t C3 = countLeadingZeros(C1);
11781 if (C2 < C3) {
11782 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11783 DAG.getConstant(C3 - C2, DL, MVT::i32));
11784 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11785 DAG.getConstant(C3, DL, MVT::i32));
11789 // First pattern, reversed: left shift, then mask off trailing bits.
11790 if (LeftShift && isMask_32(~C1)) {
11791 uint32_t C3 = countTrailingZeros(C1);
11792 if (C2 < C3) {
11793 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11794 DAG.getConstant(C3 - C2, DL, MVT::i32));
11795 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11796 DAG.getConstant(C3, DL, MVT::i32));
11800 // Second pattern: left shift, then mask off leading bits.
11801 // FIXME: Use demanded bits?
11802 if (LeftShift && isShiftedMask_32(C1)) {
11803 uint32_t Trailing = countTrailingZeros(C1);
11804 uint32_t C3 = countLeadingZeros(C1);
11805 if (Trailing == C2 && C2 + C3 < 32) {
11806 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11807 DAG.getConstant(C2 + C3, DL, MVT::i32));
11808 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11809 DAG.getConstant(C3, DL, MVT::i32));
11813 // Second pattern, reversed: right shift, then mask off trailing bits.
11814 // FIXME: Handle other patterns of known/demanded bits.
11815 if (!LeftShift && isShiftedMask_32(C1)) {
11816 uint32_t Leading = countLeadingZeros(C1);
11817 uint32_t C3 = countTrailingZeros(C1);
11818 if (Leading == C2 && C2 + C3 < 32) {
11819 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11820 DAG.getConstant(C2 + C3, DL, MVT::i32));
11821 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11822 DAG.getConstant(C3, DL, MVT::i32));
11826 // FIXME: Transform "(and (shl x, c2) c1)" ->
11827 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11828 // c1.
11829 return SDValue();
11832 static SDValue PerformANDCombine(SDNode *N,
11833 TargetLowering::DAGCombinerInfo &DCI,
11834 const ARMSubtarget *Subtarget) {
11835 // Attempt to use immediate-form VBIC
11836 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11837 SDLoc dl(N);
11838 EVT VT = N->getValueType(0);
11839 SelectionDAG &DAG = DCI.DAG;
11841 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11842 return SDValue();
11844 APInt SplatBits, SplatUndef;
11845 unsigned SplatBitSize;
11846 bool HasAnyUndefs;
11847 if (BVN && Subtarget->hasNEON() &&
11848 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11849 if (SplatBitSize <= 64) {
11850 EVT VbicVT;
11851 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11852 SplatUndef.getZExtValue(), SplatBitSize,
11853 DAG, dl, VbicVT, VT.is128BitVector(),
11854 OtherModImm);
11855 if (Val.getNode()) {
11856 SDValue Input =
11857 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11858 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11859 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11864 if (!Subtarget->isThumb1Only()) {
11865 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11866 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11867 return Result;
11869 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11870 return Result;
11873 if (Subtarget->isThumb1Only())
11874 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
11875 return Result;
11877 return SDValue();
11880 // Try combining OR nodes to SMULWB, SMULWT.
11881 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
11882 TargetLowering::DAGCombinerInfo &DCI,
11883 const ARMSubtarget *Subtarget) {
11884 if (!Subtarget->hasV6Ops() ||
11885 (Subtarget->isThumb() &&
11886 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
11887 return SDValue();
11889 SDValue SRL = OR->getOperand(0);
11890 SDValue SHL = OR->getOperand(1);
11892 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
11893 SRL = OR->getOperand(1);
11894 SHL = OR->getOperand(0);
11896 if (!isSRL16(SRL) || !isSHL16(SHL))
11897 return SDValue();
11899 // The first operands to the shifts need to be the two results from the
11900 // same smul_lohi node.
11901 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
11902 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
11903 return SDValue();
11905 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
11906 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
11907 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
11908 return SDValue();
11910 // Now we have:
11911 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
11912 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
11913 // For SMUWB the 16-bit value will signed extended somehow.
11914 // For SMULWT only the SRA is required.
11915 // Check both sides of SMUL_LOHI
11916 SDValue OpS16 = SMULLOHI->getOperand(0);
11917 SDValue OpS32 = SMULLOHI->getOperand(1);
11919 SelectionDAG &DAG = DCI.DAG;
11920 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
11921 OpS16 = OpS32;
11922 OpS32 = SMULLOHI->getOperand(0);
11925 SDLoc dl(OR);
11926 unsigned Opcode = 0;
11927 if (isS16(OpS16, DAG))
11928 Opcode = ARMISD::SMULWB;
11929 else if (isSRA16(OpS16)) {
11930 Opcode = ARMISD::SMULWT;
11931 OpS16 = OpS16->getOperand(0);
11933 else
11934 return SDValue();
11936 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11937 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11938 return SDValue(OR, 0);
11941 static SDValue PerformORCombineToBFI(SDNode *N,
11942 TargetLowering::DAGCombinerInfo &DCI,
11943 const ARMSubtarget *Subtarget) {
11944 // BFI is only available on V6T2+
11945 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11946 return SDValue();
11948 EVT VT = N->getValueType(0);
11949 SDValue N0 = N->getOperand(0);
11950 SDValue N1 = N->getOperand(1);
11951 SelectionDAG &DAG = DCI.DAG;
11952 SDLoc DL(N);
11953 // 1) or (and A, mask), val => ARMbfi A, val, mask
11954 // iff (val & mask) == val
11956 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11957 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
11958 // && mask == ~mask2
11959 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
11960 // && ~mask == mask2
11961 // (i.e., copy a bitfield value into another bitfield of the same width)
11963 if (VT != MVT::i32)
11964 return SDValue();
11966 SDValue N00 = N0.getOperand(0);
11968 // The value and the mask need to be constants so we can verify this is
11969 // actually a bitfield set. If the mask is 0xffff, we can do better
11970 // via a movt instruction, so don't use BFI in that case.
11971 SDValue MaskOp = N0.getOperand(1);
11972 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
11973 if (!MaskC)
11974 return SDValue();
11975 unsigned Mask = MaskC->getZExtValue();
11976 if (Mask == 0xffff)
11977 return SDValue();
11978 SDValue Res;
11979 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
11980 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11981 if (N1C) {
11982 unsigned Val = N1C->getZExtValue();
11983 if ((Val & ~Mask) != Val)
11984 return SDValue();
11986 if (ARM::isBitFieldInvertedMask(Mask)) {
11987 Val >>= countTrailingZeros(~Mask);
11989 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
11990 DAG.getConstant(Val, DL, MVT::i32),
11991 DAG.getConstant(Mask, DL, MVT::i32));
11993 DCI.CombineTo(N, Res, false);
11994 // Return value from the original node to inform the combiner than N is
11995 // now dead.
11996 return SDValue(N, 0);
11998 } else if (N1.getOpcode() == ISD::AND) {
11999 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12000 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12001 if (!N11C)
12002 return SDValue();
12003 unsigned Mask2 = N11C->getZExtValue();
12005 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
12006 // as is to match.
12007 if (ARM::isBitFieldInvertedMask(Mask) &&
12008 (Mask == ~Mask2)) {
12009 // The pack halfword instruction works better for masks that fit it,
12010 // so use that when it's available.
12011 if (Subtarget->hasDSP() &&
12012 (Mask == 0xffff || Mask == 0xffff0000))
12013 return SDValue();
12014 // 2a
12015 unsigned amt = countTrailingZeros(Mask2);
12016 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
12017 DAG.getConstant(amt, DL, MVT::i32));
12018 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
12019 DAG.getConstant(Mask, DL, MVT::i32));
12020 DCI.CombineTo(N, Res, false);
12021 // Return value from the original node to inform the combiner than N is
12022 // now dead.
12023 return SDValue(N, 0);
12024 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
12025 (~Mask == Mask2)) {
12026 // The pack halfword instruction works better for masks that fit it,
12027 // so use that when it's available.
12028 if (Subtarget->hasDSP() &&
12029 (Mask2 == 0xffff || Mask2 == 0xffff0000))
12030 return SDValue();
12031 // 2b
12032 unsigned lsb = countTrailingZeros(Mask);
12033 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
12034 DAG.getConstant(lsb, DL, MVT::i32));
12035 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
12036 DAG.getConstant(Mask2, DL, MVT::i32));
12037 DCI.CombineTo(N, Res, false);
12038 // Return value from the original node to inform the combiner than N is
12039 // now dead.
12040 return SDValue(N, 0);
12044 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
12045 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
12046 ARM::isBitFieldInvertedMask(~Mask)) {
12047 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
12048 // where lsb(mask) == #shamt and masked bits of B are known zero.
12049 SDValue ShAmt = N00.getOperand(1);
12050 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
12051 unsigned LSB = countTrailingZeros(Mask);
12052 if (ShAmtC != LSB)
12053 return SDValue();
12055 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
12056 DAG.getConstant(~Mask, DL, MVT::i32));
12058 DCI.CombineTo(N, Res, false);
12059 // Return value from the original node to inform the combiner than N is
12060 // now dead.
12061 return SDValue(N, 0);
12064 return SDValue();
12067 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12068 switch (CC) {
12069 case ARMCC::EQ:
12070 case ARMCC::NE:
12071 case ARMCC::LE:
12072 case ARMCC::GT:
12073 case ARMCC::GE:
12074 case ARMCC::LT:
12075 return true;
12076 case ARMCC::HS:
12077 case ARMCC::HI:
12078 return !IsFloat;
12079 default:
12080 return false;
12084 static SDValue PerformORCombine_i1(SDNode *N,
12085 TargetLowering::DAGCombinerInfo &DCI,
12086 const ARMSubtarget *Subtarget) {
12087 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12088 // together with predicates
12089 EVT VT = N->getValueType(0);
12090 SDValue N0 = N->getOperand(0);
12091 SDValue N1 = N->getOperand(1);
12093 ARMCC::CondCodes CondCode0 = ARMCC::AL;
12094 ARMCC::CondCodes CondCode1 = ARMCC::AL;
12095 if (N0->getOpcode() == ARMISD::VCMP)
12096 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
12097 ->getZExtValue();
12098 else if (N0->getOpcode() == ARMISD::VCMPZ)
12099 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
12100 ->getZExtValue();
12101 if (N1->getOpcode() == ARMISD::VCMP)
12102 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
12103 ->getZExtValue();
12104 else if (N1->getOpcode() == ARMISD::VCMPZ)
12105 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
12106 ->getZExtValue();
12108 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
12109 return SDValue();
12111 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
12112 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
12114 if (!isValidMVECond(Opposite0,
12115 N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
12116 !isValidMVECond(Opposite1,
12117 N1->getOperand(0)->getValueType(0).isFloatingPoint()))
12118 return SDValue();
12120 SmallVector<SDValue, 4> Ops0;
12121 Ops0.push_back(N0->getOperand(0));
12122 if (N0->getOpcode() == ARMISD::VCMP)
12123 Ops0.push_back(N0->getOperand(1));
12124 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12125 SmallVector<SDValue, 4> Ops1;
12126 Ops1.push_back(N1->getOperand(0));
12127 if (N1->getOpcode() == ARMISD::VCMP)
12128 Ops1.push_back(N1->getOperand(1));
12129 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12131 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12132 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12133 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12134 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12135 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12138 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12139 static SDValue PerformORCombine(SDNode *N,
12140 TargetLowering::DAGCombinerInfo &DCI,
12141 const ARMSubtarget *Subtarget) {
12142 // Attempt to use immediate-form VORR
12143 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12144 SDLoc dl(N);
12145 EVT VT = N->getValueType(0);
12146 SelectionDAG &DAG = DCI.DAG;
12148 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12149 return SDValue();
12151 APInt SplatBits, SplatUndef;
12152 unsigned SplatBitSize;
12153 bool HasAnyUndefs;
12154 if (BVN && Subtarget->hasNEON() &&
12155 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12156 if (SplatBitSize <= 64) {
12157 EVT VorrVT;
12158 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
12159 SplatUndef.getZExtValue(), SplatBitSize,
12160 DAG, dl, VorrVT, VT.is128BitVector(),
12161 OtherModImm);
12162 if (Val.getNode()) {
12163 SDValue Input =
12164 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12165 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12166 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12171 if (!Subtarget->isThumb1Only()) {
12172 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12173 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12174 return Result;
12175 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12176 return Result;
12179 SDValue N0 = N->getOperand(0);
12180 SDValue N1 = N->getOperand(1);
12182 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12183 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12184 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12186 // The code below optimizes (or (and X, Y), Z).
12187 // The AND operand needs to have a single user to make these optimizations
12188 // profitable.
12189 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12190 return SDValue();
12192 APInt SplatUndef;
12193 unsigned SplatBitSize;
12194 bool HasAnyUndefs;
12196 APInt SplatBits0, SplatBits1;
12197 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12198 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12199 // Ensure that the second operand of both ands are constants
12200 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12201 HasAnyUndefs) && !HasAnyUndefs) {
12202 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12203 HasAnyUndefs) && !HasAnyUndefs) {
12204 // Ensure that the bit width of the constants are the same and that
12205 // the splat arguments are logical inverses as per the pattern we
12206 // are trying to simplify.
12207 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12208 SplatBits0 == ~SplatBits1) {
12209 // Canonicalize the vector type to make instruction selection
12210 // simpler.
12211 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12212 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12213 N0->getOperand(1),
12214 N0->getOperand(0),
12215 N1->getOperand(0));
12216 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12222 if (Subtarget->hasMVEIntegerOps() &&
12223 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12224 return PerformORCombine_i1(N, DCI, Subtarget);
12226 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12227 // reasonable.
12228 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12229 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12230 return Res;
12233 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12234 return Result;
12236 return SDValue();
12239 static SDValue PerformXORCombine(SDNode *N,
12240 TargetLowering::DAGCombinerInfo &DCI,
12241 const ARMSubtarget *Subtarget) {
12242 EVT VT = N->getValueType(0);
12243 SelectionDAG &DAG = DCI.DAG;
12245 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12246 return SDValue();
12248 if (!Subtarget->isThumb1Only()) {
12249 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12250 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12251 return Result;
12253 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12254 return Result;
12257 return SDValue();
12260 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12261 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12262 // their position in "to" (Rd).
12263 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12264 assert(N->getOpcode() == ARMISD::BFI);
12266 SDValue From = N->getOperand(1);
12267 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12268 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12270 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12271 // #C in the base of the SHR.
12272 if (From->getOpcode() == ISD::SRL &&
12273 isa<ConstantSDNode>(From->getOperand(1))) {
12274 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12275 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12276 FromMask <<= Shift.getLimitedValue(31);
12277 From = From->getOperand(0);
12280 return From;
12283 // If A and B contain one contiguous set of bits, does A | B == A . B?
12285 // Neither A nor B must be zero.
12286 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12287 unsigned LastActiveBitInA = A.countTrailingZeros();
12288 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12289 return LastActiveBitInA - 1 == FirstActiveBitInB;
12292 static SDValue FindBFIToCombineWith(SDNode *N) {
12293 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12294 // if one exists.
12295 APInt ToMask, FromMask;
12296 SDValue From = ParseBFI(N, ToMask, FromMask);
12297 SDValue To = N->getOperand(0);
12299 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12300 // aren't compatible, but not if they set the same bit in their destination as
12301 // we do (or that of any BFI we're going to combine with).
12302 SDValue V = To;
12303 APInt CombinedToMask = ToMask;
12304 while (V.getOpcode() == ARMISD::BFI) {
12305 APInt NewToMask, NewFromMask;
12306 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12307 if (NewFrom != From) {
12308 // This BFI has a different base. Keep going.
12309 CombinedToMask |= NewToMask;
12310 V = V.getOperand(0);
12311 continue;
12314 // Do the written bits conflict with any we've seen so far?
12315 if ((NewToMask & CombinedToMask).getBoolValue())
12316 // Conflicting bits - bail out because going further is unsafe.
12317 return SDValue();
12319 // Are the new bits contiguous when combined with the old bits?
12320 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12321 BitsProperlyConcatenate(FromMask, NewFromMask))
12322 return V;
12323 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12324 BitsProperlyConcatenate(NewFromMask, FromMask))
12325 return V;
12327 // We've seen a write to some bits, so track it.
12328 CombinedToMask |= NewToMask;
12329 // Keep going...
12330 V = V.getOperand(0);
12333 return SDValue();
12336 static SDValue PerformBFICombine(SDNode *N,
12337 TargetLowering::DAGCombinerInfo &DCI) {
12338 SDValue N1 = N->getOperand(1);
12339 if (N1.getOpcode() == ISD::AND) {
12340 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12341 // the bits being cleared by the AND are not demanded by the BFI.
12342 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12343 if (!N11C)
12344 return SDValue();
12345 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12346 unsigned LSB = countTrailingZeros(~InvMask);
12347 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12348 assert(Width <
12349 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12350 "undefined behavior");
12351 unsigned Mask = (1u << Width) - 1;
12352 unsigned Mask2 = N11C->getZExtValue();
12353 if ((Mask & (~Mask2)) == 0)
12354 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12355 N->getOperand(0), N1.getOperand(0),
12356 N->getOperand(2));
12357 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12358 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12359 // Keep track of any consecutive bits set that all come from the same base
12360 // value. We can combine these together into a single BFI.
12361 SDValue CombineBFI = FindBFIToCombineWith(N);
12362 if (CombineBFI == SDValue())
12363 return SDValue();
12365 // We've found a BFI.
12366 APInt ToMask1, FromMask1;
12367 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12369 APInt ToMask2, FromMask2;
12370 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12371 assert(From1 == From2);
12372 (void)From2;
12374 // First, unlink CombineBFI.
12375 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12376 // Then create a new BFI, combining the two together.
12377 APInt NewFromMask = FromMask1 | FromMask2;
12378 APInt NewToMask = ToMask1 | ToMask2;
12380 EVT VT = N->getValueType(0);
12381 SDLoc dl(N);
12383 if (NewFromMask[0] == 0)
12384 From1 = DCI.DAG.getNode(
12385 ISD::SRL, dl, VT, From1,
12386 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12387 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12388 DCI.DAG.getConstant(~NewToMask, dl, VT));
12390 return SDValue();
12393 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12394 /// ARMISD::VMOVRRD.
12395 static SDValue PerformVMOVRRDCombine(SDNode *N,
12396 TargetLowering::DAGCombinerInfo &DCI,
12397 const ARMSubtarget *Subtarget) {
12398 // vmovrrd(vmovdrr x, y) -> x,y
12399 SDValue InDouble = N->getOperand(0);
12400 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12401 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12403 // vmovrrd(load f64) -> (load i32), (load i32)
12404 SDNode *InNode = InDouble.getNode();
12405 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12406 InNode->getValueType(0) == MVT::f64 &&
12407 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12408 !cast<LoadSDNode>(InNode)->isVolatile()) {
12409 // TODO: Should this be done for non-FrameIndex operands?
12410 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12412 SelectionDAG &DAG = DCI.DAG;
12413 SDLoc DL(LD);
12414 SDValue BasePtr = LD->getBasePtr();
12415 SDValue NewLD1 =
12416 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12417 LD->getAlignment(), LD->getMemOperand()->getFlags());
12419 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12420 DAG.getConstant(4, DL, MVT::i32));
12422 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12423 LD->getPointerInfo().getWithOffset(4),
12424 std::min(4U, LD->getAlignment()),
12425 LD->getMemOperand()->getFlags());
12427 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12428 if (DCI.DAG.getDataLayout().isBigEndian())
12429 std::swap (NewLD1, NewLD2);
12430 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12431 return Result;
12434 return SDValue();
12437 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12438 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12439 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12440 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12441 SDValue Op0 = N->getOperand(0);
12442 SDValue Op1 = N->getOperand(1);
12443 if (Op0.getOpcode() == ISD::BITCAST)
12444 Op0 = Op0.getOperand(0);
12445 if (Op1.getOpcode() == ISD::BITCAST)
12446 Op1 = Op1.getOperand(0);
12447 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12448 Op0.getNode() == Op1.getNode() &&
12449 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12450 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12451 N->getValueType(0), Op0.getOperand(0));
12452 return SDValue();
12455 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12456 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12457 /// i64 vector to have f64 elements, since the value can then be loaded
12458 /// directly into a VFP register.
12459 static bool hasNormalLoadOperand(SDNode *N) {
12460 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12461 for (unsigned i = 0; i < NumElts; ++i) {
12462 SDNode *Elt = N->getOperand(i).getNode();
12463 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12464 return true;
12466 return false;
12469 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12470 /// ISD::BUILD_VECTOR.
12471 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12472 TargetLowering::DAGCombinerInfo &DCI,
12473 const ARMSubtarget *Subtarget) {
12474 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12475 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12476 // into a pair of GPRs, which is fine when the value is used as a scalar,
12477 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12478 SelectionDAG &DAG = DCI.DAG;
12479 if (N->getNumOperands() == 2)
12480 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12481 return RV;
12483 // Load i64 elements as f64 values so that type legalization does not split
12484 // them up into i32 values.
12485 EVT VT = N->getValueType(0);
12486 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12487 return SDValue();
12488 SDLoc dl(N);
12489 SmallVector<SDValue, 8> Ops;
12490 unsigned NumElts = VT.getVectorNumElements();
12491 for (unsigned i = 0; i < NumElts; ++i) {
12492 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12493 Ops.push_back(V);
12494 // Make the DAGCombiner fold the bitcast.
12495 DCI.AddToWorklist(V.getNode());
12497 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12498 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12499 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12502 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12503 static SDValue
12504 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12505 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12506 // At that time, we may have inserted bitcasts from integer to float.
12507 // If these bitcasts have survived DAGCombine, change the lowering of this
12508 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12509 // force to use floating point types.
12511 // Make sure we can change the type of the vector.
12512 // This is possible iff:
12513 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12514 // 1.1. Vector is used only once.
12515 // 1.2. Use is a bit convert to an integer type.
12516 // 2. The size of its operands are 32-bits (64-bits are not legal).
12517 EVT VT = N->getValueType(0);
12518 EVT EltVT = VT.getVectorElementType();
12520 // Check 1.1. and 2.
12521 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12522 return SDValue();
12524 // By construction, the input type must be float.
12525 assert(EltVT == MVT::f32 && "Unexpected type!");
12527 // Check 1.2.
12528 SDNode *Use = *N->use_begin();
12529 if (Use->getOpcode() != ISD::BITCAST ||
12530 Use->getValueType(0).isFloatingPoint())
12531 return SDValue();
12533 // Check profitability.
12534 // Model is, if more than half of the relevant operands are bitcast from
12535 // i32, turn the build_vector into a sequence of insert_vector_elt.
12536 // Relevant operands are everything that is not statically
12537 // (i.e., at compile time) bitcasted.
12538 unsigned NumOfBitCastedElts = 0;
12539 unsigned NumElts = VT.getVectorNumElements();
12540 unsigned NumOfRelevantElts = NumElts;
12541 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12542 SDValue Elt = N->getOperand(Idx);
12543 if (Elt->getOpcode() == ISD::BITCAST) {
12544 // Assume only bit cast to i32 will go away.
12545 if (Elt->getOperand(0).getValueType() == MVT::i32)
12546 ++NumOfBitCastedElts;
12547 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12548 // Constants are statically casted, thus do not count them as
12549 // relevant operands.
12550 --NumOfRelevantElts;
12553 // Check if more than half of the elements require a non-free bitcast.
12554 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12555 return SDValue();
12557 SelectionDAG &DAG = DCI.DAG;
12558 // Create the new vector type.
12559 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12560 // Check if the type is legal.
12561 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12562 if (!TLI.isTypeLegal(VecVT))
12563 return SDValue();
12565 // Combine:
12566 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12567 // => BITCAST INSERT_VECTOR_ELT
12568 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12569 // (BITCAST EN), N.
12570 SDValue Vec = DAG.getUNDEF(VecVT);
12571 SDLoc dl(N);
12572 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12573 SDValue V = N->getOperand(Idx);
12574 if (V.isUndef())
12575 continue;
12576 if (V.getOpcode() == ISD::BITCAST &&
12577 V->getOperand(0).getValueType() == MVT::i32)
12578 // Fold obvious case.
12579 V = V.getOperand(0);
12580 else {
12581 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12582 // Make the DAGCombiner fold the bitcasts.
12583 DCI.AddToWorklist(V.getNode());
12585 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12586 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12588 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12589 // Make the DAGCombiner fold the bitcasts.
12590 DCI.AddToWorklist(Vec.getNode());
12591 return Vec;
12594 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12595 /// ISD::INSERT_VECTOR_ELT.
12596 static SDValue PerformInsertEltCombine(SDNode *N,
12597 TargetLowering::DAGCombinerInfo &DCI) {
12598 // Bitcast an i64 load inserted into a vector to f64.
12599 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12600 EVT VT = N->getValueType(0);
12601 SDNode *Elt = N->getOperand(1).getNode();
12602 if (VT.getVectorElementType() != MVT::i64 ||
12603 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12604 return SDValue();
12606 SelectionDAG &DAG = DCI.DAG;
12607 SDLoc dl(N);
12608 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12609 VT.getVectorNumElements());
12610 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12611 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12612 // Make the DAGCombiner fold the bitcasts.
12613 DCI.AddToWorklist(Vec.getNode());
12614 DCI.AddToWorklist(V.getNode());
12615 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12616 Vec, V, N->getOperand(2));
12617 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12620 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12621 /// ISD::VECTOR_SHUFFLE.
12622 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12623 // The LLVM shufflevector instruction does not require the shuffle mask
12624 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12625 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12626 // operands do not match the mask length, they are extended by concatenating
12627 // them with undef vectors. That is probably the right thing for other
12628 // targets, but for NEON it is better to concatenate two double-register
12629 // size vector operands into a single quad-register size vector. Do that
12630 // transformation here:
12631 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12632 // shuffle(concat(v1, v2), undef)
12633 SDValue Op0 = N->getOperand(0);
12634 SDValue Op1 = N->getOperand(1);
12635 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12636 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12637 Op0.getNumOperands() != 2 ||
12638 Op1.getNumOperands() != 2)
12639 return SDValue();
12640 SDValue Concat0Op1 = Op0.getOperand(1);
12641 SDValue Concat1Op1 = Op1.getOperand(1);
12642 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12643 return SDValue();
12644 // Skip the transformation if any of the types are illegal.
12645 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12646 EVT VT = N->getValueType(0);
12647 if (!TLI.isTypeLegal(VT) ||
12648 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12649 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12650 return SDValue();
12652 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12653 Op0.getOperand(0), Op1.getOperand(0));
12654 // Translate the shuffle mask.
12655 SmallVector<int, 16> NewMask;
12656 unsigned NumElts = VT.getVectorNumElements();
12657 unsigned HalfElts = NumElts/2;
12658 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12659 for (unsigned n = 0; n < NumElts; ++n) {
12660 int MaskElt = SVN->getMaskElt(n);
12661 int NewElt = -1;
12662 if (MaskElt < (int)HalfElts)
12663 NewElt = MaskElt;
12664 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12665 NewElt = HalfElts + MaskElt - NumElts;
12666 NewMask.push_back(NewElt);
12668 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12669 DAG.getUNDEF(VT), NewMask);
12672 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12673 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12674 /// base address updates.
12675 /// For generic load/stores, the memory type is assumed to be a vector.
12676 /// The caller is assumed to have checked legality.
12677 static SDValue CombineBaseUpdate(SDNode *N,
12678 TargetLowering::DAGCombinerInfo &DCI) {
12679 SelectionDAG &DAG = DCI.DAG;
12680 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12681 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12682 const bool isStore = N->getOpcode() == ISD::STORE;
12683 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12684 SDValue Addr = N->getOperand(AddrOpIdx);
12685 MemSDNode *MemN = cast<MemSDNode>(N);
12686 SDLoc dl(N);
12688 // Search for a use of the address operand that is an increment.
12689 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12690 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12691 SDNode *User = *UI;
12692 if (User->getOpcode() != ISD::ADD ||
12693 UI.getUse().getResNo() != Addr.getResNo())
12694 continue;
12696 // Check that the add is independent of the load/store. Otherwise, folding
12697 // it would create a cycle. We can avoid searching through Addr as it's a
12698 // predecessor to both.
12699 SmallPtrSet<const SDNode *, 32> Visited;
12700 SmallVector<const SDNode *, 16> Worklist;
12701 Visited.insert(Addr.getNode());
12702 Worklist.push_back(N);
12703 Worklist.push_back(User);
12704 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12705 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12706 continue;
12708 // Find the new opcode for the updating load/store.
12709 bool isLoadOp = true;
12710 bool isLaneOp = false;
12711 unsigned NewOpc = 0;
12712 unsigned NumVecs = 0;
12713 if (isIntrinsic) {
12714 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12715 switch (IntNo) {
12716 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12717 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12718 NumVecs = 1; break;
12719 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12720 NumVecs = 2; break;
12721 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12722 NumVecs = 3; break;
12723 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12724 NumVecs = 4; break;
12725 case Intrinsic::arm_neon_vld2dup:
12726 case Intrinsic::arm_neon_vld3dup:
12727 case Intrinsic::arm_neon_vld4dup:
12728 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12729 // combining base updates for such intrinsics.
12730 continue;
12731 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12732 NumVecs = 2; isLaneOp = true; break;
12733 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12734 NumVecs = 3; isLaneOp = true; break;
12735 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12736 NumVecs = 4; isLaneOp = true; break;
12737 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12738 NumVecs = 1; isLoadOp = false; break;
12739 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12740 NumVecs = 2; isLoadOp = false; break;
12741 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12742 NumVecs = 3; isLoadOp = false; break;
12743 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12744 NumVecs = 4; isLoadOp = false; break;
12745 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12746 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12747 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12748 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12749 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12750 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12752 } else {
12753 isLaneOp = true;
12754 switch (N->getOpcode()) {
12755 default: llvm_unreachable("unexpected opcode for Neon base update");
12756 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12757 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12758 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12759 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12760 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12761 NumVecs = 1; isLaneOp = false; break;
12762 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12763 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12767 // Find the size of memory referenced by the load/store.
12768 EVT VecTy;
12769 if (isLoadOp) {
12770 VecTy = N->getValueType(0);
12771 } else if (isIntrinsic) {
12772 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12773 } else {
12774 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12775 VecTy = N->getOperand(1).getValueType();
12778 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12779 if (isLaneOp)
12780 NumBytes /= VecTy.getVectorNumElements();
12782 // If the increment is a constant, it must match the memory ref size.
12783 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12784 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12785 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12786 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12787 // separate instructions that make it harder to use a non-constant update.
12788 continue;
12791 // OK, we found an ADD we can fold into the base update.
12792 // Now, create a _UPD node, taking care of not breaking alignment.
12794 EVT AlignedVecTy = VecTy;
12795 unsigned Alignment = MemN->getAlignment();
12797 // If this is a less-than-standard-aligned load/store, change the type to
12798 // match the standard alignment.
12799 // The alignment is overlooked when selecting _UPD variants; and it's
12800 // easier to introduce bitcasts here than fix that.
12801 // There are 3 ways to get to this base-update combine:
12802 // - intrinsics: they are assumed to be properly aligned (to the standard
12803 // alignment of the memory type), so we don't need to do anything.
12804 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12805 // intrinsics, so, likewise, there's nothing to do.
12806 // - generic load/store instructions: the alignment is specified as an
12807 // explicit operand, rather than implicitly as the standard alignment
12808 // of the memory type (like the intrisics). We need to change the
12809 // memory type to match the explicit alignment. That way, we don't
12810 // generate non-standard-aligned ARMISD::VLDx nodes.
12811 if (isa<LSBaseSDNode>(N)) {
12812 if (Alignment == 0)
12813 Alignment = 1;
12814 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12815 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12816 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12817 assert(!isLaneOp && "Unexpected generic load/store lane.");
12818 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12819 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12821 // Don't set an explicit alignment on regular load/stores that we want
12822 // to transform to VLD/VST 1_UPD nodes.
12823 // This matches the behavior of regular load/stores, which only get an
12824 // explicit alignment if the MMO alignment is larger than the standard
12825 // alignment of the memory type.
12826 // Intrinsics, however, always get an explicit alignment, set to the
12827 // alignment of the MMO.
12828 Alignment = 1;
12831 // Create the new updating load/store node.
12832 // First, create an SDVTList for the new updating node's results.
12833 EVT Tys[6];
12834 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12835 unsigned n;
12836 for (n = 0; n < NumResultVecs; ++n)
12837 Tys[n] = AlignedVecTy;
12838 Tys[n++] = MVT::i32;
12839 Tys[n] = MVT::Other;
12840 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12842 // Then, gather the new node's operands.
12843 SmallVector<SDValue, 8> Ops;
12844 Ops.push_back(N->getOperand(0)); // incoming chain
12845 Ops.push_back(N->getOperand(AddrOpIdx));
12846 Ops.push_back(Inc);
12848 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12849 // Try to match the intrinsic's signature
12850 Ops.push_back(StN->getValue());
12851 } else {
12852 // Loads (and of course intrinsics) match the intrinsics' signature,
12853 // so just add all but the alignment operand.
12854 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12855 Ops.push_back(N->getOperand(i));
12858 // For all node types, the alignment operand is always the last one.
12859 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
12861 // If this is a non-standard-aligned STORE, the penultimate operand is the
12862 // stored value. Bitcast it to the aligned type.
12863 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
12864 SDValue &StVal = Ops[Ops.size()-2];
12865 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
12868 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
12869 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
12870 MemN->getMemOperand());
12872 // Update the uses.
12873 SmallVector<SDValue, 5> NewResults;
12874 for (unsigned i = 0; i < NumResultVecs; ++i)
12875 NewResults.push_back(SDValue(UpdN.getNode(), i));
12877 // If this is an non-standard-aligned LOAD, the first result is the loaded
12878 // value. Bitcast it to the expected result type.
12879 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
12880 SDValue &LdVal = NewResults[0];
12881 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
12884 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
12885 DCI.CombineTo(N, NewResults);
12886 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12888 break;
12890 return SDValue();
12893 static SDValue PerformVLDCombine(SDNode *N,
12894 TargetLowering::DAGCombinerInfo &DCI) {
12895 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12896 return SDValue();
12898 return CombineBaseUpdate(N, DCI);
12901 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
12902 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
12903 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
12904 /// return true.
12905 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12906 SelectionDAG &DAG = DCI.DAG;
12907 EVT VT = N->getValueType(0);
12908 // vldN-dup instructions only support 64-bit vectors for N > 1.
12909 if (!VT.is64BitVector())
12910 return false;
12912 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
12913 SDNode *VLD = N->getOperand(0).getNode();
12914 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
12915 return false;
12916 unsigned NumVecs = 0;
12917 unsigned NewOpc = 0;
12918 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
12919 if (IntNo == Intrinsic::arm_neon_vld2lane) {
12920 NumVecs = 2;
12921 NewOpc = ARMISD::VLD2DUP;
12922 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
12923 NumVecs = 3;
12924 NewOpc = ARMISD::VLD3DUP;
12925 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
12926 NumVecs = 4;
12927 NewOpc = ARMISD::VLD4DUP;
12928 } else {
12929 return false;
12932 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
12933 // numbers match the load.
12934 unsigned VLDLaneNo =
12935 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
12936 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12937 UI != UE; ++UI) {
12938 // Ignore uses of the chain result.
12939 if (UI.getUse().getResNo() == NumVecs)
12940 continue;
12941 SDNode *User = *UI;
12942 if (User->getOpcode() != ARMISD::VDUPLANE ||
12943 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
12944 return false;
12947 // Create the vldN-dup node.
12948 EVT Tys[5];
12949 unsigned n;
12950 for (n = 0; n < NumVecs; ++n)
12951 Tys[n] = VT;
12952 Tys[n] = MVT::Other;
12953 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
12954 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
12955 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
12956 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
12957 Ops, VLDMemInt->getMemoryVT(),
12958 VLDMemInt->getMemOperand());
12960 // Update the uses.
12961 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12962 UI != UE; ++UI) {
12963 unsigned ResNo = UI.getUse().getResNo();
12964 // Ignore uses of the chain result.
12965 if (ResNo == NumVecs)
12966 continue;
12967 SDNode *User = *UI;
12968 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
12971 // Now the vldN-lane intrinsic is dead except for its chain result.
12972 // Update uses of the chain.
12973 std::vector<SDValue> VLDDupResults;
12974 for (unsigned n = 0; n < NumVecs; ++n)
12975 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
12976 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
12977 DCI.CombineTo(VLD, VLDDupResults);
12979 return true;
12982 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
12983 /// ARMISD::VDUPLANE.
12984 static SDValue PerformVDUPLANECombine(SDNode *N,
12985 TargetLowering::DAGCombinerInfo &DCI) {
12986 SDValue Op = N->getOperand(0);
12988 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
12989 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
12990 if (CombineVLDDUP(N, DCI))
12991 return SDValue(N, 0);
12993 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
12994 // redundant. Ignore bit_converts for now; element sizes are checked below.
12995 while (Op.getOpcode() == ISD::BITCAST)
12996 Op = Op.getOperand(0);
12997 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
12998 return SDValue();
13000 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
13001 unsigned EltSize = Op.getScalarValueSizeInBits();
13002 // The canonical VMOV for a zero vector uses a 32-bit element size.
13003 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13004 unsigned EltBits;
13005 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
13006 EltSize = 8;
13007 EVT VT = N->getValueType(0);
13008 if (EltSize > VT.getScalarSizeInBits())
13009 return SDValue();
13011 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
13014 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
13015 static SDValue PerformVDUPCombine(SDNode *N,
13016 TargetLowering::DAGCombinerInfo &DCI,
13017 const ARMSubtarget *Subtarget) {
13018 SelectionDAG &DAG = DCI.DAG;
13019 SDValue Op = N->getOperand(0);
13021 if (!Subtarget->hasNEON())
13022 return SDValue();
13024 // Match VDUP(LOAD) -> VLD1DUP.
13025 // We match this pattern here rather than waiting for isel because the
13026 // transform is only legal for unindexed loads.
13027 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
13028 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
13029 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
13030 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
13031 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
13032 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
13033 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
13034 Ops, LD->getMemoryVT(),
13035 LD->getMemOperand());
13036 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
13037 return VLDDup;
13040 return SDValue();
13043 static SDValue PerformLOADCombine(SDNode *N,
13044 TargetLowering::DAGCombinerInfo &DCI) {
13045 EVT VT = N->getValueType(0);
13047 // If this is a legal vector load, try to combine it into a VLD1_UPD.
13048 if (ISD::isNormalLoad(N) && VT.isVector() &&
13049 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13050 return CombineBaseUpdate(N, DCI);
13052 return SDValue();
13055 /// PerformSTORECombine - Target-specific dag combine xforms for
13056 /// ISD::STORE.
13057 static SDValue PerformSTORECombine(SDNode *N,
13058 TargetLowering::DAGCombinerInfo &DCI) {
13059 StoreSDNode *St = cast<StoreSDNode>(N);
13060 if (St->isVolatile())
13061 return SDValue();
13063 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
13064 // pack all of the elements in one place. Next, store to memory in fewer
13065 // chunks.
13066 SDValue StVal = St->getValue();
13067 EVT VT = StVal.getValueType();
13068 if (St->isTruncatingStore() && VT.isVector()) {
13069 SelectionDAG &DAG = DCI.DAG;
13070 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13071 EVT StVT = St->getMemoryVT();
13072 unsigned NumElems = VT.getVectorNumElements();
13073 assert(StVT != VT && "Cannot truncate to the same type");
13074 unsigned FromEltSz = VT.getScalarSizeInBits();
13075 unsigned ToEltSz = StVT.getScalarSizeInBits();
13077 // From, To sizes and ElemCount must be pow of two
13078 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
13080 // We are going to use the original vector elt for storing.
13081 // Accumulated smaller vector elements must be a multiple of the store size.
13082 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
13084 unsigned SizeRatio = FromEltSz / ToEltSz;
13085 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13087 // Create a type on which we perform the shuffle.
13088 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13089 NumElems*SizeRatio);
13090 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13092 SDLoc DL(St);
13093 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13094 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13095 for (unsigned i = 0; i < NumElems; ++i)
13096 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
13097 ? (i + 1) * SizeRatio - 1
13098 : i * SizeRatio;
13100 // Can't shuffle using an illegal type.
13101 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13103 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
13104 DAG.getUNDEF(WideVec.getValueType()),
13105 ShuffleVec);
13106 // At this point all of the data is stored at the bottom of the
13107 // register. We now need to save it to mem.
13109 // Find the largest store unit
13110 MVT StoreType = MVT::i8;
13111 for (MVT Tp : MVT::integer_valuetypes()) {
13112 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13113 StoreType = Tp;
13115 // Didn't find a legal store type.
13116 if (!TLI.isTypeLegal(StoreType))
13117 return SDValue();
13119 // Bitcast the original vector into a vector of store-size units
13120 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13121 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13122 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13123 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13124 SmallVector<SDValue, 8> Chains;
13125 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13126 TLI.getPointerTy(DAG.getDataLayout()));
13127 SDValue BasePtr = St->getBasePtr();
13129 // Perform one or more big stores into memory.
13130 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
13131 for (unsigned I = 0; I < E; I++) {
13132 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
13133 StoreType, ShuffWide,
13134 DAG.getIntPtrConstant(I, DL));
13135 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
13136 St->getPointerInfo(), St->getAlignment(),
13137 St->getMemOperand()->getFlags());
13138 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
13139 Increment);
13140 Chains.push_back(Ch);
13142 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13145 if (!ISD::isNormalStore(St))
13146 return SDValue();
13148 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
13149 // ARM stores of arguments in the same cache line.
13150 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
13151 StVal.getNode()->hasOneUse()) {
13152 SelectionDAG &DAG = DCI.DAG;
13153 bool isBigEndian = DAG.getDataLayout().isBigEndian();
13154 SDLoc DL(St);
13155 SDValue BasePtr = St->getBasePtr();
13156 SDValue NewST1 = DAG.getStore(
13157 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
13158 BasePtr, St->getPointerInfo(), St->getAlignment(),
13159 St->getMemOperand()->getFlags());
13161 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13162 DAG.getConstant(4, DL, MVT::i32));
13163 return DAG.getStore(NewST1.getValue(0), DL,
13164 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
13165 OffsetPtr, St->getPointerInfo(),
13166 std::min(4U, St->getAlignment() / 2),
13167 St->getMemOperand()->getFlags());
13170 if (StVal.getValueType() == MVT::i64 &&
13171 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13173 // Bitcast an i64 store extracted from a vector to f64.
13174 // Otherwise, the i64 value will be legalized to a pair of i32 values.
13175 SelectionDAG &DAG = DCI.DAG;
13176 SDLoc dl(StVal);
13177 SDValue IntVec = StVal.getOperand(0);
13178 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13179 IntVec.getValueType().getVectorNumElements());
13180 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
13181 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13182 Vec, StVal.getOperand(1));
13183 dl = SDLoc(N);
13184 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
13185 // Make the DAGCombiner fold the bitcasts.
13186 DCI.AddToWorklist(Vec.getNode());
13187 DCI.AddToWorklist(ExtElt.getNode());
13188 DCI.AddToWorklist(V.getNode());
13189 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
13190 St->getPointerInfo(), St->getAlignment(),
13191 St->getMemOperand()->getFlags(), St->getAAInfo());
13194 // If this is a legal vector store, try to combine it into a VST1_UPD.
13195 if (ISD::isNormalStore(N) && VT.isVector() &&
13196 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13197 return CombineBaseUpdate(N, DCI);
13199 return SDValue();
13202 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
13203 /// can replace combinations of VMUL and VCVT (floating-point to integer)
13204 /// when the VMUL has a constant operand that is a power of 2.
13206 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13207 /// vmul.f32 d16, d17, d16
13208 /// vcvt.s32.f32 d16, d16
13209 /// becomes:
13210 /// vcvt.s32.f32 d16, d16, #3
13211 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
13212 const ARMSubtarget *Subtarget) {
13213 if (!Subtarget->hasNEON())
13214 return SDValue();
13216 SDValue Op = N->getOperand(0);
13217 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13218 Op.getOpcode() != ISD::FMUL)
13219 return SDValue();
13221 SDValue ConstVec = Op->getOperand(1);
13222 if (!isa<BuildVectorSDNode>(ConstVec))
13223 return SDValue();
13225 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13226 uint32_t FloatBits = FloatTy.getSizeInBits();
13227 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13228 uint32_t IntBits = IntTy.getSizeInBits();
13229 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13230 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13231 // These instructions only exist converting from f32 to i32. We can handle
13232 // smaller integers by generating an extra truncate, but larger ones would
13233 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13234 // these intructions only support v2i32/v4i32 types.
13235 return SDValue();
13238 BitVector UndefElements;
13239 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13240 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13241 if (C == -1 || C == 0 || C > 32)
13242 return SDValue();
13244 SDLoc dl(N);
13245 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
13246 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
13247 Intrinsic::arm_neon_vcvtfp2fxu;
13248 SDValue FixConv = DAG.getNode(
13249 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13250 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
13251 DAG.getConstant(C, dl, MVT::i32));
13253 if (IntBits < FloatBits)
13254 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
13256 return FixConv;
13259 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13260 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13261 /// when the VDIV has a constant operand that is a power of 2.
13263 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13264 /// vcvt.f32.s32 d16, d16
13265 /// vdiv.f32 d16, d17, d16
13266 /// becomes:
13267 /// vcvt.f32.s32 d16, d16, #3
13268 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13269 const ARMSubtarget *Subtarget) {
13270 if (!Subtarget->hasNEON())
13271 return SDValue();
13273 SDValue Op = N->getOperand(0);
13274 unsigned OpOpcode = Op.getNode()->getOpcode();
13275 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13276 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13277 return SDValue();
13279 SDValue ConstVec = N->getOperand(1);
13280 if (!isa<BuildVectorSDNode>(ConstVec))
13281 return SDValue();
13283 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13284 uint32_t FloatBits = FloatTy.getSizeInBits();
13285 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13286 uint32_t IntBits = IntTy.getSizeInBits();
13287 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13288 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13289 // These instructions only exist converting from i32 to f32. We can handle
13290 // smaller integers by generating an extra extend, but larger ones would
13291 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13292 // these intructions only support v2i32/v4i32 types.
13293 return SDValue();
13296 BitVector UndefElements;
13297 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13298 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13299 if (C == -1 || C == 0 || C > 32)
13300 return SDValue();
13302 SDLoc dl(N);
13303 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13304 SDValue ConvInput = Op.getOperand(0);
13305 if (IntBits < FloatBits)
13306 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13307 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13308 ConvInput);
13310 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13311 Intrinsic::arm_neon_vcvtfxu2fp;
13312 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13313 Op.getValueType(),
13314 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13315 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13318 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13319 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13320 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13321 switch (IntNo) {
13322 default:
13323 // Don't do anything for most intrinsics.
13324 break;
13326 // Vector shifts: check for immediate versions and lower them.
13327 // Note: This is done during DAG combining instead of DAG legalizing because
13328 // the build_vectors for 64-bit vector element shift counts are generally
13329 // not legal, and it is hard to see their values after they get legalized to
13330 // loads from a constant pool.
13331 case Intrinsic::arm_neon_vshifts:
13332 case Intrinsic::arm_neon_vshiftu:
13333 case Intrinsic::arm_neon_vrshifts:
13334 case Intrinsic::arm_neon_vrshiftu:
13335 case Intrinsic::arm_neon_vrshiftn:
13336 case Intrinsic::arm_neon_vqshifts:
13337 case Intrinsic::arm_neon_vqshiftu:
13338 case Intrinsic::arm_neon_vqshiftsu:
13339 case Intrinsic::arm_neon_vqshiftns:
13340 case Intrinsic::arm_neon_vqshiftnu:
13341 case Intrinsic::arm_neon_vqshiftnsu:
13342 case Intrinsic::arm_neon_vqrshiftns:
13343 case Intrinsic::arm_neon_vqrshiftnu:
13344 case Intrinsic::arm_neon_vqrshiftnsu: {
13345 EVT VT = N->getOperand(1).getValueType();
13346 int64_t Cnt;
13347 unsigned VShiftOpc = 0;
13349 switch (IntNo) {
13350 case Intrinsic::arm_neon_vshifts:
13351 case Intrinsic::arm_neon_vshiftu:
13352 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13353 VShiftOpc = ARMISD::VSHLIMM;
13354 break;
13356 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13357 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13358 : ARMISD::VSHRuIMM);
13359 break;
13361 return SDValue();
13363 case Intrinsic::arm_neon_vrshifts:
13364 case Intrinsic::arm_neon_vrshiftu:
13365 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13366 break;
13367 return SDValue();
13369 case Intrinsic::arm_neon_vqshifts:
13370 case Intrinsic::arm_neon_vqshiftu:
13371 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13372 break;
13373 return SDValue();
13375 case Intrinsic::arm_neon_vqshiftsu:
13376 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13377 break;
13378 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13380 case Intrinsic::arm_neon_vrshiftn:
13381 case Intrinsic::arm_neon_vqshiftns:
13382 case Intrinsic::arm_neon_vqshiftnu:
13383 case Intrinsic::arm_neon_vqshiftnsu:
13384 case Intrinsic::arm_neon_vqrshiftns:
13385 case Intrinsic::arm_neon_vqrshiftnu:
13386 case Intrinsic::arm_neon_vqrshiftnsu:
13387 // Narrowing shifts require an immediate right shift.
13388 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13389 break;
13390 llvm_unreachable("invalid shift count for narrowing vector shift "
13391 "intrinsic");
13393 default:
13394 llvm_unreachable("unhandled vector shift");
13397 switch (IntNo) {
13398 case Intrinsic::arm_neon_vshifts:
13399 case Intrinsic::arm_neon_vshiftu:
13400 // Opcode already set above.
13401 break;
13402 case Intrinsic::arm_neon_vrshifts:
13403 VShiftOpc = ARMISD::VRSHRsIMM;
13404 break;
13405 case Intrinsic::arm_neon_vrshiftu:
13406 VShiftOpc = ARMISD::VRSHRuIMM;
13407 break;
13408 case Intrinsic::arm_neon_vrshiftn:
13409 VShiftOpc = ARMISD::VRSHRNIMM;
13410 break;
13411 case Intrinsic::arm_neon_vqshifts:
13412 VShiftOpc = ARMISD::VQSHLsIMM;
13413 break;
13414 case Intrinsic::arm_neon_vqshiftu:
13415 VShiftOpc = ARMISD::VQSHLuIMM;
13416 break;
13417 case Intrinsic::arm_neon_vqshiftsu:
13418 VShiftOpc = ARMISD::VQSHLsuIMM;
13419 break;
13420 case Intrinsic::arm_neon_vqshiftns:
13421 VShiftOpc = ARMISD::VQSHRNsIMM;
13422 break;
13423 case Intrinsic::arm_neon_vqshiftnu:
13424 VShiftOpc = ARMISD::VQSHRNuIMM;
13425 break;
13426 case Intrinsic::arm_neon_vqshiftnsu:
13427 VShiftOpc = ARMISD::VQSHRNsuIMM;
13428 break;
13429 case Intrinsic::arm_neon_vqrshiftns:
13430 VShiftOpc = ARMISD::VQRSHRNsIMM;
13431 break;
13432 case Intrinsic::arm_neon_vqrshiftnu:
13433 VShiftOpc = ARMISD::VQRSHRNuIMM;
13434 break;
13435 case Intrinsic::arm_neon_vqrshiftnsu:
13436 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13437 break;
13440 SDLoc dl(N);
13441 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13442 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13445 case Intrinsic::arm_neon_vshiftins: {
13446 EVT VT = N->getOperand(1).getValueType();
13447 int64_t Cnt;
13448 unsigned VShiftOpc = 0;
13450 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13451 VShiftOpc = ARMISD::VSLIIMM;
13452 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13453 VShiftOpc = ARMISD::VSRIIMM;
13454 else {
13455 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13458 SDLoc dl(N);
13459 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13460 N->getOperand(1), N->getOperand(2),
13461 DAG.getConstant(Cnt, dl, MVT::i32));
13464 case Intrinsic::arm_neon_vqrshifts:
13465 case Intrinsic::arm_neon_vqrshiftu:
13466 // No immediate versions of these to check for.
13467 break;
13470 return SDValue();
13473 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13474 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13475 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13476 /// vector element shift counts are generally not legal, and it is hard to see
13477 /// their values after they get legalized to loads from a constant pool.
13478 static SDValue PerformShiftCombine(SDNode *N,
13479 TargetLowering::DAGCombinerInfo &DCI,
13480 const ARMSubtarget *ST) {
13481 SelectionDAG &DAG = DCI.DAG;
13482 EVT VT = N->getValueType(0);
13483 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13484 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13485 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13486 SDValue N1 = N->getOperand(1);
13487 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13488 SDValue N0 = N->getOperand(0);
13489 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13490 DAG.MaskedValueIsZero(N0.getOperand(0),
13491 APInt::getHighBitsSet(32, 16)))
13492 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13496 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13497 N->getOperand(0)->getOpcode() == ISD::AND &&
13498 N->getOperand(0)->hasOneUse()) {
13499 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13500 return SDValue();
13501 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13502 // usually show up because instcombine prefers to canonicalize it to
13503 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13504 // out of GEP lowering in some cases.
13505 SDValue N0 = N->getOperand(0);
13506 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13507 if (!ShiftAmtNode)
13508 return SDValue();
13509 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13510 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13511 if (!AndMaskNode)
13512 return SDValue();
13513 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13514 // Don't transform uxtb/uxth.
13515 if (AndMask == 255 || AndMask == 65535)
13516 return SDValue();
13517 if (isMask_32(AndMask)) {
13518 uint32_t MaskedBits = countLeadingZeros(AndMask);
13519 if (MaskedBits > ShiftAmt) {
13520 SDLoc DL(N);
13521 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13522 DAG.getConstant(MaskedBits, DL, MVT::i32));
13523 return DAG.getNode(
13524 ISD::SRL, DL, MVT::i32, SHL,
13525 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13530 // Nothing to be done for scalar shifts.
13531 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13532 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13533 return SDValue();
13534 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13535 return SDValue();
13537 int64_t Cnt;
13539 switch (N->getOpcode()) {
13540 default: llvm_unreachable("unexpected shift opcode");
13542 case ISD::SHL:
13543 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13544 SDLoc dl(N);
13545 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13546 DAG.getConstant(Cnt, dl, MVT::i32));
13548 break;
13550 case ISD::SRA:
13551 case ISD::SRL:
13552 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13553 unsigned VShiftOpc =
13554 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13555 SDLoc dl(N);
13556 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13557 DAG.getConstant(Cnt, dl, MVT::i32));
13560 return SDValue();
13563 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13564 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13565 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13566 const ARMSubtarget *ST) {
13567 SDValue N0 = N->getOperand(0);
13569 // Check for sign- and zero-extensions of vector extract operations of 8-
13570 // and 16-bit vector elements. NEON supports these directly. They are
13571 // handled during DAG combining because type legalization will promote them
13572 // to 32-bit types and it is messy to recognize the operations after that.
13573 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13574 SDValue Vec = N0.getOperand(0);
13575 SDValue Lane = N0.getOperand(1);
13576 EVT VT = N->getValueType(0);
13577 EVT EltVT = N0.getValueType();
13578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13580 if (VT == MVT::i32 &&
13581 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13582 TLI.isTypeLegal(Vec.getValueType()) &&
13583 isa<ConstantSDNode>(Lane)) {
13585 unsigned Opc = 0;
13586 switch (N->getOpcode()) {
13587 default: llvm_unreachable("unexpected opcode");
13588 case ISD::SIGN_EXTEND:
13589 Opc = ARMISD::VGETLANEs;
13590 break;
13591 case ISD::ZERO_EXTEND:
13592 case ISD::ANY_EXTEND:
13593 Opc = ARMISD::VGETLANEu;
13594 break;
13596 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13600 return SDValue();
13603 static const APInt *isPowerOf2Constant(SDValue V) {
13604 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13605 if (!C)
13606 return nullptr;
13607 const APInt *CV = &C->getAPIntValue();
13608 return CV->isPowerOf2() ? CV : nullptr;
13611 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13612 // If we have a CMOV, OR and AND combination such as:
13613 // if (x & CN)
13614 // y |= CM;
13616 // And:
13617 // * CN is a single bit;
13618 // * All bits covered by CM are known zero in y
13620 // Then we can convert this into a sequence of BFI instructions. This will
13621 // always be a win if CM is a single bit, will always be no worse than the
13622 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13623 // three bits (due to the extra IT instruction).
13625 SDValue Op0 = CMOV->getOperand(0);
13626 SDValue Op1 = CMOV->getOperand(1);
13627 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13628 auto CC = CCNode->getAPIntValue().getLimitedValue();
13629 SDValue CmpZ = CMOV->getOperand(4);
13631 // The compare must be against zero.
13632 if (!isNullConstant(CmpZ->getOperand(1)))
13633 return SDValue();
13635 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13636 SDValue And = CmpZ->getOperand(0);
13637 if (And->getOpcode() != ISD::AND)
13638 return SDValue();
13639 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13640 if (!AndC)
13641 return SDValue();
13642 SDValue X = And->getOperand(0);
13644 if (CC == ARMCC::EQ) {
13645 // We're performing an "equal to zero" compare. Swap the operands so we
13646 // canonicalize on a "not equal to zero" compare.
13647 std::swap(Op0, Op1);
13648 } else {
13649 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13652 if (Op1->getOpcode() != ISD::OR)
13653 return SDValue();
13655 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13656 if (!OrC)
13657 return SDValue();
13658 SDValue Y = Op1->getOperand(0);
13660 if (Op0 != Y)
13661 return SDValue();
13663 // Now, is it profitable to continue?
13664 APInt OrCI = OrC->getAPIntValue();
13665 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13666 if (OrCI.countPopulation() > Heuristic)
13667 return SDValue();
13669 // Lastly, can we determine that the bits defined by OrCI
13670 // are zero in Y?
13671 KnownBits Known = DAG.computeKnownBits(Y);
13672 if ((OrCI & Known.Zero) != OrCI)
13673 return SDValue();
13675 // OK, we can do the combine.
13676 SDValue V = Y;
13677 SDLoc dl(X);
13678 EVT VT = X.getValueType();
13679 unsigned BitInX = AndC->logBase2();
13681 if (BitInX != 0) {
13682 // We must shift X first.
13683 X = DAG.getNode(ISD::SRL, dl, VT, X,
13684 DAG.getConstant(BitInX, dl, VT));
13687 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13688 BitInY < NumActiveBits; ++BitInY) {
13689 if (OrCI[BitInY] == 0)
13690 continue;
13691 APInt Mask(VT.getSizeInBits(), 0);
13692 Mask.setBit(BitInY);
13693 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13694 // Confusingly, the operand is an *inverted* mask.
13695 DAG.getConstant(~Mask, dl, VT));
13698 return V;
13701 // Given N, the value controlling the conditional branch, search for the loop
13702 // intrinsic, returning it, along with how the value is used. We need to handle
13703 // patterns such as the following:
13704 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13705 // (brcond (setcc (loop.decrement), 0, eq), exit)
13706 // (brcond (setcc (loop.decrement), 0, ne), header)
13707 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13708 bool &Negate) {
13709 switch (N->getOpcode()) {
13710 default:
13711 break;
13712 case ISD::XOR: {
13713 if (!isa<ConstantSDNode>(N.getOperand(1)))
13714 return SDValue();
13715 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13716 return SDValue();
13717 Negate = !Negate;
13718 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
13720 case ISD::SETCC: {
13721 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
13722 if (!Const)
13723 return SDValue();
13724 if (Const->isNullValue())
13725 Imm = 0;
13726 else if (Const->isOne())
13727 Imm = 1;
13728 else
13729 return SDValue();
13730 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
13731 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
13733 case ISD::INTRINSIC_W_CHAIN: {
13734 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
13735 if (IntOp != Intrinsic::test_set_loop_iterations &&
13736 IntOp != Intrinsic::loop_decrement_reg)
13737 return SDValue();
13738 return N;
13741 return SDValue();
13744 static SDValue PerformHWLoopCombine(SDNode *N,
13745 TargetLowering::DAGCombinerInfo &DCI,
13746 const ARMSubtarget *ST) {
13748 // The hwloop intrinsics that we're interested are used for control-flow,
13749 // either for entering or exiting the loop:
13750 // - test.set.loop.iterations will test whether its operand is zero. If it
13751 // is zero, the proceeding branch should not enter the loop.
13752 // - loop.decrement.reg also tests whether its operand is zero. If it is
13753 // zero, the proceeding branch should not branch back to the beginning of
13754 // the loop.
13755 // So here, we need to check that how the brcond is using the result of each
13756 // of the intrinsics to ensure that we're branching to the right place at the
13757 // right time.
13759 ISD::CondCode CC;
13760 SDValue Cond;
13761 int Imm = 1;
13762 bool Negate = false;
13763 SDValue Chain = N->getOperand(0);
13764 SDValue Dest;
13766 if (N->getOpcode() == ISD::BRCOND) {
13767 CC = ISD::SETEQ;
13768 Cond = N->getOperand(1);
13769 Dest = N->getOperand(2);
13770 } else {
13771 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
13772 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13773 Cond = N->getOperand(2);
13774 Dest = N->getOperand(4);
13775 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
13776 if (!Const->isOne() && !Const->isNullValue())
13777 return SDValue();
13778 Imm = Const->getZExtValue();
13779 } else
13780 return SDValue();
13783 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
13784 if (!Int)
13785 return SDValue();
13787 if (Negate)
13788 CC = ISD::getSetCCInverse(CC, true);
13790 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
13791 return (CC == ISD::SETEQ && Imm == 0) ||
13792 (CC == ISD::SETNE && Imm == 1) ||
13793 (CC == ISD::SETLT && Imm == 1) ||
13794 (CC == ISD::SETULT && Imm == 1);
13797 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
13798 return (CC == ISD::SETEQ && Imm == 1) ||
13799 (CC == ISD::SETNE && Imm == 0) ||
13800 (CC == ISD::SETGT && Imm == 0) ||
13801 (CC == ISD::SETUGT && Imm == 0) ||
13802 (CC == ISD::SETGE && Imm == 1) ||
13803 (CC == ISD::SETUGE && Imm == 1);
13806 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
13807 "unsupported condition");
13809 SDLoc dl(Int);
13810 SelectionDAG &DAG = DCI.DAG;
13811 SDValue Elements = Int.getOperand(2);
13812 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
13813 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
13814 && "expected single br user");
13815 SDNode *Br = *N->use_begin();
13816 SDValue OtherTarget = Br->getOperand(1);
13818 // Update the unconditional branch to branch to the given Dest.
13819 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
13820 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
13821 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
13822 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
13825 if (IntOp == Intrinsic::test_set_loop_iterations) {
13826 SDValue Res;
13827 // We expect this 'instruction' to branch when the counter is zero.
13828 if (IsTrueIfZero(CC, Imm)) {
13829 SDValue Ops[] = { Chain, Elements, Dest };
13830 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13831 } else {
13832 // The logic is the reverse of what we need for WLS, so find the other
13833 // basic block target: the target of the proceeding br.
13834 UpdateUncondBr(Br, Dest, DAG);
13836 SDValue Ops[] = { Chain, Elements, OtherTarget };
13837 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13839 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
13840 return Res;
13841 } else {
13842 SDValue Size = DAG.getTargetConstant(
13843 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
13844 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
13845 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
13846 DAG.getVTList(MVT::i32, MVT::Other), Args);
13847 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
13849 // We expect this instruction to branch when the count is not zero.
13850 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
13852 // Update the unconditional branch to target the loop preheader if we've
13853 // found the condition has been reversed.
13854 if (Target == OtherTarget)
13855 UpdateUncondBr(Br, Dest, DAG);
13857 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13858 SDValue(LoopDec.getNode(), 1), Chain);
13860 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
13861 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
13863 return SDValue();
13866 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
13867 SDValue
13868 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
13869 SDValue Cmp = N->getOperand(4);
13870 if (Cmp.getOpcode() != ARMISD::CMPZ)
13871 // Only looking at NE cases.
13872 return SDValue();
13874 EVT VT = N->getValueType(0);
13875 SDLoc dl(N);
13876 SDValue LHS = Cmp.getOperand(0);
13877 SDValue RHS = Cmp.getOperand(1);
13878 SDValue Chain = N->getOperand(0);
13879 SDValue BB = N->getOperand(1);
13880 SDValue ARMcc = N->getOperand(2);
13881 ARMCC::CondCodes CC =
13882 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13884 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
13885 // -> (brcond Chain BB CC CPSR Cmp)
13886 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
13887 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
13888 LHS->getOperand(0)->hasOneUse()) {
13889 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
13890 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
13891 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13892 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13893 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
13894 (LHS01C && LHS01C->getZExtValue() == 1) &&
13895 (LHS1C && LHS1C->getZExtValue() == 1) &&
13896 (RHSC && RHSC->getZExtValue() == 0)) {
13897 return DAG.getNode(
13898 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
13899 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
13903 return SDValue();
13906 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
13907 SDValue
13908 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
13909 SDValue Cmp = N->getOperand(4);
13910 if (Cmp.getOpcode() != ARMISD::CMPZ)
13911 // Only looking at EQ and NE cases.
13912 return SDValue();
13914 EVT VT = N->getValueType(0);
13915 SDLoc dl(N);
13916 SDValue LHS = Cmp.getOperand(0);
13917 SDValue RHS = Cmp.getOperand(1);
13918 SDValue FalseVal = N->getOperand(0);
13919 SDValue TrueVal = N->getOperand(1);
13920 SDValue ARMcc = N->getOperand(2);
13921 ARMCC::CondCodes CC =
13922 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13924 // BFI is only available on V6T2+.
13925 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
13926 SDValue R = PerformCMOVToBFICombine(N, DAG);
13927 if (R)
13928 return R;
13931 // Simplify
13932 // mov r1, r0
13933 // cmp r1, x
13934 // mov r0, y
13935 // moveq r0, x
13936 // to
13937 // cmp r0, x
13938 // movne r0, y
13940 // mov r1, r0
13941 // cmp r1, x
13942 // mov r0, x
13943 // movne r0, y
13944 // to
13945 // cmp r0, x
13946 // movne r0, y
13947 /// FIXME: Turn this into a target neutral optimization?
13948 SDValue Res;
13949 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
13950 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
13951 N->getOperand(3), Cmp);
13952 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
13953 SDValue ARMcc;
13954 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
13955 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
13956 N->getOperand(3), NewCmp);
13959 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
13960 // -> (cmov F T CC CPSR Cmp)
13961 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
13962 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
13963 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13964 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13965 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
13966 (LHS1C && LHS1C->getZExtValue() == 1) &&
13967 (RHSC && RHSC->getZExtValue() == 0)) {
13968 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
13969 LHS->getOperand(2), LHS->getOperand(3),
13970 LHS->getOperand(4));
13974 if (!VT.isInteger())
13975 return SDValue();
13977 // Materialize a boolean comparison for integers so we can avoid branching.
13978 if (isNullConstant(FalseVal)) {
13979 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
13980 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
13981 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
13982 // right 5 bits will make that 32 be 1, otherwise it will be 0.
13983 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
13984 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13985 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
13986 DAG.getConstant(5, dl, MVT::i32));
13987 } else {
13988 // CMOV 0, 1, ==, (CMPZ x, y) ->
13989 // (ADDCARRY (SUB x, y), t:0, t:1)
13990 // where t = (SUBCARRY 0, (SUB x, y), 0)
13992 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
13993 // x != y. In other words, a carry C == 1 when x == y, C == 0
13994 // otherwise.
13995 // The final ADDCARRY computes
13996 // x - y + (0 - (x - y)) + C == C
13997 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13998 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13999 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
14000 // ISD::SUBCARRY returns a borrow but we want the carry here
14001 // actually.
14002 SDValue Carry =
14003 DAG.getNode(ISD::SUB, dl, MVT::i32,
14004 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
14005 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
14007 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
14008 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
14009 // This seems pointless but will allow us to combine it further below.
14010 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14011 SDValue Sub =
14012 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14013 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14014 Sub.getValue(1), SDValue());
14015 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
14016 N->getOperand(3), CPSRGlue.getValue(1));
14017 FalseVal = Sub;
14019 } else if (isNullConstant(TrueVal)) {
14020 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
14021 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
14022 // This seems pointless but will allow us to combine it further below
14023 // Note that we change == for != as this is the dual for the case above.
14024 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14025 SDValue Sub =
14026 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14027 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14028 Sub.getValue(1), SDValue());
14029 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
14030 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
14031 N->getOperand(3), CPSRGlue.getValue(1));
14032 FalseVal = Sub;
14036 // On Thumb1, the DAG above may be further combined if z is a power of 2
14037 // (z == 2 ^ K).
14038 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
14039 // t1 = (USUBO (SUB x, y), 1)
14040 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
14041 // Result = if K != 0 then (SHL t2:0, K) else t2:0
14043 // This also handles the special case of comparing against zero; it's
14044 // essentially, the same pattern, except there's no SUBS:
14045 // CMOV x, z, !=, (CMPZ x, 0) ->
14046 // t1 = (USUBO x, 1)
14047 // t2 = (SUBCARRY x, t1:0, t1:1)
14048 // Result = if K != 0 then (SHL t2:0, K) else t2:0
14049 const APInt *TrueConst;
14050 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
14051 ((FalseVal.getOpcode() == ARMISD::SUBS &&
14052 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
14053 (FalseVal == LHS && isNullConstant(RHS))) &&
14054 (TrueConst = isPowerOf2Constant(TrueVal))) {
14055 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14056 unsigned ShiftAmount = TrueConst->logBase2();
14057 if (ShiftAmount)
14058 TrueVal = DAG.getConstant(1, dl, VT);
14059 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
14060 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
14062 if (ShiftAmount)
14063 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
14064 DAG.getConstant(ShiftAmount, dl, MVT::i32));
14067 if (Res.getNode()) {
14068 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
14069 // Capture demanded bits information that would be otherwise lost.
14070 if (Known.Zero == 0xfffffffe)
14071 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14072 DAG.getValueType(MVT::i1));
14073 else if (Known.Zero == 0xffffff00)
14074 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14075 DAG.getValueType(MVT::i8));
14076 else if (Known.Zero == 0xffff0000)
14077 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14078 DAG.getValueType(MVT::i16));
14081 return Res;
14084 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
14085 DAGCombinerInfo &DCI) const {
14086 switch (N->getOpcode()) {
14087 default: break;
14088 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
14089 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
14090 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
14091 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
14092 case ISD::SUB: return PerformSUBCombine(N, DCI);
14093 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
14094 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
14095 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
14096 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
14097 case ISD::BRCOND:
14098 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
14099 case ARMISD::ADDC:
14100 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
14101 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
14102 case ARMISD::BFI: return PerformBFICombine(N, DCI);
14103 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
14104 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
14105 case ISD::STORE: return PerformSTORECombine(N, DCI);
14106 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
14107 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
14108 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
14109 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
14110 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
14111 case ISD::FP_TO_SINT:
14112 case ISD::FP_TO_UINT:
14113 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
14114 case ISD::FDIV:
14115 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
14116 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
14117 case ISD::SHL:
14118 case ISD::SRA:
14119 case ISD::SRL:
14120 return PerformShiftCombine(N, DCI, Subtarget);
14121 case ISD::SIGN_EXTEND:
14122 case ISD::ZERO_EXTEND:
14123 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
14124 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
14125 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
14126 case ISD::LOAD: return PerformLOADCombine(N, DCI);
14127 case ARMISD::VLD1DUP:
14128 case ARMISD::VLD2DUP:
14129 case ARMISD::VLD3DUP:
14130 case ARMISD::VLD4DUP:
14131 return PerformVLDCombine(N, DCI);
14132 case ARMISD::BUILD_VECTOR:
14133 return PerformARMBUILD_VECTORCombine(N, DCI);
14134 case ARMISD::SMULWB: {
14135 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14136 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14137 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14138 return SDValue();
14139 break;
14141 case ARMISD::SMULWT: {
14142 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14143 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14144 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14145 return SDValue();
14146 break;
14148 case ARMISD::SMLALBB: {
14149 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14150 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14151 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14152 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14153 return SDValue();
14154 break;
14156 case ARMISD::SMLALBT: {
14157 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
14158 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14159 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
14160 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14161 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
14162 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
14163 return SDValue();
14164 break;
14166 case ARMISD::SMLALTB: {
14167 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
14168 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14169 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
14170 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14171 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
14172 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
14173 return SDValue();
14174 break;
14176 case ARMISD::SMLALTT: {
14177 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14178 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14179 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14180 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14181 return SDValue();
14182 break;
14184 case ISD::INTRINSIC_VOID:
14185 case ISD::INTRINSIC_W_CHAIN:
14186 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14187 case Intrinsic::arm_neon_vld1:
14188 case Intrinsic::arm_neon_vld1x2:
14189 case Intrinsic::arm_neon_vld1x3:
14190 case Intrinsic::arm_neon_vld1x4:
14191 case Intrinsic::arm_neon_vld2:
14192 case Intrinsic::arm_neon_vld3:
14193 case Intrinsic::arm_neon_vld4:
14194 case Intrinsic::arm_neon_vld2lane:
14195 case Intrinsic::arm_neon_vld3lane:
14196 case Intrinsic::arm_neon_vld4lane:
14197 case Intrinsic::arm_neon_vld2dup:
14198 case Intrinsic::arm_neon_vld3dup:
14199 case Intrinsic::arm_neon_vld4dup:
14200 case Intrinsic::arm_neon_vst1:
14201 case Intrinsic::arm_neon_vst1x2:
14202 case Intrinsic::arm_neon_vst1x3:
14203 case Intrinsic::arm_neon_vst1x4:
14204 case Intrinsic::arm_neon_vst2:
14205 case Intrinsic::arm_neon_vst3:
14206 case Intrinsic::arm_neon_vst4:
14207 case Intrinsic::arm_neon_vst2lane:
14208 case Intrinsic::arm_neon_vst3lane:
14209 case Intrinsic::arm_neon_vst4lane:
14210 return PerformVLDCombine(N, DCI);
14211 default: break;
14213 break;
14215 return SDValue();
14218 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
14219 EVT VT) const {
14220 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
14223 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
14224 unsigned Alignment,
14225 MachineMemOperand::Flags,
14226 bool *Fast) const {
14227 // Depends what it gets converted into if the type is weird.
14228 if (!VT.isSimple())
14229 return false;
14231 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
14232 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
14233 auto Ty = VT.getSimpleVT().SimpleTy;
14235 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
14236 // Unaligned access can use (for example) LRDB, LRDH, LDR
14237 if (AllowsUnaligned) {
14238 if (Fast)
14239 *Fast = Subtarget->hasV7Ops();
14240 return true;
14244 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
14245 // For any little-endian targets with neon, we can support unaligned ld/st
14246 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
14247 // A big-endian target may also explicitly support unaligned accesses
14248 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
14249 if (Fast)
14250 *Fast = true;
14251 return true;
14255 if (!Subtarget->hasMVEIntegerOps())
14256 return false;
14258 // These are for predicates
14259 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14260 if (Fast)
14261 *Fast = true;
14262 return true;
14265 // These are for truncated stores/narrowing loads. They are fine so long as
14266 // the alignment is at least the size of the item being loaded
14267 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
14268 Alignment >= VT.getScalarSizeInBits() / 8) {
14269 if (Fast)
14270 *Fast = true;
14271 return true;
14274 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
14275 // VSTRW.U32 all store the vector register in exactly the same format, and
14276 // differ only in the range of their immediate offset field and the required
14277 // alignment. So there is always a store that can be used, regardless of
14278 // actual type.
14280 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
14281 // VREV64.8) pair and get the same effect. This will likely be better than
14282 // aligning the vector through the stack.
14283 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
14284 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
14285 Ty == MVT::v2f64) {
14286 if (Fast)
14287 *Fast = true;
14288 return true;
14291 return false;
14294 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14295 unsigned AlignCheck) {
14296 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14297 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14300 EVT ARMTargetLowering::getOptimalMemOpType(
14301 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14302 bool ZeroMemset, bool MemcpyStrSrc,
14303 const AttributeList &FuncAttributes) const {
14304 // See if we can use NEON instructions for this...
14305 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14306 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14307 bool Fast;
14308 if (Size >= 16 &&
14309 (memOpAlign(SrcAlign, DstAlign, 16) ||
14310 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14311 MachineMemOperand::MONone, &Fast) &&
14312 Fast))) {
14313 return MVT::v2f64;
14314 } else if (Size >= 8 &&
14315 (memOpAlign(SrcAlign, DstAlign, 8) ||
14316 (allowsMisalignedMemoryAccesses(
14317 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14318 Fast))) {
14319 return MVT::f64;
14323 // Let the target-independent logic figure it out.
14324 return MVT::Other;
14327 // 64-bit integers are split into their high and low parts and held in two
14328 // different registers, so the trunc is free since the low register can just
14329 // be used.
14330 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14331 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14332 return false;
14333 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14334 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14335 return (SrcBits == 64 && DestBits == 32);
14338 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14339 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14340 !DstVT.isInteger())
14341 return false;
14342 unsigned SrcBits = SrcVT.getSizeInBits();
14343 unsigned DestBits = DstVT.getSizeInBits();
14344 return (SrcBits == 64 && DestBits == 32);
14347 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14348 if (Val.getOpcode() != ISD::LOAD)
14349 return false;
14351 EVT VT1 = Val.getValueType();
14352 if (!VT1.isSimple() || !VT1.isInteger() ||
14353 !VT2.isSimple() || !VT2.isInteger())
14354 return false;
14356 switch (VT1.getSimpleVT().SimpleTy) {
14357 default: break;
14358 case MVT::i1:
14359 case MVT::i8:
14360 case MVT::i16:
14361 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14362 return true;
14365 return false;
14368 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14369 if (!VT.isSimple())
14370 return false;
14372 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14373 // negate values directly (fneg is free). So, we don't want to let the DAG
14374 // combiner rewrite fneg into xors and some other instructions. For f16 and
14375 // FullFP16 argument passing, some bitcast nodes may be introduced,
14376 // triggering this DAG combine rewrite, so we are avoiding that with this.
14377 switch (VT.getSimpleVT().SimpleTy) {
14378 default: break;
14379 case MVT::f16:
14380 return Subtarget->hasFullFP16();
14383 return false;
14386 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14387 /// of the vector elements.
14388 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14389 auto areExtDoubled = [](Instruction *Ext) {
14390 return Ext->getType()->getScalarSizeInBits() ==
14391 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14394 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14395 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14396 !areExtDoubled(cast<Instruction>(Ext1)) ||
14397 !areExtDoubled(cast<Instruction>(Ext2)))
14398 return false;
14400 return true;
14403 /// Check if sinking \p I's operands to I's basic block is profitable, because
14404 /// the operands can be folded into a target instruction, e.g.
14405 /// sext/zext can be folded into vsubl.
14406 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14407 SmallVectorImpl<Use *> &Ops) const {
14408 if (!I->getType()->isVectorTy())
14409 return false;
14411 if (Subtarget->hasNEON()) {
14412 switch (I->getOpcode()) {
14413 case Instruction::Sub:
14414 case Instruction::Add: {
14415 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14416 return false;
14417 Ops.push_back(&I->getOperandUse(0));
14418 Ops.push_back(&I->getOperandUse(1));
14419 return true;
14421 default:
14422 return false;
14426 if (!Subtarget->hasMVEIntegerOps())
14427 return false;
14429 auto IsSinker = [](Instruction *I, int Operand) {
14430 switch (I->getOpcode()) {
14431 case Instruction::Add:
14432 case Instruction::Mul:
14433 return true;
14434 case Instruction::Sub:
14435 return Operand == 1;
14436 default:
14437 return false;
14441 int Op = 0;
14442 if (!isa<ShuffleVectorInst>(I->getOperand(Op)))
14443 Op = 1;
14444 if (!IsSinker(I, Op))
14445 return false;
14446 if (!match(I->getOperand(Op),
14447 m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()),
14448 m_Undef(), m_Zero()))) {
14449 return false;
14451 Instruction *Shuffle = cast<Instruction>(I->getOperand(Op));
14452 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
14453 // and vector registers
14454 for (Use &U : Shuffle->uses()) {
14455 Instruction *Insn = cast<Instruction>(U.getUser());
14456 if (!IsSinker(Insn, U.getOperandNo()))
14457 return false;
14459 Ops.push_back(&Shuffle->getOperandUse(0));
14460 Ops.push_back(&I->getOperandUse(Op));
14461 return true;
14464 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14465 EVT VT = ExtVal.getValueType();
14467 if (!isTypeLegal(VT))
14468 return false;
14470 // Don't create a loadext if we can fold the extension into a wide/long
14471 // instruction.
14472 // If there's more than one user instruction, the loadext is desirable no
14473 // matter what. There can be two uses by the same instruction.
14474 if (ExtVal->use_empty() ||
14475 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14476 return true;
14478 SDNode *U = *ExtVal->use_begin();
14479 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14480 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14481 return false;
14483 return true;
14486 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14487 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14488 return false;
14490 if (!isTypeLegal(EVT::getEVT(Ty1)))
14491 return false;
14493 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14495 // Assuming the caller doesn't have a zeroext or signext return parameter,
14496 // truncation all the way down to i1 is valid.
14497 return true;
14500 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14501 const AddrMode &AM, Type *Ty,
14502 unsigned AS) const {
14503 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14504 if (Subtarget->hasFPAO())
14505 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14506 return 0;
14508 return -1;
14511 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14512 if (V < 0)
14513 return false;
14515 unsigned Scale = 1;
14516 switch (VT.getSimpleVT().SimpleTy) {
14517 case MVT::i1:
14518 case MVT::i8:
14519 // Scale == 1;
14520 break;
14521 case MVT::i16:
14522 // Scale == 2;
14523 Scale = 2;
14524 break;
14525 default:
14526 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14527 // Scale == 4;
14528 Scale = 4;
14529 break;
14532 if ((V & (Scale - 1)) != 0)
14533 return false;
14534 return isUInt<5>(V / Scale);
14537 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14538 const ARMSubtarget *Subtarget) {
14539 if (!VT.isInteger() && !VT.isFloatingPoint())
14540 return false;
14541 if (VT.isVector() && Subtarget->hasNEON())
14542 return false;
14543 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14544 !Subtarget->hasMVEFloatOps())
14545 return false;
14547 bool IsNeg = false;
14548 if (V < 0) {
14549 IsNeg = true;
14550 V = -V;
14553 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14555 // MVE: size * imm7
14556 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14557 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14558 case MVT::i32:
14559 case MVT::f32:
14560 return isShiftedUInt<7,2>(V);
14561 case MVT::i16:
14562 case MVT::f16:
14563 return isShiftedUInt<7,1>(V);
14564 case MVT::i8:
14565 return isUInt<7>(V);
14566 default:
14567 return false;
14571 // half VLDR: 2 * imm8
14572 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14573 return isShiftedUInt<8, 1>(V);
14574 // VLDR and LDRD: 4 * imm8
14575 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14576 return isShiftedUInt<8, 2>(V);
14578 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14579 // + imm12 or - imm8
14580 if (IsNeg)
14581 return isUInt<8>(V);
14582 return isUInt<12>(V);
14585 return false;
14588 /// isLegalAddressImmediate - Return true if the integer value can be used
14589 /// as the offset of the target addressing mode for load / store of the
14590 /// given type.
14591 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14592 const ARMSubtarget *Subtarget) {
14593 if (V == 0)
14594 return true;
14596 if (!VT.isSimple())
14597 return false;
14599 if (Subtarget->isThumb1Only())
14600 return isLegalT1AddressImmediate(V, VT);
14601 else if (Subtarget->isThumb2())
14602 return isLegalT2AddressImmediate(V, VT, Subtarget);
14604 // ARM mode.
14605 if (V < 0)
14606 V = - V;
14607 switch (VT.getSimpleVT().SimpleTy) {
14608 default: return false;
14609 case MVT::i1:
14610 case MVT::i8:
14611 case MVT::i32:
14612 // +- imm12
14613 return isUInt<12>(V);
14614 case MVT::i16:
14615 // +- imm8
14616 return isUInt<8>(V);
14617 case MVT::f32:
14618 case MVT::f64:
14619 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14620 return false;
14621 return isShiftedUInt<8, 2>(V);
14625 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14626 EVT VT) const {
14627 int Scale = AM.Scale;
14628 if (Scale < 0)
14629 return false;
14631 switch (VT.getSimpleVT().SimpleTy) {
14632 default: return false;
14633 case MVT::i1:
14634 case MVT::i8:
14635 case MVT::i16:
14636 case MVT::i32:
14637 if (Scale == 1)
14638 return true;
14639 // r + r << imm
14640 Scale = Scale & ~1;
14641 return Scale == 2 || Scale == 4 || Scale == 8;
14642 case MVT::i64:
14643 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14644 // version in Thumb mode.
14645 // r + r
14646 if (Scale == 1)
14647 return true;
14648 // r * 2 (this can be lowered to r + r).
14649 if (!AM.HasBaseReg && Scale == 2)
14650 return true;
14651 return false;
14652 case MVT::isVoid:
14653 // Note, we allow "void" uses (basically, uses that aren't loads or
14654 // stores), because arm allows folding a scale into many arithmetic
14655 // operations. This should be made more precise and revisited later.
14657 // Allow r << imm, but the imm has to be a multiple of two.
14658 if (Scale & 1) return false;
14659 return isPowerOf2_32(Scale);
14663 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14664 EVT VT) const {
14665 const int Scale = AM.Scale;
14667 // Negative scales are not supported in Thumb1.
14668 if (Scale < 0)
14669 return false;
14671 // Thumb1 addressing modes do not support register scaling excepting the
14672 // following cases:
14673 // 1. Scale == 1 means no scaling.
14674 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14675 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14678 /// isLegalAddressingMode - Return true if the addressing mode represented
14679 /// by AM is legal for this target, for a load/store of the specified type.
14680 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14681 const AddrMode &AM, Type *Ty,
14682 unsigned AS, Instruction *I) const {
14683 EVT VT = getValueType(DL, Ty, true);
14684 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14685 return false;
14687 // Can never fold addr of global into load/store.
14688 if (AM.BaseGV)
14689 return false;
14691 switch (AM.Scale) {
14692 case 0: // no scale reg, must be "r+i" or "r", or "i".
14693 break;
14694 default:
14695 // ARM doesn't support any R+R*scale+imm addr modes.
14696 if (AM.BaseOffs)
14697 return false;
14699 if (!VT.isSimple())
14700 return false;
14702 if (Subtarget->isThumb1Only())
14703 return isLegalT1ScaledAddressingMode(AM, VT);
14705 if (Subtarget->isThumb2())
14706 return isLegalT2ScaledAddressingMode(AM, VT);
14708 int Scale = AM.Scale;
14709 switch (VT.getSimpleVT().SimpleTy) {
14710 default: return false;
14711 case MVT::i1:
14712 case MVT::i8:
14713 case MVT::i32:
14714 if (Scale < 0) Scale = -Scale;
14715 if (Scale == 1)
14716 return true;
14717 // r + r << imm
14718 return isPowerOf2_32(Scale & ~1);
14719 case MVT::i16:
14720 case MVT::i64:
14721 // r +/- r
14722 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
14723 return true;
14724 // r * 2 (this can be lowered to r + r).
14725 if (!AM.HasBaseReg && Scale == 2)
14726 return true;
14727 return false;
14729 case MVT::isVoid:
14730 // Note, we allow "void" uses (basically, uses that aren't loads or
14731 // stores), because arm allows folding a scale into many arithmetic
14732 // operations. This should be made more precise and revisited later.
14734 // Allow r << imm, but the imm has to be a multiple of two.
14735 if (Scale & 1) return false;
14736 return isPowerOf2_32(Scale);
14739 return true;
14742 /// isLegalICmpImmediate - Return true if the specified immediate is legal
14743 /// icmp immediate, that is the target has icmp instructions which can compare
14744 /// a register against the immediate without having to materialize the
14745 /// immediate into a register.
14746 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14747 // Thumb2 and ARM modes can use cmn for negative immediates.
14748 if (!Subtarget->isThumb())
14749 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
14750 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
14751 if (Subtarget->isThumb2())
14752 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
14753 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
14754 // Thumb1 doesn't have cmn, and only 8-bit immediates.
14755 return Imm >= 0 && Imm <= 255;
14758 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
14759 /// *or sub* immediate, that is the target has add or sub instructions which can
14760 /// add a register with the immediate without having to materialize the
14761 /// immediate into a register.
14762 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14763 // Same encoding for add/sub, just flip the sign.
14764 int64_t AbsImm = std::abs(Imm);
14765 if (!Subtarget->isThumb())
14766 return ARM_AM::getSOImmVal(AbsImm) != -1;
14767 if (Subtarget->isThumb2())
14768 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
14769 // Thumb1 only has 8-bit unsigned immediate.
14770 return AbsImm >= 0 && AbsImm <= 255;
14773 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
14774 bool isSEXTLoad, SDValue &Base,
14775 SDValue &Offset, bool &isInc,
14776 SelectionDAG &DAG) {
14777 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14778 return false;
14780 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
14781 // AddressingMode 3
14782 Base = Ptr->getOperand(0);
14783 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14784 int RHSC = (int)RHS->getZExtValue();
14785 if (RHSC < 0 && RHSC > -256) {
14786 assert(Ptr->getOpcode() == ISD::ADD);
14787 isInc = false;
14788 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14789 return true;
14792 isInc = (Ptr->getOpcode() == ISD::ADD);
14793 Offset = Ptr->getOperand(1);
14794 return true;
14795 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
14796 // AddressingMode 2
14797 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14798 int RHSC = (int)RHS->getZExtValue();
14799 if (RHSC < 0 && RHSC > -0x1000) {
14800 assert(Ptr->getOpcode() == ISD::ADD);
14801 isInc = false;
14802 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14803 Base = Ptr->getOperand(0);
14804 return true;
14808 if (Ptr->getOpcode() == ISD::ADD) {
14809 isInc = true;
14810 ARM_AM::ShiftOpc ShOpcVal=
14811 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
14812 if (ShOpcVal != ARM_AM::no_shift) {
14813 Base = Ptr->getOperand(1);
14814 Offset = Ptr->getOperand(0);
14815 } else {
14816 Base = Ptr->getOperand(0);
14817 Offset = Ptr->getOperand(1);
14819 return true;
14822 isInc = (Ptr->getOpcode() == ISD::ADD);
14823 Base = Ptr->getOperand(0);
14824 Offset = Ptr->getOperand(1);
14825 return true;
14828 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
14829 return false;
14832 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
14833 bool isSEXTLoad, SDValue &Base,
14834 SDValue &Offset, bool &isInc,
14835 SelectionDAG &DAG) {
14836 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14837 return false;
14839 Base = Ptr->getOperand(0);
14840 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14841 int RHSC = (int)RHS->getZExtValue();
14842 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
14843 assert(Ptr->getOpcode() == ISD::ADD);
14844 isInc = false;
14845 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14846 return true;
14847 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
14848 isInc = Ptr->getOpcode() == ISD::ADD;
14849 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14850 return true;
14854 return false;
14857 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
14858 bool isSEXTLoad, bool isLE, SDValue &Base,
14859 SDValue &Offset, bool &isInc,
14860 SelectionDAG &DAG) {
14861 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14862 return false;
14863 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
14864 return false;
14866 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
14867 int RHSC = (int)RHS->getZExtValue();
14869 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
14870 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
14871 assert(Ptr->getOpcode() == ISD::ADD);
14872 isInc = false;
14873 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14874 return true;
14875 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
14876 isInc = Ptr->getOpcode() == ISD::ADD;
14877 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14878 return true;
14880 return false;
14883 // Try to find a matching instruction based on s/zext, Alignment, Offset and
14884 // (in BE) type.
14885 Base = Ptr->getOperand(0);
14886 if (VT == MVT::v4i16) {
14887 if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
14888 return true;
14889 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
14890 if (IsInRange(RHSC, 0x80, 1))
14891 return true;
14892 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) &&
14893 IsInRange(RHSC, 0x80, 4))
14894 return true;
14895 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) &&
14896 IsInRange(RHSC, 0x80, 2))
14897 return true;
14898 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
14899 return true;
14900 return false;
14903 /// getPreIndexedAddressParts - returns true by value, base pointer and
14904 /// offset pointer and addressing mode by reference if the node's address
14905 /// can be legally represented as pre-indexed load / store address.
14906 bool
14907 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14908 SDValue &Offset,
14909 ISD::MemIndexedMode &AM,
14910 SelectionDAG &DAG) const {
14911 if (Subtarget->isThumb1Only())
14912 return false;
14914 EVT VT;
14915 SDValue Ptr;
14916 unsigned Align;
14917 bool isSEXTLoad = false;
14918 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14919 Ptr = LD->getBasePtr();
14920 VT = LD->getMemoryVT();
14921 Align = LD->getAlignment();
14922 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14923 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14924 Ptr = ST->getBasePtr();
14925 VT = ST->getMemoryVT();
14926 Align = ST->getAlignment();
14927 } else
14928 return false;
14930 bool isInc;
14931 bool isLegal = false;
14932 if (VT.isVector())
14933 isLegal = Subtarget->hasMVEIntegerOps() &&
14934 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
14935 Subtarget->isLittle(), Base, Offset,
14936 isInc, DAG);
14937 else {
14938 if (Subtarget->isThumb2())
14939 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14940 Offset, isInc, DAG);
14941 else
14942 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14943 Offset, isInc, DAG);
14945 if (!isLegal)
14946 return false;
14948 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
14949 return true;
14952 /// getPostIndexedAddressParts - returns true by value, base pointer and
14953 /// offset pointer and addressing mode by reference if this node can be
14954 /// combined with a load / store to form a post-indexed load / store.
14955 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
14956 SDValue &Base,
14957 SDValue &Offset,
14958 ISD::MemIndexedMode &AM,
14959 SelectionDAG &DAG) const {
14960 EVT VT;
14961 SDValue Ptr;
14962 unsigned Align;
14963 bool isSEXTLoad = false, isNonExt;
14964 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14965 VT = LD->getMemoryVT();
14966 Ptr = LD->getBasePtr();
14967 Align = LD->getAlignment();
14968 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14969 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
14970 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14971 VT = ST->getMemoryVT();
14972 Ptr = ST->getBasePtr();
14973 Align = ST->getAlignment();
14974 isNonExt = !ST->isTruncatingStore();
14975 } else
14976 return false;
14978 if (Subtarget->isThumb1Only()) {
14979 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
14980 // must be non-extending/truncating, i32, with an offset of 4.
14981 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
14982 if (Op->getOpcode() != ISD::ADD || !isNonExt)
14983 return false;
14984 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14985 if (!RHS || RHS->getZExtValue() != 4)
14986 return false;
14988 Offset = Op->getOperand(1);
14989 Base = Op->getOperand(0);
14990 AM = ISD::POST_INC;
14991 return true;
14994 bool isInc;
14995 bool isLegal = false;
14996 if (VT.isVector())
14997 isLegal = Subtarget->hasMVEIntegerOps() &&
14998 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad,
14999 Subtarget->isLittle(), Base, Offset,
15000 isInc, DAG);
15001 else {
15002 if (Subtarget->isThumb2())
15003 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15004 isInc, DAG);
15005 else
15006 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15007 isInc, DAG);
15009 if (!isLegal)
15010 return false;
15012 if (Ptr != Base) {
15013 // Swap base ptr and offset to catch more post-index load / store when
15014 // it's legal. In Thumb2 mode, offset must be an immediate.
15015 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
15016 !Subtarget->isThumb2())
15017 std::swap(Base, Offset);
15019 // Post-indexed load / store update the base pointer.
15020 if (Ptr != Base)
15021 return false;
15024 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
15025 return true;
15028 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15029 KnownBits &Known,
15030 const APInt &DemandedElts,
15031 const SelectionDAG &DAG,
15032 unsigned Depth) const {
15033 unsigned BitWidth = Known.getBitWidth();
15034 Known.resetAll();
15035 switch (Op.getOpcode()) {
15036 default: break;
15037 case ARMISD::ADDC:
15038 case ARMISD::ADDE:
15039 case ARMISD::SUBC:
15040 case ARMISD::SUBE:
15041 // Special cases when we convert a carry to a boolean.
15042 if (Op.getResNo() == 0) {
15043 SDValue LHS = Op.getOperand(0);
15044 SDValue RHS = Op.getOperand(1);
15045 // (ADDE 0, 0, C) will give us a single bit.
15046 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
15047 isNullConstant(RHS)) {
15048 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15049 return;
15052 break;
15053 case ARMISD::CMOV: {
15054 // Bits are known zero/one if known on the LHS and RHS.
15055 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
15056 if (Known.isUnknown())
15057 return;
15059 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
15060 Known.Zero &= KnownRHS.Zero;
15061 Known.One &= KnownRHS.One;
15062 return;
15064 case ISD::INTRINSIC_W_CHAIN: {
15065 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
15066 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
15067 switch (IntID) {
15068 default: return;
15069 case Intrinsic::arm_ldaex:
15070 case Intrinsic::arm_ldrex: {
15071 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
15072 unsigned MemBits = VT.getScalarSizeInBits();
15073 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
15074 return;
15078 case ARMISD::BFI: {
15079 // Conservatively, we can recurse down the first operand
15080 // and just mask out all affected bits.
15081 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
15083 // The operand to BFI is already a mask suitable for removing the bits it
15084 // sets.
15085 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
15086 const APInt &Mask = CI->getAPIntValue();
15087 Known.Zero &= Mask;
15088 Known.One &= Mask;
15089 return;
15091 case ARMISD::VGETLANEs:
15092 case ARMISD::VGETLANEu: {
15093 const SDValue &SrcSV = Op.getOperand(0);
15094 EVT VecVT = SrcSV.getValueType();
15095 assert(VecVT.isVector() && "VGETLANE expected a vector type");
15096 const unsigned NumSrcElts = VecVT.getVectorNumElements();
15097 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
15098 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
15099 "VGETLANE index out of bounds");
15100 unsigned Idx = Pos->getZExtValue();
15101 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
15102 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
15104 EVT VT = Op.getValueType();
15105 const unsigned DstSz = VT.getScalarSizeInBits();
15106 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
15107 (void)SrcSz;
15108 assert(SrcSz == Known.getBitWidth());
15109 assert(DstSz > SrcSz);
15110 if (Op.getOpcode() == ARMISD::VGETLANEs)
15111 Known = Known.sext(DstSz);
15112 else {
15113 Known = Known.zext(DstSz, true /* extended bits are known zero */);
15115 assert(DstSz == Known.getBitWidth());
15116 break;
15121 bool
15122 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
15123 const APInt &DemandedAPInt,
15124 TargetLoweringOpt &TLO) const {
15125 // Delay optimization, so we don't have to deal with illegal types, or block
15126 // optimizations.
15127 if (!TLO.LegalOps)
15128 return false;
15130 // Only optimize AND for now.
15131 if (Op.getOpcode() != ISD::AND)
15132 return false;
15134 EVT VT = Op.getValueType();
15136 // Ignore vectors.
15137 if (VT.isVector())
15138 return false;
15140 assert(VT == MVT::i32 && "Unexpected integer type");
15142 // Make sure the RHS really is a constant.
15143 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15144 if (!C)
15145 return false;
15147 unsigned Mask = C->getZExtValue();
15149 unsigned Demanded = DemandedAPInt.getZExtValue();
15150 unsigned ShrunkMask = Mask & Demanded;
15151 unsigned ExpandedMask = Mask | ~Demanded;
15153 // If the mask is all zeros, let the target-independent code replace the
15154 // result with zero.
15155 if (ShrunkMask == 0)
15156 return false;
15158 // If the mask is all ones, erase the AND. (Currently, the target-independent
15159 // code won't do this, so we have to do it explicitly to avoid an infinite
15160 // loop in obscure cases.)
15161 if (ExpandedMask == ~0U)
15162 return TLO.CombineTo(Op, Op.getOperand(0));
15164 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
15165 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
15167 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
15168 if (NewMask == Mask)
15169 return true;
15170 SDLoc DL(Op);
15171 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
15172 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
15173 return TLO.CombineTo(Op, NewOp);
15176 // Prefer uxtb mask.
15177 if (IsLegalMask(0xFF))
15178 return UseMask(0xFF);
15180 // Prefer uxth mask.
15181 if (IsLegalMask(0xFFFF))
15182 return UseMask(0xFFFF);
15184 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
15185 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15186 if (ShrunkMask < 256)
15187 return UseMask(ShrunkMask);
15189 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
15190 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15191 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
15192 return UseMask(ExpandedMask);
15194 // Potential improvements:
15196 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
15197 // We could try to prefer Thumb1 immediates which can be lowered to a
15198 // two-instruction sequence.
15199 // We could try to recognize more legal ARM/Thumb2 immediates here.
15201 return false;
15205 //===----------------------------------------------------------------------===//
15206 // ARM Inline Assembly Support
15207 //===----------------------------------------------------------------------===//
15209 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
15210 // Looking for "rev" which is V6+.
15211 if (!Subtarget->hasV6Ops())
15212 return false;
15214 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15215 std::string AsmStr = IA->getAsmString();
15216 SmallVector<StringRef, 4> AsmPieces;
15217 SplitString(AsmStr, AsmPieces, ";\n");
15219 switch (AsmPieces.size()) {
15220 default: return false;
15221 case 1:
15222 AsmStr = AsmPieces[0];
15223 AsmPieces.clear();
15224 SplitString(AsmStr, AsmPieces, " \t,");
15226 // rev $0, $1
15227 if (AsmPieces.size() == 3 &&
15228 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
15229 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
15230 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15231 if (Ty && Ty->getBitWidth() == 32)
15232 return IntrinsicLowering::LowerToByteSwap(CI);
15234 break;
15237 return false;
15240 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
15241 // At this point, we have to lower this constraint to something else, so we
15242 // lower it to an "r" or "w". However, by doing this we will force the result
15243 // to be in register, while the X constraint is much more permissive.
15245 // Although we are correct (we are free to emit anything, without
15246 // constraints), we might break use cases that would expect us to be more
15247 // efficient and emit something else.
15248 if (!Subtarget->hasVFP2Base())
15249 return "r";
15250 if (ConstraintVT.isFloatingPoint())
15251 return "w";
15252 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
15253 (ConstraintVT.getSizeInBits() == 64 ||
15254 ConstraintVT.getSizeInBits() == 128))
15255 return "w";
15257 return "r";
15260 /// getConstraintType - Given a constraint letter, return the type of
15261 /// constraint it is for this target.
15262 ARMTargetLowering::ConstraintType
15263 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
15264 unsigned S = Constraint.size();
15265 if (S == 1) {
15266 switch (Constraint[0]) {
15267 default: break;
15268 case 'l': return C_RegisterClass;
15269 case 'w': return C_RegisterClass;
15270 case 'h': return C_RegisterClass;
15271 case 'x': return C_RegisterClass;
15272 case 't': return C_RegisterClass;
15273 case 'j': return C_Immediate; // Constant for movw.
15274 // An address with a single base register. Due to the way we
15275 // currently handle addresses it is the same as an 'r' memory constraint.
15276 case 'Q': return C_Memory;
15278 } else if (S == 2) {
15279 switch (Constraint[0]) {
15280 default: break;
15281 case 'T': return C_RegisterClass;
15282 // All 'U+' constraints are addresses.
15283 case 'U': return C_Memory;
15286 return TargetLowering::getConstraintType(Constraint);
15289 /// Examine constraint type and operand type and determine a weight value.
15290 /// This object must already have been set up with the operand type
15291 /// and the current alternative constraint selected.
15292 TargetLowering::ConstraintWeight
15293 ARMTargetLowering::getSingleConstraintMatchWeight(
15294 AsmOperandInfo &info, const char *constraint) const {
15295 ConstraintWeight weight = CW_Invalid;
15296 Value *CallOperandVal = info.CallOperandVal;
15297 // If we don't have a value, we can't do a match,
15298 // but allow it at the lowest weight.
15299 if (!CallOperandVal)
15300 return CW_Default;
15301 Type *type = CallOperandVal->getType();
15302 // Look at the constraint type.
15303 switch (*constraint) {
15304 default:
15305 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15306 break;
15307 case 'l':
15308 if (type->isIntegerTy()) {
15309 if (Subtarget->isThumb())
15310 weight = CW_SpecificReg;
15311 else
15312 weight = CW_Register;
15314 break;
15315 case 'w':
15316 if (type->isFloatingPointTy())
15317 weight = CW_Register;
15318 break;
15320 return weight;
15323 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
15325 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
15326 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
15327 switch (Constraint.size()) {
15328 case 1:
15329 // GCC ARM Constraint Letters
15330 switch (Constraint[0]) {
15331 case 'l': // Low regs or general regs.
15332 if (Subtarget->isThumb())
15333 return RCPair(0U, &ARM::tGPRRegClass);
15334 return RCPair(0U, &ARM::GPRRegClass);
15335 case 'h': // High regs or no regs.
15336 if (Subtarget->isThumb())
15337 return RCPair(0U, &ARM::hGPRRegClass);
15338 break;
15339 case 'r':
15340 if (Subtarget->isThumb1Only())
15341 return RCPair(0U, &ARM::tGPRRegClass);
15342 return RCPair(0U, &ARM::GPRRegClass);
15343 case 'w':
15344 if (VT == MVT::Other)
15345 break;
15346 if (VT == MVT::f32)
15347 return RCPair(0U, &ARM::SPRRegClass);
15348 if (VT.getSizeInBits() == 64)
15349 return RCPair(0U, &ARM::DPRRegClass);
15350 if (VT.getSizeInBits() == 128)
15351 return RCPair(0U, &ARM::QPRRegClass);
15352 break;
15353 case 'x':
15354 if (VT == MVT::Other)
15355 break;
15356 if (VT == MVT::f32)
15357 return RCPair(0U, &ARM::SPR_8RegClass);
15358 if (VT.getSizeInBits() == 64)
15359 return RCPair(0U, &ARM::DPR_8RegClass);
15360 if (VT.getSizeInBits() == 128)
15361 return RCPair(0U, &ARM::QPR_8RegClass);
15362 break;
15363 case 't':
15364 if (VT == MVT::Other)
15365 break;
15366 if (VT == MVT::f32 || VT == MVT::i32)
15367 return RCPair(0U, &ARM::SPRRegClass);
15368 if (VT.getSizeInBits() == 64)
15369 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15370 if (VT.getSizeInBits() == 128)
15371 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15372 break;
15374 break;
15376 case 2:
15377 if (Constraint[0] == 'T') {
15378 switch (Constraint[1]) {
15379 default:
15380 break;
15381 case 'e':
15382 return RCPair(0U, &ARM::tGPREvenRegClass);
15383 case 'o':
15384 return RCPair(0U, &ARM::tGPROddRegClass);
15387 break;
15389 default:
15390 break;
15393 if (StringRef("{cc}").equals_lower(Constraint))
15394 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15396 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15399 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15400 /// vector. If it is invalid, don't add anything to Ops.
15401 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15402 std::string &Constraint,
15403 std::vector<SDValue>&Ops,
15404 SelectionDAG &DAG) const {
15405 SDValue Result;
15407 // Currently only support length 1 constraints.
15408 if (Constraint.length() != 1) return;
15410 char ConstraintLetter = Constraint[0];
15411 switch (ConstraintLetter) {
15412 default: break;
15413 case 'j':
15414 case 'I': case 'J': case 'K': case 'L':
15415 case 'M': case 'N': case 'O':
15416 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15417 if (!C)
15418 return;
15420 int64_t CVal64 = C->getSExtValue();
15421 int CVal = (int) CVal64;
15422 // None of these constraints allow values larger than 32 bits. Check
15423 // that the value fits in an int.
15424 if (CVal != CVal64)
15425 return;
15427 switch (ConstraintLetter) {
15428 case 'j':
15429 // Constant suitable for movw, must be between 0 and
15430 // 65535.
15431 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
15432 if (CVal >= 0 && CVal <= 65535)
15433 break;
15434 return;
15435 case 'I':
15436 if (Subtarget->isThumb1Only()) {
15437 // This must be a constant between 0 and 255, for ADD
15438 // immediates.
15439 if (CVal >= 0 && CVal <= 255)
15440 break;
15441 } else if (Subtarget->isThumb2()) {
15442 // A constant that can be used as an immediate value in a
15443 // data-processing instruction.
15444 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15445 break;
15446 } else {
15447 // A constant that can be used as an immediate value in a
15448 // data-processing instruction.
15449 if (ARM_AM::getSOImmVal(CVal) != -1)
15450 break;
15452 return;
15454 case 'J':
15455 if (Subtarget->isThumb1Only()) {
15456 // This must be a constant between -255 and -1, for negated ADD
15457 // immediates. This can be used in GCC with an "n" modifier that
15458 // prints the negated value, for use with SUB instructions. It is
15459 // not useful otherwise but is implemented for compatibility.
15460 if (CVal >= -255 && CVal <= -1)
15461 break;
15462 } else {
15463 // This must be a constant between -4095 and 4095. It is not clear
15464 // what this constraint is intended for. Implemented for
15465 // compatibility with GCC.
15466 if (CVal >= -4095 && CVal <= 4095)
15467 break;
15469 return;
15471 case 'K':
15472 if (Subtarget->isThumb1Only()) {
15473 // A 32-bit value where only one byte has a nonzero value. Exclude
15474 // zero to match GCC. This constraint is used by GCC internally for
15475 // constants that can be loaded with a move/shift combination.
15476 // It is not useful otherwise but is implemented for compatibility.
15477 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15478 break;
15479 } else if (Subtarget->isThumb2()) {
15480 // A constant whose bitwise inverse can be used as an immediate
15481 // value in a data-processing instruction. This can be used in GCC
15482 // with a "B" modifier that prints the inverted value, for use with
15483 // BIC and MVN instructions. It is not useful otherwise but is
15484 // implemented for compatibility.
15485 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15486 break;
15487 } else {
15488 // A constant whose bitwise inverse can be used as an immediate
15489 // value in a data-processing instruction. This can be used in GCC
15490 // with a "B" modifier that prints the inverted value, for use with
15491 // BIC and MVN instructions. It is not useful otherwise but is
15492 // implemented for compatibility.
15493 if (ARM_AM::getSOImmVal(~CVal) != -1)
15494 break;
15496 return;
15498 case 'L':
15499 if (Subtarget->isThumb1Only()) {
15500 // This must be a constant between -7 and 7,
15501 // for 3-operand ADD/SUB immediate instructions.
15502 if (CVal >= -7 && CVal < 7)
15503 break;
15504 } else if (Subtarget->isThumb2()) {
15505 // A constant whose negation can be used as an immediate value in a
15506 // data-processing instruction. This can be used in GCC with an "n"
15507 // modifier that prints the negated value, for use with SUB
15508 // instructions. It is not useful otherwise but is implemented for
15509 // compatibility.
15510 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15511 break;
15512 } else {
15513 // A constant whose negation can be used as an immediate value in a
15514 // data-processing instruction. This can be used in GCC with an "n"
15515 // modifier that prints the negated value, for use with SUB
15516 // instructions. It is not useful otherwise but is implemented for
15517 // compatibility.
15518 if (ARM_AM::getSOImmVal(-CVal) != -1)
15519 break;
15521 return;
15523 case 'M':
15524 if (Subtarget->isThumb1Only()) {
15525 // This must be a multiple of 4 between 0 and 1020, for
15526 // ADD sp + immediate.
15527 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15528 break;
15529 } else {
15530 // A power of two or a constant between 0 and 32. This is used in
15531 // GCC for the shift amount on shifted register operands, but it is
15532 // useful in general for any shift amounts.
15533 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15534 break;
15536 return;
15538 case 'N':
15539 if (Subtarget->isThumb1Only()) {
15540 // This must be a constant between 0 and 31, for shift amounts.
15541 if (CVal >= 0 && CVal <= 31)
15542 break;
15544 return;
15546 case 'O':
15547 if (Subtarget->isThumb1Only()) {
15548 // This must be a multiple of 4 between -508 and 508, for
15549 // ADD/SUB sp = sp + immediate.
15550 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15551 break;
15553 return;
15555 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15556 break;
15559 if (Result.getNode()) {
15560 Ops.push_back(Result);
15561 return;
15563 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15566 static RTLIB::Libcall getDivRemLibcall(
15567 const SDNode *N, MVT::SimpleValueType SVT) {
15568 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15569 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15570 "Unhandled Opcode in getDivRemLibcall");
15571 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15572 N->getOpcode() == ISD::SREM;
15573 RTLIB::Libcall LC;
15574 switch (SVT) {
15575 default: llvm_unreachable("Unexpected request for libcall!");
15576 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15577 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15578 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15579 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15581 return LC;
15584 static TargetLowering::ArgListTy getDivRemArgList(
15585 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15586 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15587 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15588 "Unhandled Opcode in getDivRemArgList");
15589 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15590 N->getOpcode() == ISD::SREM;
15591 TargetLowering::ArgListTy Args;
15592 TargetLowering::ArgListEntry Entry;
15593 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15594 EVT ArgVT = N->getOperand(i).getValueType();
15595 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15596 Entry.Node = N->getOperand(i);
15597 Entry.Ty = ArgTy;
15598 Entry.IsSExt = isSigned;
15599 Entry.IsZExt = !isSigned;
15600 Args.push_back(Entry);
15602 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15603 std::swap(Args[0], Args[1]);
15604 return Args;
15607 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15608 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15609 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15610 Subtarget->isTargetWindows()) &&
15611 "Register-based DivRem lowering only");
15612 unsigned Opcode = Op->getOpcode();
15613 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15614 "Invalid opcode for Div/Rem lowering");
15615 bool isSigned = (Opcode == ISD::SDIVREM);
15616 EVT VT = Op->getValueType(0);
15617 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15618 SDLoc dl(Op);
15620 // If the target has hardware divide, use divide + multiply + subtract:
15621 // div = a / b
15622 // rem = a - b * div
15623 // return {div, rem}
15624 // This should be lowered into UDIV/SDIV + MLS later on.
15625 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15626 : Subtarget->hasDivideInARMMode();
15627 if (hasDivide && Op->getValueType(0).isSimple() &&
15628 Op->getSimpleValueType(0) == MVT::i32) {
15629 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15630 const SDValue Dividend = Op->getOperand(0);
15631 const SDValue Divisor = Op->getOperand(1);
15632 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15633 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15634 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15636 SDValue Values[2] = {Div, Rem};
15637 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15640 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15641 VT.getSimpleVT().SimpleTy);
15642 SDValue InChain = DAG.getEntryNode();
15644 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15645 DAG.getContext(),
15646 Subtarget);
15648 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15649 getPointerTy(DAG.getDataLayout()));
15651 Type *RetTy = StructType::get(Ty, Ty);
15653 if (Subtarget->isTargetWindows())
15654 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15656 TargetLowering::CallLoweringInfo CLI(DAG);
15657 CLI.setDebugLoc(dl).setChain(InChain)
15658 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15659 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15661 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15662 return CallInfo.first;
15665 // Lowers REM using divmod helpers
15666 // see RTABI section 4.2/4.3
15667 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15668 // Build return types (div and rem)
15669 std::vector<Type*> RetTyParams;
15670 Type *RetTyElement;
15672 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15673 default: llvm_unreachable("Unexpected request for libcall!");
15674 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15675 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15676 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15677 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15680 RetTyParams.push_back(RetTyElement);
15681 RetTyParams.push_back(RetTyElement);
15682 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15683 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15685 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15686 SimpleTy);
15687 SDValue InChain = DAG.getEntryNode();
15688 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15689 Subtarget);
15690 bool isSigned = N->getOpcode() == ISD::SREM;
15691 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15692 getPointerTy(DAG.getDataLayout()));
15694 if (Subtarget->isTargetWindows())
15695 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15697 // Lower call
15698 CallLoweringInfo CLI(DAG);
15699 CLI.setChain(InChain)
15700 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
15701 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
15702 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
15704 // Return second (rem) result operand (first contains div)
15705 SDNode *ResNode = CallResult.first.getNode();
15706 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
15707 return ResNode->getOperand(1);
15710 SDValue
15711 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
15712 assert(Subtarget->isTargetWindows() && "unsupported target platform");
15713 SDLoc DL(Op);
15715 // Get the inputs.
15716 SDValue Chain = Op.getOperand(0);
15717 SDValue Size = Op.getOperand(1);
15719 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
15720 "no-stack-arg-probe")) {
15721 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15722 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15723 Chain = SP.getValue(1);
15724 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
15725 if (Align)
15726 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
15727 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
15728 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
15729 SDValue Ops[2] = { SP, Chain };
15730 return DAG.getMergeValues(Ops, DL);
15733 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
15734 DAG.getConstant(2, DL, MVT::i32));
15736 SDValue Flag;
15737 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
15738 Flag = Chain.getValue(1);
15740 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15741 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
15743 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15744 Chain = NewSP.getValue(1);
15746 SDValue Ops[2] = { NewSP, Chain };
15747 return DAG.getMergeValues(Ops, DL);
15750 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
15751 SDValue SrcVal = Op.getOperand(0);
15752 const unsigned DstSz = Op.getValueType().getSizeInBits();
15753 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
15754 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
15755 "Unexpected type for custom-lowering FP_EXTEND");
15757 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15758 "With both FP DP and 16, any FP conversion is legal!");
15760 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
15761 "With FP16, 16 to 32 conversion is legal!");
15763 // Either we are converting from 16 -> 64, without FP16 and/or
15764 // FP.double-precision or without Armv8-fp. So we must do it in two
15765 // steps.
15766 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
15767 // without FP16. So we must do a function call.
15768 SDLoc Loc(Op);
15769 RTLIB::Libcall LC;
15770 MakeLibCallOptions CallOptions;
15771 if (SrcSz == 16) {
15772 // Instruction from 16 -> 32
15773 if (Subtarget->hasFP16())
15774 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
15775 // Lib call from 16 -> 32
15776 else {
15777 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
15778 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15779 "Unexpected type for custom-lowering FP_EXTEND");
15780 SrcVal =
15781 makeLibCall(DAG, LC, MVT::f32, SrcVal, CallOptions, Loc).first;
15785 if (DstSz != 64)
15786 return SrcVal;
15787 // For sure now SrcVal is 32 bits
15788 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
15789 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
15791 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
15792 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15793 "Unexpected type for custom-lowering FP_EXTEND");
15794 return makeLibCall(DAG, LC, MVT::f64, SrcVal, CallOptions, Loc).first;
15797 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
15798 SDValue SrcVal = Op.getOperand(0);
15799 EVT SrcVT = SrcVal.getValueType();
15800 EVT DstVT = Op.getValueType();
15801 const unsigned DstSz = Op.getValueType().getSizeInBits();
15802 const unsigned SrcSz = SrcVT.getSizeInBits();
15803 (void)DstSz;
15804 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
15805 "Unexpected type for custom-lowering FP_ROUND");
15807 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15808 "With both FP DP and 16, any FP conversion is legal!");
15810 SDLoc Loc(Op);
15812 // Instruction from 32 -> 16 if hasFP16 is valid
15813 if (SrcSz == 32 && Subtarget->hasFP16())
15814 return Op;
15816 // Lib call from 32 -> 16 / 64 -> [32, 16]
15817 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
15818 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15819 "Unexpected type for custom-lowering FP_ROUND");
15820 MakeLibCallOptions CallOptions;
15821 return makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, Loc).first;
15824 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
15825 SelectionDAG &DAG) const {
15826 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
15827 MVT HalfT = MVT::i32;
15828 SDLoc dl(N);
15829 SDValue Hi, Lo, Tmp;
15831 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
15832 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
15833 return ;
15835 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
15836 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
15838 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15839 DAG.getConstant(0, dl, HalfT));
15840 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15841 DAG.getConstant(1, dl, HalfT));
15843 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
15844 DAG.getConstant(OpTypeBits - 1, dl,
15845 getShiftAmountTy(HalfT, DAG.getDataLayout())));
15846 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
15847 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
15848 SDValue(Lo.getNode(), 1));
15849 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
15850 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
15852 Results.push_back(Lo);
15853 Results.push_back(Hi);
15856 bool
15857 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15858 // The ARM target isn't yet aware of offsets.
15859 return false;
15862 bool ARM::isBitFieldInvertedMask(unsigned v) {
15863 if (v == 0xffffffff)
15864 return false;
15866 // there can be 1's on either or both "outsides", all the "inside"
15867 // bits must be 0's
15868 return isShiftedMask_32(~v);
15871 /// isFPImmLegal - Returns true if the target can instruction select the
15872 /// specified FP immediate natively. If false, the legalizer will
15873 /// materialize the FP immediate as a load from a constant pool.
15874 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15875 bool ForCodeSize) const {
15876 if (!Subtarget->hasVFP3Base())
15877 return false;
15878 if (VT == MVT::f16 && Subtarget->hasFullFP16())
15879 return ARM_AM::getFP16Imm(Imm) != -1;
15880 if (VT == MVT::f32)
15881 return ARM_AM::getFP32Imm(Imm) != -1;
15882 if (VT == MVT::f64 && Subtarget->hasFP64())
15883 return ARM_AM::getFP64Imm(Imm) != -1;
15884 return false;
15887 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
15888 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
15889 /// specified in the intrinsic calls.
15890 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15891 const CallInst &I,
15892 MachineFunction &MF,
15893 unsigned Intrinsic) const {
15894 switch (Intrinsic) {
15895 case Intrinsic::arm_neon_vld1:
15896 case Intrinsic::arm_neon_vld2:
15897 case Intrinsic::arm_neon_vld3:
15898 case Intrinsic::arm_neon_vld4:
15899 case Intrinsic::arm_neon_vld2lane:
15900 case Intrinsic::arm_neon_vld3lane:
15901 case Intrinsic::arm_neon_vld4lane:
15902 case Intrinsic::arm_neon_vld2dup:
15903 case Intrinsic::arm_neon_vld3dup:
15904 case Intrinsic::arm_neon_vld4dup: {
15905 Info.opc = ISD::INTRINSIC_W_CHAIN;
15906 // Conservatively set memVT to the entire set of vectors loaded.
15907 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15908 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15909 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15910 Info.ptrVal = I.getArgOperand(0);
15911 Info.offset = 0;
15912 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15913 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15914 // volatile loads with NEON intrinsics not supported
15915 Info.flags = MachineMemOperand::MOLoad;
15916 return true;
15918 case Intrinsic::arm_neon_vld1x2:
15919 case Intrinsic::arm_neon_vld1x3:
15920 case Intrinsic::arm_neon_vld1x4: {
15921 Info.opc = ISD::INTRINSIC_W_CHAIN;
15922 // Conservatively set memVT to the entire set of vectors loaded.
15923 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15924 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15925 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15926 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
15927 Info.offset = 0;
15928 Info.align.reset();
15929 // volatile loads with NEON intrinsics not supported
15930 Info.flags = MachineMemOperand::MOLoad;
15931 return true;
15933 case Intrinsic::arm_neon_vst1:
15934 case Intrinsic::arm_neon_vst2:
15935 case Intrinsic::arm_neon_vst3:
15936 case Intrinsic::arm_neon_vst4:
15937 case Intrinsic::arm_neon_vst2lane:
15938 case Intrinsic::arm_neon_vst3lane:
15939 case Intrinsic::arm_neon_vst4lane: {
15940 Info.opc = ISD::INTRINSIC_VOID;
15941 // Conservatively set memVT to the entire set of vectors stored.
15942 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15943 unsigned NumElts = 0;
15944 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15945 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15946 if (!ArgTy->isVectorTy())
15947 break;
15948 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15950 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15951 Info.ptrVal = I.getArgOperand(0);
15952 Info.offset = 0;
15953 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15954 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15955 // volatile stores with NEON intrinsics not supported
15956 Info.flags = MachineMemOperand::MOStore;
15957 return true;
15959 case Intrinsic::arm_neon_vst1x2:
15960 case Intrinsic::arm_neon_vst1x3:
15961 case Intrinsic::arm_neon_vst1x4: {
15962 Info.opc = ISD::INTRINSIC_VOID;
15963 // Conservatively set memVT to the entire set of vectors stored.
15964 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15965 unsigned NumElts = 0;
15966 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15967 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15968 if (!ArgTy->isVectorTy())
15969 break;
15970 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15972 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15973 Info.ptrVal = I.getArgOperand(0);
15974 Info.offset = 0;
15975 Info.align.reset();
15976 // volatile stores with NEON intrinsics not supported
15977 Info.flags = MachineMemOperand::MOStore;
15978 return true;
15980 case Intrinsic::arm_ldaex:
15981 case Intrinsic::arm_ldrex: {
15982 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15983 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
15984 Info.opc = ISD::INTRINSIC_W_CHAIN;
15985 Info.memVT = MVT::getVT(PtrTy->getElementType());
15986 Info.ptrVal = I.getArgOperand(0);
15987 Info.offset = 0;
15988 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
15989 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15990 return true;
15992 case Intrinsic::arm_stlex:
15993 case Intrinsic::arm_strex: {
15994 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15995 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
15996 Info.opc = ISD::INTRINSIC_W_CHAIN;
15997 Info.memVT = MVT::getVT(PtrTy->getElementType());
15998 Info.ptrVal = I.getArgOperand(1);
15999 Info.offset = 0;
16000 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
16001 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16002 return true;
16004 case Intrinsic::arm_stlexd:
16005 case Intrinsic::arm_strexd:
16006 Info.opc = ISD::INTRINSIC_W_CHAIN;
16007 Info.memVT = MVT::i64;
16008 Info.ptrVal = I.getArgOperand(2);
16009 Info.offset = 0;
16010 Info.align = Align(8);
16011 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16012 return true;
16014 case Intrinsic::arm_ldaexd:
16015 case Intrinsic::arm_ldrexd:
16016 Info.opc = ISD::INTRINSIC_W_CHAIN;
16017 Info.memVT = MVT::i64;
16018 Info.ptrVal = I.getArgOperand(0);
16019 Info.offset = 0;
16020 Info.align = Align(8);
16021 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16022 return true;
16024 default:
16025 break;
16028 return false;
16031 /// Returns true if it is beneficial to convert a load of a constant
16032 /// to just the constant itself.
16033 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16034 Type *Ty) const {
16035 assert(Ty->isIntegerTy());
16037 unsigned Bits = Ty->getPrimitiveSizeInBits();
16038 if (Bits == 0 || Bits > 32)
16039 return false;
16040 return true;
16043 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
16044 unsigned Index) const {
16045 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
16046 return false;
16048 return (Index == 0 || Index == ResVT.getVectorNumElements());
16051 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
16052 ARM_MB::MemBOpt Domain) const {
16053 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16055 // First, if the target has no DMB, see what fallback we can use.
16056 if (!Subtarget->hasDataBarrier()) {
16057 // Some ARMv6 cpus can support data barriers with an mcr instruction.
16058 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
16059 // here.
16060 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
16061 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
16062 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
16063 Builder.getInt32(0), Builder.getInt32(7),
16064 Builder.getInt32(10), Builder.getInt32(5)};
16065 return Builder.CreateCall(MCR, args);
16066 } else {
16067 // Instead of using barriers, atomic accesses on these subtargets use
16068 // libcalls.
16069 llvm_unreachable("makeDMB on a target so old that it has no barriers");
16071 } else {
16072 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
16073 // Only a full system barrier exists in the M-class architectures.
16074 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
16075 Constant *CDomain = Builder.getInt32(Domain);
16076 return Builder.CreateCall(DMB, CDomain);
16080 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
16081 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
16082 Instruction *Inst,
16083 AtomicOrdering Ord) const {
16084 switch (Ord) {
16085 case AtomicOrdering::NotAtomic:
16086 case AtomicOrdering::Unordered:
16087 llvm_unreachable("Invalid fence: unordered/non-atomic");
16088 case AtomicOrdering::Monotonic:
16089 case AtomicOrdering::Acquire:
16090 return nullptr; // Nothing to do
16091 case AtomicOrdering::SequentiallyConsistent:
16092 if (!Inst->hasAtomicStore())
16093 return nullptr; // Nothing to do
16094 LLVM_FALLTHROUGH;
16095 case AtomicOrdering::Release:
16096 case AtomicOrdering::AcquireRelease:
16097 if (Subtarget->preferISHSTBarriers())
16098 return makeDMB(Builder, ARM_MB::ISHST);
16099 // FIXME: add a comment with a link to documentation justifying this.
16100 else
16101 return makeDMB(Builder, ARM_MB::ISH);
16103 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
16106 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
16107 Instruction *Inst,
16108 AtomicOrdering Ord) const {
16109 switch (Ord) {
16110 case AtomicOrdering::NotAtomic:
16111 case AtomicOrdering::Unordered:
16112 llvm_unreachable("Invalid fence: unordered/not-atomic");
16113 case AtomicOrdering::Monotonic:
16114 case AtomicOrdering::Release:
16115 return nullptr; // Nothing to do
16116 case AtomicOrdering::Acquire:
16117 case AtomicOrdering::AcquireRelease:
16118 case AtomicOrdering::SequentiallyConsistent:
16119 return makeDMB(Builder, ARM_MB::ISH);
16121 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
16124 // Loads and stores less than 64-bits are already atomic; ones above that
16125 // are doomed anyway, so defer to the default libcall and blame the OS when
16126 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16127 // anything for those.
16128 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16129 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
16130 return (Size == 64) && !Subtarget->isMClass();
16133 // Loads and stores less than 64-bits are already atomic; ones above that
16134 // are doomed anyway, so defer to the default libcall and blame the OS when
16135 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16136 // anything for those.
16137 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
16138 // guarantee, see DDI0406C ARM architecture reference manual,
16139 // sections A8.8.72-74 LDRD)
16140 TargetLowering::AtomicExpansionKind
16141 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16142 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
16143 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
16144 : AtomicExpansionKind::None;
16147 // For the real atomic operations, we have ldrex/strex up to 32 bits,
16148 // and up to 64 bits on the non-M profiles
16149 TargetLowering::AtomicExpansionKind
16150 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16151 if (AI->isFloatingPointOperation())
16152 return AtomicExpansionKind::CmpXChg;
16154 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
16155 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16156 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
16157 ? AtomicExpansionKind::LLSC
16158 : AtomicExpansionKind::None;
16161 TargetLowering::AtomicExpansionKind
16162 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
16163 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16164 // implement cmpxchg without spilling. If the address being exchanged is also
16165 // on the stack and close enough to the spill slot, this can lead to a
16166 // situation where the monitor always gets cleared and the atomic operation
16167 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16168 bool HasAtomicCmpXchg =
16169 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16170 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
16171 return AtomicExpansionKind::LLSC;
16172 return AtomicExpansionKind::None;
16175 bool ARMTargetLowering::shouldInsertFencesForAtomic(
16176 const Instruction *I) const {
16177 return InsertFencesForAtomic;
16180 // This has so far only been implemented for MachO.
16181 bool ARMTargetLowering::useLoadStackGuardNode() const {
16182 return Subtarget->isTargetMachO();
16185 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
16186 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16187 return TargetLowering::insertSSPDeclarations(M);
16189 // MSVC CRT has a global variable holding security cookie.
16190 M.getOrInsertGlobal("__security_cookie",
16191 Type::getInt8PtrTy(M.getContext()));
16193 // MSVC CRT has a function to validate security cookie.
16194 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16195 "__security_check_cookie", Type::getVoidTy(M.getContext()),
16196 Type::getInt8PtrTy(M.getContext()));
16197 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
16198 F->addAttribute(1, Attribute::AttrKind::InReg);
16201 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
16202 // MSVC CRT has a global variable holding security cookie.
16203 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16204 return M.getGlobalVariable("__security_cookie");
16205 return TargetLowering::getSDagStackGuard(M);
16208 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
16209 // MSVC CRT has a function to validate security cookie.
16210 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16211 return M.getFunction("__security_check_cookie");
16212 return TargetLowering::getSSPStackGuardCheck(M);
16215 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
16216 unsigned &Cost) const {
16217 // If we do not have NEON, vector types are not natively supported.
16218 if (!Subtarget->hasNEON())
16219 return false;
16221 // Floating point values and vector values map to the same register file.
16222 // Therefore, although we could do a store extract of a vector type, this is
16223 // better to leave at float as we have more freedom in the addressing mode for
16224 // those.
16225 if (VectorTy->isFPOrFPVectorTy())
16226 return false;
16228 // If the index is unknown at compile time, this is very expensive to lower
16229 // and it is not possible to combine the store with the extract.
16230 if (!isa<ConstantInt>(Idx))
16231 return false;
16233 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
16234 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
16235 // We can do a store + vector extract on any vector that fits perfectly in a D
16236 // or Q register.
16237 if (BitWidth == 64 || BitWidth == 128) {
16238 Cost = 0;
16239 return true;
16241 return false;
16244 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
16245 return Subtarget->hasV6T2Ops();
16248 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
16249 return Subtarget->hasV6T2Ops();
16252 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
16253 return !Subtarget->hasMinSize();
16256 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16257 AtomicOrdering Ord) const {
16258 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16259 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16260 bool IsAcquire = isAcquireOrStronger(Ord);
16262 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
16263 // intrinsic must return {i32, i32} and we have to recombine them into a
16264 // single i64 here.
16265 if (ValTy->getPrimitiveSizeInBits() == 64) {
16266 Intrinsic::ID Int =
16267 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
16268 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
16270 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16271 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
16273 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16274 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16275 if (!Subtarget->isLittle())
16276 std::swap (Lo, Hi);
16277 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16278 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16279 return Builder.CreateOr(
16280 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
16283 Type *Tys[] = { Addr->getType() };
16284 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
16285 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
16287 return Builder.CreateTruncOrBitCast(
16288 Builder.CreateCall(Ldrex, Addr),
16289 cast<PointerType>(Addr->getType())->getElementType());
16292 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16293 IRBuilder<> &Builder) const {
16294 if (!Subtarget->hasV7Ops())
16295 return;
16296 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16297 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
16300 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
16301 Value *Addr,
16302 AtomicOrdering Ord) const {
16303 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16304 bool IsRelease = isReleaseOrStronger(Ord);
16306 // Since the intrinsics must have legal type, the i64 intrinsics take two
16307 // parameters: "i32, i32". We must marshal Val into the appropriate form
16308 // before the call.
16309 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
16310 Intrinsic::ID Int =
16311 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
16312 Function *Strex = Intrinsic::getDeclaration(M, Int);
16313 Type *Int32Ty = Type::getInt32Ty(M->getContext());
16315 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
16316 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
16317 if (!Subtarget->isLittle())
16318 std::swap(Lo, Hi);
16319 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16320 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
16323 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
16324 Type *Tys[] = { Addr->getType() };
16325 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
16327 return Builder.CreateCall(
16328 Strex, {Builder.CreateZExtOrBitCast(
16329 Val, Strex->getFunctionType()->getParamType(0)),
16330 Addr});
16334 bool ARMTargetLowering::alignLoopsWithOptSize() const {
16335 return Subtarget->isMClass();
16338 /// A helper function for determining the number of interleaved accesses we
16339 /// will generate when lowering accesses of the given type.
16340 unsigned
16341 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
16342 const DataLayout &DL) const {
16343 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
16346 bool ARMTargetLowering::isLegalInterleavedAccessType(
16347 VectorType *VecTy, const DataLayout &DL) const {
16349 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16350 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16352 // Ensure the vector doesn't have f16 elements. Even though we could do an
16353 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16354 // f32.
16355 if (VecTy->getElementType()->isHalfTy())
16356 return false;
16358 // Ensure the number of vector elements is greater than 1.
16359 if (VecTy->getNumElements() < 2)
16360 return false;
16362 // Ensure the element type is legal.
16363 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16364 return false;
16366 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16367 // 128 will be split into multiple interleaved accesses.
16368 return VecSize == 64 || VecSize % 128 == 0;
16371 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
16372 if (Subtarget->hasNEON())
16373 return 4;
16374 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
16377 /// Lower an interleaved load into a vldN intrinsic.
16379 /// E.g. Lower an interleaved load (Factor = 2):
16380 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16381 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16382 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16384 /// Into:
16385 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16386 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16387 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16388 bool ARMTargetLowering::lowerInterleavedLoad(
16389 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16390 ArrayRef<unsigned> Indices, unsigned Factor) const {
16391 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16392 "Invalid interleave factor");
16393 assert(!Shuffles.empty() && "Empty shufflevector input");
16394 assert(Shuffles.size() == Indices.size() &&
16395 "Unmatched number of shufflevectors and indices");
16397 VectorType *VecTy = Shuffles[0]->getType();
16398 Type *EltTy = VecTy->getVectorElementType();
16400 const DataLayout &DL = LI->getModule()->getDataLayout();
16402 // Skip if we do not have NEON and skip illegal vector types. We can
16403 // "legalize" wide vector types into multiple interleaved accesses as long as
16404 // the vector types are divisible by 128.
16405 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16406 return false;
16408 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16410 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16411 // load integer vectors first and then convert to pointer vectors.
16412 if (EltTy->isPointerTy())
16413 VecTy =
16414 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16416 IRBuilder<> Builder(LI);
16418 // The base address of the load.
16419 Value *BaseAddr = LI->getPointerOperand();
16421 if (NumLoads > 1) {
16422 // If we're going to generate more than one load, reset the sub-vector type
16423 // to something legal.
16424 VecTy = VectorType::get(VecTy->getVectorElementType(),
16425 VecTy->getVectorNumElements() / NumLoads);
16427 // We will compute the pointer operand of each load from the original base
16428 // address using GEPs. Cast the base address to a pointer to the scalar
16429 // element type.
16430 BaseAddr = Builder.CreateBitCast(
16431 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16432 LI->getPointerAddressSpace()));
16435 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16437 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16438 Type *Tys[] = {VecTy, Int8Ptr};
16439 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16440 Intrinsic::arm_neon_vld3,
16441 Intrinsic::arm_neon_vld4};
16442 Function *VldnFunc =
16443 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16445 // Holds sub-vectors extracted from the load intrinsic return values. The
16446 // sub-vectors are associated with the shufflevector instructions they will
16447 // replace.
16448 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16450 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16451 // If we're generating more than one load, compute the base address of
16452 // subsequent loads as an offset from the previous.
16453 if (LoadCount > 0)
16454 BaseAddr =
16455 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16456 VecTy->getVectorNumElements() * Factor);
16458 SmallVector<Value *, 2> Ops;
16459 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16460 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16462 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16464 // Replace uses of each shufflevector with the corresponding vector loaded
16465 // by ldN.
16466 for (unsigned i = 0; i < Shuffles.size(); i++) {
16467 ShuffleVectorInst *SV = Shuffles[i];
16468 unsigned Index = Indices[i];
16470 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16472 // Convert the integer vector to pointer vector if the element is pointer.
16473 if (EltTy->isPointerTy())
16474 SubVec = Builder.CreateIntToPtr(
16475 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16476 VecTy->getVectorNumElements()));
16478 SubVecs[SV].push_back(SubVec);
16482 // Replace uses of the shufflevector instructions with the sub-vectors
16483 // returned by the load intrinsic. If a shufflevector instruction is
16484 // associated with more than one sub-vector, those sub-vectors will be
16485 // concatenated into a single wide vector.
16486 for (ShuffleVectorInst *SVI : Shuffles) {
16487 auto &SubVec = SubVecs[SVI];
16488 auto *WideVec =
16489 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16490 SVI->replaceAllUsesWith(WideVec);
16493 return true;
16496 /// Lower an interleaved store into a vstN intrinsic.
16498 /// E.g. Lower an interleaved store (Factor = 3):
16499 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16500 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16501 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16503 /// Into:
16504 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16505 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16506 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16507 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16509 /// Note that the new shufflevectors will be removed and we'll only generate one
16510 /// vst3 instruction in CodeGen.
16512 /// Example for a more general valid mask (Factor 3). Lower:
16513 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16514 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16515 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16517 /// Into:
16518 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16519 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16520 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16521 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16522 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16523 ShuffleVectorInst *SVI,
16524 unsigned Factor) const {
16525 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16526 "Invalid interleave factor");
16528 VectorType *VecTy = SVI->getType();
16529 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16530 "Invalid interleaved store");
16532 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16533 Type *EltTy = VecTy->getVectorElementType();
16534 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16536 const DataLayout &DL = SI->getModule()->getDataLayout();
16538 // Skip if we do not have NEON and skip illegal vector types. We can
16539 // "legalize" wide vector types into multiple interleaved accesses as long as
16540 // the vector types are divisible by 128.
16541 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16542 return false;
16544 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16546 Value *Op0 = SVI->getOperand(0);
16547 Value *Op1 = SVI->getOperand(1);
16548 IRBuilder<> Builder(SI);
16550 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16551 // vectors to integer vectors.
16552 if (EltTy->isPointerTy()) {
16553 Type *IntTy = DL.getIntPtrType(EltTy);
16555 // Convert to the corresponding integer vector.
16556 Type *IntVecTy =
16557 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16558 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16559 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16561 SubVecTy = VectorType::get(IntTy, LaneLen);
16564 // The base address of the store.
16565 Value *BaseAddr = SI->getPointerOperand();
16567 if (NumStores > 1) {
16568 // If we're going to generate more than one store, reset the lane length
16569 // and sub-vector type to something legal.
16570 LaneLen /= NumStores;
16571 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16573 // We will compute the pointer operand of each store from the original base
16574 // address using GEPs. Cast the base address to a pointer to the scalar
16575 // element type.
16576 BaseAddr = Builder.CreateBitCast(
16577 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16578 SI->getPointerAddressSpace()));
16581 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16583 auto Mask = SVI->getShuffleMask();
16585 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16586 Type *Tys[] = {Int8Ptr, SubVecTy};
16587 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16588 Intrinsic::arm_neon_vst3,
16589 Intrinsic::arm_neon_vst4};
16591 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16592 // If we generating more than one store, we compute the base address of
16593 // subsequent stores as an offset from the previous.
16594 if (StoreCount > 0)
16595 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16596 BaseAddr, LaneLen * Factor);
16598 SmallVector<Value *, 6> Ops;
16599 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16601 Function *VstNFunc =
16602 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16604 // Split the shufflevector operands into sub vectors for the new vstN call.
16605 for (unsigned i = 0; i < Factor; i++) {
16606 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16607 if (Mask[IdxI] >= 0) {
16608 Ops.push_back(Builder.CreateShuffleVector(
16609 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16610 } else {
16611 unsigned StartMask = 0;
16612 for (unsigned j = 1; j < LaneLen; j++) {
16613 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16614 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16615 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16616 break;
16619 // Note: If all elements in a chunk are undefs, StartMask=0!
16620 // Note: Filling undef gaps with random elements is ok, since
16621 // those elements were being written anyway (with undefs).
16622 // In the case of all undefs we're defaulting to using elems from 0
16623 // Note: StartMask cannot be negative, it's checked in
16624 // isReInterleaveMask
16625 Ops.push_back(Builder.CreateShuffleVector(
16626 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16630 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16631 Builder.CreateCall(VstNFunc, Ops);
16633 return true;
16636 enum HABaseType {
16637 HA_UNKNOWN = 0,
16638 HA_FLOAT,
16639 HA_DOUBLE,
16640 HA_VECT64,
16641 HA_VECT128
16644 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16645 uint64_t &Members) {
16646 if (auto *ST = dyn_cast<StructType>(Ty)) {
16647 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16648 uint64_t SubMembers = 0;
16649 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16650 return false;
16651 Members += SubMembers;
16653 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16654 uint64_t SubMembers = 0;
16655 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16656 return false;
16657 Members += SubMembers * AT->getNumElements();
16658 } else if (Ty->isFloatTy()) {
16659 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16660 return false;
16661 Members = 1;
16662 Base = HA_FLOAT;
16663 } else if (Ty->isDoubleTy()) {
16664 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16665 return false;
16666 Members = 1;
16667 Base = HA_DOUBLE;
16668 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16669 Members = 1;
16670 switch (Base) {
16671 case HA_FLOAT:
16672 case HA_DOUBLE:
16673 return false;
16674 case HA_VECT64:
16675 return VT->getBitWidth() == 64;
16676 case HA_VECT128:
16677 return VT->getBitWidth() == 128;
16678 case HA_UNKNOWN:
16679 switch (VT->getBitWidth()) {
16680 case 64:
16681 Base = HA_VECT64;
16682 return true;
16683 case 128:
16684 Base = HA_VECT128;
16685 return true;
16686 default:
16687 return false;
16692 return (Members > 0 && Members <= 4);
16695 /// Return the correct alignment for the current calling convention.
16696 unsigned
16697 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16698 DataLayout DL) const {
16699 if (!ArgTy->isVectorTy())
16700 return DL.getABITypeAlignment(ArgTy);
16702 // Avoid over-aligning vector parameters. It would require realigning the
16703 // stack and waste space for no real benefit.
16704 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
16707 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
16708 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
16709 /// passing according to AAPCS rules.
16710 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
16711 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
16712 if (getEffectiveCallingConv(CallConv, isVarArg) !=
16713 CallingConv::ARM_AAPCS_VFP)
16714 return false;
16716 HABaseType Base = HA_UNKNOWN;
16717 uint64_t Members = 0;
16718 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
16719 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
16721 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
16722 return IsHA || IsIntArray;
16725 unsigned ARMTargetLowering::getExceptionPointerRegister(
16726 const Constant *PersonalityFn) const {
16727 // Platforms which do not use SjLj EH may return values in these registers
16728 // via the personality function.
16729 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
16732 unsigned ARMTargetLowering::getExceptionSelectorRegister(
16733 const Constant *PersonalityFn) const {
16734 // Platforms which do not use SjLj EH may return values in these registers
16735 // via the personality function.
16736 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
16739 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
16740 // Update IsSplitCSR in ARMFunctionInfo.
16741 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
16742 AFI->setIsSplitCSR(true);
16745 void ARMTargetLowering::insertCopiesSplitCSR(
16746 MachineBasicBlock *Entry,
16747 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
16748 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
16749 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
16750 if (!IStart)
16751 return;
16753 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
16754 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
16755 MachineBasicBlock::iterator MBBI = Entry->begin();
16756 for (const MCPhysReg *I = IStart; *I; ++I) {
16757 const TargetRegisterClass *RC = nullptr;
16758 if (ARM::GPRRegClass.contains(*I))
16759 RC = &ARM::GPRRegClass;
16760 else if (ARM::DPRRegClass.contains(*I))
16761 RC = &ARM::DPRRegClass;
16762 else
16763 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
16765 Register NewVR = MRI->createVirtualRegister(RC);
16766 // Create copy from CSR to a virtual register.
16767 // FIXME: this currently does not emit CFI pseudo-instructions, it works
16768 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
16769 // nounwind. If we want to generalize this later, we may need to emit
16770 // CFI pseudo-instructions.
16771 assert(Entry->getParent()->getFunction().hasFnAttribute(
16772 Attribute::NoUnwind) &&
16773 "Function should be nounwind in insertCopiesSplitCSR!");
16774 Entry->addLiveIn(*I);
16775 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
16776 .addReg(*I);
16778 // Insert the copy-back instructions right before the terminator.
16779 for (auto *Exit : Exits)
16780 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
16781 TII->get(TargetOpcode::COPY), *I)
16782 .addReg(NewVR);
16786 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
16787 MF.getFrameInfo().computeMaxCallFrameSize(MF);
16788 TargetLoweringBase::finalizeLowering(MF);