[AMDGPU] Check for immediate SrcC in mfma in AsmParser
[llvm-core.git] / lib / Target / ARM / ARMISelLowering.cpp
blob275859a6b912f302f6c282d1ff57dcb360603fb0
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::QPRRegClass);
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::QPRRegClass);
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::QPRRegClass);
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);
384 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
385 const ARMSubtarget &STI)
386 : TargetLowering(TM), Subtarget(&STI) {
387 RegInfo = Subtarget->getRegisterInfo();
388 Itins = Subtarget->getInstrItineraryData();
390 setBooleanContents(ZeroOrOneBooleanContent);
391 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
393 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
394 !Subtarget->isTargetWatchOS()) {
395 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
396 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
397 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
398 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
399 : CallingConv::ARM_AAPCS);
402 if (Subtarget->isTargetMachO()) {
403 // Uses VFP for Thumb libfuncs if available.
404 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
405 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
406 static const struct {
407 const RTLIB::Libcall Op;
408 const char * const Name;
409 const ISD::CondCode Cond;
410 } LibraryCalls[] = {
411 // Single-precision floating-point arithmetic.
412 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
413 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
414 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
415 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
417 // Double-precision floating-point arithmetic.
418 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
419 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
420 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
421 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
423 // Single-precision comparisons.
424 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
425 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
426 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
427 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
428 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
429 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
430 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
431 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
433 // Double-precision comparisons.
434 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
435 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
436 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
437 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
438 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
439 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
440 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
441 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
443 // Floating-point to integer conversions.
444 // i64 conversions are done via library routines even when generating VFP
445 // instructions, so use the same ones.
446 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
447 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
448 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
449 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
451 // Conversions between floating types.
452 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
453 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
455 // Integer to floating-point conversions.
456 // i64 conversions are done via library routines even when generating VFP
457 // instructions, so use the same ones.
458 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
459 // e.g., __floatunsidf vs. __floatunssidfvfp.
460 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
461 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
462 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
463 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
466 for (const auto &LC : LibraryCalls) {
467 setLibcallName(LC.Op, LC.Name);
468 if (LC.Cond != ISD::SETCC_INVALID)
469 setCmpLibcallCC(LC.Op, LC.Cond);
474 // These libcalls are not available in 32-bit.
475 setLibcallName(RTLIB::SHL_I128, nullptr);
476 setLibcallName(RTLIB::SRL_I128, nullptr);
477 setLibcallName(RTLIB::SRA_I128, nullptr);
479 // RTLIB
480 if (Subtarget->isAAPCS_ABI() &&
481 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
482 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
483 static const struct {
484 const RTLIB::Libcall Op;
485 const char * const Name;
486 const CallingConv::ID CC;
487 const ISD::CondCode Cond;
488 } LibraryCalls[] = {
489 // Double-precision floating-point arithmetic helper functions
490 // RTABI chapter 4.1.2, Table 2
491 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
492 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
493 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
494 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
496 // Double-precision floating-point comparison helper functions
497 // RTABI chapter 4.1.2, Table 3
498 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
499 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
500 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
501 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
502 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
503 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
504 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
505 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
507 // Single-precision floating-point arithmetic helper functions
508 // RTABI chapter 4.1.2, Table 4
509 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
511 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
512 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
514 // Single-precision floating-point comparison helper functions
515 // RTABI chapter 4.1.2, Table 5
516 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
517 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
518 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
519 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
520 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
521 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
522 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
523 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
525 // Floating-point to integer conversions.
526 // RTABI chapter 4.1.2, Table 6
527 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
530 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
531 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
532 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
533 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
534 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
536 // Conversions between floating types.
537 // RTABI chapter 4.1.2, Table 7
538 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
539 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
540 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
542 // Integer to floating-point conversions.
543 // RTABI chapter 4.1.2, Table 8
544 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
545 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
546 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
547 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
548 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
549 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
550 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
553 // Long long helper functions
554 // RTABI chapter 4.2, Table 9
555 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
556 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
557 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
558 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
560 // Integer division functions
561 // RTABI chapter 4.3.1
562 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
563 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
564 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
572 for (const auto &LC : LibraryCalls) {
573 setLibcallName(LC.Op, LC.Name);
574 setLibcallCallingConv(LC.Op, LC.CC);
575 if (LC.Cond != ISD::SETCC_INVALID)
576 setCmpLibcallCC(LC.Op, LC.Cond);
579 // EABI dependent RTLIB
580 if (TM.Options.EABIVersion == EABI::EABI4 ||
581 TM.Options.EABIVersion == EABI::EABI5) {
582 static const struct {
583 const RTLIB::Libcall Op;
584 const char *const Name;
585 const CallingConv::ID CC;
586 const ISD::CondCode Cond;
587 } MemOpsLibraryCalls[] = {
588 // Memory operations
589 // RTABI chapter 4.3.4
590 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
595 for (const auto &LC : MemOpsLibraryCalls) {
596 setLibcallName(LC.Op, LC.Name);
597 setLibcallCallingConv(LC.Op, LC.CC);
598 if (LC.Cond != ISD::SETCC_INVALID)
599 setCmpLibcallCC(LC.Op, LC.Cond);
604 if (Subtarget->isTargetWindows()) {
605 static const struct {
606 const RTLIB::Libcall Op;
607 const char * const Name;
608 const CallingConv::ID CC;
609 } LibraryCalls[] = {
610 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
611 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
612 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
613 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
614 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
615 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
616 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
617 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
620 for (const auto &LC : LibraryCalls) {
621 setLibcallName(LC.Op, LC.Name);
622 setLibcallCallingConv(LC.Op, LC.CC);
626 // Use divmod compiler-rt calls for iOS 5.0 and later.
627 if (Subtarget->isTargetMachO() &&
628 !(Subtarget->isTargetIOS() &&
629 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
630 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
631 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
634 // The half <-> float conversion functions are always soft-float on
635 // non-watchos platforms, but are needed for some targets which use a
636 // hard-float calling convention by default.
637 if (!Subtarget->isTargetWatchABI()) {
638 if (Subtarget->isAAPCS_ABI()) {
639 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
640 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
641 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
642 } else {
643 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
644 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
645 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
649 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
650 // a __gnu_ prefix (which is the default).
651 if (Subtarget->isTargetAEABI()) {
652 static const struct {
653 const RTLIB::Libcall Op;
654 const char * const Name;
655 const CallingConv::ID CC;
656 } LibraryCalls[] = {
657 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
658 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
659 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
662 for (const auto &LC : LibraryCalls) {
663 setLibcallName(LC.Op, LC.Name);
664 setLibcallCallingConv(LC.Op, LC.CC);
668 if (Subtarget->isThumb1Only())
669 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
670 else
671 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
673 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
674 Subtarget->hasFPRegs()) {
675 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
676 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
677 if (!Subtarget->hasVFP2Base())
678 setAllExpand(MVT::f32);
679 if (!Subtarget->hasFP64())
680 setAllExpand(MVT::f64);
683 if (Subtarget->hasFullFP16()) {
684 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
685 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
686 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
687 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
689 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
690 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
693 for (MVT VT : MVT::vector_valuetypes()) {
694 for (MVT InnerVT : MVT::vector_valuetypes()) {
695 setTruncStoreAction(VT, InnerVT, Expand);
696 addAllExtLoads(VT, InnerVT, Expand);
699 setOperationAction(ISD::MULHS, VT, Expand);
700 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701 setOperationAction(ISD::MULHU, VT, Expand);
702 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
704 setOperationAction(ISD::BSWAP, VT, Expand);
707 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
708 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
710 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
711 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
713 if (Subtarget->hasMVEIntegerOps())
714 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
716 // Combine low-overhead loop intrinsics so that we can lower i1 types.
717 if (Subtarget->hasLOB()) {
718 setTargetDAGCombine(ISD::BRCOND);
719 setTargetDAGCombine(ISD::BR_CC);
722 if (Subtarget->hasNEON()) {
723 addDRTypeForNEON(MVT::v2f32);
724 addDRTypeForNEON(MVT::v8i8);
725 addDRTypeForNEON(MVT::v4i16);
726 addDRTypeForNEON(MVT::v2i32);
727 addDRTypeForNEON(MVT::v1i64);
729 addQRTypeForNEON(MVT::v4f32);
730 addQRTypeForNEON(MVT::v2f64);
731 addQRTypeForNEON(MVT::v16i8);
732 addQRTypeForNEON(MVT::v8i16);
733 addQRTypeForNEON(MVT::v4i32);
734 addQRTypeForNEON(MVT::v2i64);
736 if (Subtarget->hasFullFP16()) {
737 addQRTypeForNEON(MVT::v8f16);
738 addDRTypeForNEON(MVT::v4f16);
742 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
743 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
744 // none of Neon, MVE or VFP supports any arithmetic operations on it.
745 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
746 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
747 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
748 // FIXME: Code duplication: FDIV and FREM are expanded always, see
749 // ARMTargetLowering::addTypeForNEON method for details.
750 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
751 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
752 // FIXME: Create unittest.
753 // In another words, find a way when "copysign" appears in DAG with vector
754 // operands.
755 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
756 // FIXME: Code duplication: SETCC has custom operation action, see
757 // ARMTargetLowering::addTypeForNEON method for details.
758 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
759 // FIXME: Create unittest for FNEG and for FABS.
760 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
761 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
762 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
763 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
764 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
765 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
766 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
767 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
768 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
769 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
770 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
771 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
772 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
773 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
774 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
775 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
776 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
777 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
780 if (Subtarget->hasNEON()) {
781 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
782 // supported for v4f32.
783 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
784 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
785 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
786 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
787 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
788 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
789 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
790 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
791 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
792 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
793 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
794 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
795 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
796 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
798 // Mark v2f32 intrinsics.
799 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
800 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
801 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
802 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
803 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
804 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
805 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
806 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
807 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
808 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
809 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
810 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
811 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
812 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
814 // Neon does not support some operations on v1i64 and v2i64 types.
815 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
816 // Custom handling for some quad-vector types to detect VMULL.
817 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
818 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
819 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
820 // Custom handling for some vector types to avoid expensive expansions
821 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
822 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
823 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
824 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
825 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
826 // a destination type that is wider than the source, and nor does
827 // it have a FP_TO_[SU]INT instruction with a narrower destination than
828 // source.
829 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
830 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
831 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
832 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
833 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
834 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
835 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
836 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
838 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
839 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
841 // NEON does not have single instruction CTPOP for vectors with element
842 // types wider than 8-bits. However, custom lowering can leverage the
843 // v8i8/v16i8 vcnt instruction.
844 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
845 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
846 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
847 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
848 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
849 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
851 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
852 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
854 // NEON does not have single instruction CTTZ for vectors.
855 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
856 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
857 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
858 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
860 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
861 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
862 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
863 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
865 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
866 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
867 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
868 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
870 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
871 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
872 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
875 // NEON only has FMA instructions as of VFP4.
876 if (!Subtarget->hasVFP4Base()) {
877 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
878 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
881 setTargetDAGCombine(ISD::INTRINSIC_VOID);
882 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
883 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
884 setTargetDAGCombine(ISD::SHL);
885 setTargetDAGCombine(ISD::SRL);
886 setTargetDAGCombine(ISD::SRA);
887 setTargetDAGCombine(ISD::SIGN_EXTEND);
888 setTargetDAGCombine(ISD::ZERO_EXTEND);
889 setTargetDAGCombine(ISD::ANY_EXTEND);
890 setTargetDAGCombine(ISD::STORE);
891 setTargetDAGCombine(ISD::FP_TO_SINT);
892 setTargetDAGCombine(ISD::FP_TO_UINT);
893 setTargetDAGCombine(ISD::FDIV);
894 setTargetDAGCombine(ISD::LOAD);
896 // It is legal to extload from v4i8 to v4i16 or v4i32.
897 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
898 MVT::v2i32}) {
899 for (MVT VT : MVT::integer_vector_valuetypes()) {
900 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
901 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
902 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
907 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
908 setTargetDAGCombine(ISD::BUILD_VECTOR);
909 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
910 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
913 if (!Subtarget->hasFP64()) {
914 // When targeting a floating-point unit with only single-precision
915 // operations, f64 is legal for the few double-precision instructions which
916 // are present However, no double-precision operations other than moves,
917 // loads and stores are provided by the hardware.
918 setOperationAction(ISD::FADD, MVT::f64, Expand);
919 setOperationAction(ISD::FSUB, MVT::f64, Expand);
920 setOperationAction(ISD::FMUL, MVT::f64, Expand);
921 setOperationAction(ISD::FMA, MVT::f64, Expand);
922 setOperationAction(ISD::FDIV, MVT::f64, Expand);
923 setOperationAction(ISD::FREM, MVT::f64, Expand);
924 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
925 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
926 setOperationAction(ISD::FNEG, MVT::f64, Expand);
927 setOperationAction(ISD::FABS, MVT::f64, Expand);
928 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
929 setOperationAction(ISD::FSIN, MVT::f64, Expand);
930 setOperationAction(ISD::FCOS, MVT::f64, Expand);
931 setOperationAction(ISD::FPOW, MVT::f64, Expand);
932 setOperationAction(ISD::FLOG, MVT::f64, Expand);
933 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
934 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
935 setOperationAction(ISD::FEXP, MVT::f64, Expand);
936 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
937 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
938 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
939 setOperationAction(ISD::FRINT, MVT::f64, Expand);
940 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
941 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
942 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
943 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
944 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
945 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
946 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
947 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
948 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
951 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
952 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
953 if (Subtarget->hasFullFP16())
954 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
957 if (!Subtarget->hasFP16())
958 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
960 if (!Subtarget->hasFP64())
961 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
963 computeRegisterProperties(Subtarget->getRegisterInfo());
965 // ARM does not have floating-point extending loads.
966 for (MVT VT : MVT::fp_valuetypes()) {
967 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
968 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
971 // ... or truncating stores
972 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
973 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
974 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
976 // ARM does not have i1 sign extending load.
977 for (MVT VT : MVT::integer_valuetypes())
978 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
980 // ARM supports all 4 flavors of integer indexed load / store.
981 if (!Subtarget->isThumb1Only()) {
982 for (unsigned im = (unsigned)ISD::PRE_INC;
983 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
984 setIndexedLoadAction(im, MVT::i1, Legal);
985 setIndexedLoadAction(im, MVT::i8, Legal);
986 setIndexedLoadAction(im, MVT::i16, Legal);
987 setIndexedLoadAction(im, MVT::i32, Legal);
988 setIndexedStoreAction(im, MVT::i1, Legal);
989 setIndexedStoreAction(im, MVT::i8, Legal);
990 setIndexedStoreAction(im, MVT::i16, Legal);
991 setIndexedStoreAction(im, MVT::i32, Legal);
993 } else {
994 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
995 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
996 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
999 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1000 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1001 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1002 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1004 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1005 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1007 // i64 operation support.
1008 setOperationAction(ISD::MUL, MVT::i64, Expand);
1009 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1010 if (Subtarget->isThumb1Only()) {
1011 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1012 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1014 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1015 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1016 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1018 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1019 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1020 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1021 setOperationAction(ISD::SRL, MVT::i64, Custom);
1022 setOperationAction(ISD::SRA, MVT::i64, Custom);
1023 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1024 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1026 // MVE lowers 64 bit shifts to lsll and lsrl
1027 // assuming that ISD::SRL and SRA of i64 are already marked custom
1028 if (Subtarget->hasMVEIntegerOps())
1029 setOperationAction(ISD::SHL, MVT::i64, Custom);
1031 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1032 if (Subtarget->isThumb1Only()) {
1033 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1034 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1035 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1038 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1039 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1041 // ARM does not have ROTL.
1042 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1043 for (MVT VT : MVT::vector_valuetypes()) {
1044 setOperationAction(ISD::ROTL, VT, Expand);
1045 setOperationAction(ISD::ROTR, VT, Expand);
1047 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1048 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1049 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1050 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1051 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1054 // @llvm.readcyclecounter requires the Performance Monitors extension.
1055 // Default to the 0 expansion on unsupported platforms.
1056 // FIXME: Technically there are older ARM CPUs that have
1057 // implementation-specific ways of obtaining this information.
1058 if (Subtarget->hasPerfMon())
1059 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1061 // Only ARMv6 has BSWAP.
1062 if (!Subtarget->hasV6Ops())
1063 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1065 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1066 : Subtarget->hasDivideInARMMode();
1067 if (!hasDivide) {
1068 // These are expanded into libcalls if the cpu doesn't have HW divider.
1069 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1070 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1073 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1074 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1075 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1077 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1078 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1081 setOperationAction(ISD::SREM, MVT::i32, Expand);
1082 setOperationAction(ISD::UREM, MVT::i32, Expand);
1084 // Register based DivRem for AEABI (RTABI 4.2)
1085 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1086 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1087 Subtarget->isTargetWindows()) {
1088 setOperationAction(ISD::SREM, MVT::i64, Custom);
1089 setOperationAction(ISD::UREM, MVT::i64, Custom);
1090 HasStandaloneRem = false;
1092 if (Subtarget->isTargetWindows()) {
1093 const struct {
1094 const RTLIB::Libcall Op;
1095 const char * const Name;
1096 const CallingConv::ID CC;
1097 } LibraryCalls[] = {
1098 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1099 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1100 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1101 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1103 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1104 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1105 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1106 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1109 for (const auto &LC : LibraryCalls) {
1110 setLibcallName(LC.Op, LC.Name);
1111 setLibcallCallingConv(LC.Op, LC.CC);
1113 } else {
1114 const struct {
1115 const RTLIB::Libcall Op;
1116 const char * const Name;
1117 const CallingConv::ID CC;
1118 } LibraryCalls[] = {
1119 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1120 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1121 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1122 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1124 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1125 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1126 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1127 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1130 for (const auto &LC : LibraryCalls) {
1131 setLibcallName(LC.Op, LC.Name);
1132 setLibcallCallingConv(LC.Op, LC.CC);
1136 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1137 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1138 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1139 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1140 } else {
1141 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1142 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1145 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
1146 for (auto &VT : {MVT::f32, MVT::f64})
1147 setOperationAction(ISD::FPOWI, VT, Custom);
1149 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1150 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1151 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1152 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1154 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1155 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1157 // Use the default implementation.
1158 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1159 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1160 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1161 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1162 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1163 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1165 if (Subtarget->isTargetWindows())
1166 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1167 else
1168 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1170 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1171 // the default expansion.
1172 InsertFencesForAtomic = false;
1173 if (Subtarget->hasAnyDataBarrier() &&
1174 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1175 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1176 // to ldrex/strex loops already.
1177 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1178 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1179 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1181 // On v8, we have particularly efficient implementations of atomic fences
1182 // if they can be combined with nearby atomic loads and stores.
1183 if (!Subtarget->hasAcquireRelease() ||
1184 getTargetMachine().getOptLevel() == 0) {
1185 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1186 InsertFencesForAtomic = true;
1188 } else {
1189 // If there's anything we can use as a barrier, go through custom lowering
1190 // for ATOMIC_FENCE.
1191 // If target has DMB in thumb, Fences can be inserted.
1192 if (Subtarget->hasDataBarrier())
1193 InsertFencesForAtomic = true;
1195 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1196 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1198 // Set them all for expansion, which will force libcalls.
1199 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1200 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1201 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1202 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1203 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1204 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1205 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1206 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1207 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1208 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1209 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1210 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1211 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1212 // Unordered/Monotonic case.
1213 if (!InsertFencesForAtomic) {
1214 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1215 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1219 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1221 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1222 if (!Subtarget->hasV6Ops()) {
1223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1224 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1228 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1229 !Subtarget->isThumb1Only()) {
1230 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1231 // iff target supports vfp2.
1232 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1233 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1236 // We want to custom lower some of our intrinsics.
1237 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1238 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1239 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1240 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1241 if (Subtarget->useSjLjEH())
1242 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1244 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1245 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1246 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1247 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1248 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1249 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1250 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1251 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1252 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1253 if (Subtarget->hasFullFP16()) {
1254 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1255 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1256 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1259 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1261 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1262 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1263 if (Subtarget->hasFullFP16())
1264 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1265 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1266 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1267 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1269 // We don't support sin/cos/fmod/copysign/pow
1270 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1271 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1272 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1273 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1274 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1275 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1276 setOperationAction(ISD::FREM, MVT::f64, Expand);
1277 setOperationAction(ISD::FREM, MVT::f32, Expand);
1278 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1279 !Subtarget->isThumb1Only()) {
1280 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1281 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1283 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1284 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1286 if (!Subtarget->hasVFP4Base()) {
1287 setOperationAction(ISD::FMA, MVT::f64, Expand);
1288 setOperationAction(ISD::FMA, MVT::f32, Expand);
1291 // Various VFP goodness
1292 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1293 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1294 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1295 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1296 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1299 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1300 if (!Subtarget->hasFP16()) {
1301 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1302 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1306 // Use __sincos_stret if available.
1307 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1308 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1309 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1310 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1313 // FP-ARMv8 implements a lot of rounding-like FP operations.
1314 if (Subtarget->hasFPARMv8Base()) {
1315 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1316 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1317 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1318 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1319 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1320 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1321 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1322 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1323 if (Subtarget->hasNEON()) {
1324 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1325 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1326 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1327 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1330 if (Subtarget->hasFP64()) {
1331 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1332 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1333 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1334 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1335 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1336 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1337 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1338 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1342 // FP16 often need to be promoted to call lib functions
1343 if (Subtarget->hasFullFP16()) {
1344 setOperationAction(ISD::FREM, MVT::f16, Promote);
1345 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1346 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1347 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1348 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1349 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1350 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1351 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1352 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1353 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1354 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1355 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1357 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1360 if (Subtarget->hasNEON()) {
1361 // vmin and vmax aren't available in a scalar form, so we use
1362 // a NEON instruction with an undef lane instead.
1363 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1364 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1365 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1366 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1367 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1368 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1369 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1370 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1372 if (Subtarget->hasFullFP16()) {
1373 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1374 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1375 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1376 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1378 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1379 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1380 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1381 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1385 // We have target-specific dag combine patterns for the following nodes:
1386 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1387 setTargetDAGCombine(ISD::ADD);
1388 setTargetDAGCombine(ISD::SUB);
1389 setTargetDAGCombine(ISD::MUL);
1390 setTargetDAGCombine(ISD::AND);
1391 setTargetDAGCombine(ISD::OR);
1392 setTargetDAGCombine(ISD::XOR);
1394 if (Subtarget->hasV6Ops())
1395 setTargetDAGCombine(ISD::SRL);
1396 if (Subtarget->isThumb1Only())
1397 setTargetDAGCombine(ISD::SHL);
1399 setStackPointerRegisterToSaveRestore(ARM::SP);
1401 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1402 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1403 setSchedulingPreference(Sched::RegPressure);
1404 else
1405 setSchedulingPreference(Sched::Hybrid);
1407 //// temporary - rewrite interface to use type
1408 MaxStoresPerMemset = 8;
1409 MaxStoresPerMemsetOptSize = 4;
1410 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1411 MaxStoresPerMemcpyOptSize = 2;
1412 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1413 MaxStoresPerMemmoveOptSize = 2;
1415 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1416 // are at least 4 bytes aligned.
1417 setMinStackArgumentAlignment(4);
1419 // Prefer likely predicted branches to selects on out-of-order cores.
1420 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1422 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment());
1424 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1426 if (Subtarget->isThumb() || Subtarget->isThumb2())
1427 setTargetDAGCombine(ISD::ABS);
1430 bool ARMTargetLowering::useSoftFloat() const {
1431 return Subtarget->useSoftFloat();
1434 // FIXME: It might make sense to define the representative register class as the
1435 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1436 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1437 // SPR's representative would be DPR_VFP2. This should work well if register
1438 // pressure tracking were modified such that a register use would increment the
1439 // pressure of the register class's representative and all of it's super
1440 // classes' representatives transitively. We have not implemented this because
1441 // of the difficulty prior to coalescing of modeling operand register classes
1442 // due to the common occurrence of cross class copies and subregister insertions
1443 // and extractions.
1444 std::pair<const TargetRegisterClass *, uint8_t>
1445 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1446 MVT VT) const {
1447 const TargetRegisterClass *RRC = nullptr;
1448 uint8_t Cost = 1;
1449 switch (VT.SimpleTy) {
1450 default:
1451 return TargetLowering::findRepresentativeClass(TRI, VT);
1452 // Use DPR as representative register class for all floating point
1453 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1454 // the cost is 1 for both f32 and f64.
1455 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1456 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1457 RRC = &ARM::DPRRegClass;
1458 // When NEON is used for SP, only half of the register file is available
1459 // because operations that define both SP and DP results will be constrained
1460 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1461 // coalescing by double-counting the SP regs. See the FIXME above.
1462 if (Subtarget->useNEONForSinglePrecisionFP())
1463 Cost = 2;
1464 break;
1465 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1466 case MVT::v4f32: case MVT::v2f64:
1467 RRC = &ARM::DPRRegClass;
1468 Cost = 2;
1469 break;
1470 case MVT::v4i64:
1471 RRC = &ARM::DPRRegClass;
1472 Cost = 4;
1473 break;
1474 case MVT::v8i64:
1475 RRC = &ARM::DPRRegClass;
1476 Cost = 8;
1477 break;
1479 return std::make_pair(RRC, Cost);
1482 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1483 switch ((ARMISD::NodeType)Opcode) {
1484 case ARMISD::FIRST_NUMBER: break;
1485 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1486 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1487 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1488 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1489 case ARMISD::CALL: return "ARMISD::CALL";
1490 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1491 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1492 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1493 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1494 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1495 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1496 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1497 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1498 case ARMISD::CMP: return "ARMISD::CMP";
1499 case ARMISD::CMN: return "ARMISD::CMN";
1500 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1501 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1502 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1503 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1504 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1506 case ARMISD::CMOV: return "ARMISD::CMOV";
1507 case ARMISD::SUBS: return "ARMISD::SUBS";
1509 case ARMISD::SSAT: return "ARMISD::SSAT";
1510 case ARMISD::USAT: return "ARMISD::USAT";
1512 case ARMISD::ASRL: return "ARMISD::ASRL";
1513 case ARMISD::LSRL: return "ARMISD::LSRL";
1514 case ARMISD::LSLL: return "ARMISD::LSLL";
1516 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1517 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1518 case ARMISD::RRX: return "ARMISD::RRX";
1520 case ARMISD::ADDC: return "ARMISD::ADDC";
1521 case ARMISD::ADDE: return "ARMISD::ADDE";
1522 case ARMISD::SUBC: return "ARMISD::SUBC";
1523 case ARMISD::SUBE: return "ARMISD::SUBE";
1524 case ARMISD::LSLS: return "ARMISD::LSLS";
1526 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1527 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1528 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1529 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1530 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1532 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1533 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1534 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1536 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1538 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1540 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1542 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1544 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1546 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1547 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1549 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1550 case ARMISD::VCMP: return "ARMISD::VCMP";
1551 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1552 case ARMISD::VTST: return "ARMISD::VTST";
1554 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1555 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1556 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1557 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1558 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1559 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1560 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1561 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1562 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1563 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1564 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1565 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1566 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1567 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1568 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1569 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1570 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1571 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1572 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1573 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1574 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1575 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1576 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1577 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1578 case ARMISD::VDUP: return "ARMISD::VDUP";
1579 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1580 case ARMISD::VEXT: return "ARMISD::VEXT";
1581 case ARMISD::VREV64: return "ARMISD::VREV64";
1582 case ARMISD::VREV32: return "ARMISD::VREV32";
1583 case ARMISD::VREV16: return "ARMISD::VREV16";
1584 case ARMISD::VZIP: return "ARMISD::VZIP";
1585 case ARMISD::VUZP: return "ARMISD::VUZP";
1586 case ARMISD::VTRN: return "ARMISD::VTRN";
1587 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1588 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1589 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1590 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1591 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1592 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1593 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1594 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1595 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1596 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1597 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1598 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1599 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1600 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1601 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1602 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1603 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1604 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1605 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1606 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1607 case ARMISD::BFI: return "ARMISD::BFI";
1608 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1609 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1610 case ARMISD::VBSL: return "ARMISD::VBSL";
1611 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1612 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1613 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1614 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1615 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1616 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1617 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1618 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1619 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1620 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1621 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1622 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1623 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1624 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1625 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1626 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1627 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1628 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1629 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1630 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1631 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1632 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1633 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1634 case ARMISD::WLS: return "ARMISD::WLS";
1635 case ARMISD::LE: return "ARMISD::LE";
1636 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1638 return nullptr;
1641 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1642 EVT VT) const {
1643 if (!VT.isVector())
1644 return getPointerTy(DL);
1646 // MVE has a predicate register.
1647 if (Subtarget->hasMVEIntegerOps() &&
1648 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1649 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1650 return VT.changeVectorElementTypeToInteger();
1653 /// getRegClassFor - Return the register class that should be used for the
1654 /// specified value type.
1655 const TargetRegisterClass *
1656 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1657 (void)isDivergent;
1658 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1659 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1660 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1661 // MVE Q registers.
1662 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1663 if (VT == MVT::v4i64)
1664 return &ARM::QQPRRegClass;
1665 if (VT == MVT::v8i64)
1666 return &ARM::QQQQPRRegClass;
1668 return TargetLowering::getRegClassFor(VT);
1671 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1672 // source/dest is aligned and the copy size is large enough. We therefore want
1673 // to align such objects passed to memory intrinsics.
1674 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1675 unsigned &PrefAlign) const {
1676 if (!isa<MemIntrinsic>(CI))
1677 return false;
1678 MinSize = 8;
1679 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1680 // cycle faster than 4-byte aligned LDM.
1681 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1682 return true;
1685 // Create a fast isel object.
1686 FastISel *
1687 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1688 const TargetLibraryInfo *libInfo) const {
1689 return ARM::createFastISel(funcInfo, libInfo);
1692 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1693 unsigned NumVals = N->getNumValues();
1694 if (!NumVals)
1695 return Sched::RegPressure;
1697 for (unsigned i = 0; i != NumVals; ++i) {
1698 EVT VT = N->getValueType(i);
1699 if (VT == MVT::Glue || VT == MVT::Other)
1700 continue;
1701 if (VT.isFloatingPoint() || VT.isVector())
1702 return Sched::ILP;
1705 if (!N->isMachineOpcode())
1706 return Sched::RegPressure;
1708 // Load are scheduled for latency even if there instruction itinerary
1709 // is not available.
1710 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1711 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1713 if (MCID.getNumDefs() == 0)
1714 return Sched::RegPressure;
1715 if (!Itins->isEmpty() &&
1716 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1717 return Sched::ILP;
1719 return Sched::RegPressure;
1722 //===----------------------------------------------------------------------===//
1723 // Lowering Code
1724 //===----------------------------------------------------------------------===//
1726 static bool isSRL16(const SDValue &Op) {
1727 if (Op.getOpcode() != ISD::SRL)
1728 return false;
1729 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1730 return Const->getZExtValue() == 16;
1731 return false;
1734 static bool isSRA16(const SDValue &Op) {
1735 if (Op.getOpcode() != ISD::SRA)
1736 return false;
1737 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1738 return Const->getZExtValue() == 16;
1739 return false;
1742 static bool isSHL16(const SDValue &Op) {
1743 if (Op.getOpcode() != ISD::SHL)
1744 return false;
1745 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1746 return Const->getZExtValue() == 16;
1747 return false;
1750 // Check for a signed 16-bit value. We special case SRA because it makes it
1751 // more simple when also looking for SRAs that aren't sign extending a
1752 // smaller value. Without the check, we'd need to take extra care with
1753 // checking order for some operations.
1754 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1755 if (isSRA16(Op))
1756 return isSHL16(Op.getOperand(0));
1757 return DAG.ComputeNumSignBits(Op) == 17;
1760 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1761 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1762 switch (CC) {
1763 default: llvm_unreachable("Unknown condition code!");
1764 case ISD::SETNE: return ARMCC::NE;
1765 case ISD::SETEQ: return ARMCC::EQ;
1766 case ISD::SETGT: return ARMCC::GT;
1767 case ISD::SETGE: return ARMCC::GE;
1768 case ISD::SETLT: return ARMCC::LT;
1769 case ISD::SETLE: return ARMCC::LE;
1770 case ISD::SETUGT: return ARMCC::HI;
1771 case ISD::SETUGE: return ARMCC::HS;
1772 case ISD::SETULT: return ARMCC::LO;
1773 case ISD::SETULE: return ARMCC::LS;
1777 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1778 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1779 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1780 CondCode2 = ARMCC::AL;
1781 InvalidOnQNaN = true;
1782 switch (CC) {
1783 default: llvm_unreachable("Unknown FP condition!");
1784 case ISD::SETEQ:
1785 case ISD::SETOEQ:
1786 CondCode = ARMCC::EQ;
1787 InvalidOnQNaN = false;
1788 break;
1789 case ISD::SETGT:
1790 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1791 case ISD::SETGE:
1792 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1793 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1794 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1795 case ISD::SETONE:
1796 CondCode = ARMCC::MI;
1797 CondCode2 = ARMCC::GT;
1798 InvalidOnQNaN = false;
1799 break;
1800 case ISD::SETO: CondCode = ARMCC::VC; break;
1801 case ISD::SETUO: CondCode = ARMCC::VS; break;
1802 case ISD::SETUEQ:
1803 CondCode = ARMCC::EQ;
1804 CondCode2 = ARMCC::VS;
1805 InvalidOnQNaN = false;
1806 break;
1807 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1808 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1809 case ISD::SETLT:
1810 case ISD::SETULT: CondCode = ARMCC::LT; break;
1811 case ISD::SETLE:
1812 case ISD::SETULE: CondCode = ARMCC::LE; break;
1813 case ISD::SETNE:
1814 case ISD::SETUNE:
1815 CondCode = ARMCC::NE;
1816 InvalidOnQNaN = false;
1817 break;
1821 //===----------------------------------------------------------------------===//
1822 // Calling Convention Implementation
1823 //===----------------------------------------------------------------------===//
1825 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1826 /// account presence of floating point hardware and calling convention
1827 /// limitations, such as support for variadic functions.
1828 CallingConv::ID
1829 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1830 bool isVarArg) const {
1831 switch (CC) {
1832 default:
1833 report_fatal_error("Unsupported calling convention");
1834 case CallingConv::ARM_AAPCS:
1835 case CallingConv::ARM_APCS:
1836 case CallingConv::GHC:
1837 return CC;
1838 case CallingConv::PreserveMost:
1839 return CallingConv::PreserveMost;
1840 case CallingConv::ARM_AAPCS_VFP:
1841 case CallingConv::Swift:
1842 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1843 case CallingConv::C:
1844 if (!Subtarget->isAAPCS_ABI())
1845 return CallingConv::ARM_APCS;
1846 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1847 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1848 !isVarArg)
1849 return CallingConv::ARM_AAPCS_VFP;
1850 else
1851 return CallingConv::ARM_AAPCS;
1852 case CallingConv::Fast:
1853 case CallingConv::CXX_FAST_TLS:
1854 if (!Subtarget->isAAPCS_ABI()) {
1855 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1856 return CallingConv::Fast;
1857 return CallingConv::ARM_APCS;
1858 } else if (Subtarget->hasVFP2Base() &&
1859 !Subtarget->isThumb1Only() && !isVarArg)
1860 return CallingConv::ARM_AAPCS_VFP;
1861 else
1862 return CallingConv::ARM_AAPCS;
1866 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1867 bool isVarArg) const {
1868 return CCAssignFnForNode(CC, false, isVarArg);
1871 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1872 bool isVarArg) const {
1873 return CCAssignFnForNode(CC, true, isVarArg);
1876 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1877 /// CallingConvention.
1878 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1879 bool Return,
1880 bool isVarArg) const {
1881 switch (getEffectiveCallingConv(CC, isVarArg)) {
1882 default:
1883 report_fatal_error("Unsupported calling convention");
1884 case CallingConv::ARM_APCS:
1885 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1886 case CallingConv::ARM_AAPCS:
1887 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1888 case CallingConv::ARM_AAPCS_VFP:
1889 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1890 case CallingConv::Fast:
1891 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1892 case CallingConv::GHC:
1893 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1894 case CallingConv::PreserveMost:
1895 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1899 /// LowerCallResult - Lower the result values of a call into the
1900 /// appropriate copies out of appropriate physical registers.
1901 SDValue ARMTargetLowering::LowerCallResult(
1902 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1903 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1904 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1905 SDValue ThisVal) const {
1906 // Assign locations to each value returned by this call.
1907 SmallVector<CCValAssign, 16> RVLocs;
1908 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1909 *DAG.getContext());
1910 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1912 // Copy all of the result registers out of their specified physreg.
1913 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1914 CCValAssign VA = RVLocs[i];
1916 // Pass 'this' value directly from the argument to return value, to avoid
1917 // reg unit interference
1918 if (i == 0 && isThisReturn) {
1919 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1920 "unexpected return calling convention register assignment");
1921 InVals.push_back(ThisVal);
1922 continue;
1925 SDValue Val;
1926 if (VA.needsCustom()) {
1927 // Handle f64 or half of a v2f64.
1928 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1929 InFlag);
1930 Chain = Lo.getValue(1);
1931 InFlag = Lo.getValue(2);
1932 VA = RVLocs[++i]; // skip ahead to next loc
1933 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1934 InFlag);
1935 Chain = Hi.getValue(1);
1936 InFlag = Hi.getValue(2);
1937 if (!Subtarget->isLittle())
1938 std::swap (Lo, Hi);
1939 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1941 if (VA.getLocVT() == MVT::v2f64) {
1942 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1943 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1944 DAG.getConstant(0, dl, MVT::i32));
1946 VA = RVLocs[++i]; // skip ahead to next loc
1947 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1948 Chain = Lo.getValue(1);
1949 InFlag = Lo.getValue(2);
1950 VA = RVLocs[++i]; // skip ahead to next loc
1951 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1952 Chain = Hi.getValue(1);
1953 InFlag = Hi.getValue(2);
1954 if (!Subtarget->isLittle())
1955 std::swap (Lo, Hi);
1956 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1957 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1958 DAG.getConstant(1, dl, MVT::i32));
1960 } else {
1961 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1962 InFlag);
1963 Chain = Val.getValue(1);
1964 InFlag = Val.getValue(2);
1967 switch (VA.getLocInfo()) {
1968 default: llvm_unreachable("Unknown loc info!");
1969 case CCValAssign::Full: break;
1970 case CCValAssign::BCvt:
1971 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1972 break;
1975 InVals.push_back(Val);
1978 return Chain;
1981 /// LowerMemOpCallTo - Store the argument to the stack.
1982 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1983 SDValue Arg, const SDLoc &dl,
1984 SelectionDAG &DAG,
1985 const CCValAssign &VA,
1986 ISD::ArgFlagsTy Flags) const {
1987 unsigned LocMemOffset = VA.getLocMemOffset();
1988 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1989 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1990 StackPtr, PtrOff);
1991 return DAG.getStore(
1992 Chain, dl, Arg, PtrOff,
1993 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1996 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1997 SDValue Chain, SDValue &Arg,
1998 RegsToPassVector &RegsToPass,
1999 CCValAssign &VA, CCValAssign &NextVA,
2000 SDValue &StackPtr,
2001 SmallVectorImpl<SDValue> &MemOpChains,
2002 ISD::ArgFlagsTy Flags) const {
2003 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2004 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2005 unsigned id = Subtarget->isLittle() ? 0 : 1;
2006 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2008 if (NextVA.isRegLoc())
2009 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2010 else {
2011 assert(NextVA.isMemLoc());
2012 if (!StackPtr.getNode())
2013 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2014 getPointerTy(DAG.getDataLayout()));
2016 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2017 dl, DAG, NextVA,
2018 Flags));
2022 /// LowerCall - Lowering a call into a callseq_start <-
2023 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2024 /// nodes.
2025 SDValue
2026 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2027 SmallVectorImpl<SDValue> &InVals) const {
2028 SelectionDAG &DAG = CLI.DAG;
2029 SDLoc &dl = CLI.DL;
2030 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2031 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2032 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2033 SDValue Chain = CLI.Chain;
2034 SDValue Callee = CLI.Callee;
2035 bool &isTailCall = CLI.IsTailCall;
2036 CallingConv::ID CallConv = CLI.CallConv;
2037 bool doesNotRet = CLI.DoesNotReturn;
2038 bool isVarArg = CLI.IsVarArg;
2040 MachineFunction &MF = DAG.getMachineFunction();
2041 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2042 bool isThisReturn = false;
2043 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2044 bool PreferIndirect = false;
2046 // Disable tail calls if they're not supported.
2047 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2048 isTailCall = false;
2050 if (isa<GlobalAddressSDNode>(Callee)) {
2051 // If we're optimizing for minimum size and the function is called three or
2052 // more times in this block, we can improve codesize by calling indirectly
2053 // as BLXr has a 16-bit encoding.
2054 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2055 if (CLI.CS) {
2056 auto *BB = CLI.CS.getParent();
2057 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2058 count_if(GV->users(), [&BB](const User *U) {
2059 return isa<Instruction>(U) &&
2060 cast<Instruction>(U)->getParent() == BB;
2061 }) > 2;
2064 if (isTailCall) {
2065 // Check if it's really possible to do a tail call.
2066 isTailCall = IsEligibleForTailCallOptimization(
2067 Callee, CallConv, isVarArg, isStructRet,
2068 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2069 PreferIndirect);
2070 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2071 report_fatal_error("failed to perform tail call elimination on a call "
2072 "site marked musttail");
2073 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2074 // detected sibcalls.
2075 if (isTailCall)
2076 ++NumTailCalls;
2079 // Analyze operands of the call, assigning locations to each operand.
2080 SmallVector<CCValAssign, 16> ArgLocs;
2081 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2082 *DAG.getContext());
2083 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2085 // Get a count of how many bytes are to be pushed on the stack.
2086 unsigned NumBytes = CCInfo.getNextStackOffset();
2088 if (isTailCall) {
2089 // For tail calls, memory operands are available in our caller's stack.
2090 NumBytes = 0;
2091 } else {
2092 // Adjust the stack pointer for the new arguments...
2093 // These operations are automatically eliminated by the prolog/epilog pass
2094 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2097 SDValue StackPtr =
2098 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2100 RegsToPassVector RegsToPass;
2101 SmallVector<SDValue, 8> MemOpChains;
2103 // Walk the register/memloc assignments, inserting copies/loads. In the case
2104 // of tail call optimization, arguments are handled later.
2105 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2106 i != e;
2107 ++i, ++realArgIdx) {
2108 CCValAssign &VA = ArgLocs[i];
2109 SDValue Arg = OutVals[realArgIdx];
2110 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2111 bool isByVal = Flags.isByVal();
2113 // Promote the value if needed.
2114 switch (VA.getLocInfo()) {
2115 default: llvm_unreachable("Unknown loc info!");
2116 case CCValAssign::Full: break;
2117 case CCValAssign::SExt:
2118 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2119 break;
2120 case CCValAssign::ZExt:
2121 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2122 break;
2123 case CCValAssign::AExt:
2124 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2125 break;
2126 case CCValAssign::BCvt:
2127 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2128 break;
2131 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2132 if (VA.needsCustom()) {
2133 if (VA.getLocVT() == MVT::v2f64) {
2134 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2135 DAG.getConstant(0, dl, MVT::i32));
2136 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2137 DAG.getConstant(1, dl, MVT::i32));
2139 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2140 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2142 VA = ArgLocs[++i]; // skip ahead to next loc
2143 if (VA.isRegLoc()) {
2144 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2145 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2146 } else {
2147 assert(VA.isMemLoc());
2149 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2150 dl, DAG, VA, Flags));
2152 } else {
2153 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2154 StackPtr, MemOpChains, Flags);
2156 } else if (VA.isRegLoc()) {
2157 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2158 Outs[0].VT == MVT::i32) {
2159 assert(VA.getLocVT() == MVT::i32 &&
2160 "unexpected calling convention register assignment");
2161 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2162 "unexpected use of 'returned'");
2163 isThisReturn = true;
2165 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2166 } else if (isByVal) {
2167 assert(VA.isMemLoc());
2168 unsigned offset = 0;
2170 // True if this byval aggregate will be split between registers
2171 // and memory.
2172 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2173 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2175 if (CurByValIdx < ByValArgsCount) {
2177 unsigned RegBegin, RegEnd;
2178 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2180 EVT PtrVT =
2181 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2182 unsigned int i, j;
2183 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2184 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2185 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2186 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2187 MachinePointerInfo(),
2188 DAG.InferPtrAlignment(AddArg));
2189 MemOpChains.push_back(Load.getValue(1));
2190 RegsToPass.push_back(std::make_pair(j, Load));
2193 // If parameter size outsides register area, "offset" value
2194 // helps us to calculate stack slot for remained part properly.
2195 offset = RegEnd - RegBegin;
2197 CCInfo.nextInRegsParam();
2200 if (Flags.getByValSize() > 4*offset) {
2201 auto PtrVT = getPointerTy(DAG.getDataLayout());
2202 unsigned LocMemOffset = VA.getLocMemOffset();
2203 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2204 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2205 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2206 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2207 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2208 MVT::i32);
2209 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2210 MVT::i32);
2212 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2213 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2214 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2215 Ops));
2217 } else if (!isTailCall) {
2218 assert(VA.isMemLoc());
2220 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2221 dl, DAG, VA, Flags));
2225 if (!MemOpChains.empty())
2226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2228 // Build a sequence of copy-to-reg nodes chained together with token chain
2229 // and flag operands which copy the outgoing args into the appropriate regs.
2230 SDValue InFlag;
2231 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2232 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2233 RegsToPass[i].second, InFlag);
2234 InFlag = Chain.getValue(1);
2237 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2238 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2239 // node so that legalize doesn't hack it.
2240 bool isDirect = false;
2242 const TargetMachine &TM = getTargetMachine();
2243 const Module *Mod = MF.getFunction().getParent();
2244 const GlobalValue *GV = nullptr;
2245 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2246 GV = G->getGlobal();
2247 bool isStub =
2248 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2250 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2251 bool isLocalARMFunc = false;
2252 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2253 auto PtrVt = getPointerTy(DAG.getDataLayout());
2255 if (Subtarget->genLongCalls()) {
2256 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2257 "long-calls codegen is not position independent!");
2258 // Handle a global address or an external symbol. If it's not one of
2259 // those, the target's already in a register, so we don't need to do
2260 // anything extra.
2261 if (isa<GlobalAddressSDNode>(Callee)) {
2262 // Create a constant pool entry for the callee address
2263 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2264 ARMConstantPoolValue *CPV =
2265 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2267 // Get the address of the callee into a register
2268 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2269 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2270 Callee = DAG.getLoad(
2271 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2272 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2273 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2274 const char *Sym = S->getSymbol();
2276 // Create a constant pool entry for the callee address
2277 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2278 ARMConstantPoolValue *CPV =
2279 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2280 ARMPCLabelIndex, 0);
2281 // Get the address of the callee into a register
2282 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2283 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2284 Callee = DAG.getLoad(
2285 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2286 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2288 } else if (isa<GlobalAddressSDNode>(Callee)) {
2289 if (!PreferIndirect) {
2290 isDirect = true;
2291 bool isDef = GV->isStrongDefinitionForLinker();
2293 // ARM call to a local ARM function is predicable.
2294 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2295 // tBX takes a register source operand.
2296 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2297 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2298 Callee = DAG.getNode(
2299 ARMISD::WrapperPIC, dl, PtrVt,
2300 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2301 Callee = DAG.getLoad(
2302 PtrVt, dl, DAG.getEntryNode(), Callee,
2303 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2304 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2305 MachineMemOperand::MOInvariant);
2306 } else if (Subtarget->isTargetCOFF()) {
2307 assert(Subtarget->isTargetWindows() &&
2308 "Windows is the only supported COFF target");
2309 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2310 ? ARMII::MO_DLLIMPORT
2311 : ARMII::MO_NO_FLAG;
2312 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2313 TargetFlags);
2314 if (GV->hasDLLImportStorageClass())
2315 Callee =
2316 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2317 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2318 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2319 } else {
2320 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2323 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2324 isDirect = true;
2325 // tBX takes a register source operand.
2326 const char *Sym = S->getSymbol();
2327 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2328 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2329 ARMConstantPoolValue *CPV =
2330 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2331 ARMPCLabelIndex, 4);
2332 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2333 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2334 Callee = DAG.getLoad(
2335 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2336 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2337 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2338 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2339 } else {
2340 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2344 // FIXME: handle tail calls differently.
2345 unsigned CallOpc;
2346 if (Subtarget->isThumb()) {
2347 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2348 CallOpc = ARMISD::CALL_NOLINK;
2349 else
2350 CallOpc = ARMISD::CALL;
2351 } else {
2352 if (!isDirect && !Subtarget->hasV5TOps())
2353 CallOpc = ARMISD::CALL_NOLINK;
2354 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2355 // Emit regular call when code size is the priority
2356 !Subtarget->hasMinSize())
2357 // "mov lr, pc; b _foo" to avoid confusing the RSP
2358 CallOpc = ARMISD::CALL_NOLINK;
2359 else
2360 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2363 std::vector<SDValue> Ops;
2364 Ops.push_back(Chain);
2365 Ops.push_back(Callee);
2367 // Add argument registers to the end of the list so that they are known live
2368 // into the call.
2369 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2370 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2371 RegsToPass[i].second.getValueType()));
2373 // Add a register mask operand representing the call-preserved registers.
2374 if (!isTailCall) {
2375 const uint32_t *Mask;
2376 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2377 if (isThisReturn) {
2378 // For 'this' returns, use the R0-preserving mask if applicable
2379 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2380 if (!Mask) {
2381 // Set isThisReturn to false if the calling convention is not one that
2382 // allows 'returned' to be modeled in this way, so LowerCallResult does
2383 // not try to pass 'this' straight through
2384 isThisReturn = false;
2385 Mask = ARI->getCallPreservedMask(MF, CallConv);
2387 } else
2388 Mask = ARI->getCallPreservedMask(MF, CallConv);
2390 assert(Mask && "Missing call preserved mask for calling convention");
2391 Ops.push_back(DAG.getRegisterMask(Mask));
2394 if (InFlag.getNode())
2395 Ops.push_back(InFlag);
2397 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2398 if (isTailCall) {
2399 MF.getFrameInfo().setHasTailCall();
2400 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2403 // Returns a chain and a flag for retval copy to use.
2404 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2405 InFlag = Chain.getValue(1);
2407 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2408 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2409 if (!Ins.empty())
2410 InFlag = Chain.getValue(1);
2412 // Handle result values, copying them out of physregs into vregs that we
2413 // return.
2414 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2415 InVals, isThisReturn,
2416 isThisReturn ? OutVals[0] : SDValue());
2419 /// HandleByVal - Every parameter *after* a byval parameter is passed
2420 /// on the stack. Remember the next parameter register to allocate,
2421 /// and then confiscate the rest of the parameter registers to insure
2422 /// this.
2423 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2424 unsigned Align) const {
2425 // Byval (as with any stack) slots are always at least 4 byte aligned.
2426 Align = std::max(Align, 4U);
2428 unsigned Reg = State->AllocateReg(GPRArgRegs);
2429 if (!Reg)
2430 return;
2432 unsigned AlignInRegs = Align / 4;
2433 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2434 for (unsigned i = 0; i < Waste; ++i)
2435 Reg = State->AllocateReg(GPRArgRegs);
2437 if (!Reg)
2438 return;
2440 unsigned Excess = 4 * (ARM::R4 - Reg);
2442 // Special case when NSAA != SP and parameter size greater than size of
2443 // all remained GPR regs. In that case we can't split parameter, we must
2444 // send it to stack. We also must set NCRN to R4, so waste all
2445 // remained registers.
2446 const unsigned NSAAOffset = State->getNextStackOffset();
2447 if (NSAAOffset != 0 && Size > Excess) {
2448 while (State->AllocateReg(GPRArgRegs))
2450 return;
2453 // First register for byval parameter is the first register that wasn't
2454 // allocated before this method call, so it would be "reg".
2455 // If parameter is small enough to be saved in range [reg, r4), then
2456 // the end (first after last) register would be reg + param-size-in-regs,
2457 // else parameter would be splitted between registers and stack,
2458 // end register would be r4 in this case.
2459 unsigned ByValRegBegin = Reg;
2460 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2461 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2462 // Note, first register is allocated in the beginning of function already,
2463 // allocate remained amount of registers we need.
2464 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2465 State->AllocateReg(GPRArgRegs);
2466 // A byval parameter that is split between registers and memory needs its
2467 // size truncated here.
2468 // In the case where the entire structure fits in registers, we set the
2469 // size in memory to zero.
2470 Size = std::max<int>(Size - Excess, 0);
2473 /// MatchingStackOffset - Return true if the given stack call argument is
2474 /// already available in the same position (relatively) of the caller's
2475 /// incoming argument stack.
2476 static
2477 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2478 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2479 const TargetInstrInfo *TII) {
2480 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2481 int FI = std::numeric_limits<int>::max();
2482 if (Arg.getOpcode() == ISD::CopyFromReg) {
2483 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2484 if (!Register::isVirtualRegister(VR))
2485 return false;
2486 MachineInstr *Def = MRI->getVRegDef(VR);
2487 if (!Def)
2488 return false;
2489 if (!Flags.isByVal()) {
2490 if (!TII->isLoadFromStackSlot(*Def, FI))
2491 return false;
2492 } else {
2493 return false;
2495 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2496 if (Flags.isByVal())
2497 // ByVal argument is passed in as a pointer but it's now being
2498 // dereferenced. e.g.
2499 // define @foo(%struct.X* %A) {
2500 // tail call @bar(%struct.X* byval %A)
2501 // }
2502 return false;
2503 SDValue Ptr = Ld->getBasePtr();
2504 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2505 if (!FINode)
2506 return false;
2507 FI = FINode->getIndex();
2508 } else
2509 return false;
2511 assert(FI != std::numeric_limits<int>::max());
2512 if (!MFI.isFixedObjectIndex(FI))
2513 return false;
2514 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2517 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2518 /// for tail call optimization. Targets which want to do tail call
2519 /// optimization should implement this function.
2520 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2521 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2522 bool isCalleeStructRet, bool isCallerStructRet,
2523 const SmallVectorImpl<ISD::OutputArg> &Outs,
2524 const SmallVectorImpl<SDValue> &OutVals,
2525 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2526 const bool isIndirect) const {
2527 MachineFunction &MF = DAG.getMachineFunction();
2528 const Function &CallerF = MF.getFunction();
2529 CallingConv::ID CallerCC = CallerF.getCallingConv();
2531 assert(Subtarget->supportsTailCall());
2533 // Indirect tail calls cannot be optimized for Thumb1 if the args
2534 // to the call take up r0-r3. The reason is that there are no legal registers
2535 // left to hold the pointer to the function to be called.
2536 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2537 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2538 return false;
2540 // Look for obvious safe cases to perform tail call optimization that do not
2541 // require ABI changes. This is what gcc calls sibcall.
2543 // Exception-handling functions need a special set of instructions to indicate
2544 // a return to the hardware. Tail-calling another function would probably
2545 // break this.
2546 if (CallerF.hasFnAttribute("interrupt"))
2547 return false;
2549 // Also avoid sibcall optimization if either caller or callee uses struct
2550 // return semantics.
2551 if (isCalleeStructRet || isCallerStructRet)
2552 return false;
2554 // Externally-defined functions with weak linkage should not be
2555 // tail-called on ARM when the OS does not support dynamic
2556 // pre-emption of symbols, as the AAELF spec requires normal calls
2557 // to undefined weak functions to be replaced with a NOP or jump to the
2558 // next instruction. The behaviour of branch instructions in this
2559 // situation (as used for tail calls) is implementation-defined, so we
2560 // cannot rely on the linker replacing the tail call with a return.
2561 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2562 const GlobalValue *GV = G->getGlobal();
2563 const Triple &TT = getTargetMachine().getTargetTriple();
2564 if (GV->hasExternalWeakLinkage() &&
2565 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2566 return false;
2569 // Check that the call results are passed in the same way.
2570 LLVMContext &C = *DAG.getContext();
2571 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2572 CCAssignFnForReturn(CalleeCC, isVarArg),
2573 CCAssignFnForReturn(CallerCC, isVarArg)))
2574 return false;
2575 // The callee has to preserve all registers the caller needs to preserve.
2576 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2577 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2578 if (CalleeCC != CallerCC) {
2579 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2580 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2581 return false;
2584 // If Caller's vararg or byval argument has been split between registers and
2585 // stack, do not perform tail call, since part of the argument is in caller's
2586 // local frame.
2587 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2588 if (AFI_Caller->getArgRegsSaveSize())
2589 return false;
2591 // If the callee takes no arguments then go on to check the results of the
2592 // call.
2593 if (!Outs.empty()) {
2594 // Check if stack adjustment is needed. For now, do not do this if any
2595 // argument is passed on the stack.
2596 SmallVector<CCValAssign, 16> ArgLocs;
2597 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2598 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2599 if (CCInfo.getNextStackOffset()) {
2600 // Check if the arguments are already laid out in the right way as
2601 // the caller's fixed stack objects.
2602 MachineFrameInfo &MFI = MF.getFrameInfo();
2603 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2604 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2605 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2606 i != e;
2607 ++i, ++realArgIdx) {
2608 CCValAssign &VA = ArgLocs[i];
2609 EVT RegVT = VA.getLocVT();
2610 SDValue Arg = OutVals[realArgIdx];
2611 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2612 if (VA.getLocInfo() == CCValAssign::Indirect)
2613 return false;
2614 if (VA.needsCustom()) {
2615 // f64 and vector types are split into multiple registers or
2616 // register/stack-slot combinations. The types will not match
2617 // the registers; give up on memory f64 refs until we figure
2618 // out what to do about this.
2619 if (!VA.isRegLoc())
2620 return false;
2621 if (!ArgLocs[++i].isRegLoc())
2622 return false;
2623 if (RegVT == MVT::v2f64) {
2624 if (!ArgLocs[++i].isRegLoc())
2625 return false;
2626 if (!ArgLocs[++i].isRegLoc())
2627 return false;
2629 } else if (!VA.isRegLoc()) {
2630 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2631 MFI, MRI, TII))
2632 return false;
2637 const MachineRegisterInfo &MRI = MF.getRegInfo();
2638 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2639 return false;
2642 return true;
2645 bool
2646 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2647 MachineFunction &MF, bool isVarArg,
2648 const SmallVectorImpl<ISD::OutputArg> &Outs,
2649 LLVMContext &Context) const {
2650 SmallVector<CCValAssign, 16> RVLocs;
2651 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2652 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2655 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2656 const SDLoc &DL, SelectionDAG &DAG) {
2657 const MachineFunction &MF = DAG.getMachineFunction();
2658 const Function &F = MF.getFunction();
2660 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2662 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2663 // version of the "preferred return address". These offsets affect the return
2664 // instruction if this is a return from PL1 without hypervisor extensions.
2665 // IRQ/FIQ: +4 "subs pc, lr, #4"
2666 // SWI: 0 "subs pc, lr, #0"
2667 // ABORT: +4 "subs pc, lr, #4"
2668 // UNDEF: +4/+2 "subs pc, lr, #0"
2669 // UNDEF varies depending on where the exception came from ARM or Thumb
2670 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2672 int64_t LROffset;
2673 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2674 IntKind == "ABORT")
2675 LROffset = 4;
2676 else if (IntKind == "SWI" || IntKind == "UNDEF")
2677 LROffset = 0;
2678 else
2679 report_fatal_error("Unsupported interrupt attribute. If present, value "
2680 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2682 RetOps.insert(RetOps.begin() + 1,
2683 DAG.getConstant(LROffset, DL, MVT::i32, false));
2685 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2688 SDValue
2689 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2690 bool isVarArg,
2691 const SmallVectorImpl<ISD::OutputArg> &Outs,
2692 const SmallVectorImpl<SDValue> &OutVals,
2693 const SDLoc &dl, SelectionDAG &DAG) const {
2694 // CCValAssign - represent the assignment of the return value to a location.
2695 SmallVector<CCValAssign, 16> RVLocs;
2697 // CCState - Info about the registers and stack slots.
2698 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2699 *DAG.getContext());
2701 // Analyze outgoing return values.
2702 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2704 SDValue Flag;
2705 SmallVector<SDValue, 4> RetOps;
2706 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2707 bool isLittleEndian = Subtarget->isLittle();
2709 MachineFunction &MF = DAG.getMachineFunction();
2710 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2711 AFI->setReturnRegsCount(RVLocs.size());
2713 // Copy the result values into the output registers.
2714 for (unsigned i = 0, realRVLocIdx = 0;
2715 i != RVLocs.size();
2716 ++i, ++realRVLocIdx) {
2717 CCValAssign &VA = RVLocs[i];
2718 assert(VA.isRegLoc() && "Can only return in registers!");
2720 SDValue Arg = OutVals[realRVLocIdx];
2721 bool ReturnF16 = false;
2723 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2724 // Half-precision return values can be returned like this:
2726 // t11 f16 = fadd ...
2727 // t12: i16 = bitcast t11
2728 // t13: i32 = zero_extend t12
2729 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2731 // to avoid code generation for bitcasts, we simply set Arg to the node
2732 // that produces the f16 value, t11 in this case.
2734 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2735 SDValue ZE = Arg.getOperand(0);
2736 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2737 SDValue BC = ZE.getOperand(0);
2738 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2739 Arg = BC.getOperand(0);
2740 ReturnF16 = true;
2746 switch (VA.getLocInfo()) {
2747 default: llvm_unreachable("Unknown loc info!");
2748 case CCValAssign::Full: break;
2749 case CCValAssign::BCvt:
2750 if (!ReturnF16)
2751 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2752 break;
2755 if (VA.needsCustom()) {
2756 if (VA.getLocVT() == MVT::v2f64) {
2757 // Extract the first half and return it in two registers.
2758 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2759 DAG.getConstant(0, dl, MVT::i32));
2760 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2761 DAG.getVTList(MVT::i32, MVT::i32), Half);
2763 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2764 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2765 Flag);
2766 Flag = Chain.getValue(1);
2767 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2768 VA = RVLocs[++i]; // skip ahead to next loc
2769 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2770 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2771 Flag);
2772 Flag = Chain.getValue(1);
2773 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2774 VA = RVLocs[++i]; // skip ahead to next loc
2776 // Extract the 2nd half and fall through to handle it as an f64 value.
2777 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2778 DAG.getConstant(1, dl, MVT::i32));
2780 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2781 // available.
2782 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2783 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2784 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2785 fmrrd.getValue(isLittleEndian ? 0 : 1),
2786 Flag);
2787 Flag = Chain.getValue(1);
2788 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2789 VA = RVLocs[++i]; // skip ahead to next loc
2790 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2791 fmrrd.getValue(isLittleEndian ? 1 : 0),
2792 Flag);
2793 } else
2794 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2796 // Guarantee that all emitted copies are
2797 // stuck together, avoiding something bad.
2798 Flag = Chain.getValue(1);
2799 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2800 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2802 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2803 const MCPhysReg *I =
2804 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2805 if (I) {
2806 for (; *I; ++I) {
2807 if (ARM::GPRRegClass.contains(*I))
2808 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2809 else if (ARM::DPRRegClass.contains(*I))
2810 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2811 else
2812 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2816 // Update chain and glue.
2817 RetOps[0] = Chain;
2818 if (Flag.getNode())
2819 RetOps.push_back(Flag);
2821 // CPUs which aren't M-class use a special sequence to return from
2822 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2823 // though we use "subs pc, lr, #N").
2825 // M-class CPUs actually use a normal return sequence with a special
2826 // (hardware-provided) value in LR, so the normal code path works.
2827 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2828 !Subtarget->isMClass()) {
2829 if (Subtarget->isThumb1Only())
2830 report_fatal_error("interrupt attribute is not supported in Thumb1");
2831 return LowerInterruptReturn(RetOps, dl, DAG);
2834 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2837 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2838 if (N->getNumValues() != 1)
2839 return false;
2840 if (!N->hasNUsesOfValue(1, 0))
2841 return false;
2843 SDValue TCChain = Chain;
2844 SDNode *Copy = *N->use_begin();
2845 if (Copy->getOpcode() == ISD::CopyToReg) {
2846 // If the copy has a glue operand, we conservatively assume it isn't safe to
2847 // perform a tail call.
2848 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2849 return false;
2850 TCChain = Copy->getOperand(0);
2851 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2852 SDNode *VMov = Copy;
2853 // f64 returned in a pair of GPRs.
2854 SmallPtrSet<SDNode*, 2> Copies;
2855 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2856 UI != UE; ++UI) {
2857 if (UI->getOpcode() != ISD::CopyToReg)
2858 return false;
2859 Copies.insert(*UI);
2861 if (Copies.size() > 2)
2862 return false;
2864 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2865 UI != UE; ++UI) {
2866 SDValue UseChain = UI->getOperand(0);
2867 if (Copies.count(UseChain.getNode()))
2868 // Second CopyToReg
2869 Copy = *UI;
2870 else {
2871 // We are at the top of this chain.
2872 // If the copy has a glue operand, we conservatively assume it
2873 // isn't safe to perform a tail call.
2874 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2875 return false;
2876 // First CopyToReg
2877 TCChain = UseChain;
2880 } else if (Copy->getOpcode() == ISD::BITCAST) {
2881 // f32 returned in a single GPR.
2882 if (!Copy->hasOneUse())
2883 return false;
2884 Copy = *Copy->use_begin();
2885 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2886 return false;
2887 // If the copy has a glue operand, we conservatively assume it isn't safe to
2888 // perform a tail call.
2889 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2890 return false;
2891 TCChain = Copy->getOperand(0);
2892 } else {
2893 return false;
2896 bool HasRet = false;
2897 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2898 UI != UE; ++UI) {
2899 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2900 UI->getOpcode() != ARMISD::INTRET_FLAG)
2901 return false;
2902 HasRet = true;
2905 if (!HasRet)
2906 return false;
2908 Chain = TCChain;
2909 return true;
2912 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2913 if (!Subtarget->supportsTailCall())
2914 return false;
2916 auto Attr =
2917 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2918 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2919 return false;
2921 return true;
2924 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2925 // and pass the lower and high parts through.
2926 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2927 SDLoc DL(Op);
2928 SDValue WriteValue = Op->getOperand(2);
2930 // This function is only supposed to be called for i64 type argument.
2931 assert(WriteValue.getValueType() == MVT::i64
2932 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2934 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2935 DAG.getConstant(0, DL, MVT::i32));
2936 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2937 DAG.getConstant(1, DL, MVT::i32));
2938 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2939 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2942 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2943 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2944 // one of the above mentioned nodes. It has to be wrapped because otherwise
2945 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2946 // be used to form addressing mode. These wrapped nodes will be selected
2947 // into MOVi.
2948 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2949 SelectionDAG &DAG) const {
2950 EVT PtrVT = Op.getValueType();
2951 // FIXME there is no actual debug info here
2952 SDLoc dl(Op);
2953 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2954 SDValue Res;
2956 // When generating execute-only code Constant Pools must be promoted to the
2957 // global data section. It's a bit ugly that we can't share them across basic
2958 // blocks, but this way we guarantee that execute-only behaves correct with
2959 // position-independent addressing modes.
2960 if (Subtarget->genExecuteOnly()) {
2961 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2962 auto T = const_cast<Type*>(CP->getType());
2963 auto C = const_cast<Constant*>(CP->getConstVal());
2964 auto M = const_cast<Module*>(DAG.getMachineFunction().
2965 getFunction().getParent());
2966 auto GV = new GlobalVariable(
2967 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2968 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2969 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2970 Twine(AFI->createPICLabelUId())
2972 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2973 dl, PtrVT);
2974 return LowerGlobalAddress(GA, DAG);
2977 if (CP->isMachineConstantPoolEntry())
2978 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2979 CP->getAlignment());
2980 else
2981 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2982 CP->getAlignment());
2983 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2986 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2987 return MachineJumpTableInfo::EK_Inline;
2990 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2991 SelectionDAG &DAG) const {
2992 MachineFunction &MF = DAG.getMachineFunction();
2993 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2994 unsigned ARMPCLabelIndex = 0;
2995 SDLoc DL(Op);
2996 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2997 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2998 SDValue CPAddr;
2999 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3000 if (!IsPositionIndependent) {
3001 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3002 } else {
3003 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3004 ARMPCLabelIndex = AFI->createPICLabelUId();
3005 ARMConstantPoolValue *CPV =
3006 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3007 ARMCP::CPBlockAddress, PCAdj);
3008 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3010 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3011 SDValue Result = DAG.getLoad(
3012 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3013 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3014 if (!IsPositionIndependent)
3015 return Result;
3016 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3017 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3020 /// Convert a TLS address reference into the correct sequence of loads
3021 /// and calls to compute the variable's address for Darwin, and return an
3022 /// SDValue containing the final node.
3024 /// Darwin only has one TLS scheme which must be capable of dealing with the
3025 /// fully general situation, in the worst case. This means:
3026 /// + "extern __thread" declaration.
3027 /// + Defined in a possibly unknown dynamic library.
3029 /// The general system is that each __thread variable has a [3 x i32] descriptor
3030 /// which contains information used by the runtime to calculate the address. The
3031 /// only part of this the compiler needs to know about is the first word, which
3032 /// contains a function pointer that must be called with the address of the
3033 /// entire descriptor in "r0".
3035 /// Since this descriptor may be in a different unit, in general access must
3036 /// proceed along the usual ARM rules. A common sequence to produce is:
3038 /// movw rT1, :lower16:_var$non_lazy_ptr
3039 /// movt rT1, :upper16:_var$non_lazy_ptr
3040 /// ldr r0, [rT1]
3041 /// ldr rT2, [r0]
3042 /// blx rT2
3043 /// [...address now in r0...]
3044 SDValue
3045 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3046 SelectionDAG &DAG) const {
3047 assert(Subtarget->isTargetDarwin() &&
3048 "This function expects a Darwin target");
3049 SDLoc DL(Op);
3051 // First step is to get the address of the actua global symbol. This is where
3052 // the TLS descriptor lives.
3053 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3055 // The first entry in the descriptor is a function pointer that we must call
3056 // to obtain the address of the variable.
3057 SDValue Chain = DAG.getEntryNode();
3058 SDValue FuncTLVGet = DAG.getLoad(
3059 MVT::i32, DL, Chain, DescAddr,
3060 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3061 /* Alignment = */ 4,
3062 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3063 MachineMemOperand::MOInvariant);
3064 Chain = FuncTLVGet.getValue(1);
3066 MachineFunction &F = DAG.getMachineFunction();
3067 MachineFrameInfo &MFI = F.getFrameInfo();
3068 MFI.setAdjustsStack(true);
3070 // TLS calls preserve all registers except those that absolutely must be
3071 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3072 // silly).
3073 auto TRI =
3074 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3075 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3076 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3078 // Finally, we can make the call. This is just a degenerate version of a
3079 // normal AArch64 call node: r0 takes the address of the descriptor, and
3080 // returns the address of the variable in this thread.
3081 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3082 Chain =
3083 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3084 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3085 DAG.getRegisterMask(Mask), Chain.getValue(1));
3086 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3089 SDValue
3090 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3091 SelectionDAG &DAG) const {
3092 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3094 SDValue Chain = DAG.getEntryNode();
3095 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3096 SDLoc DL(Op);
3098 // Load the current TEB (thread environment block)
3099 SDValue Ops[] = {Chain,
3100 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3101 DAG.getConstant(15, DL, MVT::i32),
3102 DAG.getConstant(0, DL, MVT::i32),
3103 DAG.getConstant(13, DL, MVT::i32),
3104 DAG.getConstant(0, DL, MVT::i32),
3105 DAG.getConstant(2, DL, MVT::i32)};
3106 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3107 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3109 SDValue TEB = CurrentTEB.getValue(0);
3110 Chain = CurrentTEB.getValue(1);
3112 // Load the ThreadLocalStoragePointer from the TEB
3113 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3114 SDValue TLSArray =
3115 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3116 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3118 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3119 // offset into the TLSArray.
3121 // Load the TLS index from the C runtime
3122 SDValue TLSIndex =
3123 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3124 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3125 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3127 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3128 DAG.getConstant(2, DL, MVT::i32));
3129 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3130 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3131 MachinePointerInfo());
3133 // Get the offset of the start of the .tls section (section base)
3134 const auto *GA = cast<GlobalAddressSDNode>(Op);
3135 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3136 SDValue Offset = DAG.getLoad(
3137 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3138 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3139 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3141 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3144 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3145 SDValue
3146 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3147 SelectionDAG &DAG) const {
3148 SDLoc dl(GA);
3149 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3150 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3151 MachineFunction &MF = DAG.getMachineFunction();
3152 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3153 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3154 ARMConstantPoolValue *CPV =
3155 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3156 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3157 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3158 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3159 Argument = DAG.getLoad(
3160 PtrVT, dl, DAG.getEntryNode(), Argument,
3161 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3162 SDValue Chain = Argument.getValue(1);
3164 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3165 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3167 // call __tls_get_addr.
3168 ArgListTy Args;
3169 ArgListEntry Entry;
3170 Entry.Node = Argument;
3171 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3172 Args.push_back(Entry);
3174 // FIXME: is there useful debug info available here?
3175 TargetLowering::CallLoweringInfo CLI(DAG);
3176 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3177 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3178 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3180 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3181 return CallResult.first;
3184 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3185 // "local exec" model.
3186 SDValue
3187 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3188 SelectionDAG &DAG,
3189 TLSModel::Model model) const {
3190 const GlobalValue *GV = GA->getGlobal();
3191 SDLoc dl(GA);
3192 SDValue Offset;
3193 SDValue Chain = DAG.getEntryNode();
3194 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3195 // Get the Thread Pointer
3196 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3198 if (model == TLSModel::InitialExec) {
3199 MachineFunction &MF = DAG.getMachineFunction();
3200 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3201 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3202 // Initial exec model.
3203 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3204 ARMConstantPoolValue *CPV =
3205 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3206 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3207 true);
3208 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3209 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3210 Offset = DAG.getLoad(
3211 PtrVT, dl, Chain, Offset,
3212 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3213 Chain = Offset.getValue(1);
3215 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3216 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3218 Offset = DAG.getLoad(
3219 PtrVT, dl, Chain, Offset,
3220 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3221 } else {
3222 // local exec model
3223 assert(model == TLSModel::LocalExec);
3224 ARMConstantPoolValue *CPV =
3225 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3226 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3227 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3228 Offset = DAG.getLoad(
3229 PtrVT, dl, Chain, Offset,
3230 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3233 // The address of the thread local variable is the add of the thread
3234 // pointer with the offset of the variable.
3235 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3238 SDValue
3239 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3240 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3241 if (DAG.getTarget().useEmulatedTLS())
3242 return LowerToTLSEmulatedModel(GA, DAG);
3244 if (Subtarget->isTargetDarwin())
3245 return LowerGlobalTLSAddressDarwin(Op, DAG);
3247 if (Subtarget->isTargetWindows())
3248 return LowerGlobalTLSAddressWindows(Op, DAG);
3250 // TODO: implement the "local dynamic" model
3251 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3252 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3254 switch (model) {
3255 case TLSModel::GeneralDynamic:
3256 case TLSModel::LocalDynamic:
3257 return LowerToTLSGeneralDynamicModel(GA, DAG);
3258 case TLSModel::InitialExec:
3259 case TLSModel::LocalExec:
3260 return LowerToTLSExecModels(GA, DAG, model);
3262 llvm_unreachable("bogus TLS model");
3265 /// Return true if all users of V are within function F, looking through
3266 /// ConstantExprs.
3267 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3268 SmallVector<const User*,4> Worklist;
3269 for (auto *U : V->users())
3270 Worklist.push_back(U);
3271 while (!Worklist.empty()) {
3272 auto *U = Worklist.pop_back_val();
3273 if (isa<ConstantExpr>(U)) {
3274 for (auto *UU : U->users())
3275 Worklist.push_back(UU);
3276 continue;
3279 auto *I = dyn_cast<Instruction>(U);
3280 if (!I || I->getParent()->getParent() != F)
3281 return false;
3283 return true;
3286 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3287 const GlobalValue *GV, SelectionDAG &DAG,
3288 EVT PtrVT, const SDLoc &dl) {
3289 // If we're creating a pool entry for a constant global with unnamed address,
3290 // and the global is small enough, we can emit it inline into the constant pool
3291 // to save ourselves an indirection.
3293 // This is a win if the constant is only used in one function (so it doesn't
3294 // need to be duplicated) or duplicating the constant wouldn't increase code
3295 // size (implying the constant is no larger than 4 bytes).
3296 const Function &F = DAG.getMachineFunction().getFunction();
3298 // We rely on this decision to inline being idemopotent and unrelated to the
3299 // use-site. We know that if we inline a variable at one use site, we'll
3300 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3301 // doesn't know about this optimization, so bail out if it's enabled else
3302 // we could decide to inline here (and thus never emit the GV) but require
3303 // the GV from fast-isel generated code.
3304 if (!EnableConstpoolPromotion ||
3305 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3306 return SDValue();
3308 auto *GVar = dyn_cast<GlobalVariable>(GV);
3309 if (!GVar || !GVar->hasInitializer() ||
3310 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3311 !GVar->hasLocalLinkage())
3312 return SDValue();
3314 // If we inline a value that contains relocations, we move the relocations
3315 // from .data to .text. This is not allowed in position-independent code.
3316 auto *Init = GVar->getInitializer();
3317 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3318 Init->needsRelocation())
3319 return SDValue();
3321 // The constant islands pass can only really deal with alignment requests
3322 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3323 // any type wanting greater alignment requirements than 4 bytes. We also
3324 // can only promote constants that are multiples of 4 bytes in size or
3325 // are paddable to a multiple of 4. Currently we only try and pad constants
3326 // that are strings for simplicity.
3327 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3328 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3329 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3330 unsigned RequiredPadding = 4 - (Size % 4);
3331 bool PaddingPossible =
3332 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3333 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3334 Size == 0)
3335 return SDValue();
3337 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3338 MachineFunction &MF = DAG.getMachineFunction();
3339 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3341 // We can't bloat the constant pool too much, else the ConstantIslands pass
3342 // may fail to converge. If we haven't promoted this global yet (it may have
3343 // multiple uses), and promoting it would increase the constant pool size (Sz
3344 // > 4), ensure we have space to do so up to MaxTotal.
3345 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3346 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3347 ConstpoolPromotionMaxTotal)
3348 return SDValue();
3350 // This is only valid if all users are in a single function; we can't clone
3351 // the constant in general. The LLVM IR unnamed_addr allows merging
3352 // constants, but not cloning them.
3354 // We could potentially allow cloning if we could prove all uses of the
3355 // constant in the current function don't care about the address, like
3356 // printf format strings. But that isn't implemented for now.
3357 if (!allUsersAreInFunction(GVar, &F))
3358 return SDValue();
3360 // We're going to inline this global. Pad it out if needed.
3361 if (RequiredPadding != 4) {
3362 StringRef S = CDAInit->getAsString();
3364 SmallVector<uint8_t,16> V(S.size());
3365 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3366 while (RequiredPadding--)
3367 V.push_back(0);
3368 Init = ConstantDataArray::get(*DAG.getContext(), V);
3371 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3372 SDValue CPAddr =
3373 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3374 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3375 AFI->markGlobalAsPromotedToConstantPool(GVar);
3376 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3377 PaddedSize - 4);
3379 ++NumConstpoolPromoted;
3380 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3383 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3384 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3385 if (!(GV = GA->getBaseObject()))
3386 return false;
3387 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3388 return V->isConstant();
3389 return isa<Function>(GV);
3392 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3393 SelectionDAG &DAG) const {
3394 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3395 default: llvm_unreachable("unknown object format");
3396 case Triple::COFF:
3397 return LowerGlobalAddressWindows(Op, DAG);
3398 case Triple::ELF:
3399 return LowerGlobalAddressELF(Op, DAG);
3400 case Triple::MachO:
3401 return LowerGlobalAddressDarwin(Op, DAG);
3405 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3406 SelectionDAG &DAG) const {
3407 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3408 SDLoc dl(Op);
3409 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3410 const TargetMachine &TM = getTargetMachine();
3411 bool IsRO = isReadOnly(GV);
3413 // promoteToConstantPool only if not generating XO text section
3414 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3415 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3416 return V;
3418 if (isPositionIndependent()) {
3419 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3420 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3421 UseGOT_PREL ? ARMII::MO_GOT : 0);
3422 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3423 if (UseGOT_PREL)
3424 Result =
3425 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3426 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3427 return Result;
3428 } else if (Subtarget->isROPI() && IsRO) {
3429 // PC-relative.
3430 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3431 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3432 return Result;
3433 } else if (Subtarget->isRWPI() && !IsRO) {
3434 // SB-relative.
3435 SDValue RelAddr;
3436 if (Subtarget->useMovt()) {
3437 ++NumMovwMovt;
3438 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3439 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3440 } else { // use literal pool for address constant
3441 ARMConstantPoolValue *CPV =
3442 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3443 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3444 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3445 RelAddr = DAG.getLoad(
3446 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3447 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3449 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3450 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3451 return Result;
3454 // If we have T2 ops, we can materialize the address directly via movt/movw
3455 // pair. This is always cheaper.
3456 if (Subtarget->useMovt()) {
3457 ++NumMovwMovt;
3458 // FIXME: Once remat is capable of dealing with instructions with register
3459 // operands, expand this into two nodes.
3460 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3461 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3462 } else {
3463 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3464 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3465 return DAG.getLoad(
3466 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3467 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3471 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3472 SelectionDAG &DAG) const {
3473 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3474 "ROPI/RWPI not currently supported for Darwin");
3475 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3476 SDLoc dl(Op);
3477 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3479 if (Subtarget->useMovt())
3480 ++NumMovwMovt;
3482 // FIXME: Once remat is capable of dealing with instructions with register
3483 // operands, expand this into multiple nodes
3484 unsigned Wrapper =
3485 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3487 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3488 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3490 if (Subtarget->isGVIndirectSymbol(GV))
3491 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3492 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3493 return Result;
3496 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3497 SelectionDAG &DAG) const {
3498 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3499 assert(Subtarget->useMovt() &&
3500 "Windows on ARM expects to use movw/movt");
3501 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3502 "ROPI/RWPI not currently supported for Windows");
3504 const TargetMachine &TM = getTargetMachine();
3505 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3506 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3507 if (GV->hasDLLImportStorageClass())
3508 TargetFlags = ARMII::MO_DLLIMPORT;
3509 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3510 TargetFlags = ARMII::MO_COFFSTUB;
3511 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3512 SDValue Result;
3513 SDLoc DL(Op);
3515 ++NumMovwMovt;
3517 // FIXME: Once remat is capable of dealing with instructions with register
3518 // operands, expand this into two nodes.
3519 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3520 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3521 TargetFlags));
3522 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3523 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3524 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3525 return Result;
3528 SDValue
3529 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3530 SDLoc dl(Op);
3531 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3532 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3533 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3534 Op.getOperand(1), Val);
3537 SDValue
3538 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3539 SDLoc dl(Op);
3540 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3541 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3544 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3545 SelectionDAG &DAG) const {
3546 SDLoc dl(Op);
3547 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3548 Op.getOperand(0));
3551 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3552 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3553 unsigned IntNo =
3554 cast<ConstantSDNode>(
3555 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3556 ->getZExtValue();
3557 switch (IntNo) {
3558 default:
3559 return SDValue(); // Don't custom lower most intrinsics.
3560 case Intrinsic::arm_gnu_eabi_mcount: {
3561 MachineFunction &MF = DAG.getMachineFunction();
3562 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3563 SDLoc dl(Op);
3564 SDValue Chain = Op.getOperand(0);
3565 // call "\01__gnu_mcount_nc"
3566 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3567 const uint32_t *Mask =
3568 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3569 assert(Mask && "Missing call preserved mask for calling convention");
3570 // Mark LR an implicit live-in.
3571 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3572 SDValue ReturnAddress =
3573 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3574 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue};
3575 SDValue Callee =
3576 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3577 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3578 if (Subtarget->isThumb())
3579 return SDValue(
3580 DAG.getMachineNode(
3581 ARM::tBL_PUSHLR, dl, ResultTys,
3582 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3583 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3585 return SDValue(
3586 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3587 {ReturnAddress, Callee, RegisterMask, Chain}),
3593 SDValue
3594 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3595 const ARMSubtarget *Subtarget) const {
3596 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3597 SDLoc dl(Op);
3598 switch (IntNo) {
3599 default: return SDValue(); // Don't custom lower most intrinsics.
3600 case Intrinsic::thread_pointer: {
3601 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3602 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3604 case Intrinsic::eh_sjlj_lsda: {
3605 MachineFunction &MF = DAG.getMachineFunction();
3606 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3607 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3608 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3609 SDValue CPAddr;
3610 bool IsPositionIndependent = isPositionIndependent();
3611 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3612 ARMConstantPoolValue *CPV =
3613 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3614 ARMCP::CPLSDA, PCAdj);
3615 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3616 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3617 SDValue Result = DAG.getLoad(
3618 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3619 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3621 if (IsPositionIndependent) {
3622 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3623 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3625 return Result;
3627 case Intrinsic::arm_neon_vabs:
3628 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3629 Op.getOperand(1));
3630 case Intrinsic::arm_neon_vmulls:
3631 case Intrinsic::arm_neon_vmullu: {
3632 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3633 ? ARMISD::VMULLs : ARMISD::VMULLu;
3634 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3635 Op.getOperand(1), Op.getOperand(2));
3637 case Intrinsic::arm_neon_vminnm:
3638 case Intrinsic::arm_neon_vmaxnm: {
3639 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3640 ? ISD::FMINNUM : ISD::FMAXNUM;
3641 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3642 Op.getOperand(1), Op.getOperand(2));
3644 case Intrinsic::arm_neon_vminu:
3645 case Intrinsic::arm_neon_vmaxu: {
3646 if (Op.getValueType().isFloatingPoint())
3647 return SDValue();
3648 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3649 ? ISD::UMIN : ISD::UMAX;
3650 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3651 Op.getOperand(1), Op.getOperand(2));
3653 case Intrinsic::arm_neon_vmins:
3654 case Intrinsic::arm_neon_vmaxs: {
3655 // v{min,max}s is overloaded between signed integers and floats.
3656 if (!Op.getValueType().isFloatingPoint()) {
3657 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3658 ? ISD::SMIN : ISD::SMAX;
3659 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3660 Op.getOperand(1), Op.getOperand(2));
3662 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3663 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3664 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3665 Op.getOperand(1), Op.getOperand(2));
3667 case Intrinsic::arm_neon_vtbl1:
3668 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3669 Op.getOperand(1), Op.getOperand(2));
3670 case Intrinsic::arm_neon_vtbl2:
3671 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3672 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3676 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3677 const ARMSubtarget *Subtarget) {
3678 SDLoc dl(Op);
3679 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3680 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3681 if (SSID == SyncScope::SingleThread)
3682 return Op;
3684 if (!Subtarget->hasDataBarrier()) {
3685 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3686 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3687 // here.
3688 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3689 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3690 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3691 DAG.getConstant(0, dl, MVT::i32));
3694 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3695 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3696 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3697 if (Subtarget->isMClass()) {
3698 // Only a full system barrier exists in the M-class architectures.
3699 Domain = ARM_MB::SY;
3700 } else if (Subtarget->preferISHSTBarriers() &&
3701 Ord == AtomicOrdering::Release) {
3702 // Swift happens to implement ISHST barriers in a way that's compatible with
3703 // Release semantics but weaker than ISH so we'd be fools not to use
3704 // it. Beware: other processors probably don't!
3705 Domain = ARM_MB::ISHST;
3708 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3709 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3710 DAG.getConstant(Domain, dl, MVT::i32));
3713 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3714 const ARMSubtarget *Subtarget) {
3715 // ARM pre v5TE and Thumb1 does not have preload instructions.
3716 if (!(Subtarget->isThumb2() ||
3717 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3718 // Just preserve the chain.
3719 return Op.getOperand(0);
3721 SDLoc dl(Op);
3722 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3723 if (!isRead &&
3724 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3725 // ARMv7 with MP extension has PLDW.
3726 return Op.getOperand(0);
3728 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3729 if (Subtarget->isThumb()) {
3730 // Invert the bits.
3731 isRead = ~isRead & 1;
3732 isData = ~isData & 1;
3735 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3736 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3737 DAG.getConstant(isData, dl, MVT::i32));
3740 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3741 MachineFunction &MF = DAG.getMachineFunction();
3742 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3744 // vastart just stores the address of the VarArgsFrameIndex slot into the
3745 // memory location argument.
3746 SDLoc dl(Op);
3747 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3748 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3749 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3750 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3751 MachinePointerInfo(SV));
3754 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3755 CCValAssign &NextVA,
3756 SDValue &Root,
3757 SelectionDAG &DAG,
3758 const SDLoc &dl) const {
3759 MachineFunction &MF = DAG.getMachineFunction();
3760 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3762 const TargetRegisterClass *RC;
3763 if (AFI->isThumb1OnlyFunction())
3764 RC = &ARM::tGPRRegClass;
3765 else
3766 RC = &ARM::GPRRegClass;
3768 // Transform the arguments stored in physical registers into virtual ones.
3769 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3770 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3772 SDValue ArgValue2;
3773 if (NextVA.isMemLoc()) {
3774 MachineFrameInfo &MFI = MF.getFrameInfo();
3775 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3777 // Create load node to retrieve arguments from the stack.
3778 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3779 ArgValue2 = DAG.getLoad(
3780 MVT::i32, dl, Root, FIN,
3781 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3782 } else {
3783 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3784 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3786 if (!Subtarget->isLittle())
3787 std::swap (ArgValue, ArgValue2);
3788 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3791 // The remaining GPRs hold either the beginning of variable-argument
3792 // data, or the beginning of an aggregate passed by value (usually
3793 // byval). Either way, we allocate stack slots adjacent to the data
3794 // provided by our caller, and store the unallocated registers there.
3795 // If this is a variadic function, the va_list pointer will begin with
3796 // these values; otherwise, this reassembles a (byval) structure that
3797 // was split between registers and memory.
3798 // Return: The frame index registers were stored into.
3799 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3800 const SDLoc &dl, SDValue &Chain,
3801 const Value *OrigArg,
3802 unsigned InRegsParamRecordIdx,
3803 int ArgOffset, unsigned ArgSize) const {
3804 // Currently, two use-cases possible:
3805 // Case #1. Non-var-args function, and we meet first byval parameter.
3806 // Setup first unallocated register as first byval register;
3807 // eat all remained registers
3808 // (these two actions are performed by HandleByVal method).
3809 // Then, here, we initialize stack frame with
3810 // "store-reg" instructions.
3811 // Case #2. Var-args function, that doesn't contain byval parameters.
3812 // The same: eat all remained unallocated registers,
3813 // initialize stack frame.
3815 MachineFunction &MF = DAG.getMachineFunction();
3816 MachineFrameInfo &MFI = MF.getFrameInfo();
3817 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3818 unsigned RBegin, REnd;
3819 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3820 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3821 } else {
3822 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3823 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3824 REnd = ARM::R4;
3827 if (REnd != RBegin)
3828 ArgOffset = -4 * (ARM::R4 - RBegin);
3830 auto PtrVT = getPointerTy(DAG.getDataLayout());
3831 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3832 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3834 SmallVector<SDValue, 4> MemOps;
3835 const TargetRegisterClass *RC =
3836 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3838 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3839 unsigned VReg = MF.addLiveIn(Reg, RC);
3840 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3841 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3842 MachinePointerInfo(OrigArg, 4 * i));
3843 MemOps.push_back(Store);
3844 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3847 if (!MemOps.empty())
3848 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3849 return FrameIndex;
3852 // Setup stack frame, the va_list pointer will start from.
3853 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3854 const SDLoc &dl, SDValue &Chain,
3855 unsigned ArgOffset,
3856 unsigned TotalArgRegsSaveSize,
3857 bool ForceMutable) const {
3858 MachineFunction &MF = DAG.getMachineFunction();
3859 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3861 // Try to store any remaining integer argument regs
3862 // to their spots on the stack so that they may be loaded by dereferencing
3863 // the result of va_next.
3864 // If there is no regs to be stored, just point address after last
3865 // argument passed via stack.
3866 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3867 CCInfo.getInRegsParamsCount(),
3868 CCInfo.getNextStackOffset(),
3869 std::max(4U, TotalArgRegsSaveSize));
3870 AFI->setVarArgsFrameIndex(FrameIndex);
3873 SDValue ARMTargetLowering::LowerFormalArguments(
3874 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3875 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3876 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3877 MachineFunction &MF = DAG.getMachineFunction();
3878 MachineFrameInfo &MFI = MF.getFrameInfo();
3880 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3882 // Assign locations to all of the incoming arguments.
3883 SmallVector<CCValAssign, 16> ArgLocs;
3884 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3885 *DAG.getContext());
3886 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3888 SmallVector<SDValue, 16> ArgValues;
3889 SDValue ArgValue;
3890 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3891 unsigned CurArgIdx = 0;
3893 // Initially ArgRegsSaveSize is zero.
3894 // Then we increase this value each time we meet byval parameter.
3895 // We also increase this value in case of varargs function.
3896 AFI->setArgRegsSaveSize(0);
3898 // Calculate the amount of stack space that we need to allocate to store
3899 // byval and variadic arguments that are passed in registers.
3900 // We need to know this before we allocate the first byval or variadic
3901 // argument, as they will be allocated a stack slot below the CFA (Canonical
3902 // Frame Address, the stack pointer at entry to the function).
3903 unsigned ArgRegBegin = ARM::R4;
3904 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3905 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3906 break;
3908 CCValAssign &VA = ArgLocs[i];
3909 unsigned Index = VA.getValNo();
3910 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3911 if (!Flags.isByVal())
3912 continue;
3914 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3915 unsigned RBegin, REnd;
3916 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3917 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3919 CCInfo.nextInRegsParam();
3921 CCInfo.rewindByValRegsInfo();
3923 int lastInsIndex = -1;
3924 if (isVarArg && MFI.hasVAStart()) {
3925 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3926 if (RegIdx != array_lengthof(GPRArgRegs))
3927 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3930 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3931 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3932 auto PtrVT = getPointerTy(DAG.getDataLayout());
3934 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3935 CCValAssign &VA = ArgLocs[i];
3936 if (Ins[VA.getValNo()].isOrigArg()) {
3937 std::advance(CurOrigArg,
3938 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3939 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3941 // Arguments stored in registers.
3942 if (VA.isRegLoc()) {
3943 EVT RegVT = VA.getLocVT();
3945 if (VA.needsCustom()) {
3946 // f64 and vector types are split up into multiple registers or
3947 // combinations of registers and stack slots.
3948 if (VA.getLocVT() == MVT::v2f64) {
3949 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3950 Chain, DAG, dl);
3951 VA = ArgLocs[++i]; // skip ahead to next loc
3952 SDValue ArgValue2;
3953 if (VA.isMemLoc()) {
3954 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3955 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3956 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3957 MachinePointerInfo::getFixedStack(
3958 DAG.getMachineFunction(), FI));
3959 } else {
3960 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3961 Chain, DAG, dl);
3963 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3964 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3965 ArgValue, ArgValue1,
3966 DAG.getIntPtrConstant(0, dl));
3967 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3968 ArgValue, ArgValue2,
3969 DAG.getIntPtrConstant(1, dl));
3970 } else
3971 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3972 } else {
3973 const TargetRegisterClass *RC;
3976 if (RegVT == MVT::f16)
3977 RC = &ARM::HPRRegClass;
3978 else if (RegVT == MVT::f32)
3979 RC = &ARM::SPRRegClass;
3980 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3981 RC = &ARM::DPRRegClass;
3982 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3983 RC = &ARM::QPRRegClass;
3984 else if (RegVT == MVT::i32)
3985 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3986 : &ARM::GPRRegClass;
3987 else
3988 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3990 // Transform the arguments in physical registers into virtual ones.
3991 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3992 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3994 // If this value is passed in r0 and has the returned attribute (e.g.
3995 // C++ 'structors), record this fact for later use.
3996 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
3997 AFI->setPreservesR0();
4001 // If this is an 8 or 16-bit value, it is really passed promoted
4002 // to 32 bits. Insert an assert[sz]ext to capture this, then
4003 // truncate to the right size.
4004 switch (VA.getLocInfo()) {
4005 default: llvm_unreachable("Unknown loc info!");
4006 case CCValAssign::Full: break;
4007 case CCValAssign::BCvt:
4008 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4009 break;
4010 case CCValAssign::SExt:
4011 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4012 DAG.getValueType(VA.getValVT()));
4013 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4014 break;
4015 case CCValAssign::ZExt:
4016 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4017 DAG.getValueType(VA.getValVT()));
4018 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4019 break;
4022 InVals.push_back(ArgValue);
4023 } else { // VA.isRegLoc()
4024 // sanity check
4025 assert(VA.isMemLoc());
4026 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4028 int index = VA.getValNo();
4030 // Some Ins[] entries become multiple ArgLoc[] entries.
4031 // Process them only once.
4032 if (index != lastInsIndex)
4034 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4035 // FIXME: For now, all byval parameter objects are marked mutable.
4036 // This can be changed with more analysis.
4037 // In case of tail call optimization mark all arguments mutable.
4038 // Since they could be overwritten by lowering of arguments in case of
4039 // a tail call.
4040 if (Flags.isByVal()) {
4041 assert(Ins[index].isOrigArg() &&
4042 "Byval arguments cannot be implicit");
4043 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4045 int FrameIndex = StoreByValRegs(
4046 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4047 VA.getLocMemOffset(), Flags.getByValSize());
4048 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4049 CCInfo.nextInRegsParam();
4050 } else {
4051 unsigned FIOffset = VA.getLocMemOffset();
4052 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4053 FIOffset, true);
4055 // Create load nodes to retrieve arguments from the stack.
4056 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4057 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4058 MachinePointerInfo::getFixedStack(
4059 DAG.getMachineFunction(), FI)));
4061 lastInsIndex = index;
4066 // varargs
4067 if (isVarArg && MFI.hasVAStart())
4068 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4069 CCInfo.getNextStackOffset(),
4070 TotalArgRegsSaveSize);
4072 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4074 return Chain;
4077 /// isFloatingPointZero - Return true if this is +0.0.
4078 static bool isFloatingPointZero(SDValue Op) {
4079 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4080 return CFP->getValueAPF().isPosZero();
4081 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4082 // Maybe this has already been legalized into the constant pool?
4083 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4084 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4085 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4086 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4087 return CFP->getValueAPF().isPosZero();
4089 } else if (Op->getOpcode() == ISD::BITCAST &&
4090 Op->getValueType(0) == MVT::f64) {
4091 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4092 // created by LowerConstantFP().
4093 SDValue BitcastOp = Op->getOperand(0);
4094 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4095 isNullConstant(BitcastOp->getOperand(0)))
4096 return true;
4098 return false;
4101 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4102 /// the given operands.
4103 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4104 SDValue &ARMcc, SelectionDAG &DAG,
4105 const SDLoc &dl) const {
4106 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4107 unsigned C = RHSC->getZExtValue();
4108 if (!isLegalICmpImmediate((int32_t)C)) {
4109 // Constant does not fit, try adjusting it by one.
4110 switch (CC) {
4111 default: break;
4112 case ISD::SETLT:
4113 case ISD::SETGE:
4114 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4115 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4116 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4118 break;
4119 case ISD::SETULT:
4120 case ISD::SETUGE:
4121 if (C != 0 && isLegalICmpImmediate(C-1)) {
4122 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4123 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4125 break;
4126 case ISD::SETLE:
4127 case ISD::SETGT:
4128 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4129 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4130 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4132 break;
4133 case ISD::SETULE:
4134 case ISD::SETUGT:
4135 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4136 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4137 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4139 break;
4142 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4143 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4144 // In ARM and Thumb-2, the compare instructions can shift their second
4145 // operand.
4146 CC = ISD::getSetCCSwappedOperands(CC);
4147 std::swap(LHS, RHS);
4150 // Thumb1 has very limited immediate modes, so turning an "and" into a
4151 // shift can save multiple instructions.
4153 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4154 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4155 // own. If it's the operand to an unsigned comparison with an immediate,
4156 // we can eliminate one of the shifts: we transform
4157 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4159 // We avoid transforming cases which aren't profitable due to encoding
4160 // details:
4162 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4163 // would not; in that case, we're essentially trading one immediate load for
4164 // another.
4165 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4166 // 3. C2 is zero; we have other code for this special case.
4168 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4169 // instruction, since the AND is always one instruction anyway, but we could
4170 // use narrow instructions in some cases.
4171 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4172 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4173 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4174 !isSignedIntSetCC(CC)) {
4175 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4176 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4177 uint64_t RHSV = RHSC->getZExtValue();
4178 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4179 unsigned ShiftBits = countLeadingZeros(Mask);
4180 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4181 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4182 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4183 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4188 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4189 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4190 // way a cmp would.
4191 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4192 // some tweaks to the heuristics for the previous and->shift transform.
4193 // FIXME: Optimize cases where the LHS isn't a shift.
4194 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4195 isa<ConstantSDNode>(RHS) &&
4196 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4197 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4198 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4199 unsigned ShiftAmt =
4200 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4201 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4202 DAG.getVTList(MVT::i32, MVT::i32),
4203 LHS.getOperand(0),
4204 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4205 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4206 Shift.getValue(1), SDValue());
4207 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4208 return Chain.getValue(1);
4211 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4213 // If the RHS is a constant zero then the V (overflow) flag will never be
4214 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4215 // simpler for other passes (like the peephole optimiser) to deal with.
4216 if (isNullConstant(RHS)) {
4217 switch (CondCode) {
4218 default: break;
4219 case ARMCC::GE:
4220 CondCode = ARMCC::PL;
4221 break;
4222 case ARMCC::LT:
4223 CondCode = ARMCC::MI;
4224 break;
4228 ARMISD::NodeType CompareType;
4229 switch (CondCode) {
4230 default:
4231 CompareType = ARMISD::CMP;
4232 break;
4233 case ARMCC::EQ:
4234 case ARMCC::NE:
4235 // Uses only Z Flag
4236 CompareType = ARMISD::CMPZ;
4237 break;
4239 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4240 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4243 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4244 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4245 SelectionDAG &DAG, const SDLoc &dl,
4246 bool InvalidOnQNaN) const {
4247 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4248 SDValue Cmp;
4249 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
4250 if (!isFloatingPointZero(RHS))
4251 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
4252 else
4253 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
4254 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4257 /// duplicateCmp - Glue values can have only one use, so this function
4258 /// duplicates a comparison node.
4259 SDValue
4260 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4261 unsigned Opc = Cmp.getOpcode();
4262 SDLoc DL(Cmp);
4263 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4264 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4266 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4267 Cmp = Cmp.getOperand(0);
4268 Opc = Cmp.getOpcode();
4269 if (Opc == ARMISD::CMPFP)
4270 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4271 Cmp.getOperand(1), Cmp.getOperand(2));
4272 else {
4273 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4274 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4275 Cmp.getOperand(1));
4277 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4280 // This function returns three things: the arithmetic computation itself
4281 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4282 // comparison and the condition code define the case in which the arithmetic
4283 // computation *does not* overflow.
4284 std::pair<SDValue, SDValue>
4285 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4286 SDValue &ARMcc) const {
4287 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4289 SDValue Value, OverflowCmp;
4290 SDValue LHS = Op.getOperand(0);
4291 SDValue RHS = Op.getOperand(1);
4292 SDLoc dl(Op);
4294 // FIXME: We are currently always generating CMPs because we don't support
4295 // generating CMN through the backend. This is not as good as the natural
4296 // CMP case because it causes a register dependency and cannot be folded
4297 // later.
4299 switch (Op.getOpcode()) {
4300 default:
4301 llvm_unreachable("Unknown overflow instruction!");
4302 case ISD::SADDO:
4303 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4304 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4305 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4306 break;
4307 case ISD::UADDO:
4308 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4309 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4310 // We do not use it in the USUBO case as Value may not be used.
4311 Value = DAG.getNode(ARMISD::ADDC, dl,
4312 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4313 .getValue(0);
4314 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4315 break;
4316 case ISD::SSUBO:
4317 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4318 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4319 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4320 break;
4321 case ISD::USUBO:
4322 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4323 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4324 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4325 break;
4326 case ISD::UMULO:
4327 // We generate a UMUL_LOHI and then check if the high word is 0.
4328 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4329 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4330 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4331 LHS, RHS);
4332 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4333 DAG.getConstant(0, dl, MVT::i32));
4334 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4335 break;
4336 case ISD::SMULO:
4337 // We generate a SMUL_LOHI and then check if all the bits of the high word
4338 // are the same as the sign bit of the low word.
4339 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4340 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4341 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4342 LHS, RHS);
4343 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4344 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4345 Value.getValue(0),
4346 DAG.getConstant(31, dl, MVT::i32)));
4347 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4348 break;
4349 } // switch (...)
4351 return std::make_pair(Value, OverflowCmp);
4354 SDValue
4355 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4356 // Let legalize expand this if it isn't a legal type yet.
4357 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4358 return SDValue();
4360 SDValue Value, OverflowCmp;
4361 SDValue ARMcc;
4362 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4363 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4364 SDLoc dl(Op);
4365 // We use 0 and 1 as false and true values.
4366 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4367 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4368 EVT VT = Op.getValueType();
4370 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4371 ARMcc, CCR, OverflowCmp);
4373 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4374 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4377 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4378 SelectionDAG &DAG) {
4379 SDLoc DL(BoolCarry);
4380 EVT CarryVT = BoolCarry.getValueType();
4382 // This converts the boolean value carry into the carry flag by doing
4383 // ARMISD::SUBC Carry, 1
4384 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4385 DAG.getVTList(CarryVT, MVT::i32),
4386 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4387 return Carry.getValue(1);
4390 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4391 SelectionDAG &DAG) {
4392 SDLoc DL(Flags);
4394 // Now convert the carry flag into a boolean carry. We do this
4395 // using ARMISD:ADDE 0, 0, Carry
4396 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4397 DAG.getConstant(0, DL, MVT::i32),
4398 DAG.getConstant(0, DL, MVT::i32), Flags);
4401 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4402 SelectionDAG &DAG) const {
4403 // Let legalize expand this if it isn't a legal type yet.
4404 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4405 return SDValue();
4407 SDValue LHS = Op.getOperand(0);
4408 SDValue RHS = Op.getOperand(1);
4409 SDLoc dl(Op);
4411 EVT VT = Op.getValueType();
4412 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4413 SDValue Value;
4414 SDValue Overflow;
4415 switch (Op.getOpcode()) {
4416 default:
4417 llvm_unreachable("Unknown overflow instruction!");
4418 case ISD::UADDO:
4419 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4420 // Convert the carry flag into a boolean value.
4421 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4422 break;
4423 case ISD::USUBO: {
4424 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4425 // Convert the carry flag into a boolean value.
4426 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4427 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4428 // value. So compute 1 - C.
4429 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4430 DAG.getConstant(1, dl, MVT::i32), Overflow);
4431 break;
4435 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4438 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4439 SDValue Cond = Op.getOperand(0);
4440 SDValue SelectTrue = Op.getOperand(1);
4441 SDValue SelectFalse = Op.getOperand(2);
4442 SDLoc dl(Op);
4443 unsigned Opc = Cond.getOpcode();
4445 if (Cond.getResNo() == 1 &&
4446 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4447 Opc == ISD::USUBO)) {
4448 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4449 return SDValue();
4451 SDValue Value, OverflowCmp;
4452 SDValue ARMcc;
4453 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4454 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4455 EVT VT = Op.getValueType();
4457 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4458 OverflowCmp, DAG);
4461 // Convert:
4463 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4464 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4466 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4467 const ConstantSDNode *CMOVTrue =
4468 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4469 const ConstantSDNode *CMOVFalse =
4470 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4472 if (CMOVTrue && CMOVFalse) {
4473 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4474 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4476 SDValue True;
4477 SDValue False;
4478 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4479 True = SelectTrue;
4480 False = SelectFalse;
4481 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4482 True = SelectFalse;
4483 False = SelectTrue;
4486 if (True.getNode() && False.getNode()) {
4487 EVT VT = Op.getValueType();
4488 SDValue ARMcc = Cond.getOperand(2);
4489 SDValue CCR = Cond.getOperand(3);
4490 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4491 assert(True.getValueType() == VT);
4492 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4497 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4498 // undefined bits before doing a full-word comparison with zero.
4499 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4500 DAG.getConstant(1, dl, Cond.getValueType()));
4502 return DAG.getSelectCC(dl, Cond,
4503 DAG.getConstant(0, dl, Cond.getValueType()),
4504 SelectTrue, SelectFalse, ISD::SETNE);
4507 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4508 bool &swpCmpOps, bool &swpVselOps) {
4509 // Start by selecting the GE condition code for opcodes that return true for
4510 // 'equality'
4511 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4512 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4513 CondCode = ARMCC::GE;
4515 // and GT for opcodes that return false for 'equality'.
4516 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4517 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4518 CondCode = ARMCC::GT;
4520 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4521 // to swap the compare operands.
4522 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4523 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4524 swpCmpOps = true;
4526 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4527 // If we have an unordered opcode, we need to swap the operands to the VSEL
4528 // instruction (effectively negating the condition).
4530 // This also has the effect of swapping which one of 'less' or 'greater'
4531 // returns true, so we also swap the compare operands. It also switches
4532 // whether we return true for 'equality', so we compensate by picking the
4533 // opposite condition code to our original choice.
4534 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4535 CC == ISD::SETUGT) {
4536 swpCmpOps = !swpCmpOps;
4537 swpVselOps = !swpVselOps;
4538 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4541 // 'ordered' is 'anything but unordered', so use the VS condition code and
4542 // swap the VSEL operands.
4543 if (CC == ISD::SETO) {
4544 CondCode = ARMCC::VS;
4545 swpVselOps = true;
4548 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4549 // code and swap the VSEL operands. Also do this if we don't care about the
4550 // unordered case.
4551 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4552 CondCode = ARMCC::EQ;
4553 swpVselOps = true;
4557 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4558 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4559 SDValue Cmp, SelectionDAG &DAG) const {
4560 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4561 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4562 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4563 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4564 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4566 SDValue TrueLow = TrueVal.getValue(0);
4567 SDValue TrueHigh = TrueVal.getValue(1);
4568 SDValue FalseLow = FalseVal.getValue(0);
4569 SDValue FalseHigh = FalseVal.getValue(1);
4571 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4572 ARMcc, CCR, Cmp);
4573 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4574 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4576 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4577 } else {
4578 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4579 Cmp);
4583 static bool isGTorGE(ISD::CondCode CC) {
4584 return CC == ISD::SETGT || CC == ISD::SETGE;
4587 static bool isLTorLE(ISD::CondCode CC) {
4588 return CC == ISD::SETLT || CC == ISD::SETLE;
4591 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4592 // All of these conditions (and their <= and >= counterparts) will do:
4593 // x < k ? k : x
4594 // x > k ? x : k
4595 // k < x ? x : k
4596 // k > x ? k : x
4597 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4598 const SDValue TrueVal, const SDValue FalseVal,
4599 const ISD::CondCode CC, const SDValue K) {
4600 return (isGTorGE(CC) &&
4601 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4602 (isLTorLE(CC) &&
4603 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4606 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4607 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4608 const SDValue TrueVal, const SDValue FalseVal,
4609 const ISD::CondCode CC, const SDValue K) {
4610 return (isGTorGE(CC) &&
4611 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4612 (isLTorLE(CC) &&
4613 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4616 // Check if two chained conditionals could be converted into SSAT or USAT.
4618 // SSAT can replace a set of two conditional selectors that bound a number to an
4619 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4621 // x < -k ? -k : (x > k ? k : x)
4622 // x < -k ? -k : (x < k ? x : k)
4623 // x > -k ? (x > k ? k : x) : -k
4624 // x < k ? (x < -k ? -k : x) : k
4625 // etc.
4627 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4628 // a power of 2.
4630 // It returns true if the conversion can be done, false otherwise.
4631 // Additionally, the variable is returned in parameter V, the constant in K and
4632 // usat is set to true if the conditional represents an unsigned saturation
4633 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4634 uint64_t &K, bool &usat) {
4635 SDValue LHS1 = Op.getOperand(0);
4636 SDValue RHS1 = Op.getOperand(1);
4637 SDValue TrueVal1 = Op.getOperand(2);
4638 SDValue FalseVal1 = Op.getOperand(3);
4639 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4641 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4642 if (Op2.getOpcode() != ISD::SELECT_CC)
4643 return false;
4645 SDValue LHS2 = Op2.getOperand(0);
4646 SDValue RHS2 = Op2.getOperand(1);
4647 SDValue TrueVal2 = Op2.getOperand(2);
4648 SDValue FalseVal2 = Op2.getOperand(3);
4649 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4651 // Find out which are the constants and which are the variables
4652 // in each conditional
4653 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4654 ? &RHS1
4655 : nullptr;
4656 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4657 ? &RHS2
4658 : nullptr;
4659 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4660 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4661 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4662 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4664 // We must detect cases where the original operations worked with 16- or
4665 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4666 // must work with sign-extended values but the select operations return
4667 // the original non-extended value.
4668 SDValue V2TmpReg = V2Tmp;
4669 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4670 V2TmpReg = V2Tmp->getOperand(0);
4672 // Check that the registers and the constants have the correct values
4673 // in both conditionals
4674 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4675 V2TmpReg != V2)
4676 return false;
4678 // Figure out which conditional is saturating the lower/upper bound.
4679 const SDValue *LowerCheckOp =
4680 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4681 ? &Op
4682 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4683 ? &Op2
4684 : nullptr;
4685 const SDValue *UpperCheckOp =
4686 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4687 ? &Op
4688 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4689 ? &Op2
4690 : nullptr;
4692 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4693 return false;
4695 // Check that the constant in the lower-bound check is
4696 // the opposite of the constant in the upper-bound check
4697 // in 1's complement.
4698 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4699 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4700 int64_t PosVal = std::max(Val1, Val2);
4701 int64_t NegVal = std::min(Val1, Val2);
4703 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4704 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4705 isPowerOf2_64(PosVal + 1)) {
4707 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4708 if (Val1 == ~Val2)
4709 usat = false;
4710 else if (NegVal == 0)
4711 usat = true;
4712 else
4713 return false;
4715 V = V2;
4716 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4718 return true;
4721 return false;
4724 // Check if a condition of the type x < k ? k : x can be converted into a
4725 // bit operation instead of conditional moves.
4726 // Currently this is allowed given:
4727 // - The conditions and values match up
4728 // - k is 0 or -1 (all ones)
4729 // This function will not check the last condition, thats up to the caller
4730 // It returns true if the transformation can be made, and in such case
4731 // returns x in V, and k in SatK.
4732 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4733 SDValue &SatK)
4735 SDValue LHS = Op.getOperand(0);
4736 SDValue RHS = Op.getOperand(1);
4737 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4738 SDValue TrueVal = Op.getOperand(2);
4739 SDValue FalseVal = Op.getOperand(3);
4741 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4742 ? &RHS
4743 : nullptr;
4745 // No constant operation in comparison, early out
4746 if (!K)
4747 return false;
4749 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4750 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4751 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4753 // If the constant on left and right side, or variable on left and right,
4754 // does not match, early out
4755 if (*K != KTmp || V != VTmp)
4756 return false;
4758 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4759 SatK = *K;
4760 return true;
4763 return false;
4766 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4767 if (VT == MVT::f32)
4768 return !Subtarget->hasVFP2Base();
4769 if (VT == MVT::f64)
4770 return !Subtarget->hasFP64();
4771 if (VT == MVT::f16)
4772 return !Subtarget->hasFullFP16();
4773 return false;
4776 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4777 EVT VT = Op.getValueType();
4778 SDLoc dl(Op);
4780 // Try to convert two saturating conditional selects into a single SSAT
4781 SDValue SatValue;
4782 uint64_t SatConstant;
4783 bool SatUSat;
4784 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4785 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4786 if (SatUSat)
4787 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4788 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4789 else
4790 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4791 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4794 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4795 // into more efficient bit operations, which is possible when k is 0 or -1
4796 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4797 // single instructions. On Thumb the shift and the bit operation will be two
4798 // instructions.
4799 // Only allow this transformation on full-width (32-bit) operations
4800 SDValue LowerSatConstant;
4801 if (VT == MVT::i32 &&
4802 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4803 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4804 DAG.getConstant(31, dl, VT));
4805 if (isNullConstant(LowerSatConstant)) {
4806 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4807 DAG.getAllOnesConstant(dl, VT));
4808 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4809 } else if (isAllOnesConstant(LowerSatConstant))
4810 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4813 SDValue LHS = Op.getOperand(0);
4814 SDValue RHS = Op.getOperand(1);
4815 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4816 SDValue TrueVal = Op.getOperand(2);
4817 SDValue FalseVal = Op.getOperand(3);
4819 if (isUnsupportedFloatingType(LHS.getValueType())) {
4820 DAG.getTargetLoweringInfo().softenSetCCOperands(
4821 DAG, LHS.getValueType(), LHS, RHS, CC, dl);
4823 // If softenSetCCOperands only returned one value, we should compare it to
4824 // zero.
4825 if (!RHS.getNode()) {
4826 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4827 CC = ISD::SETNE;
4831 if (LHS.getValueType() == MVT::i32) {
4832 // Try to generate VSEL on ARMv8.
4833 // The VSEL instruction can't use all the usual ARM condition
4834 // codes: it only has two bits to select the condition code, so it's
4835 // constrained to use only GE, GT, VS and EQ.
4837 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4838 // swap the operands of the previous compare instruction (effectively
4839 // inverting the compare condition, swapping 'less' and 'greater') and
4840 // sometimes need to swap the operands to the VSEL (which inverts the
4841 // condition in the sense of firing whenever the previous condition didn't)
4842 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4843 TrueVal.getValueType() == MVT::f32 ||
4844 TrueVal.getValueType() == MVT::f64)) {
4845 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4846 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4847 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4848 CC = ISD::getSetCCInverse(CC, true);
4849 std::swap(TrueVal, FalseVal);
4853 SDValue ARMcc;
4854 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4855 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4856 // Choose GE over PL, which vsel does now support
4857 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4858 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4859 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4862 ARMCC::CondCodes CondCode, CondCode2;
4863 bool InvalidOnQNaN;
4864 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4866 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4867 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4868 // must use VSEL (limited condition codes), due to not having conditional f16
4869 // moves.
4870 if (Subtarget->hasFPARMv8Base() &&
4871 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4872 (TrueVal.getValueType() == MVT::f16 ||
4873 TrueVal.getValueType() == MVT::f32 ||
4874 TrueVal.getValueType() == MVT::f64)) {
4875 bool swpCmpOps = false;
4876 bool swpVselOps = false;
4877 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4879 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4880 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4881 if (swpCmpOps)
4882 std::swap(LHS, RHS);
4883 if (swpVselOps)
4884 std::swap(TrueVal, FalseVal);
4888 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4889 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4890 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4891 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4892 if (CondCode2 != ARMCC::AL) {
4893 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4894 // FIXME: Needs another CMP because flag can have but one use.
4895 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4896 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4898 return Result;
4901 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4902 /// to morph to an integer compare sequence.
4903 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4904 const ARMSubtarget *Subtarget) {
4905 SDNode *N = Op.getNode();
4906 if (!N->hasOneUse())
4907 // Otherwise it requires moving the value from fp to integer registers.
4908 return false;
4909 if (!N->getNumValues())
4910 return false;
4911 EVT VT = Op.getValueType();
4912 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4913 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4914 // vmrs are very slow, e.g. cortex-a8.
4915 return false;
4917 if (isFloatingPointZero(Op)) {
4918 SeenZero = true;
4919 return true;
4921 return ISD::isNormalLoad(N);
4924 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4925 if (isFloatingPointZero(Op))
4926 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4928 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4929 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4930 Ld->getPointerInfo(), Ld->getAlignment(),
4931 Ld->getMemOperand()->getFlags());
4933 llvm_unreachable("Unknown VFP cmp argument!");
4936 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4937 SDValue &RetVal1, SDValue &RetVal2) {
4938 SDLoc dl(Op);
4940 if (isFloatingPointZero(Op)) {
4941 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4942 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4943 return;
4946 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4947 SDValue Ptr = Ld->getBasePtr();
4948 RetVal1 =
4949 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4950 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4952 EVT PtrType = Ptr.getValueType();
4953 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4954 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4955 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4956 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4957 Ld->getPointerInfo().getWithOffset(4), NewAlign,
4958 Ld->getMemOperand()->getFlags());
4959 return;
4962 llvm_unreachable("Unknown VFP cmp argument!");
4965 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4966 /// f32 and even f64 comparisons to integer ones.
4967 SDValue
4968 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4969 SDValue Chain = Op.getOperand(0);
4970 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4971 SDValue LHS = Op.getOperand(2);
4972 SDValue RHS = Op.getOperand(3);
4973 SDValue Dest = Op.getOperand(4);
4974 SDLoc dl(Op);
4976 bool LHSSeenZero = false;
4977 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4978 bool RHSSeenZero = false;
4979 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4980 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4981 // If unsafe fp math optimization is enabled and there are no other uses of
4982 // the CMP operands, and the condition code is EQ or NE, we can optimize it
4983 // to an integer comparison.
4984 if (CC == ISD::SETOEQ)
4985 CC = ISD::SETEQ;
4986 else if (CC == ISD::SETUNE)
4987 CC = ISD::SETNE;
4989 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4990 SDValue ARMcc;
4991 if (LHS.getValueType() == MVT::f32) {
4992 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4993 bitcastf32Toi32(LHS, DAG), Mask);
4994 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4995 bitcastf32Toi32(RHS, DAG), Mask);
4996 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4997 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4998 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4999 Chain, Dest, ARMcc, CCR, Cmp);
5002 SDValue LHS1, LHS2;
5003 SDValue RHS1, RHS2;
5004 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5005 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5006 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5007 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5008 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5009 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5010 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5011 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5012 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5015 return SDValue();
5018 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5019 SDValue Chain = Op.getOperand(0);
5020 SDValue Cond = Op.getOperand(1);
5021 SDValue Dest = Op.getOperand(2);
5022 SDLoc dl(Op);
5024 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5025 // instruction.
5026 unsigned Opc = Cond.getOpcode();
5027 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5028 !Subtarget->isThumb1Only();
5029 if (Cond.getResNo() == 1 &&
5030 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5031 Opc == ISD::USUBO || OptimizeMul)) {
5032 // Only lower legal XALUO ops.
5033 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5034 return SDValue();
5036 // The actual operation with overflow check.
5037 SDValue Value, OverflowCmp;
5038 SDValue ARMcc;
5039 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5041 // Reverse the condition code.
5042 ARMCC::CondCodes CondCode =
5043 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5044 CondCode = ARMCC::getOppositeCondition(CondCode);
5045 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5046 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5048 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5049 OverflowCmp);
5052 return SDValue();
5055 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5056 SDValue Chain = Op.getOperand(0);
5057 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5058 SDValue LHS = Op.getOperand(2);
5059 SDValue RHS = Op.getOperand(3);
5060 SDValue Dest = Op.getOperand(4);
5061 SDLoc dl(Op);
5063 if (isUnsupportedFloatingType(LHS.getValueType())) {
5064 DAG.getTargetLoweringInfo().softenSetCCOperands(
5065 DAG, LHS.getValueType(), LHS, RHS, CC, dl);
5067 // If softenSetCCOperands only returned one value, we should compare it to
5068 // zero.
5069 if (!RHS.getNode()) {
5070 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5071 CC = ISD::SETNE;
5075 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5076 // instruction.
5077 unsigned Opc = LHS.getOpcode();
5078 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5079 !Subtarget->isThumb1Only();
5080 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5081 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5082 Opc == ISD::USUBO || OptimizeMul) &&
5083 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5084 // Only lower legal XALUO ops.
5085 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5086 return SDValue();
5088 // The actual operation with overflow check.
5089 SDValue Value, OverflowCmp;
5090 SDValue ARMcc;
5091 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5093 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5094 // Reverse the condition code.
5095 ARMCC::CondCodes CondCode =
5096 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5097 CondCode = ARMCC::getOppositeCondition(CondCode);
5098 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5100 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5102 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5103 OverflowCmp);
5106 if (LHS.getValueType() == MVT::i32) {
5107 SDValue ARMcc;
5108 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5109 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5110 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5111 Chain, Dest, ARMcc, CCR, Cmp);
5114 if (getTargetMachine().Options.UnsafeFPMath &&
5115 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5116 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5117 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5118 return Result;
5121 ARMCC::CondCodes CondCode, CondCode2;
5122 bool InvalidOnQNaN;
5123 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
5125 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5126 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
5127 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5128 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5129 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5130 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5131 if (CondCode2 != ARMCC::AL) {
5132 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5133 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5134 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5136 return Res;
5139 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5140 SDValue Chain = Op.getOperand(0);
5141 SDValue Table = Op.getOperand(1);
5142 SDValue Index = Op.getOperand(2);
5143 SDLoc dl(Op);
5145 EVT PTy = getPointerTy(DAG.getDataLayout());
5146 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5147 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5148 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5149 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5150 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5151 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5152 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5153 // which does another jump to the destination. This also makes it easier
5154 // to translate it to TBB / TBH later (Thumb2 only).
5155 // FIXME: This might not work if the function is extremely large.
5156 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5157 Addr, Op.getOperand(2), JTI);
5159 if (isPositionIndependent() || Subtarget->isROPI()) {
5160 Addr =
5161 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5162 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5163 Chain = Addr.getValue(1);
5164 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5165 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5166 } else {
5167 Addr =
5168 DAG.getLoad(PTy, dl, Chain, Addr,
5169 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5170 Chain = Addr.getValue(1);
5171 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5175 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5176 EVT VT = Op.getValueType();
5177 SDLoc dl(Op);
5179 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5180 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5181 return Op;
5182 return DAG.UnrollVectorOp(Op.getNode());
5185 const bool HasFullFP16 =
5186 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5188 EVT NewTy;
5189 const EVT OpTy = Op.getOperand(0).getValueType();
5190 if (OpTy == MVT::v4f32)
5191 NewTy = MVT::v4i32;
5192 else if (OpTy == MVT::v4f16 && HasFullFP16)
5193 NewTy = MVT::v4i16;
5194 else if (OpTy == MVT::v8f16 && HasFullFP16)
5195 NewTy = MVT::v8i16;
5196 else
5197 llvm_unreachable("Invalid type for custom lowering!");
5199 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5200 return DAG.UnrollVectorOp(Op.getNode());
5202 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5203 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5206 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5207 EVT VT = Op.getValueType();
5208 if (VT.isVector())
5209 return LowerVectorFP_TO_INT(Op, DAG);
5210 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5211 RTLIB::Libcall LC;
5212 if (Op.getOpcode() == ISD::FP_TO_SINT)
5213 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5214 Op.getValueType());
5215 else
5216 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5217 Op.getValueType());
5218 MakeLibCallOptions CallOptions;
5219 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5220 CallOptions, SDLoc(Op)).first;
5223 return Op;
5226 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5227 EVT VT = Op.getValueType();
5228 SDLoc dl(Op);
5230 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5231 if (VT.getVectorElementType() == MVT::f32)
5232 return Op;
5233 return DAG.UnrollVectorOp(Op.getNode());
5236 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5237 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5238 "Invalid type for custom lowering!");
5240 const bool HasFullFP16 =
5241 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5243 EVT DestVecType;
5244 if (VT == MVT::v4f32)
5245 DestVecType = MVT::v4i32;
5246 else if (VT == MVT::v4f16 && HasFullFP16)
5247 DestVecType = MVT::v4i16;
5248 else if (VT == MVT::v8f16 && HasFullFP16)
5249 DestVecType = MVT::v8i16;
5250 else
5251 return DAG.UnrollVectorOp(Op.getNode());
5253 unsigned CastOpc;
5254 unsigned Opc;
5255 switch (Op.getOpcode()) {
5256 default: llvm_unreachable("Invalid opcode!");
5257 case ISD::SINT_TO_FP:
5258 CastOpc = ISD::SIGN_EXTEND;
5259 Opc = ISD::SINT_TO_FP;
5260 break;
5261 case ISD::UINT_TO_FP:
5262 CastOpc = ISD::ZERO_EXTEND;
5263 Opc = ISD::UINT_TO_FP;
5264 break;
5267 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5268 return DAG.getNode(Opc, dl, VT, Op);
5271 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5272 EVT VT = Op.getValueType();
5273 if (VT.isVector())
5274 return LowerVectorINT_TO_FP(Op, DAG);
5275 if (isUnsupportedFloatingType(VT)) {
5276 RTLIB::Libcall LC;
5277 if (Op.getOpcode() == ISD::SINT_TO_FP)
5278 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5279 Op.getValueType());
5280 else
5281 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5282 Op.getValueType());
5283 MakeLibCallOptions CallOptions;
5284 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5285 CallOptions, SDLoc(Op)).first;
5288 return Op;
5291 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5292 // Implement fcopysign with a fabs and a conditional fneg.
5293 SDValue Tmp0 = Op.getOperand(0);
5294 SDValue Tmp1 = Op.getOperand(1);
5295 SDLoc dl(Op);
5296 EVT VT = Op.getValueType();
5297 EVT SrcVT = Tmp1.getValueType();
5298 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5299 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5300 bool UseNEON = !InGPR && Subtarget->hasNEON();
5302 if (UseNEON) {
5303 // Use VBSL to copy the sign bit.
5304 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5305 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5306 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5307 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5308 if (VT == MVT::f64)
5309 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5310 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5311 DAG.getConstant(32, dl, MVT::i32));
5312 else /*if (VT == MVT::f32)*/
5313 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5314 if (SrcVT == MVT::f32) {
5315 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5316 if (VT == MVT::f64)
5317 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5318 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5319 DAG.getConstant(32, dl, MVT::i32));
5320 } else if (VT == MVT::f32)
5321 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5322 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5323 DAG.getConstant(32, dl, MVT::i32));
5324 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5325 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5327 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5328 dl, MVT::i32);
5329 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5330 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5331 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5333 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5334 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5335 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5336 if (VT == MVT::f32) {
5337 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5338 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5339 DAG.getConstant(0, dl, MVT::i32));
5340 } else {
5341 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5344 return Res;
5347 // Bitcast operand 1 to i32.
5348 if (SrcVT == MVT::f64)
5349 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5350 Tmp1).getValue(1);
5351 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5353 // Or in the signbit with integer operations.
5354 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5355 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5356 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5357 if (VT == MVT::f32) {
5358 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5359 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5360 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5361 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5364 // f64: Or the high part with signbit and then combine two parts.
5365 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5366 Tmp0);
5367 SDValue Lo = Tmp0.getValue(0);
5368 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5369 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5370 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5373 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5374 MachineFunction &MF = DAG.getMachineFunction();
5375 MachineFrameInfo &MFI = MF.getFrameInfo();
5376 MFI.setReturnAddressIsTaken(true);
5378 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5379 return SDValue();
5381 EVT VT = Op.getValueType();
5382 SDLoc dl(Op);
5383 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5384 if (Depth) {
5385 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5386 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5387 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5388 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5389 MachinePointerInfo());
5392 // Return LR, which contains the return address. Mark it an implicit live-in.
5393 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5394 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5397 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5398 const ARMBaseRegisterInfo &ARI =
5399 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5400 MachineFunction &MF = DAG.getMachineFunction();
5401 MachineFrameInfo &MFI = MF.getFrameInfo();
5402 MFI.setFrameAddressIsTaken(true);
5404 EVT VT = Op.getValueType();
5405 SDLoc dl(Op); // FIXME probably not meaningful
5406 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5407 Register FrameReg = ARI.getFrameRegister(MF);
5408 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5409 while (Depth--)
5410 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5411 MachinePointerInfo());
5412 return FrameAddr;
5415 // FIXME? Maybe this could be a TableGen attribute on some registers and
5416 // this table could be generated automatically from RegInfo.
5417 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5418 SelectionDAG &DAG) const {
5419 unsigned Reg = StringSwitch<unsigned>(RegName)
5420 .Case("sp", ARM::SP)
5421 .Default(0);
5422 if (Reg)
5423 return Reg;
5424 report_fatal_error(Twine("Invalid register name \""
5425 + StringRef(RegName) + "\"."));
5428 // Result is 64 bit value so split into two 32 bit values and return as a
5429 // pair of values.
5430 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5431 SelectionDAG &DAG) {
5432 SDLoc DL(N);
5434 // This function is only supposed to be called for i64 type destination.
5435 assert(N->getValueType(0) == MVT::i64
5436 && "ExpandREAD_REGISTER called for non-i64 type result.");
5438 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5439 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5440 N->getOperand(0),
5441 N->getOperand(1));
5443 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5444 Read.getValue(1)));
5445 Results.push_back(Read.getOperand(0));
5448 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5449 /// When \p DstVT, the destination type of \p BC, is on the vector
5450 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5451 /// it might be possible to combine them, such that everything stays on the
5452 /// vector register bank.
5453 /// \p return The node that would replace \p BT, if the combine
5454 /// is possible.
5455 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5456 SelectionDAG &DAG) {
5457 SDValue Op = BC->getOperand(0);
5458 EVT DstVT = BC->getValueType(0);
5460 // The only vector instruction that can produce a scalar (remember,
5461 // since the bitcast was about to be turned into VMOVDRR, the source
5462 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5463 // Moreover, we can do this combine only if there is one use.
5464 // Finally, if the destination type is not a vector, there is not
5465 // much point on forcing everything on the vector bank.
5466 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5467 !Op.hasOneUse())
5468 return SDValue();
5470 // If the index is not constant, we will introduce an additional
5471 // multiply that will stick.
5472 // Give up in that case.
5473 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5474 if (!Index)
5475 return SDValue();
5476 unsigned DstNumElt = DstVT.getVectorNumElements();
5478 // Compute the new index.
5479 const APInt &APIntIndex = Index->getAPIntValue();
5480 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5481 NewIndex *= APIntIndex;
5482 // Check if the new constant index fits into i32.
5483 if (NewIndex.getBitWidth() > 32)
5484 return SDValue();
5486 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5487 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5488 SDLoc dl(Op);
5489 SDValue ExtractSrc = Op.getOperand(0);
5490 EVT VecVT = EVT::getVectorVT(
5491 *DAG.getContext(), DstVT.getScalarType(),
5492 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5493 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5494 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5495 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5498 /// ExpandBITCAST - If the target supports VFP, this function is called to
5499 /// expand a bit convert where either the source or destination type is i64 to
5500 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5501 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5502 /// vectors), since the legalizer won't know what to do with that.
5503 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5504 const ARMSubtarget *Subtarget) {
5505 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5506 SDLoc dl(N);
5507 SDValue Op = N->getOperand(0);
5509 // This function is only supposed to be called for i64 types, either as the
5510 // source or destination of the bit convert.
5511 EVT SrcVT = Op.getValueType();
5512 EVT DstVT = N->getValueType(0);
5513 const bool HasFullFP16 = Subtarget->hasFullFP16();
5515 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5516 // FullFP16: half values are passed in S-registers, and we don't
5517 // need any of the bitcast and moves:
5519 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5520 // t5: i32 = bitcast t2
5521 // t18: f16 = ARMISD::VMOVhr t5
5522 if (Op.getOpcode() != ISD::CopyFromReg ||
5523 Op.getValueType() != MVT::f32)
5524 return SDValue();
5526 auto Move = N->use_begin();
5527 if (Move->getOpcode() != ARMISD::VMOVhr)
5528 return SDValue();
5530 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5531 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5532 DAG.ReplaceAllUsesWith(*Move, &Copy);
5533 return Copy;
5536 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5537 if (!HasFullFP16)
5538 return SDValue();
5539 // SoftFP: read half-precision arguments:
5541 // t2: i32,ch = ...
5542 // t7: i16 = truncate t2 <~~~~ Op
5543 // t8: f16 = bitcast t7 <~~~~ N
5545 if (Op.getOperand(0).getValueType() == MVT::i32)
5546 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5547 MVT::f16, Op.getOperand(0));
5549 return SDValue();
5552 // Half-precision return values
5553 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5554 if (!HasFullFP16)
5555 return SDValue();
5557 // t11: f16 = fadd t8, t10
5558 // t12: i16 = bitcast t11 <~~~ SDNode N
5559 // t13: i32 = zero_extend t12
5560 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5561 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5563 // transform this into:
5565 // t20: i32 = ARMISD::VMOVrh t11
5566 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5568 auto ZeroExtend = N->use_begin();
5569 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5570 ZeroExtend->getValueType(0) != MVT::i32)
5571 return SDValue();
5573 auto Copy = ZeroExtend->use_begin();
5574 if (Copy->getOpcode() == ISD::CopyToReg &&
5575 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5576 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5577 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5578 return Cvt;
5580 return SDValue();
5583 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5584 return SDValue();
5586 // Turn i64->f64 into VMOVDRR.
5587 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5588 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5589 // if we can combine the bitcast with its source.
5590 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5591 return Val;
5593 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5594 DAG.getConstant(0, dl, MVT::i32));
5595 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5596 DAG.getConstant(1, dl, MVT::i32));
5597 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5598 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5601 // Turn f64->i64 into VMOVRRD.
5602 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5603 SDValue Cvt;
5604 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5605 SrcVT.getVectorNumElements() > 1)
5606 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5607 DAG.getVTList(MVT::i32, MVT::i32),
5608 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5609 else
5610 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5611 DAG.getVTList(MVT::i32, MVT::i32), Op);
5612 // Merge the pieces into a single i64 value.
5613 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5616 return SDValue();
5619 /// getZeroVector - Returns a vector of specified type with all zero elements.
5620 /// Zero vectors are used to represent vector negation and in those cases
5621 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5622 /// not support i64 elements, so sometimes the zero vectors will need to be
5623 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5624 /// zero vector.
5625 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5626 assert(VT.isVector() && "Expected a vector type");
5627 // The canonical modified immediate encoding of a zero vector is....0!
5628 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5629 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5630 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5631 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5634 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5635 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5636 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5637 SelectionDAG &DAG) const {
5638 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5639 EVT VT = Op.getValueType();
5640 unsigned VTBits = VT.getSizeInBits();
5641 SDLoc dl(Op);
5642 SDValue ShOpLo = Op.getOperand(0);
5643 SDValue ShOpHi = Op.getOperand(1);
5644 SDValue ShAmt = Op.getOperand(2);
5645 SDValue ARMcc;
5646 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5647 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5649 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5651 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5652 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5653 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5654 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5655 DAG.getConstant(VTBits, dl, MVT::i32));
5656 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5657 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5658 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5659 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5660 ISD::SETGE, ARMcc, DAG, dl);
5661 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5662 ARMcc, CCR, CmpLo);
5664 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5665 SDValue HiBigShift = Opc == ISD::SRA
5666 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5667 DAG.getConstant(VTBits - 1, dl, VT))
5668 : DAG.getConstant(0, dl, VT);
5669 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5670 ISD::SETGE, ARMcc, DAG, dl);
5671 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5672 ARMcc, CCR, CmpHi);
5674 SDValue Ops[2] = { Lo, Hi };
5675 return DAG.getMergeValues(Ops, dl);
5678 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5679 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5680 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5681 SelectionDAG &DAG) const {
5682 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5683 EVT VT = Op.getValueType();
5684 unsigned VTBits = VT.getSizeInBits();
5685 SDLoc dl(Op);
5686 SDValue ShOpLo = Op.getOperand(0);
5687 SDValue ShOpHi = Op.getOperand(1);
5688 SDValue ShAmt = Op.getOperand(2);
5689 SDValue ARMcc;
5690 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5692 assert(Op.getOpcode() == ISD::SHL_PARTS);
5693 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5694 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5695 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5696 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5697 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5699 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5700 DAG.getConstant(VTBits, dl, MVT::i32));
5701 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5702 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5703 ISD::SETGE, ARMcc, DAG, dl);
5704 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5705 ARMcc, CCR, CmpHi);
5707 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5708 ISD::SETGE, ARMcc, DAG, dl);
5709 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5710 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5711 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5713 SDValue Ops[2] = { Lo, Hi };
5714 return DAG.getMergeValues(Ops, dl);
5717 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5718 SelectionDAG &DAG) const {
5719 // The rounding mode is in bits 23:22 of the FPSCR.
5720 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5721 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5722 // so that the shift + and get folded into a bitfield extract.
5723 SDLoc dl(Op);
5724 SDValue Ops[] = { DAG.getEntryNode(),
5725 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5727 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5728 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5729 DAG.getConstant(1U << 22, dl, MVT::i32));
5730 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5731 DAG.getConstant(22, dl, MVT::i32));
5732 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5733 DAG.getConstant(3, dl, MVT::i32));
5736 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5737 const ARMSubtarget *ST) {
5738 SDLoc dl(N);
5739 EVT VT = N->getValueType(0);
5740 if (VT.isVector()) {
5741 assert(ST->hasNEON());
5743 // Compute the least significant set bit: LSB = X & -X
5744 SDValue X = N->getOperand(0);
5745 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5746 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5748 EVT ElemTy = VT.getVectorElementType();
5750 if (ElemTy == MVT::i8) {
5751 // Compute with: cttz(x) = ctpop(lsb - 1)
5752 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5753 DAG.getTargetConstant(1, dl, ElemTy));
5754 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5755 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5758 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5759 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5760 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5761 unsigned NumBits = ElemTy.getSizeInBits();
5762 SDValue WidthMinus1 =
5763 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5764 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5765 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5766 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5769 // Compute with: cttz(x) = ctpop(lsb - 1)
5771 // Compute LSB - 1.
5772 SDValue Bits;
5773 if (ElemTy == MVT::i64) {
5774 // Load constant 0xffff'ffff'ffff'ffff to register.
5775 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5776 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5777 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5778 } else {
5779 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5780 DAG.getTargetConstant(1, dl, ElemTy));
5781 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5783 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5786 if (!ST->hasV6T2Ops())
5787 return SDValue();
5789 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5790 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5793 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5794 const ARMSubtarget *ST) {
5795 EVT VT = N->getValueType(0);
5796 SDLoc DL(N);
5798 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5799 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5800 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5801 "Unexpected type for custom ctpop lowering");
5803 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5804 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5805 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5806 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5808 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5809 unsigned EltSize = 8;
5810 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5811 while (EltSize != VT.getScalarSizeInBits()) {
5812 SmallVector<SDValue, 8> Ops;
5813 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5814 TLI.getPointerTy(DAG.getDataLayout())));
5815 Ops.push_back(Res);
5817 EltSize *= 2;
5818 NumElts /= 2;
5819 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5820 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5823 return Res;
5826 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5827 /// operand of a vector shift operation, where all the elements of the
5828 /// build_vector must have the same constant integer value.
5829 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5830 // Ignore bit_converts.
5831 while (Op.getOpcode() == ISD::BITCAST)
5832 Op = Op.getOperand(0);
5833 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5834 APInt SplatBits, SplatUndef;
5835 unsigned SplatBitSize;
5836 bool HasAnyUndefs;
5837 if (!BVN ||
5838 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5839 ElementBits) ||
5840 SplatBitSize > ElementBits)
5841 return false;
5842 Cnt = SplatBits.getSExtValue();
5843 return true;
5846 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5847 /// operand of a vector shift left operation. That value must be in the range:
5848 /// 0 <= Value < ElementBits for a left shift; or
5849 /// 0 <= Value <= ElementBits for a long left shift.
5850 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5851 assert(VT.isVector() && "vector shift count is not a vector type");
5852 int64_t ElementBits = VT.getScalarSizeInBits();
5853 if (!getVShiftImm(Op, ElementBits, Cnt))
5854 return false;
5855 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5858 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5859 /// operand of a vector shift right operation. For a shift opcode, the value
5860 /// is positive, but for an intrinsic the value count must be negative. The
5861 /// absolute value must be in the range:
5862 /// 1 <= |Value| <= ElementBits for a right shift; or
5863 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5864 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5865 int64_t &Cnt) {
5866 assert(VT.isVector() && "vector shift count is not a vector type");
5867 int64_t ElementBits = VT.getScalarSizeInBits();
5868 if (!getVShiftImm(Op, ElementBits, Cnt))
5869 return false;
5870 if (!isIntrinsic)
5871 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5872 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5873 Cnt = -Cnt;
5874 return true;
5876 return false;
5879 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5880 const ARMSubtarget *ST) {
5881 EVT VT = N->getValueType(0);
5882 SDLoc dl(N);
5883 int64_t Cnt;
5885 if (!VT.isVector())
5886 return SDValue();
5888 // We essentially have two forms here. Shift by an immediate and shift by a
5889 // vector register (there are also shift by a gpr, but that is just handled
5890 // with a tablegen pattern). We cannot easily match shift by an immediate in
5891 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5892 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5893 // signed or unsigned, and a negative shift indicates a shift right).
5894 if (N->getOpcode() == ISD::SHL) {
5895 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5896 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5897 DAG.getConstant(Cnt, dl, MVT::i32));
5898 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
5899 N->getOperand(1));
5902 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
5903 "unexpected vector shift opcode");
5905 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
5906 unsigned VShiftOpc =
5907 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
5908 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
5909 DAG.getConstant(Cnt, dl, MVT::i32));
5912 // Other right shifts we don't have operations for (we use a shift left by a
5913 // negative number).
5914 EVT ShiftVT = N->getOperand(1).getValueType();
5915 SDValue NegatedCount = DAG.getNode(
5916 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
5917 unsigned VShiftOpc =
5918 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
5919 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
5922 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5923 const ARMSubtarget *ST) {
5924 EVT VT = N->getValueType(0);
5925 SDLoc dl(N);
5927 // We can get here for a node like i32 = ISD::SHL i32, i64
5928 if (VT != MVT::i64)
5929 return SDValue();
5931 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
5932 N->getOpcode() == ISD::SHL) &&
5933 "Unknown shift to lower!");
5935 unsigned ShOpc = N->getOpcode();
5936 if (ST->hasMVEIntegerOps()) {
5937 SDValue ShAmt = N->getOperand(1);
5938 unsigned ShPartsOpc = ARMISD::LSLL;
5939 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
5941 // If the shift amount is greater than 32 or has a greater bitwidth than 64
5942 // then do the default optimisation
5943 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
5944 (Con && Con->getZExtValue() >= 32))
5945 return SDValue();
5947 // Extract the lower 32 bits of the shift amount if it's not an i32
5948 if (ShAmt->getValueType(0) != MVT::i32)
5949 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
5951 if (ShOpc == ISD::SRL) {
5952 if (!Con)
5953 // There is no t2LSRLr instruction so negate and perform an lsll if the
5954 // shift amount is in a register, emulating a right shift.
5955 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5956 DAG.getConstant(0, dl, MVT::i32), ShAmt);
5957 else
5958 // Else generate an lsrl on the immediate shift amount
5959 ShPartsOpc = ARMISD::LSRL;
5960 } else if (ShOpc == ISD::SRA)
5961 ShPartsOpc = ARMISD::ASRL;
5963 // Lower 32 bits of the destination/source
5964 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5965 DAG.getConstant(0, dl, MVT::i32));
5966 // Upper 32 bits of the destination/source
5967 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5968 DAG.getConstant(1, dl, MVT::i32));
5970 // Generate the shift operation as computed above
5971 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
5972 ShAmt);
5973 // The upper 32 bits come from the second return value of lsll
5974 Hi = SDValue(Lo.getNode(), 1);
5975 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5978 // We only lower SRA, SRL of 1 here, all others use generic lowering.
5979 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
5980 return SDValue();
5982 // If we are in thumb mode, we don't have RRX.
5983 if (ST->isThumb1Only())
5984 return SDValue();
5986 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
5987 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5988 DAG.getConstant(0, dl, MVT::i32));
5989 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5990 DAG.getConstant(1, dl, MVT::i32));
5992 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5993 // captures the result into a carry flag.
5994 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5995 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5997 // The low part is an ARMISD::RRX operand, which shifts the carry in.
5998 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6000 // Merge the pieces into a single i64 value.
6001 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6004 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6005 const ARMSubtarget *ST) {
6006 bool Invert = false;
6007 bool Swap = false;
6008 unsigned Opc = ARMCC::AL;
6010 SDValue Op0 = Op.getOperand(0);
6011 SDValue Op1 = Op.getOperand(1);
6012 SDValue CC = Op.getOperand(2);
6013 EVT VT = Op.getValueType();
6014 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6015 SDLoc dl(Op);
6017 EVT CmpVT;
6018 if (ST->hasNEON())
6019 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6020 else {
6021 assert(ST->hasMVEIntegerOps() &&
6022 "No hardware support for integer vector comparison!");
6024 if (Op.getValueType().getVectorElementType() != MVT::i1)
6025 return SDValue();
6027 // Make sure we expand floating point setcc to scalar if we do not have
6028 // mve.fp, so that we can handle them from there.
6029 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6030 return SDValue();
6032 CmpVT = VT;
6035 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6036 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6037 // Special-case integer 64-bit equality comparisons. They aren't legal,
6038 // but they can be lowered with a few vector instructions.
6039 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6040 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6041 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6042 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6043 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6044 DAG.getCondCode(ISD::SETEQ));
6045 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6046 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6047 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6048 if (SetCCOpcode == ISD::SETNE)
6049 Merged = DAG.getNOT(dl, Merged, CmpVT);
6050 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6051 return Merged;
6054 if (CmpVT.getVectorElementType() == MVT::i64)
6055 // 64-bit comparisons are not legal in general.
6056 return SDValue();
6058 if (Op1.getValueType().isFloatingPoint()) {
6059 switch (SetCCOpcode) {
6060 default: llvm_unreachable("Illegal FP comparison");
6061 case ISD::SETUNE:
6062 case ISD::SETNE:
6063 if (ST->hasMVEFloatOps()) {
6064 Opc = ARMCC::NE; break;
6065 } else {
6066 Invert = true; LLVM_FALLTHROUGH;
6068 case ISD::SETOEQ:
6069 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6070 case ISD::SETOLT:
6071 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6072 case ISD::SETOGT:
6073 case ISD::SETGT: Opc = ARMCC::GT; break;
6074 case ISD::SETOLE:
6075 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6076 case ISD::SETOGE:
6077 case ISD::SETGE: Opc = ARMCC::GE; break;
6078 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6079 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6080 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6081 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6082 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6083 case ISD::SETONE: {
6084 // Expand this to (OLT | OGT).
6085 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6086 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6087 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6088 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6089 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6090 if (Invert)
6091 Result = DAG.getNOT(dl, Result, VT);
6092 return Result;
6094 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6095 case ISD::SETO: {
6096 // Expand this to (OLT | OGE).
6097 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6098 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6099 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6100 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6101 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6102 if (Invert)
6103 Result = DAG.getNOT(dl, Result, VT);
6104 return Result;
6107 } else {
6108 // Integer comparisons.
6109 switch (SetCCOpcode) {
6110 default: llvm_unreachable("Illegal integer comparison");
6111 case ISD::SETNE:
6112 if (ST->hasMVEIntegerOps()) {
6113 Opc = ARMCC::NE; break;
6114 } else {
6115 Invert = true; LLVM_FALLTHROUGH;
6117 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6118 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6119 case ISD::SETGT: Opc = ARMCC::GT; break;
6120 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6121 case ISD::SETGE: Opc = ARMCC::GE; break;
6122 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6123 case ISD::SETUGT: Opc = ARMCC::HI; break;
6124 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6125 case ISD::SETUGE: Opc = ARMCC::HS; break;
6128 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6129 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6130 SDValue AndOp;
6131 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6132 AndOp = Op0;
6133 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6134 AndOp = Op1;
6136 // Ignore bitconvert.
6137 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6138 AndOp = AndOp.getOperand(0);
6140 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6141 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6142 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6143 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6144 if (!Invert)
6145 Result = DAG.getNOT(dl, Result, VT);
6146 return Result;
6151 if (Swap)
6152 std::swap(Op0, Op1);
6154 // If one of the operands is a constant vector zero, attempt to fold the
6155 // comparison to a specialized compare-against-zero form.
6156 SDValue SingleOp;
6157 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6158 SingleOp = Op0;
6159 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6160 if (Opc == ARMCC::GE)
6161 Opc = ARMCC::LE;
6162 else if (Opc == ARMCC::GT)
6163 Opc = ARMCC::LT;
6164 SingleOp = Op1;
6167 SDValue Result;
6168 if (SingleOp.getNode()) {
6169 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6170 DAG.getConstant(Opc, dl, MVT::i32));
6171 } else {
6172 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6173 DAG.getConstant(Opc, dl, MVT::i32));
6176 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6178 if (Invert)
6179 Result = DAG.getNOT(dl, Result, VT);
6181 return Result;
6184 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6185 SDValue LHS = Op.getOperand(0);
6186 SDValue RHS = Op.getOperand(1);
6187 SDValue Carry = Op.getOperand(2);
6188 SDValue Cond = Op.getOperand(3);
6189 SDLoc DL(Op);
6191 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6193 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6194 // have to invert the carry first.
6195 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6196 DAG.getConstant(1, DL, MVT::i32), Carry);
6197 // This converts the boolean value carry into the carry flag.
6198 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6200 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6201 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6203 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6204 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6205 SDValue ARMcc = DAG.getConstant(
6206 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6207 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6208 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6209 Cmp.getValue(1), SDValue());
6210 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6211 CCR, Chain.getValue(1));
6214 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6215 /// valid vector constant for a NEON or MVE instruction with a "modified
6216 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6217 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6218 unsigned SplatBitSize, SelectionDAG &DAG,
6219 const SDLoc &dl, EVT &VT, bool is128Bits,
6220 VMOVModImmType type) {
6221 unsigned OpCmode, Imm;
6223 // SplatBitSize is set to the smallest size that splats the vector, so a
6224 // zero vector will always have SplatBitSize == 8. However, NEON modified
6225 // immediate instructions others than VMOV do not support the 8-bit encoding
6226 // of a zero vector, and the default encoding of zero is supposed to be the
6227 // 32-bit version.
6228 if (SplatBits == 0)
6229 SplatBitSize = 32;
6231 switch (SplatBitSize) {
6232 case 8:
6233 if (type != VMOVModImm)
6234 return SDValue();
6235 // Any 1-byte value is OK. Op=0, Cmode=1110.
6236 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6237 OpCmode = 0xe;
6238 Imm = SplatBits;
6239 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6240 break;
6242 case 16:
6243 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6244 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6245 if ((SplatBits & ~0xff) == 0) {
6246 // Value = 0x00nn: Op=x, Cmode=100x.
6247 OpCmode = 0x8;
6248 Imm = SplatBits;
6249 break;
6251 if ((SplatBits & ~0xff00) == 0) {
6252 // Value = 0xnn00: Op=x, Cmode=101x.
6253 OpCmode = 0xa;
6254 Imm = SplatBits >> 8;
6255 break;
6257 return SDValue();
6259 case 32:
6260 // NEON's 32-bit VMOV supports splat values where:
6261 // * only one byte is nonzero, or
6262 // * the least significant byte is 0xff and the second byte is nonzero, or
6263 // * the least significant 2 bytes are 0xff and the third is nonzero.
6264 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6265 if ((SplatBits & ~0xff) == 0) {
6266 // Value = 0x000000nn: Op=x, Cmode=000x.
6267 OpCmode = 0;
6268 Imm = SplatBits;
6269 break;
6271 if ((SplatBits & ~0xff00) == 0) {
6272 // Value = 0x0000nn00: Op=x, Cmode=001x.
6273 OpCmode = 0x2;
6274 Imm = SplatBits >> 8;
6275 break;
6277 if ((SplatBits & ~0xff0000) == 0) {
6278 // Value = 0x00nn0000: Op=x, Cmode=010x.
6279 OpCmode = 0x4;
6280 Imm = SplatBits >> 16;
6281 break;
6283 if ((SplatBits & ~0xff000000) == 0) {
6284 // Value = 0xnn000000: Op=x, Cmode=011x.
6285 OpCmode = 0x6;
6286 Imm = SplatBits >> 24;
6287 break;
6290 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6291 if (type == OtherModImm) return SDValue();
6293 if ((SplatBits & ~0xffff) == 0 &&
6294 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6295 // Value = 0x0000nnff: Op=x, Cmode=1100.
6296 OpCmode = 0xc;
6297 Imm = SplatBits >> 8;
6298 break;
6301 // cmode == 0b1101 is not supported for MVE VMVN
6302 if (type == MVEVMVNModImm)
6303 return SDValue();
6305 if ((SplatBits & ~0xffffff) == 0 &&
6306 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6307 // Value = 0x00nnffff: Op=x, Cmode=1101.
6308 OpCmode = 0xd;
6309 Imm = SplatBits >> 16;
6310 break;
6313 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6314 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6315 // VMOV.I32. A (very) minor optimization would be to replicate the value
6316 // and fall through here to test for a valid 64-bit splat. But, then the
6317 // caller would also need to check and handle the change in size.
6318 return SDValue();
6320 case 64: {
6321 if (type != VMOVModImm)
6322 return SDValue();
6323 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6324 uint64_t BitMask = 0xff;
6325 uint64_t Val = 0;
6326 unsigned ImmMask = 1;
6327 Imm = 0;
6328 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6329 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6330 Val |= BitMask;
6331 Imm |= ImmMask;
6332 } else if ((SplatBits & BitMask) != 0) {
6333 return SDValue();
6335 BitMask <<= 8;
6336 ImmMask <<= 1;
6339 if (DAG.getDataLayout().isBigEndian())
6340 // swap higher and lower 32 bit word
6341 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6343 // Op=1, Cmode=1110.
6344 OpCmode = 0x1e;
6345 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6346 break;
6349 default:
6350 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6353 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6354 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6357 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6358 const ARMSubtarget *ST) const {
6359 EVT VT = Op.getValueType();
6360 bool IsDouble = (VT == MVT::f64);
6361 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6362 const APFloat &FPVal = CFP->getValueAPF();
6364 // Prevent floating-point constants from using literal loads
6365 // when execute-only is enabled.
6366 if (ST->genExecuteOnly()) {
6367 // If we can represent the constant as an immediate, don't lower it
6368 if (isFPImmLegal(FPVal, VT))
6369 return Op;
6370 // Otherwise, construct as integer, and move to float register
6371 APInt INTVal = FPVal.bitcastToAPInt();
6372 SDLoc DL(CFP);
6373 switch (VT.getSimpleVT().SimpleTy) {
6374 default:
6375 llvm_unreachable("Unknown floating point type!");
6376 break;
6377 case MVT::f64: {
6378 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6379 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6380 if (!ST->isLittle())
6381 std::swap(Lo, Hi);
6382 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6384 case MVT::f32:
6385 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6386 DAG.getConstant(INTVal, DL, MVT::i32));
6390 if (!ST->hasVFP3Base())
6391 return SDValue();
6393 // Use the default (constant pool) lowering for double constants when we have
6394 // an SP-only FPU
6395 if (IsDouble && !Subtarget->hasFP64())
6396 return SDValue();
6398 // Try splatting with a VMOV.f32...
6399 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6401 if (ImmVal != -1) {
6402 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6403 // We have code in place to select a valid ConstantFP already, no need to
6404 // do any mangling.
6405 return Op;
6408 // It's a float and we are trying to use NEON operations where
6409 // possible. Lower it to a splat followed by an extract.
6410 SDLoc DL(Op);
6411 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6412 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6413 NewVal);
6414 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6415 DAG.getConstant(0, DL, MVT::i32));
6418 // The rest of our options are NEON only, make sure that's allowed before
6419 // proceeding..
6420 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6421 return SDValue();
6423 EVT VMovVT;
6424 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6426 // It wouldn't really be worth bothering for doubles except for one very
6427 // important value, which does happen to match: 0.0. So make sure we don't do
6428 // anything stupid.
6429 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6430 return SDValue();
6432 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6433 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6434 VMovVT, false, VMOVModImm);
6435 if (NewVal != SDValue()) {
6436 SDLoc DL(Op);
6437 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6438 NewVal);
6439 if (IsDouble)
6440 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6442 // It's a float: cast and extract a vector element.
6443 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6444 VecConstant);
6445 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6446 DAG.getConstant(0, DL, MVT::i32));
6449 // Finally, try a VMVN.i32
6450 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6451 false, VMVNModImm);
6452 if (NewVal != SDValue()) {
6453 SDLoc DL(Op);
6454 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6456 if (IsDouble)
6457 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6459 // It's a float: cast and extract a vector element.
6460 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6461 VecConstant);
6462 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6463 DAG.getConstant(0, DL, MVT::i32));
6466 return SDValue();
6469 // check if an VEXT instruction can handle the shuffle mask when the
6470 // vector sources of the shuffle are the same.
6471 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6472 unsigned NumElts = VT.getVectorNumElements();
6474 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6475 if (M[0] < 0)
6476 return false;
6478 Imm = M[0];
6480 // If this is a VEXT shuffle, the immediate value is the index of the first
6481 // element. The other shuffle indices must be the successive elements after
6482 // the first one.
6483 unsigned ExpectedElt = Imm;
6484 for (unsigned i = 1; i < NumElts; ++i) {
6485 // Increment the expected index. If it wraps around, just follow it
6486 // back to index zero and keep going.
6487 ++ExpectedElt;
6488 if (ExpectedElt == NumElts)
6489 ExpectedElt = 0;
6491 if (M[i] < 0) continue; // ignore UNDEF indices
6492 if (ExpectedElt != static_cast<unsigned>(M[i]))
6493 return false;
6496 return true;
6499 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6500 bool &ReverseVEXT, unsigned &Imm) {
6501 unsigned NumElts = VT.getVectorNumElements();
6502 ReverseVEXT = false;
6504 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6505 if (M[0] < 0)
6506 return false;
6508 Imm = M[0];
6510 // If this is a VEXT shuffle, the immediate value is the index of the first
6511 // element. The other shuffle indices must be the successive elements after
6512 // the first one.
6513 unsigned ExpectedElt = Imm;
6514 for (unsigned i = 1; i < NumElts; ++i) {
6515 // Increment the expected index. If it wraps around, it may still be
6516 // a VEXT but the source vectors must be swapped.
6517 ExpectedElt += 1;
6518 if (ExpectedElt == NumElts * 2) {
6519 ExpectedElt = 0;
6520 ReverseVEXT = true;
6523 if (M[i] < 0) continue; // ignore UNDEF indices
6524 if (ExpectedElt != static_cast<unsigned>(M[i]))
6525 return false;
6528 // Adjust the index value if the source operands will be swapped.
6529 if (ReverseVEXT)
6530 Imm -= NumElts;
6532 return true;
6535 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6536 /// instruction with the specified blocksize. (The order of the elements
6537 /// within each block of the vector is reversed.)
6538 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6539 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6540 "Only possible block sizes for VREV are: 16, 32, 64");
6542 unsigned EltSz = VT.getScalarSizeInBits();
6543 if (EltSz == 64)
6544 return false;
6546 unsigned NumElts = VT.getVectorNumElements();
6547 unsigned BlockElts = M[0] + 1;
6548 // If the first shuffle index is UNDEF, be optimistic.
6549 if (M[0] < 0)
6550 BlockElts = BlockSize / EltSz;
6552 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6553 return false;
6555 for (unsigned i = 0; i < NumElts; ++i) {
6556 if (M[i] < 0) continue; // ignore UNDEF indices
6557 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6558 return false;
6561 return true;
6564 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6565 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6566 // range, then 0 is placed into the resulting vector. So pretty much any mask
6567 // of 8 elements can work here.
6568 return VT == MVT::v8i8 && M.size() == 8;
6571 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6572 unsigned Index) {
6573 if (Mask.size() == Elements * 2)
6574 return Index / Elements;
6575 return Mask[Index] == 0 ? 0 : 1;
6578 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6579 // checking that pairs of elements in the shuffle mask represent the same index
6580 // in each vector, incrementing the expected index by 2 at each step.
6581 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6582 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6583 // v2={e,f,g,h}
6584 // WhichResult gives the offset for each element in the mask based on which
6585 // of the two results it belongs to.
6587 // The transpose can be represented either as:
6588 // result1 = shufflevector v1, v2, result1_shuffle_mask
6589 // result2 = shufflevector v1, v2, result2_shuffle_mask
6590 // where v1/v2 and the shuffle masks have the same number of elements
6591 // (here WhichResult (see below) indicates which result is being checked)
6593 // or as:
6594 // results = shufflevector v1, v2, shuffle_mask
6595 // where both results are returned in one vector and the shuffle mask has twice
6596 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6597 // want to check the low half and high half of the shuffle mask as if it were
6598 // the other case
6599 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6600 unsigned EltSz = VT.getScalarSizeInBits();
6601 if (EltSz == 64)
6602 return false;
6604 unsigned NumElts = VT.getVectorNumElements();
6605 if (M.size() != NumElts && M.size() != NumElts*2)
6606 return false;
6608 // If the mask is twice as long as the input vector then we need to check the
6609 // upper and lower parts of the mask with a matching value for WhichResult
6610 // FIXME: A mask with only even values will be rejected in case the first
6611 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6612 // M[0] is used to determine WhichResult
6613 for (unsigned i = 0; i < M.size(); i += NumElts) {
6614 WhichResult = SelectPairHalf(NumElts, M, i);
6615 for (unsigned j = 0; j < NumElts; j += 2) {
6616 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6617 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6618 return false;
6622 if (M.size() == NumElts*2)
6623 WhichResult = 0;
6625 return true;
6628 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6629 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6630 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6631 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6632 unsigned EltSz = VT.getScalarSizeInBits();
6633 if (EltSz == 64)
6634 return false;
6636 unsigned NumElts = VT.getVectorNumElements();
6637 if (M.size() != NumElts && M.size() != NumElts*2)
6638 return false;
6640 for (unsigned i = 0; i < M.size(); i += NumElts) {
6641 WhichResult = SelectPairHalf(NumElts, M, i);
6642 for (unsigned j = 0; j < NumElts; j += 2) {
6643 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6644 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6645 return false;
6649 if (M.size() == NumElts*2)
6650 WhichResult = 0;
6652 return true;
6655 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6656 // that the mask elements are either all even and in steps of size 2 or all odd
6657 // and in steps of size 2.
6658 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6659 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6660 // v2={e,f,g,h}
6661 // Requires similar checks to that of isVTRNMask with
6662 // respect the how results are returned.
6663 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6664 unsigned EltSz = VT.getScalarSizeInBits();
6665 if (EltSz == 64)
6666 return false;
6668 unsigned NumElts = VT.getVectorNumElements();
6669 if (M.size() != NumElts && M.size() != NumElts*2)
6670 return false;
6672 for (unsigned i = 0; i < M.size(); i += NumElts) {
6673 WhichResult = SelectPairHalf(NumElts, M, i);
6674 for (unsigned j = 0; j < NumElts; ++j) {
6675 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6676 return false;
6680 if (M.size() == NumElts*2)
6681 WhichResult = 0;
6683 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6684 if (VT.is64BitVector() && EltSz == 32)
6685 return false;
6687 return true;
6690 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6691 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6692 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6693 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6694 unsigned EltSz = VT.getScalarSizeInBits();
6695 if (EltSz == 64)
6696 return false;
6698 unsigned NumElts = VT.getVectorNumElements();
6699 if (M.size() != NumElts && M.size() != NumElts*2)
6700 return false;
6702 unsigned Half = NumElts / 2;
6703 for (unsigned i = 0; i < M.size(); i += NumElts) {
6704 WhichResult = SelectPairHalf(NumElts, M, i);
6705 for (unsigned j = 0; j < NumElts; j += Half) {
6706 unsigned Idx = WhichResult;
6707 for (unsigned k = 0; k < Half; ++k) {
6708 int MIdx = M[i + j + k];
6709 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6710 return false;
6711 Idx += 2;
6716 if (M.size() == NumElts*2)
6717 WhichResult = 0;
6719 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6720 if (VT.is64BitVector() && EltSz == 32)
6721 return false;
6723 return true;
6726 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6727 // that pairs of elements of the shufflemask represent the same index in each
6728 // vector incrementing sequentially through the vectors.
6729 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6730 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6731 // v2={e,f,g,h}
6732 // Requires similar checks to that of isVTRNMask with respect the how results
6733 // are returned.
6734 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6735 unsigned EltSz = VT.getScalarSizeInBits();
6736 if (EltSz == 64)
6737 return false;
6739 unsigned NumElts = VT.getVectorNumElements();
6740 if (M.size() != NumElts && M.size() != NumElts*2)
6741 return false;
6743 for (unsigned i = 0; i < M.size(); i += NumElts) {
6744 WhichResult = SelectPairHalf(NumElts, M, i);
6745 unsigned Idx = WhichResult * NumElts / 2;
6746 for (unsigned j = 0; j < NumElts; j += 2) {
6747 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6748 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6749 return false;
6750 Idx += 1;
6754 if (M.size() == NumElts*2)
6755 WhichResult = 0;
6757 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6758 if (VT.is64BitVector() && EltSz == 32)
6759 return false;
6761 return true;
6764 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6765 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6766 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6767 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6768 unsigned EltSz = VT.getScalarSizeInBits();
6769 if (EltSz == 64)
6770 return false;
6772 unsigned NumElts = VT.getVectorNumElements();
6773 if (M.size() != NumElts && M.size() != NumElts*2)
6774 return false;
6776 for (unsigned i = 0; i < M.size(); i += NumElts) {
6777 WhichResult = SelectPairHalf(NumElts, M, i);
6778 unsigned Idx = WhichResult * NumElts / 2;
6779 for (unsigned j = 0; j < NumElts; j += 2) {
6780 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6781 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6782 return false;
6783 Idx += 1;
6787 if (M.size() == NumElts*2)
6788 WhichResult = 0;
6790 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6791 if (VT.is64BitVector() && EltSz == 32)
6792 return false;
6794 return true;
6797 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6798 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6799 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6800 unsigned &WhichResult,
6801 bool &isV_UNDEF) {
6802 isV_UNDEF = false;
6803 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6804 return ARMISD::VTRN;
6805 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6806 return ARMISD::VUZP;
6807 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6808 return ARMISD::VZIP;
6810 isV_UNDEF = true;
6811 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6812 return ARMISD::VTRN;
6813 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6814 return ARMISD::VUZP;
6815 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6816 return ARMISD::VZIP;
6818 return 0;
6821 /// \return true if this is a reverse operation on an vector.
6822 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6823 unsigned NumElts = VT.getVectorNumElements();
6824 // Make sure the mask has the right size.
6825 if (NumElts != M.size())
6826 return false;
6828 // Look for <15, ..., 3, -1, 1, 0>.
6829 for (unsigned i = 0; i != NumElts; ++i)
6830 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6831 return false;
6833 return true;
6836 // If N is an integer constant that can be moved into a register in one
6837 // instruction, return an SDValue of such a constant (will become a MOV
6838 // instruction). Otherwise return null.
6839 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6840 const ARMSubtarget *ST, const SDLoc &dl) {
6841 uint64_t Val;
6842 if (!isa<ConstantSDNode>(N))
6843 return SDValue();
6844 Val = cast<ConstantSDNode>(N)->getZExtValue();
6846 if (ST->isThumb1Only()) {
6847 if (Val <= 255 || ~Val <= 255)
6848 return DAG.getConstant(Val, dl, MVT::i32);
6849 } else {
6850 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6851 return DAG.getConstant(Val, dl, MVT::i32);
6853 return SDValue();
6856 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6857 const ARMSubtarget *ST) {
6858 SDLoc dl(Op);
6859 EVT VT = Op.getValueType();
6861 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6863 unsigned NumElts = VT.getVectorNumElements();
6864 unsigned BoolMask;
6865 unsigned BitsPerBool;
6866 if (NumElts == 4) {
6867 BitsPerBool = 4;
6868 BoolMask = 0xf;
6869 } else if (NumElts == 8) {
6870 BitsPerBool = 2;
6871 BoolMask = 0x3;
6872 } else if (NumElts == 16) {
6873 BitsPerBool = 1;
6874 BoolMask = 0x1;
6875 } else
6876 return SDValue();
6878 // First create base with bits set where known
6879 unsigned Bits32 = 0;
6880 for (unsigned i = 0; i < NumElts; ++i) {
6881 SDValue V = Op.getOperand(i);
6882 if (!isa<ConstantSDNode>(V) && !V.isUndef())
6883 continue;
6884 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
6885 if (BitSet)
6886 Bits32 |= BoolMask << (i * BitsPerBool);
6889 // Add in unknown nodes
6890 // FIXME: Handle splats of the same value better.
6891 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
6892 DAG.getConstant(Bits32, dl, MVT::i32));
6893 for (unsigned i = 0; i < NumElts; ++i) {
6894 SDValue V = Op.getOperand(i);
6895 if (isa<ConstantSDNode>(V) || V.isUndef())
6896 continue;
6897 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
6898 DAG.getConstant(i, dl, MVT::i32));
6901 return Base;
6904 // If this is a case we can't handle, return null and let the default
6905 // expansion code take care of it.
6906 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6907 const ARMSubtarget *ST) const {
6908 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6909 SDLoc dl(Op);
6910 EVT VT = Op.getValueType();
6912 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
6913 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
6915 APInt SplatBits, SplatUndef;
6916 unsigned SplatBitSize;
6917 bool HasAnyUndefs;
6918 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6919 if (SplatUndef.isAllOnesValue())
6920 return DAG.getUNDEF(VT);
6922 if ((ST->hasNEON() && SplatBitSize <= 64) ||
6923 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
6924 // Check if an immediate VMOV works.
6925 EVT VmovVT;
6926 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
6927 SplatUndef.getZExtValue(), SplatBitSize,
6928 DAG, dl, VmovVT, VT.is128BitVector(),
6929 VMOVModImm);
6931 if (Val.getNode()) {
6932 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6933 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6936 // Try an immediate VMVN.
6937 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6938 Val = isVMOVModifiedImm(
6939 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
6940 DAG, dl, VmovVT, VT.is128BitVector(),
6941 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
6942 if (Val.getNode()) {
6943 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6944 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6947 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6948 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6949 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6950 if (ImmVal != -1) {
6951 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6952 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6958 // Scan through the operands to see if only one value is used.
6960 // As an optimisation, even if more than one value is used it may be more
6961 // profitable to splat with one value then change some lanes.
6963 // Heuristically we decide to do this if the vector has a "dominant" value,
6964 // defined as splatted to more than half of the lanes.
6965 unsigned NumElts = VT.getVectorNumElements();
6966 bool isOnlyLowElement = true;
6967 bool usesOnlyOneValue = true;
6968 bool hasDominantValue = false;
6969 bool isConstant = true;
6971 // Map of the number of times a particular SDValue appears in the
6972 // element list.
6973 DenseMap<SDValue, unsigned> ValueCounts;
6974 SDValue Value;
6975 for (unsigned i = 0; i < NumElts; ++i) {
6976 SDValue V = Op.getOperand(i);
6977 if (V.isUndef())
6978 continue;
6979 if (i > 0)
6980 isOnlyLowElement = false;
6981 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6982 isConstant = false;
6984 ValueCounts.insert(std::make_pair(V, 0));
6985 unsigned &Count = ValueCounts[V];
6987 // Is this value dominant? (takes up more than half of the lanes)
6988 if (++Count > (NumElts / 2)) {
6989 hasDominantValue = true;
6990 Value = V;
6993 if (ValueCounts.size() != 1)
6994 usesOnlyOneValue = false;
6995 if (!Value.getNode() && !ValueCounts.empty())
6996 Value = ValueCounts.begin()->first;
6998 if (ValueCounts.empty())
6999 return DAG.getUNDEF(VT);
7001 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7002 // Keep going if we are hitting this case.
7003 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7004 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7006 unsigned EltSize = VT.getScalarSizeInBits();
7008 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7009 // i32 and try again.
7010 if (hasDominantValue && EltSize <= 32) {
7011 if (!isConstant) {
7012 SDValue N;
7014 // If we are VDUPing a value that comes directly from a vector, that will
7015 // cause an unnecessary move to and from a GPR, where instead we could
7016 // just use VDUPLANE. We can only do this if the lane being extracted
7017 // is at a constant index, as the VDUP from lane instructions only have
7018 // constant-index forms.
7019 ConstantSDNode *constIndex;
7020 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7021 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7022 // We need to create a new undef vector to use for the VDUPLANE if the
7023 // size of the vector from which we get the value is different than the
7024 // size of the vector that we need to create. We will insert the element
7025 // such that the register coalescer will remove unnecessary copies.
7026 if (VT != Value->getOperand(0).getValueType()) {
7027 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7028 VT.getVectorNumElements();
7029 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7030 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7031 Value, DAG.getConstant(index, dl, MVT::i32)),
7032 DAG.getConstant(index, dl, MVT::i32));
7033 } else
7034 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7035 Value->getOperand(0), Value->getOperand(1));
7036 } else
7037 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7039 if (!usesOnlyOneValue) {
7040 // The dominant value was splatted as 'N', but we now have to insert
7041 // all differing elements.
7042 for (unsigned I = 0; I < NumElts; ++I) {
7043 if (Op.getOperand(I) == Value)
7044 continue;
7045 SmallVector<SDValue, 3> Ops;
7046 Ops.push_back(N);
7047 Ops.push_back(Op.getOperand(I));
7048 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7049 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7052 return N;
7054 if (VT.getVectorElementType().isFloatingPoint()) {
7055 SmallVector<SDValue, 8> Ops;
7056 MVT FVT = VT.getVectorElementType().getSimpleVT();
7057 assert(FVT == MVT::f32 || FVT == MVT::f16);
7058 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7059 for (unsigned i = 0; i < NumElts; ++i)
7060 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7061 Op.getOperand(i)));
7062 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7063 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7064 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7065 if (Val.getNode())
7066 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7068 if (usesOnlyOneValue) {
7069 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7070 if (isConstant && Val.getNode())
7071 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7075 // If all elements are constants and the case above didn't get hit, fall back
7076 // to the default expansion, which will generate a load from the constant
7077 // pool.
7078 if (isConstant)
7079 return SDValue();
7081 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7082 if (NumElts >= 4) {
7083 SDValue shuffle = ReconstructShuffle(Op, DAG);
7084 if (shuffle != SDValue())
7085 return shuffle;
7088 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7089 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7090 // into two 64-bit vectors; we might discover a better way to lower it.
7091 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7092 EVT ExtVT = VT.getVectorElementType();
7093 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7094 SDValue Lower =
7095 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7096 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7097 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7098 SDValue Upper = DAG.getBuildVector(
7099 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7100 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7101 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7102 if (Lower && Upper)
7103 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7106 // Vectors with 32- or 64-bit elements can be built by directly assigning
7107 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7108 // will be legalized.
7109 if (EltSize >= 32) {
7110 // Do the expansion with floating-point types, since that is what the VFP
7111 // registers are defined to use, and since i64 is not legal.
7112 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7113 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7114 SmallVector<SDValue, 8> Ops;
7115 for (unsigned i = 0; i < NumElts; ++i)
7116 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7117 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7118 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7121 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7122 // know the default expansion would otherwise fall back on something even
7123 // worse. For a vector with one or two non-undef values, that's
7124 // scalar_to_vector for the elements followed by a shuffle (provided the
7125 // shuffle is valid for the target) and materialization element by element
7126 // on the stack followed by a load for everything else.
7127 if (!isConstant && !usesOnlyOneValue) {
7128 SDValue Vec = DAG.getUNDEF(VT);
7129 for (unsigned i = 0 ; i < NumElts; ++i) {
7130 SDValue V = Op.getOperand(i);
7131 if (V.isUndef())
7132 continue;
7133 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7134 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7136 return Vec;
7139 return SDValue();
7142 // Gather data to see if the operation can be modelled as a
7143 // shuffle in combination with VEXTs.
7144 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7145 SelectionDAG &DAG) const {
7146 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7147 SDLoc dl(Op);
7148 EVT VT = Op.getValueType();
7149 unsigned NumElts = VT.getVectorNumElements();
7151 struct ShuffleSourceInfo {
7152 SDValue Vec;
7153 unsigned MinElt = std::numeric_limits<unsigned>::max();
7154 unsigned MaxElt = 0;
7156 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7157 // be compatible with the shuffle we intend to construct. As a result
7158 // ShuffleVec will be some sliding window into the original Vec.
7159 SDValue ShuffleVec;
7161 // Code should guarantee that element i in Vec starts at element "WindowBase
7162 // + i * WindowScale in ShuffleVec".
7163 int WindowBase = 0;
7164 int WindowScale = 1;
7166 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7168 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7171 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7172 // node.
7173 SmallVector<ShuffleSourceInfo, 2> Sources;
7174 for (unsigned i = 0; i < NumElts; ++i) {
7175 SDValue V = Op.getOperand(i);
7176 if (V.isUndef())
7177 continue;
7178 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7179 // A shuffle can only come from building a vector from various
7180 // elements of other vectors.
7181 return SDValue();
7182 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7183 // Furthermore, shuffles require a constant mask, whereas extractelts
7184 // accept variable indices.
7185 return SDValue();
7188 // Add this element source to the list if it's not already there.
7189 SDValue SourceVec = V.getOperand(0);
7190 auto Source = llvm::find(Sources, SourceVec);
7191 if (Source == Sources.end())
7192 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7194 // Update the minimum and maximum lane number seen.
7195 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7196 Source->MinElt = std::min(Source->MinElt, EltNo);
7197 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7200 // Currently only do something sane when at most two source vectors
7201 // are involved.
7202 if (Sources.size() > 2)
7203 return SDValue();
7205 // Find out the smallest element size among result and two sources, and use
7206 // it as element size to build the shuffle_vector.
7207 EVT SmallestEltTy = VT.getVectorElementType();
7208 for (auto &Source : Sources) {
7209 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7210 if (SrcEltTy.bitsLT(SmallestEltTy))
7211 SmallestEltTy = SrcEltTy;
7213 unsigned ResMultiplier =
7214 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7215 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7216 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7218 // If the source vector is too wide or too narrow, we may nevertheless be able
7219 // to construct a compatible shuffle either by concatenating it with UNDEF or
7220 // extracting a suitable range of elements.
7221 for (auto &Src : Sources) {
7222 EVT SrcVT = Src.ShuffleVec.getValueType();
7224 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7225 continue;
7227 // This stage of the search produces a source with the same element type as
7228 // the original, but with a total width matching the BUILD_VECTOR output.
7229 EVT EltVT = SrcVT.getVectorElementType();
7230 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7231 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7233 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7234 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7235 return SDValue();
7236 // We can pad out the smaller vector for free, so if it's part of a
7237 // shuffle...
7238 Src.ShuffleVec =
7239 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7240 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7241 continue;
7244 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7245 return SDValue();
7247 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7248 // Span too large for a VEXT to cope
7249 return SDValue();
7252 if (Src.MinElt >= NumSrcElts) {
7253 // The extraction can just take the second half
7254 Src.ShuffleVec =
7255 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7256 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7257 Src.WindowBase = -NumSrcElts;
7258 } else if (Src.MaxElt < NumSrcElts) {
7259 // The extraction can just take the first half
7260 Src.ShuffleVec =
7261 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7262 DAG.getConstant(0, dl, MVT::i32));
7263 } else {
7264 // An actual VEXT is needed
7265 SDValue VEXTSrc1 =
7266 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7267 DAG.getConstant(0, dl, MVT::i32));
7268 SDValue VEXTSrc2 =
7269 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7270 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7272 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7273 VEXTSrc2,
7274 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7275 Src.WindowBase = -Src.MinElt;
7279 // Another possible incompatibility occurs from the vector element types. We
7280 // can fix this by bitcasting the source vectors to the same type we intend
7281 // for the shuffle.
7282 for (auto &Src : Sources) {
7283 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7284 if (SrcEltTy == SmallestEltTy)
7285 continue;
7286 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7287 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7288 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7289 Src.WindowBase *= Src.WindowScale;
7292 // Final sanity check before we try to actually produce a shuffle.
7293 LLVM_DEBUG(for (auto Src
7294 : Sources)
7295 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7297 // The stars all align, our next step is to produce the mask for the shuffle.
7298 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7299 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7300 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7301 SDValue Entry = Op.getOperand(i);
7302 if (Entry.isUndef())
7303 continue;
7305 auto Src = llvm::find(Sources, Entry.getOperand(0));
7306 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7308 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7309 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7310 // segment.
7311 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7312 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7313 VT.getScalarSizeInBits());
7314 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7316 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7317 // starting at the appropriate offset.
7318 int *LaneMask = &Mask[i * ResMultiplier];
7320 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7321 ExtractBase += NumElts * (Src - Sources.begin());
7322 for (int j = 0; j < LanesDefined; ++j)
7323 LaneMask[j] = ExtractBase + j;
7326 // Final check before we try to produce nonsense...
7327 if (!isShuffleMaskLegal(Mask, ShuffleVT))
7328 return SDValue();
7330 // We can't handle more than two sources. This should have already
7331 // been checked before this point.
7332 assert(Sources.size() <= 2 && "Too many sources!");
7334 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7335 for (unsigned i = 0; i < Sources.size(); ++i)
7336 ShuffleOps[i] = Sources[i].ShuffleVec;
7338 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7339 ShuffleOps[1], Mask);
7340 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7343 enum ShuffleOpCodes {
7344 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7345 OP_VREV,
7346 OP_VDUP0,
7347 OP_VDUP1,
7348 OP_VDUP2,
7349 OP_VDUP3,
7350 OP_VEXT1,
7351 OP_VEXT2,
7352 OP_VEXT3,
7353 OP_VUZPL, // VUZP, left result
7354 OP_VUZPR, // VUZP, right result
7355 OP_VZIPL, // VZIP, left result
7356 OP_VZIPR, // VZIP, right result
7357 OP_VTRNL, // VTRN, left result
7358 OP_VTRNR // VTRN, right result
7361 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7362 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7363 switch (OpNum) {
7364 case OP_COPY:
7365 case OP_VREV:
7366 case OP_VDUP0:
7367 case OP_VDUP1:
7368 case OP_VDUP2:
7369 case OP_VDUP3:
7370 return true;
7372 return false;
7375 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7376 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7377 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7378 /// are assumed to be legal.
7379 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7380 if (VT.getVectorNumElements() == 4 &&
7381 (VT.is128BitVector() || VT.is64BitVector())) {
7382 unsigned PFIndexes[4];
7383 for (unsigned i = 0; i != 4; ++i) {
7384 if (M[i] < 0)
7385 PFIndexes[i] = 8;
7386 else
7387 PFIndexes[i] = M[i];
7390 // Compute the index in the perfect shuffle table.
7391 unsigned PFTableIndex =
7392 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7393 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7394 unsigned Cost = (PFEntry >> 30);
7396 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7397 return true;
7400 bool ReverseVEXT, isV_UNDEF;
7401 unsigned Imm, WhichResult;
7403 unsigned EltSize = VT.getScalarSizeInBits();
7404 if (EltSize >= 32 ||
7405 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7406 isVREVMask(M, VT, 64) ||
7407 isVREVMask(M, VT, 32) ||
7408 isVREVMask(M, VT, 16))
7409 return true;
7410 else if (Subtarget->hasNEON() &&
7411 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7412 isVTBLMask(M, VT) ||
7413 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7414 return true;
7415 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7416 isReverseMask(M, VT))
7417 return true;
7418 else
7419 return false;
7422 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7423 /// the specified operations to build the shuffle.
7424 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7425 SDValue RHS, SelectionDAG &DAG,
7426 const SDLoc &dl) {
7427 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7428 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7429 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7431 if (OpNum == OP_COPY) {
7432 if (LHSID == (1*9+2)*9+3) return LHS;
7433 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7434 return RHS;
7437 SDValue OpLHS, OpRHS;
7438 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7439 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7440 EVT VT = OpLHS.getValueType();
7442 switch (OpNum) {
7443 default: llvm_unreachable("Unknown shuffle opcode!");
7444 case OP_VREV:
7445 // VREV divides the vector in half and swaps within the half.
7446 if (VT.getVectorElementType() == MVT::i32 ||
7447 VT.getVectorElementType() == MVT::f32)
7448 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7449 // vrev <4 x i16> -> VREV32
7450 if (VT.getVectorElementType() == MVT::i16)
7451 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7452 // vrev <4 x i8> -> VREV16
7453 assert(VT.getVectorElementType() == MVT::i8);
7454 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7455 case OP_VDUP0:
7456 case OP_VDUP1:
7457 case OP_VDUP2:
7458 case OP_VDUP3:
7459 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7460 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7461 case OP_VEXT1:
7462 case OP_VEXT2:
7463 case OP_VEXT3:
7464 return DAG.getNode(ARMISD::VEXT, dl, VT,
7465 OpLHS, OpRHS,
7466 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7467 case OP_VUZPL:
7468 case OP_VUZPR:
7469 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7470 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7471 case OP_VZIPL:
7472 case OP_VZIPR:
7473 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7474 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7475 case OP_VTRNL:
7476 case OP_VTRNR:
7477 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7478 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7482 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7483 ArrayRef<int> ShuffleMask,
7484 SelectionDAG &DAG) {
7485 // Check to see if we can use the VTBL instruction.
7486 SDValue V1 = Op.getOperand(0);
7487 SDValue V2 = Op.getOperand(1);
7488 SDLoc DL(Op);
7490 SmallVector<SDValue, 8> VTBLMask;
7491 for (ArrayRef<int>::iterator
7492 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7493 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7495 if (V2.getNode()->isUndef())
7496 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7497 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7499 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7500 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7503 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7504 SelectionDAG &DAG) {
7505 SDLoc DL(Op);
7506 SDValue OpLHS = Op.getOperand(0);
7507 EVT VT = OpLHS.getValueType();
7509 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7510 "Expect an v8i16/v16i8 type");
7511 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7512 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7513 // extract the first 8 bytes into the top double word and the last 8 bytes
7514 // into the bottom double word. The v8i16 case is similar.
7515 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7516 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7517 DAG.getConstant(ExtractNum, DL, MVT::i32));
7520 static EVT getVectorTyFromPredicateVector(EVT VT) {
7521 switch (VT.getSimpleVT().SimpleTy) {
7522 case MVT::v4i1:
7523 return MVT::v4i32;
7524 case MVT::v8i1:
7525 return MVT::v8i16;
7526 case MVT::v16i1:
7527 return MVT::v16i8;
7528 default:
7529 llvm_unreachable("Unexpected vector predicate type");
7533 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7534 SelectionDAG &DAG) {
7535 // Converting from boolean predicates to integers involves creating a vector
7536 // of all ones or all zeroes and selecting the lanes based upon the real
7537 // predicate.
7538 SDValue AllOnes =
7539 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7540 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7542 SDValue AllZeroes =
7543 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7544 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7546 // Get full vector type from predicate type
7547 EVT NewVT = getVectorTyFromPredicateVector(VT);
7549 SDValue RecastV1;
7550 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7551 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7552 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7553 // since we know in hardware the sizes are really the same.
7554 if (VT != MVT::v16i1)
7555 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7556 else
7557 RecastV1 = Pred;
7559 // Select either all ones or zeroes depending upon the real predicate bits.
7560 SDValue PredAsVector =
7561 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7563 // Recast our new predicate-as-integer v16i8 vector into something
7564 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7565 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7568 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7569 const ARMSubtarget *ST) {
7570 EVT VT = Op.getValueType();
7571 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7572 ArrayRef<int> ShuffleMask = SVN->getMask();
7574 assert(ST->hasMVEIntegerOps() &&
7575 "No support for vector shuffle of boolean predicates");
7577 SDValue V1 = Op.getOperand(0);
7578 SDLoc dl(Op);
7579 if (isReverseMask(ShuffleMask, VT)) {
7580 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7581 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7582 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7583 DAG.getConstant(16, dl, MVT::i32));
7584 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7587 // Until we can come up with optimised cases for every single vector
7588 // shuffle in existence we have chosen the least painful strategy. This is
7589 // to essentially promote the boolean predicate to a 8-bit integer, where
7590 // each predicate represents a byte. Then we fall back on a normal integer
7591 // vector shuffle and convert the result back into a predicate vector. In
7592 // many cases the generated code might be even better than scalar code
7593 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7594 // fields in a register into 8 other arbitrary 2-bit fields!
7595 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7596 EVT NewVT = PredAsVector.getValueType();
7598 // Do the shuffle!
7599 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7600 DAG.getUNDEF(NewVT), ShuffleMask);
7602 // Now return the result of comparing the shuffled vector with zero,
7603 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7604 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7605 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7608 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7609 const ARMSubtarget *ST) {
7610 SDValue V1 = Op.getOperand(0);
7611 SDValue V2 = Op.getOperand(1);
7612 SDLoc dl(Op);
7613 EVT VT = Op.getValueType();
7614 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7615 unsigned EltSize = VT.getScalarSizeInBits();
7617 if (ST->hasMVEIntegerOps() && EltSize == 1)
7618 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7620 // Convert shuffles that are directly supported on NEON to target-specific
7621 // DAG nodes, instead of keeping them as shuffles and matching them again
7622 // during code selection. This is more efficient and avoids the possibility
7623 // of inconsistencies between legalization and selection.
7624 // FIXME: floating-point vectors should be canonicalized to integer vectors
7625 // of the same time so that they get CSEd properly.
7626 ArrayRef<int> ShuffleMask = SVN->getMask();
7628 if (EltSize <= 32) {
7629 if (SVN->isSplat()) {
7630 int Lane = SVN->getSplatIndex();
7631 // If this is undef splat, generate it via "just" vdup, if possible.
7632 if (Lane == -1) Lane = 0;
7634 // Test if V1 is a SCALAR_TO_VECTOR.
7635 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7636 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7638 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7639 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7640 // reaches it).
7641 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7642 !isa<ConstantSDNode>(V1.getOperand(0))) {
7643 bool IsScalarToVector = true;
7644 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7645 if (!V1.getOperand(i).isUndef()) {
7646 IsScalarToVector = false;
7647 break;
7649 if (IsScalarToVector)
7650 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7652 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7653 DAG.getConstant(Lane, dl, MVT::i32));
7656 bool ReverseVEXT = false;
7657 unsigned Imm = 0;
7658 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7659 if (ReverseVEXT)
7660 std::swap(V1, V2);
7661 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7662 DAG.getConstant(Imm, dl, MVT::i32));
7665 if (isVREVMask(ShuffleMask, VT, 64))
7666 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7667 if (isVREVMask(ShuffleMask, VT, 32))
7668 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7669 if (isVREVMask(ShuffleMask, VT, 16))
7670 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7672 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7673 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7674 DAG.getConstant(Imm, dl, MVT::i32));
7677 // Check for Neon shuffles that modify both input vectors in place.
7678 // If both results are used, i.e., if there are two shuffles with the same
7679 // source operands and with masks corresponding to both results of one of
7680 // these operations, DAG memoization will ensure that a single node is
7681 // used for both shuffles.
7682 unsigned WhichResult = 0;
7683 bool isV_UNDEF = false;
7684 if (ST->hasNEON()) {
7685 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7686 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7687 if (isV_UNDEF)
7688 V2 = V1;
7689 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7690 .getValue(WhichResult);
7694 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7695 // shuffles that produce a result larger than their operands with:
7696 // shuffle(concat(v1, undef), concat(v2, undef))
7697 // ->
7698 // shuffle(concat(v1, v2), undef)
7699 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7701 // This is useful in the general case, but there are special cases where
7702 // native shuffles produce larger results: the two-result ops.
7704 // Look through the concat when lowering them:
7705 // shuffle(concat(v1, v2), undef)
7706 // ->
7707 // concat(VZIP(v1, v2):0, :1)
7709 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7710 SDValue SubV1 = V1->getOperand(0);
7711 SDValue SubV2 = V1->getOperand(1);
7712 EVT SubVT = SubV1.getValueType();
7714 // We expect these to have been canonicalized to -1.
7715 assert(llvm::all_of(ShuffleMask, [&](int i) {
7716 return i < (int)VT.getVectorNumElements();
7717 }) && "Unexpected shuffle index into UNDEF operand!");
7719 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7720 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7721 if (isV_UNDEF)
7722 SubV2 = SubV1;
7723 assert((WhichResult == 0) &&
7724 "In-place shuffle of concat can only have one result!");
7725 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7726 SubV1, SubV2);
7727 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7728 Res.getValue(1));
7733 // If the shuffle is not directly supported and it has 4 elements, use
7734 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7735 unsigned NumElts = VT.getVectorNumElements();
7736 if (NumElts == 4) {
7737 unsigned PFIndexes[4];
7738 for (unsigned i = 0; i != 4; ++i) {
7739 if (ShuffleMask[i] < 0)
7740 PFIndexes[i] = 8;
7741 else
7742 PFIndexes[i] = ShuffleMask[i];
7745 // Compute the index in the perfect shuffle table.
7746 unsigned PFTableIndex =
7747 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7748 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7749 unsigned Cost = (PFEntry >> 30);
7751 if (Cost <= 4) {
7752 if (ST->hasNEON())
7753 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7754 else if (isLegalMVEShuffleOp(PFEntry)) {
7755 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7756 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7757 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7758 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7759 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7760 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7765 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7766 if (EltSize >= 32) {
7767 // Do the expansion with floating-point types, since that is what the VFP
7768 // registers are defined to use, and since i64 is not legal.
7769 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7770 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7771 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7772 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7773 SmallVector<SDValue, 8> Ops;
7774 for (unsigned i = 0; i < NumElts; ++i) {
7775 if (ShuffleMask[i] < 0)
7776 Ops.push_back(DAG.getUNDEF(EltVT));
7777 else
7778 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7779 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7780 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7781 dl, MVT::i32)));
7783 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7784 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7787 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7788 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7790 if (ST->hasNEON() && VT == MVT::v8i8)
7791 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7792 return NewOp;
7794 return SDValue();
7797 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7798 const ARMSubtarget *ST) {
7799 EVT VecVT = Op.getOperand(0).getValueType();
7800 SDLoc dl(Op);
7802 assert(ST->hasMVEIntegerOps() &&
7803 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7805 SDValue Conv =
7806 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7807 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7808 unsigned LaneWidth =
7809 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7810 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7811 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7812 Op.getOperand(1), DAG.getValueType(MVT::i1));
7813 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7814 DAG.getConstant(~Mask, dl, MVT::i32));
7815 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7818 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7819 SelectionDAG &DAG) const {
7820 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7821 SDValue Lane = Op.getOperand(2);
7822 if (!isa<ConstantSDNode>(Lane))
7823 return SDValue();
7825 SDValue Elt = Op.getOperand(1);
7826 EVT EltVT = Elt.getValueType();
7828 if (Subtarget->hasMVEIntegerOps() &&
7829 Op.getValueType().getScalarSizeInBits() == 1)
7830 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7832 if (getTypeAction(*DAG.getContext(), EltVT) ==
7833 TargetLowering::TypePromoteFloat) {
7834 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7835 // but the type system will try to do that if we don't intervene.
7836 // Reinterpret any such vector-element insertion as one with the
7837 // corresponding integer types.
7839 SDLoc dl(Op);
7841 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7842 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7843 TargetLowering::TypePromoteFloat);
7845 SDValue VecIn = Op.getOperand(0);
7846 EVT VecVT = VecIn.getValueType();
7847 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7848 VecVT.getVectorNumElements());
7850 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7851 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7852 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7853 IVecIn, IElt, Lane);
7854 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
7857 return Op;
7860 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7861 const ARMSubtarget *ST) {
7862 EVT VecVT = Op.getOperand(0).getValueType();
7863 SDLoc dl(Op);
7865 assert(ST->hasMVEIntegerOps() &&
7866 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7868 SDValue Conv =
7869 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7870 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7871 unsigned LaneWidth =
7872 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7873 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
7874 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
7875 return Shift;
7878 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
7879 const ARMSubtarget *ST) {
7880 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7881 SDValue Lane = Op.getOperand(1);
7882 if (!isa<ConstantSDNode>(Lane))
7883 return SDValue();
7885 SDValue Vec = Op.getOperand(0);
7886 EVT VT = Vec.getValueType();
7888 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7889 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
7891 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7892 SDLoc dl(Op);
7893 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7896 return Op;
7899 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
7900 const ARMSubtarget *ST) {
7901 SDValue V1 = Op.getOperand(0);
7902 SDValue V2 = Op.getOperand(1);
7903 SDLoc dl(Op);
7904 EVT VT = Op.getValueType();
7905 EVT Op1VT = V1.getValueType();
7906 EVT Op2VT = V2.getValueType();
7907 unsigned NumElts = VT.getVectorNumElements();
7909 assert(Op1VT == Op2VT && "Operand types don't match!");
7910 assert(VT.getScalarSizeInBits() == 1 &&
7911 "Unexpected custom CONCAT_VECTORS lowering");
7912 assert(ST->hasMVEIntegerOps() &&
7913 "CONCAT_VECTORS lowering only supported for MVE");
7915 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7916 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
7918 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
7919 // promoted to v8i16, etc.
7921 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7923 // Extract the vector elements from Op1 and Op2 one by one and truncate them
7924 // to be the right size for the destination. For example, if Op1 is v4i1 then
7925 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
7926 // which when promoted is v8i16. That means each i32 element from Op1 needs
7927 // truncating to i16 and inserting in the result.
7928 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
7929 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
7930 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
7931 EVT NewVT = NewV.getValueType();
7932 EVT ConcatVT = ConVec.getValueType();
7933 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
7934 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
7935 DAG.getIntPtrConstant(i, dl));
7936 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
7937 DAG.getConstant(j, dl, MVT::i32));
7939 return ConVec;
7941 unsigned j = 0;
7942 ConVec = ExractInto(NewV1, ConVec, j);
7943 ConVec = ExractInto(NewV2, ConVec, j);
7945 // Now return the result of comparing the subvector with zero,
7946 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7947 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
7948 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7951 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
7952 const ARMSubtarget *ST) {
7953 EVT VT = Op->getValueType(0);
7954 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7955 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
7957 // The only time a CONCAT_VECTORS operation can have legal types is when
7958 // two 64-bit vectors are concatenated to a 128-bit vector.
7959 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7960 "unexpected CONCAT_VECTORS");
7961 SDLoc dl(Op);
7962 SDValue Val = DAG.getUNDEF(MVT::v2f64);
7963 SDValue Op0 = Op.getOperand(0);
7964 SDValue Op1 = Op.getOperand(1);
7965 if (!Op0.isUndef())
7966 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7967 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7968 DAG.getIntPtrConstant(0, dl));
7969 if (!Op1.isUndef())
7970 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7971 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7972 DAG.getIntPtrConstant(1, dl));
7973 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7976 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
7977 const ARMSubtarget *ST) {
7978 SDValue V1 = Op.getOperand(0);
7979 SDValue V2 = Op.getOperand(1);
7980 SDLoc dl(Op);
7981 EVT VT = Op.getValueType();
7982 EVT Op1VT = V1.getValueType();
7983 unsigned NumElts = VT.getVectorNumElements();
7984 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
7986 assert(VT.getScalarSizeInBits() == 1 &&
7987 "Unexpected custom EXTRACT_SUBVECTOR lowering");
7988 assert(ST->hasMVEIntegerOps() &&
7989 "EXTRACT_SUBVECTOR lowering only supported for MVE");
7991 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7993 // We now have Op1 promoted to a vector of integers, where v8i1 gets
7994 // promoted to v8i16, etc.
7996 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7998 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
7999 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8000 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8001 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8002 DAG.getIntPtrConstant(i, dl));
8003 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8004 DAG.getConstant(j, dl, MVT::i32));
8007 // Now return the result of comparing the subvector with zero,
8008 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8009 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8010 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8013 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8014 /// element has been zero/sign-extended, depending on the isSigned parameter,
8015 /// from an integer type half its size.
8016 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8017 bool isSigned) {
8018 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8019 EVT VT = N->getValueType(0);
8020 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8021 SDNode *BVN = N->getOperand(0).getNode();
8022 if (BVN->getValueType(0) != MVT::v4i32 ||
8023 BVN->getOpcode() != ISD::BUILD_VECTOR)
8024 return false;
8025 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8026 unsigned HiElt = 1 - LoElt;
8027 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8028 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8029 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8030 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8031 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8032 return false;
8033 if (isSigned) {
8034 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8035 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8036 return true;
8037 } else {
8038 if (Hi0->isNullValue() && Hi1->isNullValue())
8039 return true;
8041 return false;
8044 if (N->getOpcode() != ISD::BUILD_VECTOR)
8045 return false;
8047 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8048 SDNode *Elt = N->getOperand(i).getNode();
8049 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8050 unsigned EltSize = VT.getScalarSizeInBits();
8051 unsigned HalfSize = EltSize / 2;
8052 if (isSigned) {
8053 if (!isIntN(HalfSize, C->getSExtValue()))
8054 return false;
8055 } else {
8056 if (!isUIntN(HalfSize, C->getZExtValue()))
8057 return false;
8059 continue;
8061 return false;
8064 return true;
8067 /// isSignExtended - Check if a node is a vector value that is sign-extended
8068 /// or a constant BUILD_VECTOR with sign-extended elements.
8069 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8070 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8071 return true;
8072 if (isExtendedBUILD_VECTOR(N, DAG, true))
8073 return true;
8074 return false;
8077 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8078 /// or a constant BUILD_VECTOR with zero-extended elements.
8079 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8080 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8081 return true;
8082 if (isExtendedBUILD_VECTOR(N, DAG, false))
8083 return true;
8084 return false;
8087 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8088 if (OrigVT.getSizeInBits() >= 64)
8089 return OrigVT;
8091 assert(OrigVT.isSimple() && "Expecting a simple value type");
8093 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8094 switch (OrigSimpleTy) {
8095 default: llvm_unreachable("Unexpected Vector Type");
8096 case MVT::v2i8:
8097 case MVT::v2i16:
8098 return MVT::v2i32;
8099 case MVT::v4i8:
8100 return MVT::v4i16;
8104 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8105 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8106 /// We insert the required extension here to get the vector to fill a D register.
8107 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8108 const EVT &OrigTy,
8109 const EVT &ExtTy,
8110 unsigned ExtOpcode) {
8111 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8112 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8113 // 64-bits we need to insert a new extension so that it will be 64-bits.
8114 assert(ExtTy.is128BitVector() && "Unexpected extension size");
8115 if (OrigTy.getSizeInBits() >= 64)
8116 return N;
8118 // Must extend size to at least 64 bits to be used as an operand for VMULL.
8119 EVT NewVT = getExtensionTo64Bits(OrigTy);
8121 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8124 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8125 /// does not do any sign/zero extension. If the original vector is less
8126 /// than 64 bits, an appropriate extension will be added after the load to
8127 /// reach a total size of 64 bits. We have to add the extension separately
8128 /// because ARM does not have a sign/zero extending load for vectors.
8129 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8130 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8132 // The load already has the right type.
8133 if (ExtendedTy == LD->getMemoryVT())
8134 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8135 LD->getBasePtr(), LD->getPointerInfo(),
8136 LD->getAlignment(), LD->getMemOperand()->getFlags());
8138 // We need to create a zextload/sextload. We cannot just create a load
8139 // followed by a zext/zext node because LowerMUL is also run during normal
8140 // operation legalization where we can't create illegal types.
8141 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8142 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8143 LD->getMemoryVT(), LD->getAlignment(),
8144 LD->getMemOperand()->getFlags());
8147 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8148 /// extending load, or BUILD_VECTOR with extended elements, return the
8149 /// unextended value. The unextended vector should be 64 bits so that it can
8150 /// be used as an operand to a VMULL instruction. If the original vector size
8151 /// before extension is less than 64 bits we add a an extension to resize
8152 /// the vector to 64 bits.
8153 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8154 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8155 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8156 N->getOperand(0)->getValueType(0),
8157 N->getValueType(0),
8158 N->getOpcode());
8160 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8161 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8162 "Expected extending load");
8164 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8165 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8166 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8167 SDValue extLoad =
8168 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8169 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8171 return newLoad;
8174 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8175 // have been legalized as a BITCAST from v4i32.
8176 if (N->getOpcode() == ISD::BITCAST) {
8177 SDNode *BVN = N->getOperand(0).getNode();
8178 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8179 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8180 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8181 return DAG.getBuildVector(
8182 MVT::v2i32, SDLoc(N),
8183 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8185 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8186 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8187 EVT VT = N->getValueType(0);
8188 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8189 unsigned NumElts = VT.getVectorNumElements();
8190 MVT TruncVT = MVT::getIntegerVT(EltSize);
8191 SmallVector<SDValue, 8> Ops;
8192 SDLoc dl(N);
8193 for (unsigned i = 0; i != NumElts; ++i) {
8194 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8195 const APInt &CInt = C->getAPIntValue();
8196 // Element types smaller than 32 bits are not legal, so use i32 elements.
8197 // The values are implicitly truncated so sext vs. zext doesn't matter.
8198 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8200 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8203 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8204 unsigned Opcode = N->getOpcode();
8205 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8206 SDNode *N0 = N->getOperand(0).getNode();
8207 SDNode *N1 = N->getOperand(1).getNode();
8208 return N0->hasOneUse() && N1->hasOneUse() &&
8209 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8211 return false;
8214 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8215 unsigned Opcode = N->getOpcode();
8216 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8217 SDNode *N0 = N->getOperand(0).getNode();
8218 SDNode *N1 = N->getOperand(1).getNode();
8219 return N0->hasOneUse() && N1->hasOneUse() &&
8220 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8222 return false;
8225 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8226 // Multiplications are only custom-lowered for 128-bit vectors so that
8227 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8228 EVT VT = Op.getValueType();
8229 assert(VT.is128BitVector() && VT.isInteger() &&
8230 "unexpected type for custom-lowering ISD::MUL");
8231 SDNode *N0 = Op.getOperand(0).getNode();
8232 SDNode *N1 = Op.getOperand(1).getNode();
8233 unsigned NewOpc = 0;
8234 bool isMLA = false;
8235 bool isN0SExt = isSignExtended(N0, DAG);
8236 bool isN1SExt = isSignExtended(N1, DAG);
8237 if (isN0SExt && isN1SExt)
8238 NewOpc = ARMISD::VMULLs;
8239 else {
8240 bool isN0ZExt = isZeroExtended(N0, DAG);
8241 bool isN1ZExt = isZeroExtended(N1, DAG);
8242 if (isN0ZExt && isN1ZExt)
8243 NewOpc = ARMISD::VMULLu;
8244 else if (isN1SExt || isN1ZExt) {
8245 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8246 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8247 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8248 NewOpc = ARMISD::VMULLs;
8249 isMLA = true;
8250 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8251 NewOpc = ARMISD::VMULLu;
8252 isMLA = true;
8253 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8254 std::swap(N0, N1);
8255 NewOpc = ARMISD::VMULLu;
8256 isMLA = true;
8260 if (!NewOpc) {
8261 if (VT == MVT::v2i64)
8262 // Fall through to expand this. It is not legal.
8263 return SDValue();
8264 else
8265 // Other vector multiplications are legal.
8266 return Op;
8270 // Legalize to a VMULL instruction.
8271 SDLoc DL(Op);
8272 SDValue Op0;
8273 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8274 if (!isMLA) {
8275 Op0 = SkipExtensionForVMULL(N0, DAG);
8276 assert(Op0.getValueType().is64BitVector() &&
8277 Op1.getValueType().is64BitVector() &&
8278 "unexpected types for extended operands to VMULL");
8279 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8282 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8283 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8284 // vmull q0, d4, d6
8285 // vmlal q0, d5, d6
8286 // is faster than
8287 // vaddl q0, d4, d5
8288 // vmovl q1, d6
8289 // vmul q0, q0, q1
8290 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8291 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8292 EVT Op1VT = Op1.getValueType();
8293 return DAG.getNode(N0->getOpcode(), DL, VT,
8294 DAG.getNode(NewOpc, DL, VT,
8295 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8296 DAG.getNode(NewOpc, DL, VT,
8297 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8300 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8301 SelectionDAG &DAG) {
8302 // TODO: Should this propagate fast-math-flags?
8304 // Convert to float
8305 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8306 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8307 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8308 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8309 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8310 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8311 // Get reciprocal estimate.
8312 // float4 recip = vrecpeq_f32(yf);
8313 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8314 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8316 // Because char has a smaller range than uchar, we can actually get away
8317 // without any newton steps. This requires that we use a weird bias
8318 // of 0xb000, however (again, this has been exhaustively tested).
8319 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8320 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8321 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8322 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8323 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8324 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8325 // Convert back to short.
8326 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8327 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8328 return X;
8331 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8332 SelectionDAG &DAG) {
8333 // TODO: Should this propagate fast-math-flags?
8335 SDValue N2;
8336 // Convert to float.
8337 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8338 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8339 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8340 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8341 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8342 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8344 // Use reciprocal estimate and one refinement step.
8345 // float4 recip = vrecpeq_f32(yf);
8346 // recip *= vrecpsq_f32(yf, recip);
8347 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8348 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8349 N1);
8350 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8351 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8352 N1, N2);
8353 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8354 // Because short has a smaller range than ushort, we can actually get away
8355 // with only a single newton step. This requires that we use a weird bias
8356 // of 89, however (again, this has been exhaustively tested).
8357 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8358 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8359 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8360 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8361 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8362 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8363 // Convert back to integer and return.
8364 // return vmovn_s32(vcvt_s32_f32(result));
8365 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8366 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8367 return N0;
8370 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8371 const ARMSubtarget *ST) {
8372 EVT VT = Op.getValueType();
8373 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8374 "unexpected type for custom-lowering ISD::SDIV");
8376 SDLoc dl(Op);
8377 SDValue N0 = Op.getOperand(0);
8378 SDValue N1 = Op.getOperand(1);
8379 SDValue N2, N3;
8381 if (VT == MVT::v8i8) {
8382 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8383 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8385 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8386 DAG.getIntPtrConstant(4, dl));
8387 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8388 DAG.getIntPtrConstant(4, dl));
8389 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8390 DAG.getIntPtrConstant(0, dl));
8391 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8392 DAG.getIntPtrConstant(0, dl));
8394 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8395 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8397 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8398 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8400 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8401 return N0;
8403 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8406 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8407 const ARMSubtarget *ST) {
8408 // TODO: Should this propagate fast-math-flags?
8409 EVT VT = Op.getValueType();
8410 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8411 "unexpected type for custom-lowering ISD::UDIV");
8413 SDLoc dl(Op);
8414 SDValue N0 = Op.getOperand(0);
8415 SDValue N1 = Op.getOperand(1);
8416 SDValue N2, N3;
8418 if (VT == MVT::v8i8) {
8419 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8420 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8422 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8423 DAG.getIntPtrConstant(4, dl));
8424 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8425 DAG.getIntPtrConstant(4, dl));
8426 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8427 DAG.getIntPtrConstant(0, dl));
8428 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8429 DAG.getIntPtrConstant(0, dl));
8431 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8432 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8434 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8435 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8437 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8438 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8439 MVT::i32),
8440 N0);
8441 return N0;
8444 // v4i16 sdiv ... Convert to float.
8445 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8446 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8447 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8448 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8449 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8450 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8452 // Use reciprocal estimate and two refinement steps.
8453 // float4 recip = vrecpeq_f32(yf);
8454 // recip *= vrecpsq_f32(yf, recip);
8455 // recip *= vrecpsq_f32(yf, recip);
8456 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8457 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8458 BN1);
8459 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8460 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8461 BN1, N2);
8462 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8463 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8464 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8465 BN1, N2);
8466 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8467 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8468 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8469 // and that it will never cause us to return an answer too large).
8470 // float4 result = as_float4(as_int4(xf*recip) + 2);
8471 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8472 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8473 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8474 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8475 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8476 // Convert back to integer and return.
8477 // return vmovn_u32(vcvt_s32_f32(result));
8478 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8479 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8480 return N0;
8483 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8484 SDNode *N = Op.getNode();
8485 EVT VT = N->getValueType(0);
8486 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8488 SDValue Carry = Op.getOperand(2);
8490 SDLoc DL(Op);
8492 SDValue Result;
8493 if (Op.getOpcode() == ISD::ADDCARRY) {
8494 // This converts the boolean value carry into the carry flag.
8495 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8497 // Do the addition proper using the carry flag we wanted.
8498 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8499 Op.getOperand(1), Carry);
8501 // Now convert the carry flag into a boolean value.
8502 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8503 } else {
8504 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8505 // have to invert the carry first.
8506 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8507 DAG.getConstant(1, DL, MVT::i32), Carry);
8508 // This converts the boolean value carry into the carry flag.
8509 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8511 // Do the subtraction proper using the carry flag we wanted.
8512 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8513 Op.getOperand(1), Carry);
8515 // Now convert the carry flag into a boolean value.
8516 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8517 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8518 // by ISD::SUBCARRY, so compute 1 - C.
8519 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8520 DAG.getConstant(1, DL, MVT::i32), Carry);
8523 // Return both values.
8524 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8527 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8528 assert(Subtarget->isTargetDarwin());
8530 // For iOS, we want to call an alternative entry point: __sincos_stret,
8531 // return values are passed via sret.
8532 SDLoc dl(Op);
8533 SDValue Arg = Op.getOperand(0);
8534 EVT ArgVT = Arg.getValueType();
8535 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8536 auto PtrVT = getPointerTy(DAG.getDataLayout());
8538 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8539 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8541 // Pair of floats / doubles used to pass the result.
8542 Type *RetTy = StructType::get(ArgTy, ArgTy);
8543 auto &DL = DAG.getDataLayout();
8545 ArgListTy Args;
8546 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8547 SDValue SRet;
8548 if (ShouldUseSRet) {
8549 // Create stack object for sret.
8550 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8551 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8552 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8553 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8555 ArgListEntry Entry;
8556 Entry.Node = SRet;
8557 Entry.Ty = RetTy->getPointerTo();
8558 Entry.IsSExt = false;
8559 Entry.IsZExt = false;
8560 Entry.IsSRet = true;
8561 Args.push_back(Entry);
8562 RetTy = Type::getVoidTy(*DAG.getContext());
8565 ArgListEntry Entry;
8566 Entry.Node = Arg;
8567 Entry.Ty = ArgTy;
8568 Entry.IsSExt = false;
8569 Entry.IsZExt = false;
8570 Args.push_back(Entry);
8572 RTLIB::Libcall LC =
8573 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8574 const char *LibcallName = getLibcallName(LC);
8575 CallingConv::ID CC = getLibcallCallingConv(LC);
8576 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8578 TargetLowering::CallLoweringInfo CLI(DAG);
8579 CLI.setDebugLoc(dl)
8580 .setChain(DAG.getEntryNode())
8581 .setCallee(CC, RetTy, Callee, std::move(Args))
8582 .setDiscardResult(ShouldUseSRet);
8583 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8585 if (!ShouldUseSRet)
8586 return CallResult.first;
8588 SDValue LoadSin =
8589 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8591 // Address of cos field.
8592 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8593 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8594 SDValue LoadCos =
8595 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8597 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8598 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8599 LoadSin.getValue(0), LoadCos.getValue(0));
8602 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8603 bool Signed,
8604 SDValue &Chain) const {
8605 EVT VT = Op.getValueType();
8606 assert((VT == MVT::i32 || VT == MVT::i64) &&
8607 "unexpected type for custom lowering DIV");
8608 SDLoc dl(Op);
8610 const auto &DL = DAG.getDataLayout();
8611 const auto &TLI = DAG.getTargetLoweringInfo();
8613 const char *Name = nullptr;
8614 if (Signed)
8615 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8616 else
8617 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8619 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8621 ARMTargetLowering::ArgListTy Args;
8623 for (auto AI : {1, 0}) {
8624 ArgListEntry Arg;
8625 Arg.Node = Op.getOperand(AI);
8626 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8627 Args.push_back(Arg);
8630 CallLoweringInfo CLI(DAG);
8631 CLI.setDebugLoc(dl)
8632 .setChain(Chain)
8633 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8634 ES, std::move(Args));
8636 return LowerCallTo(CLI).first;
8639 // This is a code size optimisation: return the original SDIV node to
8640 // DAGCombiner when we don't want to expand SDIV into a sequence of
8641 // instructions, and an empty node otherwise which will cause the
8642 // SDIV to be expanded in DAGCombine.
8643 SDValue
8644 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8645 SelectionDAG &DAG,
8646 SmallVectorImpl<SDNode *> &Created) const {
8647 // TODO: Support SREM
8648 if (N->getOpcode() != ISD::SDIV)
8649 return SDValue();
8651 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8652 const bool MinSize = ST.hasMinSize();
8653 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8654 : ST.hasDivideInARMMode();
8656 // Don't touch vector types; rewriting this may lead to scalarizing
8657 // the int divs.
8658 if (N->getOperand(0).getValueType().isVector())
8659 return SDValue();
8661 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8662 // hwdiv support for this to be really profitable.
8663 if (!(MinSize && HasDivide))
8664 return SDValue();
8666 // ARM mode is a bit simpler than Thumb: we can handle large power
8667 // of 2 immediates with 1 mov instruction; no further checks required,
8668 // just return the sdiv node.
8669 if (!ST.isThumb())
8670 return SDValue(N, 0);
8672 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8673 // and thus lose the code size benefits of a MOVS that requires only 2.
8674 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8675 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8676 if (Divisor.sgt(128))
8677 return SDValue();
8679 return SDValue(N, 0);
8682 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8683 bool Signed) const {
8684 assert(Op.getValueType() == MVT::i32 &&
8685 "unexpected type for custom lowering DIV");
8686 SDLoc dl(Op);
8688 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8689 DAG.getEntryNode(), Op.getOperand(1));
8691 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8694 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8695 SDLoc DL(N);
8696 SDValue Op = N->getOperand(1);
8697 if (N->getValueType(0) == MVT::i32)
8698 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8699 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8700 DAG.getConstant(0, DL, MVT::i32));
8701 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8702 DAG.getConstant(1, DL, MVT::i32));
8703 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8704 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8707 void ARMTargetLowering::ExpandDIV_Windows(
8708 SDValue Op, SelectionDAG &DAG, bool Signed,
8709 SmallVectorImpl<SDValue> &Results) const {
8710 const auto &DL = DAG.getDataLayout();
8711 const auto &TLI = DAG.getTargetLoweringInfo();
8713 assert(Op.getValueType() == MVT::i64 &&
8714 "unexpected type for custom lowering DIV");
8715 SDLoc dl(Op);
8717 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8719 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8721 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8722 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8723 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8724 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8726 Results.push_back(Lower);
8727 Results.push_back(Upper);
8730 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8731 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8732 // Acquire/Release load/store is not legal for targets without a dmb or
8733 // equivalent available.
8734 return SDValue();
8736 // Monotonic load/store is legal for all targets.
8737 return Op;
8740 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8741 SmallVectorImpl<SDValue> &Results,
8742 SelectionDAG &DAG,
8743 const ARMSubtarget *Subtarget) {
8744 SDLoc DL(N);
8745 // Under Power Management extensions, the cycle-count is:
8746 // mrc p15, #0, <Rt>, c9, c13, #0
8747 SDValue Ops[] = { N->getOperand(0), // Chain
8748 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8749 DAG.getConstant(15, DL, MVT::i32),
8750 DAG.getConstant(0, DL, MVT::i32),
8751 DAG.getConstant(9, DL, MVT::i32),
8752 DAG.getConstant(13, DL, MVT::i32),
8753 DAG.getConstant(0, DL, MVT::i32)
8756 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8757 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8758 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8759 DAG.getConstant(0, DL, MVT::i32)));
8760 Results.push_back(Cycles32.getValue(1));
8763 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8764 SDLoc dl(V.getNode());
8765 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
8766 SDValue VHi = DAG.getAnyExtOrTrunc(
8767 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
8768 dl, MVT::i32);
8769 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8770 if (isBigEndian)
8771 std::swap (VLo, VHi);
8772 SDValue RegClass =
8773 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
8774 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
8775 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
8776 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
8777 return SDValue(
8778 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
8781 static void ReplaceCMP_SWAP_64Results(SDNode *N,
8782 SmallVectorImpl<SDValue> & Results,
8783 SelectionDAG &DAG) {
8784 assert(N->getValueType(0) == MVT::i64 &&
8785 "AtomicCmpSwap on types less than 64 should be legal");
8786 SDValue Ops[] = {N->getOperand(1),
8787 createGPRPairNode(DAG, N->getOperand(2)),
8788 createGPRPairNode(DAG, N->getOperand(3)),
8789 N->getOperand(0)};
8790 SDNode *CmpSwap = DAG.getMachineNode(
8791 ARM::CMP_SWAP_64, SDLoc(N),
8792 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
8794 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
8795 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8797 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8799 Results.push_back(
8800 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8801 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8802 Results.push_back(
8803 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8804 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8805 Results.push_back(SDValue(CmpSwap, 2));
8808 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8809 SelectionDAG &DAG) {
8810 const auto &TLI = DAG.getTargetLoweringInfo();
8812 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8813 "Custom lowering is MSVCRT specific!");
8815 SDLoc dl(Op);
8816 SDValue Val = Op.getOperand(0);
8817 MVT Ty = Val->getSimpleValueType(0);
8818 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8819 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8820 TLI.getPointerTy(DAG.getDataLayout()));
8822 TargetLowering::ArgListTy Args;
8823 TargetLowering::ArgListEntry Entry;
8825 Entry.Node = Val;
8826 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8827 Entry.IsZExt = true;
8828 Args.push_back(Entry);
8830 Entry.Node = Exponent;
8831 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8832 Entry.IsZExt = true;
8833 Args.push_back(Entry);
8835 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8837 // In the in-chain to the call is the entry node If we are emitting a
8838 // tailcall, the chain will be mutated if the node has a non-entry input
8839 // chain.
8840 SDValue InChain = DAG.getEntryNode();
8841 SDValue TCChain = InChain;
8843 const Function &F = DAG.getMachineFunction().getFunction();
8844 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8845 F.getReturnType() == LCRTy;
8846 if (IsTC)
8847 InChain = TCChain;
8849 TargetLowering::CallLoweringInfo CLI(DAG);
8850 CLI.setDebugLoc(dl)
8851 .setChain(InChain)
8852 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8853 .setTailCall(IsTC);
8854 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8856 // Return the chain (the DAG root) if it is a tail call
8857 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8860 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8861 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8862 switch (Op.getOpcode()) {
8863 default: llvm_unreachable("Don't know how to custom lower this!");
8864 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8865 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8866 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8867 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8868 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8869 case ISD::SELECT: return LowerSELECT(Op, DAG);
8870 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8871 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8872 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
8873 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
8874 case ISD::VASTART: return LowerVASTART(Op, DAG);
8875 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8876 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
8877 case ISD::SINT_TO_FP:
8878 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8879 case ISD::FP_TO_SINT:
8880 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
8881 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8882 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8883 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8884 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8885 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8886 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8887 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
8888 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8889 Subtarget);
8890 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8891 case ISD::SHL:
8892 case ISD::SRL:
8893 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
8894 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
8895 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
8896 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
8897 case ISD::SRL_PARTS:
8898 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
8899 case ISD::CTTZ:
8900 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8901 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8902 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
8903 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
8904 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
8905 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8906 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
8907 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
8908 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8909 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
8910 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
8911 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8912 case ISD::MUL: return LowerMUL(Op, DAG);
8913 case ISD::SDIV:
8914 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8915 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8916 return LowerSDIV(Op, DAG, Subtarget);
8917 case ISD::UDIV:
8918 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8919 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8920 return LowerUDIV(Op, DAG, Subtarget);
8921 case ISD::ADDCARRY:
8922 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
8923 case ISD::SADDO:
8924 case ISD::SSUBO:
8925 return LowerSignedALUO(Op, DAG);
8926 case ISD::UADDO:
8927 case ISD::USUBO:
8928 return LowerUnsignedALUO(Op, DAG);
8929 case ISD::ATOMIC_LOAD:
8930 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
8931 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
8932 case ISD::SDIVREM:
8933 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
8934 case ISD::DYNAMIC_STACKALLOC:
8935 if (Subtarget->isTargetWindows())
8936 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8937 llvm_unreachable("Don't know how to custom lower this!");
8938 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8939 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8940 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8941 case ARMISD::WIN__DBZCHK: return SDValue();
8945 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8946 SelectionDAG &DAG) {
8947 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8948 unsigned Opc = 0;
8949 if (IntNo == Intrinsic::arm_smlald)
8950 Opc = ARMISD::SMLALD;
8951 else if (IntNo == Intrinsic::arm_smlaldx)
8952 Opc = ARMISD::SMLALDX;
8953 else if (IntNo == Intrinsic::arm_smlsld)
8954 Opc = ARMISD::SMLSLD;
8955 else if (IntNo == Intrinsic::arm_smlsldx)
8956 Opc = ARMISD::SMLSLDX;
8957 else
8958 return;
8960 SDLoc dl(N);
8961 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8962 N->getOperand(3),
8963 DAG.getConstant(0, dl, MVT::i32));
8964 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8965 N->getOperand(3),
8966 DAG.getConstant(1, dl, MVT::i32));
8968 SDValue LongMul = DAG.getNode(Opc, dl,
8969 DAG.getVTList(MVT::i32, MVT::i32),
8970 N->getOperand(1), N->getOperand(2),
8971 Lo, Hi);
8972 Results.push_back(LongMul.getValue(0));
8973 Results.push_back(LongMul.getValue(1));
8976 /// ReplaceNodeResults - Replace the results of node with an illegal result
8977 /// type with new values built out of custom code.
8978 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8979 SmallVectorImpl<SDValue> &Results,
8980 SelectionDAG &DAG) const {
8981 SDValue Res;
8982 switch (N->getOpcode()) {
8983 default:
8984 llvm_unreachable("Don't know how to custom expand this!");
8985 case ISD::READ_REGISTER:
8986 ExpandREAD_REGISTER(N, Results, DAG);
8987 break;
8988 case ISD::BITCAST:
8989 Res = ExpandBITCAST(N, DAG, Subtarget);
8990 break;
8991 case ISD::SRL:
8992 case ISD::SRA:
8993 case ISD::SHL:
8994 Res = Expand64BitShift(N, DAG, Subtarget);
8995 break;
8996 case ISD::SREM:
8997 case ISD::UREM:
8998 Res = LowerREM(N, DAG);
8999 break;
9000 case ISD::SDIVREM:
9001 case ISD::UDIVREM:
9002 Res = LowerDivRem(SDValue(N, 0), DAG);
9003 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9004 Results.push_back(Res.getValue(0));
9005 Results.push_back(Res.getValue(1));
9006 return;
9007 case ISD::READCYCLECOUNTER:
9008 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9009 return;
9010 case ISD::UDIV:
9011 case ISD::SDIV:
9012 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9013 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9014 Results);
9015 case ISD::ATOMIC_CMP_SWAP:
9016 ReplaceCMP_SWAP_64Results(N, Results, DAG);
9017 return;
9018 case ISD::INTRINSIC_WO_CHAIN:
9019 return ReplaceLongIntrinsic(N, Results, DAG);
9020 case ISD::ABS:
9021 lowerABS(N, Results, DAG);
9022 return ;
9025 if (Res.getNode())
9026 Results.push_back(Res);
9029 //===----------------------------------------------------------------------===//
9030 // ARM Scheduler Hooks
9031 //===----------------------------------------------------------------------===//
9033 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9034 /// registers the function context.
9035 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9036 MachineBasicBlock *MBB,
9037 MachineBasicBlock *DispatchBB,
9038 int FI) const {
9039 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9040 "ROPI/RWPI not currently supported with SjLj");
9041 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9042 DebugLoc dl = MI.getDebugLoc();
9043 MachineFunction *MF = MBB->getParent();
9044 MachineRegisterInfo *MRI = &MF->getRegInfo();
9045 MachineConstantPool *MCP = MF->getConstantPool();
9046 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9047 const Function &F = MF->getFunction();
9049 bool isThumb = Subtarget->isThumb();
9050 bool isThumb2 = Subtarget->isThumb2();
9052 unsigned PCLabelId = AFI->createPICLabelUId();
9053 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9054 ARMConstantPoolValue *CPV =
9055 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9056 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9058 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9059 : &ARM::GPRRegClass;
9061 // Grab constant pool and fixed stack memory operands.
9062 MachineMemOperand *CPMMO =
9063 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9064 MachineMemOperand::MOLoad, 4, 4);
9066 MachineMemOperand *FIMMOSt =
9067 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9068 MachineMemOperand::MOStore, 4, 4);
9070 // Load the address of the dispatch MBB into the jump buffer.
9071 if (isThumb2) {
9072 // Incoming value: jbuf
9073 // ldr.n r5, LCPI1_1
9074 // orr r5, r5, #1
9075 // add r5, pc
9076 // str r5, [$jbuf, #+4] ; &jbuf[1]
9077 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9078 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9079 .addConstantPoolIndex(CPI)
9080 .addMemOperand(CPMMO)
9081 .add(predOps(ARMCC::AL));
9082 // Set the low bit because of thumb mode.
9083 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9084 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9085 .addReg(NewVReg1, RegState::Kill)
9086 .addImm(0x01)
9087 .add(predOps(ARMCC::AL))
9088 .add(condCodeOp());
9089 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9090 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9091 .addReg(NewVReg2, RegState::Kill)
9092 .addImm(PCLabelId);
9093 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9094 .addReg(NewVReg3, RegState::Kill)
9095 .addFrameIndex(FI)
9096 .addImm(36) // &jbuf[1] :: pc
9097 .addMemOperand(FIMMOSt)
9098 .add(predOps(ARMCC::AL));
9099 } else if (isThumb) {
9100 // Incoming value: jbuf
9101 // ldr.n r1, LCPI1_4
9102 // add r1, pc
9103 // mov r2, #1
9104 // orrs r1, r2
9105 // add r2, $jbuf, #+4 ; &jbuf[1]
9106 // str r1, [r2]
9107 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9108 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9109 .addConstantPoolIndex(CPI)
9110 .addMemOperand(CPMMO)
9111 .add(predOps(ARMCC::AL));
9112 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9113 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9114 .addReg(NewVReg1, RegState::Kill)
9115 .addImm(PCLabelId);
9116 // Set the low bit because of thumb mode.
9117 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9118 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9119 .addReg(ARM::CPSR, RegState::Define)
9120 .addImm(1)
9121 .add(predOps(ARMCC::AL));
9122 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9123 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9124 .addReg(ARM::CPSR, RegState::Define)
9125 .addReg(NewVReg2, RegState::Kill)
9126 .addReg(NewVReg3, RegState::Kill)
9127 .add(predOps(ARMCC::AL));
9128 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9129 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9130 .addFrameIndex(FI)
9131 .addImm(36); // &jbuf[1] :: pc
9132 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9133 .addReg(NewVReg4, RegState::Kill)
9134 .addReg(NewVReg5, RegState::Kill)
9135 .addImm(0)
9136 .addMemOperand(FIMMOSt)
9137 .add(predOps(ARMCC::AL));
9138 } else {
9139 // Incoming value: jbuf
9140 // ldr r1, LCPI1_1
9141 // add r1, pc, r1
9142 // str r1, [$jbuf, #+4] ; &jbuf[1]
9143 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9144 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9145 .addConstantPoolIndex(CPI)
9146 .addImm(0)
9147 .addMemOperand(CPMMO)
9148 .add(predOps(ARMCC::AL));
9149 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9150 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9151 .addReg(NewVReg1, RegState::Kill)
9152 .addImm(PCLabelId)
9153 .add(predOps(ARMCC::AL));
9154 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9155 .addReg(NewVReg2, RegState::Kill)
9156 .addFrameIndex(FI)
9157 .addImm(36) // &jbuf[1] :: pc
9158 .addMemOperand(FIMMOSt)
9159 .add(predOps(ARMCC::AL));
9163 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9164 MachineBasicBlock *MBB) const {
9165 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9166 DebugLoc dl = MI.getDebugLoc();
9167 MachineFunction *MF = MBB->getParent();
9168 MachineRegisterInfo *MRI = &MF->getRegInfo();
9169 MachineFrameInfo &MFI = MF->getFrameInfo();
9170 int FI = MFI.getFunctionContextIndex();
9172 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9173 : &ARM::GPRnopcRegClass;
9175 // Get a mapping of the call site numbers to all of the landing pads they're
9176 // associated with.
9177 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9178 unsigned MaxCSNum = 0;
9179 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9180 ++BB) {
9181 if (!BB->isEHPad()) continue;
9183 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9184 // pad.
9185 for (MachineBasicBlock::iterator
9186 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9187 if (!II->isEHLabel()) continue;
9189 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9190 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9192 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9193 for (SmallVectorImpl<unsigned>::iterator
9194 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9195 CSI != CSE; ++CSI) {
9196 CallSiteNumToLPad[*CSI].push_back(&*BB);
9197 MaxCSNum = std::max(MaxCSNum, *CSI);
9199 break;
9203 // Get an ordered list of the machine basic blocks for the jump table.
9204 std::vector<MachineBasicBlock*> LPadList;
9205 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9206 LPadList.reserve(CallSiteNumToLPad.size());
9207 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9208 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9209 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9210 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9211 LPadList.push_back(*II);
9212 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9216 assert(!LPadList.empty() &&
9217 "No landing pad destinations for the dispatch jump table!");
9219 // Create the jump table and associated information.
9220 MachineJumpTableInfo *JTI =
9221 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9222 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9224 // Create the MBBs for the dispatch code.
9226 // Shove the dispatch's address into the return slot in the function context.
9227 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9228 DispatchBB->setIsEHPad();
9230 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9231 unsigned trap_opcode;
9232 if (Subtarget->isThumb())
9233 trap_opcode = ARM::tTRAP;
9234 else
9235 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9237 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9238 DispatchBB->addSuccessor(TrapBB);
9240 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9241 DispatchBB->addSuccessor(DispContBB);
9243 // Insert and MBBs.
9244 MF->insert(MF->end(), DispatchBB);
9245 MF->insert(MF->end(), DispContBB);
9246 MF->insert(MF->end(), TrapBB);
9248 // Insert code into the entry block that creates and registers the function
9249 // context.
9250 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9252 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9253 MachinePointerInfo::getFixedStack(*MF, FI),
9254 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9256 MachineInstrBuilder MIB;
9257 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9259 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9260 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9262 // Add a register mask with no preserved registers. This results in all
9263 // registers being marked as clobbered. This can't work if the dispatch block
9264 // is in a Thumb1 function and is linked with ARM code which uses the FP
9265 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9266 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9268 bool IsPositionIndependent = isPositionIndependent();
9269 unsigned NumLPads = LPadList.size();
9270 if (Subtarget->isThumb2()) {
9271 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9272 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9273 .addFrameIndex(FI)
9274 .addImm(4)
9275 .addMemOperand(FIMMOLd)
9276 .add(predOps(ARMCC::AL));
9278 if (NumLPads < 256) {
9279 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9280 .addReg(NewVReg1)
9281 .addImm(LPadList.size())
9282 .add(predOps(ARMCC::AL));
9283 } else {
9284 Register VReg1 = MRI->createVirtualRegister(TRC);
9285 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9286 .addImm(NumLPads & 0xFFFF)
9287 .add(predOps(ARMCC::AL));
9289 unsigned VReg2 = VReg1;
9290 if ((NumLPads & 0xFFFF0000) != 0) {
9291 VReg2 = MRI->createVirtualRegister(TRC);
9292 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9293 .addReg(VReg1)
9294 .addImm(NumLPads >> 16)
9295 .add(predOps(ARMCC::AL));
9298 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9299 .addReg(NewVReg1)
9300 .addReg(VReg2)
9301 .add(predOps(ARMCC::AL));
9304 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9305 .addMBB(TrapBB)
9306 .addImm(ARMCC::HI)
9307 .addReg(ARM::CPSR);
9309 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9310 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9311 .addJumpTableIndex(MJTI)
9312 .add(predOps(ARMCC::AL));
9314 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9315 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9316 .addReg(NewVReg3, RegState::Kill)
9317 .addReg(NewVReg1)
9318 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9319 .add(predOps(ARMCC::AL))
9320 .add(condCodeOp());
9322 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9323 .addReg(NewVReg4, RegState::Kill)
9324 .addReg(NewVReg1)
9325 .addJumpTableIndex(MJTI);
9326 } else if (Subtarget->isThumb()) {
9327 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9328 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9329 .addFrameIndex(FI)
9330 .addImm(1)
9331 .addMemOperand(FIMMOLd)
9332 .add(predOps(ARMCC::AL));
9334 if (NumLPads < 256) {
9335 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9336 .addReg(NewVReg1)
9337 .addImm(NumLPads)
9338 .add(predOps(ARMCC::AL));
9339 } else {
9340 MachineConstantPool *ConstantPool = MF->getConstantPool();
9341 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9342 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9344 // MachineConstantPool wants an explicit alignment.
9345 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9346 if (Align == 0)
9347 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9348 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9350 Register VReg1 = MRI->createVirtualRegister(TRC);
9351 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9352 .addReg(VReg1, RegState::Define)
9353 .addConstantPoolIndex(Idx)
9354 .add(predOps(ARMCC::AL));
9355 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9356 .addReg(NewVReg1)
9357 .addReg(VReg1)
9358 .add(predOps(ARMCC::AL));
9361 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9362 .addMBB(TrapBB)
9363 .addImm(ARMCC::HI)
9364 .addReg(ARM::CPSR);
9366 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9367 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9368 .addReg(ARM::CPSR, RegState::Define)
9369 .addReg(NewVReg1)
9370 .addImm(2)
9371 .add(predOps(ARMCC::AL));
9373 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9374 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9375 .addJumpTableIndex(MJTI)
9376 .add(predOps(ARMCC::AL));
9378 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9379 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9380 .addReg(ARM::CPSR, RegState::Define)
9381 .addReg(NewVReg2, RegState::Kill)
9382 .addReg(NewVReg3)
9383 .add(predOps(ARMCC::AL));
9385 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9386 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9388 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9389 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9390 .addReg(NewVReg4, RegState::Kill)
9391 .addImm(0)
9392 .addMemOperand(JTMMOLd)
9393 .add(predOps(ARMCC::AL));
9395 unsigned NewVReg6 = NewVReg5;
9396 if (IsPositionIndependent) {
9397 NewVReg6 = MRI->createVirtualRegister(TRC);
9398 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9399 .addReg(ARM::CPSR, RegState::Define)
9400 .addReg(NewVReg5, RegState::Kill)
9401 .addReg(NewVReg3)
9402 .add(predOps(ARMCC::AL));
9405 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9406 .addReg(NewVReg6, RegState::Kill)
9407 .addJumpTableIndex(MJTI);
9408 } else {
9409 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9410 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9411 .addFrameIndex(FI)
9412 .addImm(4)
9413 .addMemOperand(FIMMOLd)
9414 .add(predOps(ARMCC::AL));
9416 if (NumLPads < 256) {
9417 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9418 .addReg(NewVReg1)
9419 .addImm(NumLPads)
9420 .add(predOps(ARMCC::AL));
9421 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9422 Register VReg1 = MRI->createVirtualRegister(TRC);
9423 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9424 .addImm(NumLPads & 0xFFFF)
9425 .add(predOps(ARMCC::AL));
9427 unsigned VReg2 = VReg1;
9428 if ((NumLPads & 0xFFFF0000) != 0) {
9429 VReg2 = MRI->createVirtualRegister(TRC);
9430 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9431 .addReg(VReg1)
9432 .addImm(NumLPads >> 16)
9433 .add(predOps(ARMCC::AL));
9436 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9437 .addReg(NewVReg1)
9438 .addReg(VReg2)
9439 .add(predOps(ARMCC::AL));
9440 } else {
9441 MachineConstantPool *ConstantPool = MF->getConstantPool();
9442 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9443 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9445 // MachineConstantPool wants an explicit alignment.
9446 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9447 if (Align == 0)
9448 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9449 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9451 Register VReg1 = MRI->createVirtualRegister(TRC);
9452 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9453 .addReg(VReg1, RegState::Define)
9454 .addConstantPoolIndex(Idx)
9455 .addImm(0)
9456 .add(predOps(ARMCC::AL));
9457 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9458 .addReg(NewVReg1)
9459 .addReg(VReg1, RegState::Kill)
9460 .add(predOps(ARMCC::AL));
9463 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9464 .addMBB(TrapBB)
9465 .addImm(ARMCC::HI)
9466 .addReg(ARM::CPSR);
9468 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9469 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9470 .addReg(NewVReg1)
9471 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9472 .add(predOps(ARMCC::AL))
9473 .add(condCodeOp());
9474 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9475 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9476 .addJumpTableIndex(MJTI)
9477 .add(predOps(ARMCC::AL));
9479 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9480 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9481 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9482 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9483 .addReg(NewVReg3, RegState::Kill)
9484 .addReg(NewVReg4)
9485 .addImm(0)
9486 .addMemOperand(JTMMOLd)
9487 .add(predOps(ARMCC::AL));
9489 if (IsPositionIndependent) {
9490 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9491 .addReg(NewVReg5, RegState::Kill)
9492 .addReg(NewVReg4)
9493 .addJumpTableIndex(MJTI);
9494 } else {
9495 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9496 .addReg(NewVReg5, RegState::Kill)
9497 .addJumpTableIndex(MJTI);
9501 // Add the jump table entries as successors to the MBB.
9502 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9503 for (std::vector<MachineBasicBlock*>::iterator
9504 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9505 MachineBasicBlock *CurMBB = *I;
9506 if (SeenMBBs.insert(CurMBB).second)
9507 DispContBB->addSuccessor(CurMBB);
9510 // N.B. the order the invoke BBs are processed in doesn't matter here.
9511 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9512 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9513 for (MachineBasicBlock *BB : InvokeBBs) {
9515 // Remove the landing pad successor from the invoke block and replace it
9516 // with the new dispatch block.
9517 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9518 BB->succ_end());
9519 while (!Successors.empty()) {
9520 MachineBasicBlock *SMBB = Successors.pop_back_val();
9521 if (SMBB->isEHPad()) {
9522 BB->removeSuccessor(SMBB);
9523 MBBLPads.push_back(SMBB);
9527 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9528 BB->normalizeSuccProbs();
9530 // Find the invoke call and mark all of the callee-saved registers as
9531 // 'implicit defined' so that they're spilled. This prevents code from
9532 // moving instructions to before the EH block, where they will never be
9533 // executed.
9534 for (MachineBasicBlock::reverse_iterator
9535 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9536 if (!II->isCall()) continue;
9538 DenseMap<unsigned, bool> DefRegs;
9539 for (MachineInstr::mop_iterator
9540 OI = II->operands_begin(), OE = II->operands_end();
9541 OI != OE; ++OI) {
9542 if (!OI->isReg()) continue;
9543 DefRegs[OI->getReg()] = true;
9546 MachineInstrBuilder MIB(*MF, &*II);
9548 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9549 unsigned Reg = SavedRegs[i];
9550 if (Subtarget->isThumb2() &&
9551 !ARM::tGPRRegClass.contains(Reg) &&
9552 !ARM::hGPRRegClass.contains(Reg))
9553 continue;
9554 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9555 continue;
9556 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9557 continue;
9558 if (!DefRegs[Reg])
9559 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9562 break;
9566 // Mark all former landing pads as non-landing pads. The dispatch is the only
9567 // landing pad now.
9568 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9569 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9570 (*I)->setIsEHPad(false);
9572 // The instruction is gone now.
9573 MI.eraseFromParent();
9576 static
9577 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9578 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9579 E = MBB->succ_end(); I != E; ++I)
9580 if (*I != Succ)
9581 return *I;
9582 llvm_unreachable("Expecting a BB with two successors!");
9585 /// Return the load opcode for a given load size. If load size >= 8,
9586 /// neon opcode will be returned.
9587 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9588 if (LdSize >= 8)
9589 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9590 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9591 if (IsThumb1)
9592 return LdSize == 4 ? ARM::tLDRi
9593 : LdSize == 2 ? ARM::tLDRHi
9594 : LdSize == 1 ? ARM::tLDRBi : 0;
9595 if (IsThumb2)
9596 return LdSize == 4 ? ARM::t2LDR_POST
9597 : LdSize == 2 ? ARM::t2LDRH_POST
9598 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9599 return LdSize == 4 ? ARM::LDR_POST_IMM
9600 : LdSize == 2 ? ARM::LDRH_POST
9601 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9604 /// Return the store opcode for a given store size. If store size >= 8,
9605 /// neon opcode will be returned.
9606 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9607 if (StSize >= 8)
9608 return StSize == 16 ? ARM::VST1q32wb_fixed
9609 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9610 if (IsThumb1)
9611 return StSize == 4 ? ARM::tSTRi
9612 : StSize == 2 ? ARM::tSTRHi
9613 : StSize == 1 ? ARM::tSTRBi : 0;
9614 if (IsThumb2)
9615 return StSize == 4 ? ARM::t2STR_POST
9616 : StSize == 2 ? ARM::t2STRH_POST
9617 : StSize == 1 ? ARM::t2STRB_POST : 0;
9618 return StSize == 4 ? ARM::STR_POST_IMM
9619 : StSize == 2 ? ARM::STRH_POST
9620 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9623 /// Emit a post-increment load operation with given size. The instructions
9624 /// will be added to BB at Pos.
9625 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9626 const TargetInstrInfo *TII, const DebugLoc &dl,
9627 unsigned LdSize, unsigned Data, unsigned AddrIn,
9628 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9629 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9630 assert(LdOpc != 0 && "Should have a load opcode");
9631 if (LdSize >= 8) {
9632 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9633 .addReg(AddrOut, RegState::Define)
9634 .addReg(AddrIn)
9635 .addImm(0)
9636 .add(predOps(ARMCC::AL));
9637 } else if (IsThumb1) {
9638 // load + update AddrIn
9639 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9640 .addReg(AddrIn)
9641 .addImm(0)
9642 .add(predOps(ARMCC::AL));
9643 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9644 .add(t1CondCodeOp())
9645 .addReg(AddrIn)
9646 .addImm(LdSize)
9647 .add(predOps(ARMCC::AL));
9648 } else if (IsThumb2) {
9649 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9650 .addReg(AddrOut, RegState::Define)
9651 .addReg(AddrIn)
9652 .addImm(LdSize)
9653 .add(predOps(ARMCC::AL));
9654 } else { // arm
9655 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9656 .addReg(AddrOut, RegState::Define)
9657 .addReg(AddrIn)
9658 .addReg(0)
9659 .addImm(LdSize)
9660 .add(predOps(ARMCC::AL));
9664 /// Emit a post-increment store operation with given size. The instructions
9665 /// will be added to BB at Pos.
9666 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9667 const TargetInstrInfo *TII, const DebugLoc &dl,
9668 unsigned StSize, unsigned Data, unsigned AddrIn,
9669 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9670 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9671 assert(StOpc != 0 && "Should have a store opcode");
9672 if (StSize >= 8) {
9673 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9674 .addReg(AddrIn)
9675 .addImm(0)
9676 .addReg(Data)
9677 .add(predOps(ARMCC::AL));
9678 } else if (IsThumb1) {
9679 // store + update AddrIn
9680 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9681 .addReg(Data)
9682 .addReg(AddrIn)
9683 .addImm(0)
9684 .add(predOps(ARMCC::AL));
9685 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9686 .add(t1CondCodeOp())
9687 .addReg(AddrIn)
9688 .addImm(StSize)
9689 .add(predOps(ARMCC::AL));
9690 } else if (IsThumb2) {
9691 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9692 .addReg(Data)
9693 .addReg(AddrIn)
9694 .addImm(StSize)
9695 .add(predOps(ARMCC::AL));
9696 } else { // arm
9697 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9698 .addReg(Data)
9699 .addReg(AddrIn)
9700 .addReg(0)
9701 .addImm(StSize)
9702 .add(predOps(ARMCC::AL));
9706 MachineBasicBlock *
9707 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9708 MachineBasicBlock *BB) const {
9709 // This pseudo instruction has 3 operands: dst, src, size
9710 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9711 // Otherwise, we will generate unrolled scalar copies.
9712 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9713 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9714 MachineFunction::iterator It = ++BB->getIterator();
9716 Register dest = MI.getOperand(0).getReg();
9717 Register src = MI.getOperand(1).getReg();
9718 unsigned SizeVal = MI.getOperand(2).getImm();
9719 unsigned Align = MI.getOperand(3).getImm();
9720 DebugLoc dl = MI.getDebugLoc();
9722 MachineFunction *MF = BB->getParent();
9723 MachineRegisterInfo &MRI = MF->getRegInfo();
9724 unsigned UnitSize = 0;
9725 const TargetRegisterClass *TRC = nullptr;
9726 const TargetRegisterClass *VecTRC = nullptr;
9728 bool IsThumb1 = Subtarget->isThumb1Only();
9729 bool IsThumb2 = Subtarget->isThumb2();
9730 bool IsThumb = Subtarget->isThumb();
9732 if (Align & 1) {
9733 UnitSize = 1;
9734 } else if (Align & 2) {
9735 UnitSize = 2;
9736 } else {
9737 // Check whether we can use NEON instructions.
9738 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9739 Subtarget->hasNEON()) {
9740 if ((Align % 16 == 0) && SizeVal >= 16)
9741 UnitSize = 16;
9742 else if ((Align % 8 == 0) && SizeVal >= 8)
9743 UnitSize = 8;
9745 // Can't use NEON instructions.
9746 if (UnitSize == 0)
9747 UnitSize = 4;
9750 // Select the correct opcode and register class for unit size load/store
9751 bool IsNeon = UnitSize >= 8;
9752 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
9753 if (IsNeon)
9754 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
9755 : UnitSize == 8 ? &ARM::DPRRegClass
9756 : nullptr;
9758 unsigned BytesLeft = SizeVal % UnitSize;
9759 unsigned LoopSize = SizeVal - BytesLeft;
9761 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
9762 // Use LDR and STR to copy.
9763 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
9764 // [destOut] = STR_POST(scratch, destIn, UnitSize)
9765 unsigned srcIn = src;
9766 unsigned destIn = dest;
9767 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
9768 Register srcOut = MRI.createVirtualRegister(TRC);
9769 Register destOut = MRI.createVirtualRegister(TRC);
9770 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9771 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
9772 IsThumb1, IsThumb2);
9773 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
9774 IsThumb1, IsThumb2);
9775 srcIn = srcOut;
9776 destIn = destOut;
9779 // Handle the leftover bytes with LDRB and STRB.
9780 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
9781 // [destOut] = STRB_POST(scratch, destIn, 1)
9782 for (unsigned i = 0; i < BytesLeft; i++) {
9783 Register srcOut = MRI.createVirtualRegister(TRC);
9784 Register destOut = MRI.createVirtualRegister(TRC);
9785 Register scratch = MRI.createVirtualRegister(TRC);
9786 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
9787 IsThumb1, IsThumb2);
9788 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
9789 IsThumb1, IsThumb2);
9790 srcIn = srcOut;
9791 destIn = destOut;
9793 MI.eraseFromParent(); // The instruction is gone now.
9794 return BB;
9797 // Expand the pseudo op to a loop.
9798 // thisMBB:
9799 // ...
9800 // movw varEnd, # --> with thumb2
9801 // movt varEnd, #
9802 // ldrcp varEnd, idx --> without thumb2
9803 // fallthrough --> loopMBB
9804 // loopMBB:
9805 // PHI varPhi, varEnd, varLoop
9806 // PHI srcPhi, src, srcLoop
9807 // PHI destPhi, dst, destLoop
9808 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9809 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9810 // subs varLoop, varPhi, #UnitSize
9811 // bne loopMBB
9812 // fallthrough --> exitMBB
9813 // exitMBB:
9814 // epilogue to handle left-over bytes
9815 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9816 // [destOut] = STRB_POST(scratch, destLoop, 1)
9817 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9818 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9819 MF->insert(It, loopMBB);
9820 MF->insert(It, exitMBB);
9822 // Transfer the remainder of BB and its successor edges to exitMBB.
9823 exitMBB->splice(exitMBB->begin(), BB,
9824 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9825 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9827 // Load an immediate to varEnd.
9828 Register varEnd = MRI.createVirtualRegister(TRC);
9829 if (Subtarget->useMovt()) {
9830 unsigned Vtmp = varEnd;
9831 if ((LoopSize & 0xFFFF0000) != 0)
9832 Vtmp = MRI.createVirtualRegister(TRC);
9833 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9834 .addImm(LoopSize & 0xFFFF)
9835 .add(predOps(ARMCC::AL));
9837 if ((LoopSize & 0xFFFF0000) != 0)
9838 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9839 .addReg(Vtmp)
9840 .addImm(LoopSize >> 16)
9841 .add(predOps(ARMCC::AL));
9842 } else {
9843 MachineConstantPool *ConstantPool = MF->getConstantPool();
9844 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9845 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9847 // MachineConstantPool wants an explicit alignment.
9848 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9849 if (Align == 0)
9850 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9851 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9852 MachineMemOperand *CPMMO =
9853 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9854 MachineMemOperand::MOLoad, 4, 4);
9856 if (IsThumb)
9857 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9858 .addReg(varEnd, RegState::Define)
9859 .addConstantPoolIndex(Idx)
9860 .add(predOps(ARMCC::AL))
9861 .addMemOperand(CPMMO);
9862 else
9863 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9864 .addReg(varEnd, RegState::Define)
9865 .addConstantPoolIndex(Idx)
9866 .addImm(0)
9867 .add(predOps(ARMCC::AL))
9868 .addMemOperand(CPMMO);
9870 BB->addSuccessor(loopMBB);
9872 // Generate the loop body:
9873 // varPhi = PHI(varLoop, varEnd)
9874 // srcPhi = PHI(srcLoop, src)
9875 // destPhi = PHI(destLoop, dst)
9876 MachineBasicBlock *entryBB = BB;
9877 BB = loopMBB;
9878 Register varLoop = MRI.createVirtualRegister(TRC);
9879 Register varPhi = MRI.createVirtualRegister(TRC);
9880 Register srcLoop = MRI.createVirtualRegister(TRC);
9881 Register srcPhi = MRI.createVirtualRegister(TRC);
9882 Register destLoop = MRI.createVirtualRegister(TRC);
9883 Register destPhi = MRI.createVirtualRegister(TRC);
9885 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9886 .addReg(varLoop).addMBB(loopMBB)
9887 .addReg(varEnd).addMBB(entryBB);
9888 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9889 .addReg(srcLoop).addMBB(loopMBB)
9890 .addReg(src).addMBB(entryBB);
9891 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9892 .addReg(destLoop).addMBB(loopMBB)
9893 .addReg(dest).addMBB(entryBB);
9895 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9896 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9897 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9898 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9899 IsThumb1, IsThumb2);
9900 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9901 IsThumb1, IsThumb2);
9903 // Decrement loop variable by UnitSize.
9904 if (IsThumb1) {
9905 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9906 .add(t1CondCodeOp())
9907 .addReg(varPhi)
9908 .addImm(UnitSize)
9909 .add(predOps(ARMCC::AL));
9910 } else {
9911 MachineInstrBuilder MIB =
9912 BuildMI(*BB, BB->end(), dl,
9913 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9914 MIB.addReg(varPhi)
9915 .addImm(UnitSize)
9916 .add(predOps(ARMCC::AL))
9917 .add(condCodeOp());
9918 MIB->getOperand(5).setReg(ARM::CPSR);
9919 MIB->getOperand(5).setIsDef(true);
9921 BuildMI(*BB, BB->end(), dl,
9922 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9923 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9925 // loopMBB can loop back to loopMBB or fall through to exitMBB.
9926 BB->addSuccessor(loopMBB);
9927 BB->addSuccessor(exitMBB);
9929 // Add epilogue to handle BytesLeft.
9930 BB = exitMBB;
9931 auto StartOfExit = exitMBB->begin();
9933 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9934 // [destOut] = STRB_POST(scratch, destLoop, 1)
9935 unsigned srcIn = srcLoop;
9936 unsigned destIn = destLoop;
9937 for (unsigned i = 0; i < BytesLeft; i++) {
9938 Register srcOut = MRI.createVirtualRegister(TRC);
9939 Register destOut = MRI.createVirtualRegister(TRC);
9940 Register scratch = MRI.createVirtualRegister(TRC);
9941 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9942 IsThumb1, IsThumb2);
9943 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9944 IsThumb1, IsThumb2);
9945 srcIn = srcOut;
9946 destIn = destOut;
9949 MI.eraseFromParent(); // The instruction is gone now.
9950 return BB;
9953 MachineBasicBlock *
9954 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9955 MachineBasicBlock *MBB) const {
9956 const TargetMachine &TM = getTargetMachine();
9957 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9958 DebugLoc DL = MI.getDebugLoc();
9960 assert(Subtarget->isTargetWindows() &&
9961 "__chkstk is only supported on Windows");
9962 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9964 // __chkstk takes the number of words to allocate on the stack in R4, and
9965 // returns the stack adjustment in number of bytes in R4. This will not
9966 // clober any other registers (other than the obvious lr).
9968 // Although, technically, IP should be considered a register which may be
9969 // clobbered, the call itself will not touch it. Windows on ARM is a pure
9970 // thumb-2 environment, so there is no interworking required. As a result, we
9971 // do not expect a veneer to be emitted by the linker, clobbering IP.
9973 // Each module receives its own copy of __chkstk, so no import thunk is
9974 // required, again, ensuring that IP is not clobbered.
9976 // Finally, although some linkers may theoretically provide a trampoline for
9977 // out of range calls (which is quite common due to a 32M range limitation of
9978 // branches for Thumb), we can generate the long-call version via
9979 // -mcmodel=large, alleviating the need for the trampoline which may clobber
9980 // IP.
9982 switch (TM.getCodeModel()) {
9983 case CodeModel::Tiny:
9984 llvm_unreachable("Tiny code model not available on ARM.");
9985 case CodeModel::Small:
9986 case CodeModel::Medium:
9987 case CodeModel::Kernel:
9988 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9989 .add(predOps(ARMCC::AL))
9990 .addExternalSymbol("__chkstk")
9991 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9992 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9993 .addReg(ARM::R12,
9994 RegState::Implicit | RegState::Define | RegState::Dead)
9995 .addReg(ARM::CPSR,
9996 RegState::Implicit | RegState::Define | RegState::Dead);
9997 break;
9998 case CodeModel::Large: {
9999 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10000 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10002 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10003 .addExternalSymbol("__chkstk");
10004 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10005 .add(predOps(ARMCC::AL))
10006 .addReg(Reg, RegState::Kill)
10007 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10008 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10009 .addReg(ARM::R12,
10010 RegState::Implicit | RegState::Define | RegState::Dead)
10011 .addReg(ARM::CPSR,
10012 RegState::Implicit | RegState::Define | RegState::Dead);
10013 break;
10017 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10018 .addReg(ARM::SP, RegState::Kill)
10019 .addReg(ARM::R4, RegState::Kill)
10020 .setMIFlags(MachineInstr::FrameSetup)
10021 .add(predOps(ARMCC::AL))
10022 .add(condCodeOp());
10024 MI.eraseFromParent();
10025 return MBB;
10028 MachineBasicBlock *
10029 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10030 MachineBasicBlock *MBB) const {
10031 DebugLoc DL = MI.getDebugLoc();
10032 MachineFunction *MF = MBB->getParent();
10033 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10035 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10036 MF->insert(++MBB->getIterator(), ContBB);
10037 ContBB->splice(ContBB->begin(), MBB,
10038 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10039 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10040 MBB->addSuccessor(ContBB);
10042 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10043 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10044 MF->push_back(TrapBB);
10045 MBB->addSuccessor(TrapBB);
10047 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10048 .addReg(MI.getOperand(0).getReg())
10049 .addImm(0)
10050 .add(predOps(ARMCC::AL));
10051 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10052 .addMBB(TrapBB)
10053 .addImm(ARMCC::EQ)
10054 .addReg(ARM::CPSR);
10056 MI.eraseFromParent();
10057 return ContBB;
10060 // The CPSR operand of SelectItr might be missing a kill marker
10061 // because there were multiple uses of CPSR, and ISel didn't know
10062 // which to mark. Figure out whether SelectItr should have had a
10063 // kill marker, and set it if it should. Returns the correct kill
10064 // marker value.
10065 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10066 MachineBasicBlock* BB,
10067 const TargetRegisterInfo* TRI) {
10068 // Scan forward through BB for a use/def of CPSR.
10069 MachineBasicBlock::iterator miI(std::next(SelectItr));
10070 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10071 const MachineInstr& mi = *miI;
10072 if (mi.readsRegister(ARM::CPSR))
10073 return false;
10074 if (mi.definesRegister(ARM::CPSR))
10075 break; // Should have kill-flag - update below.
10078 // If we hit the end of the block, check whether CPSR is live into a
10079 // successor.
10080 if (miI == BB->end()) {
10081 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10082 sEnd = BB->succ_end();
10083 sItr != sEnd; ++sItr) {
10084 MachineBasicBlock* succ = *sItr;
10085 if (succ->isLiveIn(ARM::CPSR))
10086 return false;
10090 // We found a def, or hit the end of the basic block and CPSR wasn't live
10091 // out. SelectMI should have a kill flag on CPSR.
10092 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10093 return true;
10096 MachineBasicBlock *
10097 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10098 MachineBasicBlock *BB) const {
10099 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10100 DebugLoc dl = MI.getDebugLoc();
10101 bool isThumb2 = Subtarget->isThumb2();
10102 switch (MI.getOpcode()) {
10103 default: {
10104 MI.print(errs());
10105 llvm_unreachable("Unexpected instr type to insert");
10108 // Thumb1 post-indexed loads are really just single-register LDMs.
10109 case ARM::tLDR_postidx: {
10110 MachineOperand Def(MI.getOperand(1));
10111 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10112 .add(Def) // Rn_wb
10113 .add(MI.getOperand(2)) // Rn
10114 .add(MI.getOperand(3)) // PredImm
10115 .add(MI.getOperand(4)) // PredReg
10116 .add(MI.getOperand(0)) // Rt
10117 .cloneMemRefs(MI);
10118 MI.eraseFromParent();
10119 return BB;
10122 // The Thumb2 pre-indexed stores have the same MI operands, they just
10123 // define them differently in the .td files from the isel patterns, so
10124 // they need pseudos.
10125 case ARM::t2STR_preidx:
10126 MI.setDesc(TII->get(ARM::t2STR_PRE));
10127 return BB;
10128 case ARM::t2STRB_preidx:
10129 MI.setDesc(TII->get(ARM::t2STRB_PRE));
10130 return BB;
10131 case ARM::t2STRH_preidx:
10132 MI.setDesc(TII->get(ARM::t2STRH_PRE));
10133 return BB;
10135 case ARM::STRi_preidx:
10136 case ARM::STRBi_preidx: {
10137 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10138 : ARM::STRB_PRE_IMM;
10139 // Decode the offset.
10140 unsigned Offset = MI.getOperand(4).getImm();
10141 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10142 Offset = ARM_AM::getAM2Offset(Offset);
10143 if (isSub)
10144 Offset = -Offset;
10146 MachineMemOperand *MMO = *MI.memoperands_begin();
10147 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10148 .add(MI.getOperand(0)) // Rn_wb
10149 .add(MI.getOperand(1)) // Rt
10150 .add(MI.getOperand(2)) // Rn
10151 .addImm(Offset) // offset (skip GPR==zero_reg)
10152 .add(MI.getOperand(5)) // pred
10153 .add(MI.getOperand(6))
10154 .addMemOperand(MMO);
10155 MI.eraseFromParent();
10156 return BB;
10158 case ARM::STRr_preidx:
10159 case ARM::STRBr_preidx:
10160 case ARM::STRH_preidx: {
10161 unsigned NewOpc;
10162 switch (MI.getOpcode()) {
10163 default: llvm_unreachable("unexpected opcode!");
10164 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10165 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10166 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10168 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10169 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10170 MIB.add(MI.getOperand(i));
10171 MI.eraseFromParent();
10172 return BB;
10175 case ARM::tMOVCCr_pseudo: {
10176 // To "insert" a SELECT_CC instruction, we actually have to insert the
10177 // diamond control-flow pattern. The incoming instruction knows the
10178 // destination vreg to set, the condition code register to branch on, the
10179 // true/false values to select between, and a branch opcode to use.
10180 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10181 MachineFunction::iterator It = ++BB->getIterator();
10183 // thisMBB:
10184 // ...
10185 // TrueVal = ...
10186 // cmpTY ccX, r1, r2
10187 // bCC copy1MBB
10188 // fallthrough --> copy0MBB
10189 MachineBasicBlock *thisMBB = BB;
10190 MachineFunction *F = BB->getParent();
10191 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10192 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10193 F->insert(It, copy0MBB);
10194 F->insert(It, sinkMBB);
10196 // Check whether CPSR is live past the tMOVCCr_pseudo.
10197 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10198 if (!MI.killsRegister(ARM::CPSR) &&
10199 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10200 copy0MBB->addLiveIn(ARM::CPSR);
10201 sinkMBB->addLiveIn(ARM::CPSR);
10204 // Transfer the remainder of BB and its successor edges to sinkMBB.
10205 sinkMBB->splice(sinkMBB->begin(), BB,
10206 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10207 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10209 BB->addSuccessor(copy0MBB);
10210 BB->addSuccessor(sinkMBB);
10212 BuildMI(BB, dl, TII->get(ARM::tBcc))
10213 .addMBB(sinkMBB)
10214 .addImm(MI.getOperand(3).getImm())
10215 .addReg(MI.getOperand(4).getReg());
10217 // copy0MBB:
10218 // %FalseValue = ...
10219 // # fallthrough to sinkMBB
10220 BB = copy0MBB;
10222 // Update machine-CFG edges
10223 BB->addSuccessor(sinkMBB);
10225 // sinkMBB:
10226 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10227 // ...
10228 BB = sinkMBB;
10229 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10230 .addReg(MI.getOperand(1).getReg())
10231 .addMBB(copy0MBB)
10232 .addReg(MI.getOperand(2).getReg())
10233 .addMBB(thisMBB);
10235 MI.eraseFromParent(); // The pseudo instruction is gone now.
10236 return BB;
10239 case ARM::BCCi64:
10240 case ARM::BCCZi64: {
10241 // If there is an unconditional branch to the other successor, remove it.
10242 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10244 // Compare both parts that make up the double comparison separately for
10245 // equality.
10246 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10248 Register LHS1 = MI.getOperand(1).getReg();
10249 Register LHS2 = MI.getOperand(2).getReg();
10250 if (RHSisZero) {
10251 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10252 .addReg(LHS1)
10253 .addImm(0)
10254 .add(predOps(ARMCC::AL));
10255 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10256 .addReg(LHS2).addImm(0)
10257 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10258 } else {
10259 Register RHS1 = MI.getOperand(3).getReg();
10260 Register RHS2 = MI.getOperand(4).getReg();
10261 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10262 .addReg(LHS1)
10263 .addReg(RHS1)
10264 .add(predOps(ARMCC::AL));
10265 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10266 .addReg(LHS2).addReg(RHS2)
10267 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10270 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10271 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10272 if (MI.getOperand(0).getImm() == ARMCC::NE)
10273 std::swap(destMBB, exitMBB);
10275 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10276 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10277 if (isThumb2)
10278 BuildMI(BB, dl, TII->get(ARM::t2B))
10279 .addMBB(exitMBB)
10280 .add(predOps(ARMCC::AL));
10281 else
10282 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10284 MI.eraseFromParent(); // The pseudo instruction is gone now.
10285 return BB;
10288 case ARM::Int_eh_sjlj_setjmp:
10289 case ARM::Int_eh_sjlj_setjmp_nofp:
10290 case ARM::tInt_eh_sjlj_setjmp:
10291 case ARM::t2Int_eh_sjlj_setjmp:
10292 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10293 return BB;
10295 case ARM::Int_eh_sjlj_setup_dispatch:
10296 EmitSjLjDispatchBlock(MI, BB);
10297 return BB;
10299 case ARM::ABS:
10300 case ARM::t2ABS: {
10301 // To insert an ABS instruction, we have to insert the
10302 // diamond control-flow pattern. The incoming instruction knows the
10303 // source vreg to test against 0, the destination vreg to set,
10304 // the condition code register to branch on, the
10305 // true/false values to select between, and a branch opcode to use.
10306 // It transforms
10307 // V1 = ABS V0
10308 // into
10309 // V2 = MOVS V0
10310 // BCC (branch to SinkBB if V0 >= 0)
10311 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10312 // SinkBB: V1 = PHI(V2, V3)
10313 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10314 MachineFunction::iterator BBI = ++BB->getIterator();
10315 MachineFunction *Fn = BB->getParent();
10316 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10317 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10318 Fn->insert(BBI, RSBBB);
10319 Fn->insert(BBI, SinkBB);
10321 Register ABSSrcReg = MI.getOperand(1).getReg();
10322 Register ABSDstReg = MI.getOperand(0).getReg();
10323 bool ABSSrcKIll = MI.getOperand(1).isKill();
10324 bool isThumb2 = Subtarget->isThumb2();
10325 MachineRegisterInfo &MRI = Fn->getRegInfo();
10326 // In Thumb mode S must not be specified if source register is the SP or
10327 // PC and if destination register is the SP, so restrict register class
10328 Register NewRsbDstReg = MRI.createVirtualRegister(
10329 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10331 // Transfer the remainder of BB and its successor edges to sinkMBB.
10332 SinkBB->splice(SinkBB->begin(), BB,
10333 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10334 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10336 BB->addSuccessor(RSBBB);
10337 BB->addSuccessor(SinkBB);
10339 // fall through to SinkMBB
10340 RSBBB->addSuccessor(SinkBB);
10342 // insert a cmp at the end of BB
10343 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10344 .addReg(ABSSrcReg)
10345 .addImm(0)
10346 .add(predOps(ARMCC::AL));
10348 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10349 BuildMI(BB, dl,
10350 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10351 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10353 // insert rsbri in RSBBB
10354 // Note: BCC and rsbri will be converted into predicated rsbmi
10355 // by if-conversion pass
10356 BuildMI(*RSBBB, RSBBB->begin(), dl,
10357 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10358 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10359 .addImm(0)
10360 .add(predOps(ARMCC::AL))
10361 .add(condCodeOp());
10363 // insert PHI in SinkBB,
10364 // reuse ABSDstReg to not change uses of ABS instruction
10365 BuildMI(*SinkBB, SinkBB->begin(), dl,
10366 TII->get(ARM::PHI), ABSDstReg)
10367 .addReg(NewRsbDstReg).addMBB(RSBBB)
10368 .addReg(ABSSrcReg).addMBB(BB);
10370 // remove ABS instruction
10371 MI.eraseFromParent();
10373 // return last added BB
10374 return SinkBB;
10376 case ARM::COPY_STRUCT_BYVAL_I32:
10377 ++NumLoopByVals;
10378 return EmitStructByval(MI, BB);
10379 case ARM::WIN__CHKSTK:
10380 return EmitLowered__chkstk(MI, BB);
10381 case ARM::WIN__DBZCHK:
10382 return EmitLowered__dbzchk(MI, BB);
10386 /// Attaches vregs to MEMCPY that it will use as scratch registers
10387 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10388 /// instead of as a custom inserter because we need the use list from the SDNode.
10389 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10390 MachineInstr &MI, const SDNode *Node) {
10391 bool isThumb1 = Subtarget->isThumb1Only();
10393 DebugLoc DL = MI.getDebugLoc();
10394 MachineFunction *MF = MI.getParent()->getParent();
10395 MachineRegisterInfo &MRI = MF->getRegInfo();
10396 MachineInstrBuilder MIB(*MF, MI);
10398 // If the new dst/src is unused mark it as dead.
10399 if (!Node->hasAnyUseOfValue(0)) {
10400 MI.getOperand(0).setIsDead(true);
10402 if (!Node->hasAnyUseOfValue(1)) {
10403 MI.getOperand(1).setIsDead(true);
10406 // The MEMCPY both defines and kills the scratch registers.
10407 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10408 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10409 : &ARM::GPRRegClass);
10410 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10414 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10415 SDNode *Node) const {
10416 if (MI.getOpcode() == ARM::MEMCPY) {
10417 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10418 return;
10421 const MCInstrDesc *MCID = &MI.getDesc();
10422 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10423 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10424 // operand is still set to noreg. If needed, set the optional operand's
10425 // register to CPSR, and remove the redundant implicit def.
10427 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10429 // Rename pseudo opcodes.
10430 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10431 unsigned ccOutIdx;
10432 if (NewOpc) {
10433 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10434 MCID = &TII->get(NewOpc);
10436 assert(MCID->getNumOperands() ==
10437 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10438 && "converted opcode should be the same except for cc_out"
10439 " (and, on Thumb1, pred)");
10441 MI.setDesc(*MCID);
10443 // Add the optional cc_out operand
10444 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10446 // On Thumb1, move all input operands to the end, then add the predicate
10447 if (Subtarget->isThumb1Only()) {
10448 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10449 MI.addOperand(MI.getOperand(1));
10450 MI.RemoveOperand(1);
10453 // Restore the ties
10454 for (unsigned i = MI.getNumOperands(); i--;) {
10455 const MachineOperand& op = MI.getOperand(i);
10456 if (op.isReg() && op.isUse()) {
10457 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10458 if (DefIdx != -1)
10459 MI.tieOperands(DefIdx, i);
10463 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10464 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10465 ccOutIdx = 1;
10466 } else
10467 ccOutIdx = MCID->getNumOperands() - 1;
10468 } else
10469 ccOutIdx = MCID->getNumOperands() - 1;
10471 // Any ARM instruction that sets the 's' bit should specify an optional
10472 // "cc_out" operand in the last operand position.
10473 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10474 assert(!NewOpc && "Optional cc_out operand required");
10475 return;
10477 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10478 // since we already have an optional CPSR def.
10479 bool definesCPSR = false;
10480 bool deadCPSR = false;
10481 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10482 ++i) {
10483 const MachineOperand &MO = MI.getOperand(i);
10484 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10485 definesCPSR = true;
10486 if (MO.isDead())
10487 deadCPSR = true;
10488 MI.RemoveOperand(i);
10489 break;
10492 if (!definesCPSR) {
10493 assert(!NewOpc && "Optional cc_out operand required");
10494 return;
10496 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10497 if (deadCPSR) {
10498 assert(!MI.getOperand(ccOutIdx).getReg() &&
10499 "expect uninitialized optional cc_out operand");
10500 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10501 if (!Subtarget->isThumb1Only())
10502 return;
10505 // If this instruction was defined with an optional CPSR def and its dag node
10506 // had a live implicit CPSR def, then activate the optional CPSR def.
10507 MachineOperand &MO = MI.getOperand(ccOutIdx);
10508 MO.setReg(ARM::CPSR);
10509 MO.setIsDef(true);
10512 //===----------------------------------------------------------------------===//
10513 // ARM Optimization Hooks
10514 //===----------------------------------------------------------------------===//
10516 // Helper function that checks if N is a null or all ones constant.
10517 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10518 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10521 // Return true if N is conditionally 0 or all ones.
10522 // Detects these expressions where cc is an i1 value:
10524 // (select cc 0, y) [AllOnes=0]
10525 // (select cc y, 0) [AllOnes=0]
10526 // (zext cc) [AllOnes=0]
10527 // (sext cc) [AllOnes=0/1]
10528 // (select cc -1, y) [AllOnes=1]
10529 // (select cc y, -1) [AllOnes=1]
10531 // Invert is set when N is the null/all ones constant when CC is false.
10532 // OtherOp is set to the alternative value of N.
10533 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10534 SDValue &CC, bool &Invert,
10535 SDValue &OtherOp,
10536 SelectionDAG &DAG) {
10537 switch (N->getOpcode()) {
10538 default: return false;
10539 case ISD::SELECT: {
10540 CC = N->getOperand(0);
10541 SDValue N1 = N->getOperand(1);
10542 SDValue N2 = N->getOperand(2);
10543 if (isZeroOrAllOnes(N1, AllOnes)) {
10544 Invert = false;
10545 OtherOp = N2;
10546 return true;
10548 if (isZeroOrAllOnes(N2, AllOnes)) {
10549 Invert = true;
10550 OtherOp = N1;
10551 return true;
10553 return false;
10555 case ISD::ZERO_EXTEND:
10556 // (zext cc) can never be the all ones value.
10557 if (AllOnes)
10558 return false;
10559 LLVM_FALLTHROUGH;
10560 case ISD::SIGN_EXTEND: {
10561 SDLoc dl(N);
10562 EVT VT = N->getValueType(0);
10563 CC = N->getOperand(0);
10564 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10565 return false;
10566 Invert = !AllOnes;
10567 if (AllOnes)
10568 // When looking for an AllOnes constant, N is an sext, and the 'other'
10569 // value is 0.
10570 OtherOp = DAG.getConstant(0, dl, VT);
10571 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10572 // When looking for a 0 constant, N can be zext or sext.
10573 OtherOp = DAG.getConstant(1, dl, VT);
10574 else
10575 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10576 VT);
10577 return true;
10582 // Combine a constant select operand into its use:
10584 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10585 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10586 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10587 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10588 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10590 // The transform is rejected if the select doesn't have a constant operand that
10591 // is null, or all ones when AllOnes is set.
10593 // Also recognize sext/zext from i1:
10595 // (add (zext cc), x) -> (select cc (add x, 1), x)
10596 // (add (sext cc), x) -> (select cc (add x, -1), x)
10598 // These transformations eventually create predicated instructions.
10600 // @param N The node to transform.
10601 // @param Slct The N operand that is a select.
10602 // @param OtherOp The other N operand (x above).
10603 // @param DCI Context.
10604 // @param AllOnes Require the select constant to be all ones instead of null.
10605 // @returns The new node, or SDValue() on failure.
10606 static
10607 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10608 TargetLowering::DAGCombinerInfo &DCI,
10609 bool AllOnes = false) {
10610 SelectionDAG &DAG = DCI.DAG;
10611 EVT VT = N->getValueType(0);
10612 SDValue NonConstantVal;
10613 SDValue CCOp;
10614 bool SwapSelectOps;
10615 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10616 NonConstantVal, DAG))
10617 return SDValue();
10619 // Slct is now know to be the desired identity constant when CC is true.
10620 SDValue TrueVal = OtherOp;
10621 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10622 OtherOp, NonConstantVal);
10623 // Unless SwapSelectOps says CC should be false.
10624 if (SwapSelectOps)
10625 std::swap(TrueVal, FalseVal);
10627 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10628 CCOp, TrueVal, FalseVal);
10631 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10632 static
10633 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10634 TargetLowering::DAGCombinerInfo &DCI) {
10635 SDValue N0 = N->getOperand(0);
10636 SDValue N1 = N->getOperand(1);
10637 if (N0.getNode()->hasOneUse())
10638 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10639 return Result;
10640 if (N1.getNode()->hasOneUse())
10641 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10642 return Result;
10643 return SDValue();
10646 static bool IsVUZPShuffleNode(SDNode *N) {
10647 // VUZP shuffle node.
10648 if (N->getOpcode() == ARMISD::VUZP)
10649 return true;
10651 // "VUZP" on i32 is an alias for VTRN.
10652 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10653 return true;
10655 return false;
10658 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10659 TargetLowering::DAGCombinerInfo &DCI,
10660 const ARMSubtarget *Subtarget) {
10661 // Look for ADD(VUZP.0, VUZP.1).
10662 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10663 N0 == N1)
10664 return SDValue();
10666 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10667 if (!N->getValueType(0).is64BitVector())
10668 return SDValue();
10670 // Generate vpadd.
10671 SelectionDAG &DAG = DCI.DAG;
10672 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10673 SDLoc dl(N);
10674 SDNode *Unzip = N0.getNode();
10675 EVT VT = N->getValueType(0);
10677 SmallVector<SDValue, 8> Ops;
10678 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10679 TLI.getPointerTy(DAG.getDataLayout())));
10680 Ops.push_back(Unzip->getOperand(0));
10681 Ops.push_back(Unzip->getOperand(1));
10683 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10686 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10687 TargetLowering::DAGCombinerInfo &DCI,
10688 const ARMSubtarget *Subtarget) {
10689 // Check for two extended operands.
10690 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10691 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10692 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10693 N1.getOpcode() == ISD::ZERO_EXTEND))
10694 return SDValue();
10696 SDValue N00 = N0.getOperand(0);
10697 SDValue N10 = N1.getOperand(0);
10699 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10700 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10701 N00 == N10)
10702 return SDValue();
10704 // We only recognize Q register paddl here; this can't be reached until
10705 // after type legalization.
10706 if (!N00.getValueType().is64BitVector() ||
10707 !N0.getValueType().is128BitVector())
10708 return SDValue();
10710 // Generate vpaddl.
10711 SelectionDAG &DAG = DCI.DAG;
10712 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10713 SDLoc dl(N);
10714 EVT VT = N->getValueType(0);
10716 SmallVector<SDValue, 8> Ops;
10717 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10718 unsigned Opcode;
10719 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10720 Opcode = Intrinsic::arm_neon_vpaddls;
10721 else
10722 Opcode = Intrinsic::arm_neon_vpaddlu;
10723 Ops.push_back(DAG.getConstant(Opcode, dl,
10724 TLI.getPointerTy(DAG.getDataLayout())));
10725 EVT ElemTy = N00.getValueType().getVectorElementType();
10726 unsigned NumElts = VT.getVectorNumElements();
10727 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10728 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10729 N00.getOperand(0), N00.getOperand(1));
10730 Ops.push_back(Concat);
10732 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10735 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10736 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10737 // much easier to match.
10738 static SDValue
10739 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10740 TargetLowering::DAGCombinerInfo &DCI,
10741 const ARMSubtarget *Subtarget) {
10742 // Only perform optimization if after legalize, and if NEON is available. We
10743 // also expected both operands to be BUILD_VECTORs.
10744 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10745 || N0.getOpcode() != ISD::BUILD_VECTOR
10746 || N1.getOpcode() != ISD::BUILD_VECTOR)
10747 return SDValue();
10749 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10750 EVT VT = N->getValueType(0);
10751 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10752 return SDValue();
10754 // Check that the vector operands are of the right form.
10755 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
10756 // operands, where N is the size of the formed vector.
10757 // Each EXTRACT_VECTOR should have the same input vector and odd or even
10758 // index such that we have a pair wise add pattern.
10760 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
10761 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10762 return SDValue();
10763 SDValue Vec = N0->getOperand(0)->getOperand(0);
10764 SDNode *V = Vec.getNode();
10765 unsigned nextIndex = 0;
10767 // For each operands to the ADD which are BUILD_VECTORs,
10768 // check to see if each of their operands are an EXTRACT_VECTOR with
10769 // the same vector and appropriate index.
10770 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
10771 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
10772 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10774 SDValue ExtVec0 = N0->getOperand(i);
10775 SDValue ExtVec1 = N1->getOperand(i);
10777 // First operand is the vector, verify its the same.
10778 if (V != ExtVec0->getOperand(0).getNode() ||
10779 V != ExtVec1->getOperand(0).getNode())
10780 return SDValue();
10782 // Second is the constant, verify its correct.
10783 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
10784 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
10786 // For the constant, we want to see all the even or all the odd.
10787 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
10788 || C1->getZExtValue() != nextIndex+1)
10789 return SDValue();
10791 // Increment index.
10792 nextIndex+=2;
10793 } else
10794 return SDValue();
10797 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
10798 // we're using the entire input vector, otherwise there's a size/legality
10799 // mismatch somewhere.
10800 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10801 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10802 return SDValue();
10804 // Create VPADDL node.
10805 SelectionDAG &DAG = DCI.DAG;
10806 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10808 SDLoc dl(N);
10810 // Build operand list.
10811 SmallVector<SDValue, 8> Ops;
10812 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10813 TLI.getPointerTy(DAG.getDataLayout())));
10815 // Input is the vector.
10816 Ops.push_back(Vec);
10818 // Get widened type and narrowed type.
10819 MVT widenType;
10820 unsigned numElem = VT.getVectorNumElements();
10822 EVT inputLaneType = Vec.getValueType().getVectorElementType();
10823 switch (inputLaneType.getSimpleVT().SimpleTy) {
10824 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10825 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10826 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10827 default:
10828 llvm_unreachable("Invalid vector element type for padd optimization.");
10831 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
10832 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
10833 return DAG.getNode(ExtOp, dl, VT, tmp);
10836 static SDValue findMUL_LOHI(SDValue V) {
10837 if (V->getOpcode() == ISD::UMUL_LOHI ||
10838 V->getOpcode() == ISD::SMUL_LOHI)
10839 return V;
10840 return SDValue();
10843 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
10844 TargetLowering::DAGCombinerInfo &DCI,
10845 const ARMSubtarget *Subtarget) {
10846 if (Subtarget->isThumb()) {
10847 if (!Subtarget->hasDSP())
10848 return SDValue();
10849 } else if (!Subtarget->hasV5TEOps())
10850 return SDValue();
10852 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10853 // accumulates the product into a 64-bit value. The 16-bit values will
10854 // be sign extended somehow or SRA'd into 32-bit values
10855 // (addc (adde (mul 16bit, 16bit), lo), hi)
10856 SDValue Mul = AddcNode->getOperand(0);
10857 SDValue Lo = AddcNode->getOperand(1);
10858 if (Mul.getOpcode() != ISD::MUL) {
10859 Lo = AddcNode->getOperand(0);
10860 Mul = AddcNode->getOperand(1);
10861 if (Mul.getOpcode() != ISD::MUL)
10862 return SDValue();
10865 SDValue SRA = AddeNode->getOperand(0);
10866 SDValue Hi = AddeNode->getOperand(1);
10867 if (SRA.getOpcode() != ISD::SRA) {
10868 SRA = AddeNode->getOperand(1);
10869 Hi = AddeNode->getOperand(0);
10870 if (SRA.getOpcode() != ISD::SRA)
10871 return SDValue();
10873 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10874 if (Const->getZExtValue() != 31)
10875 return SDValue();
10876 } else
10877 return SDValue();
10879 if (SRA.getOperand(0) != Mul)
10880 return SDValue();
10882 SelectionDAG &DAG = DCI.DAG;
10883 SDLoc dl(AddcNode);
10884 unsigned Opcode = 0;
10885 SDValue Op0;
10886 SDValue Op1;
10888 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10889 Opcode = ARMISD::SMLALBB;
10890 Op0 = Mul.getOperand(0);
10891 Op1 = Mul.getOperand(1);
10892 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10893 Opcode = ARMISD::SMLALBT;
10894 Op0 = Mul.getOperand(0);
10895 Op1 = Mul.getOperand(1).getOperand(0);
10896 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10897 Opcode = ARMISD::SMLALTB;
10898 Op0 = Mul.getOperand(0).getOperand(0);
10899 Op1 = Mul.getOperand(1);
10900 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10901 Opcode = ARMISD::SMLALTT;
10902 Op0 = Mul->getOperand(0).getOperand(0);
10903 Op1 = Mul->getOperand(1).getOperand(0);
10906 if (!Op0 || !Op1)
10907 return SDValue();
10909 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10910 Op0, Op1, Lo, Hi);
10911 // Replace the ADDs' nodes uses by the MLA node's values.
10912 SDValue HiMLALResult(SMLAL.getNode(), 1);
10913 SDValue LoMLALResult(SMLAL.getNode(), 0);
10915 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10916 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10918 // Return original node to notify the driver to stop replacing.
10919 SDValue resNode(AddcNode, 0);
10920 return resNode;
10923 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10924 TargetLowering::DAGCombinerInfo &DCI,
10925 const ARMSubtarget *Subtarget) {
10926 // Look for multiply add opportunities.
10927 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10928 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10929 // a glue link from the first add to the second add.
10930 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10931 // a S/UMLAL instruction.
10932 // UMUL_LOHI
10933 // / :lo \ :hi
10934 // V \ [no multiline comment]
10935 // loAdd -> ADDC |
10936 // \ :carry /
10937 // V V
10938 // ADDE <- hiAdd
10940 // In the special case where only the higher part of a signed result is used
10941 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10942 // a constant with the exact value of 0x80000000, we recognize we are dealing
10943 // with a "rounded multiply and add" (or subtract) and transform it into
10944 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10946 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10947 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10948 "Expect an ADDE or SUBE");
10950 assert(AddeSubeNode->getNumOperands() == 3 &&
10951 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10952 "ADDE node has the wrong inputs");
10954 // Check that we are chained to the right ADDC or SUBC node.
10955 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10956 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10957 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10958 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10959 AddcSubcNode->getOpcode() != ARMISD::SUBC))
10960 return SDValue();
10962 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10963 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10965 // Check if the two operands are from the same mul_lohi node.
10966 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10967 return SDValue();
10969 assert(AddcSubcNode->getNumValues() == 2 &&
10970 AddcSubcNode->getValueType(0) == MVT::i32 &&
10971 "Expect ADDC with two result values. First: i32");
10973 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10974 // maybe a SMLAL which multiplies two 16-bit values.
10975 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10976 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10977 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10978 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10979 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10980 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10982 // Check for the triangle shape.
10983 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10984 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10986 // Make sure that the ADDE/SUBE operands are not coming from the same node.
10987 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10988 return SDValue();
10990 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10991 bool IsLeftOperandMUL = false;
10992 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10993 if (MULOp == SDValue())
10994 MULOp = findMUL_LOHI(AddeSubeOp1);
10995 else
10996 IsLeftOperandMUL = true;
10997 if (MULOp == SDValue())
10998 return SDValue();
11000 // Figure out the right opcode.
11001 unsigned Opc = MULOp->getOpcode();
11002 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11004 // Figure out the high and low input values to the MLAL node.
11005 SDValue *HiAddSub = nullptr;
11006 SDValue *LoMul = nullptr;
11007 SDValue *LowAddSub = nullptr;
11009 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11010 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11011 return SDValue();
11013 if (IsLeftOperandMUL)
11014 HiAddSub = &AddeSubeOp1;
11015 else
11016 HiAddSub = &AddeSubeOp0;
11018 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11019 // whose low result is fed to the ADDC/SUBC we are checking.
11021 if (AddcSubcOp0 == MULOp.getValue(0)) {
11022 LoMul = &AddcSubcOp0;
11023 LowAddSub = &AddcSubcOp1;
11025 if (AddcSubcOp1 == MULOp.getValue(0)) {
11026 LoMul = &AddcSubcOp1;
11027 LowAddSub = &AddcSubcOp0;
11030 if (!LoMul)
11031 return SDValue();
11033 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11034 // the replacement below will create a cycle.
11035 if (AddcSubcNode == HiAddSub->getNode() ||
11036 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11037 return SDValue();
11039 // Create the merged node.
11040 SelectionDAG &DAG = DCI.DAG;
11042 // Start building operand list.
11043 SmallVector<SDValue, 8> Ops;
11044 Ops.push_back(LoMul->getOperand(0));
11045 Ops.push_back(LoMul->getOperand(1));
11047 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
11048 // the case, we must be doing signed multiplication and only use the higher
11049 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11050 // addition or subtraction with the value of 0x800000.
11051 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11052 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11053 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11054 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11055 0x80000000) {
11056 Ops.push_back(*HiAddSub);
11057 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11058 FinalOpc = ARMISD::SMMLSR;
11059 } else {
11060 FinalOpc = ARMISD::SMMLAR;
11062 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11063 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11065 return SDValue(AddeSubeNode, 0);
11066 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11067 // SMMLS is generated during instruction selection and the rest of this
11068 // function can not handle the case where AddcSubcNode is a SUBC.
11069 return SDValue();
11071 // Finish building the operand list for {U/S}MLAL
11072 Ops.push_back(*LowAddSub);
11073 Ops.push_back(*HiAddSub);
11075 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11076 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11078 // Replace the ADDs' nodes uses by the MLA node's values.
11079 SDValue HiMLALResult(MLALNode.getNode(), 1);
11080 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11082 SDValue LoMLALResult(MLALNode.getNode(), 0);
11083 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11085 // Return original node to notify the driver to stop replacing.
11086 return SDValue(AddeSubeNode, 0);
11089 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11090 TargetLowering::DAGCombinerInfo &DCI,
11091 const ARMSubtarget *Subtarget) {
11092 // UMAAL is similar to UMLAL except that it adds two unsigned values.
11093 // While trying to combine for the other MLAL nodes, first search for the
11094 // chance to use UMAAL. Check if Addc uses a node which has already
11095 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11096 // as the addend, and it's handled in PerformUMLALCombine.
11098 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11099 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11101 // Check that we have a glued ADDC node.
11102 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11103 if (AddcNode->getOpcode() != ARMISD::ADDC)
11104 return SDValue();
11106 // Find the converted UMAAL or quit if it doesn't exist.
11107 SDNode *UmlalNode = nullptr;
11108 SDValue AddHi;
11109 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11110 UmlalNode = AddcNode->getOperand(0).getNode();
11111 AddHi = AddcNode->getOperand(1);
11112 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11113 UmlalNode = AddcNode->getOperand(1).getNode();
11114 AddHi = AddcNode->getOperand(0);
11115 } else {
11116 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11119 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11120 // the ADDC as well as Zero.
11121 if (!isNullConstant(UmlalNode->getOperand(3)))
11122 return SDValue();
11124 if ((isNullConstant(AddeNode->getOperand(0)) &&
11125 AddeNode->getOperand(1).getNode() == UmlalNode) ||
11126 (AddeNode->getOperand(0).getNode() == UmlalNode &&
11127 isNullConstant(AddeNode->getOperand(1)))) {
11128 SelectionDAG &DAG = DCI.DAG;
11129 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11130 UmlalNode->getOperand(2), AddHi };
11131 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11132 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11134 // Replace the ADDs' nodes uses by the UMAAL node's values.
11135 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11136 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11138 // Return original node to notify the driver to stop replacing.
11139 return SDValue(AddeNode, 0);
11141 return SDValue();
11144 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11145 const ARMSubtarget *Subtarget) {
11146 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11147 return SDValue();
11149 // Check that we have a pair of ADDC and ADDE as operands.
11150 // Both addends of the ADDE must be zero.
11151 SDNode* AddcNode = N->getOperand(2).getNode();
11152 SDNode* AddeNode = N->getOperand(3).getNode();
11153 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11154 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11155 isNullConstant(AddeNode->getOperand(0)) &&
11156 isNullConstant(AddeNode->getOperand(1)) &&
11157 (AddeNode->getOperand(2).getNode() == AddcNode))
11158 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11159 DAG.getVTList(MVT::i32, MVT::i32),
11160 {N->getOperand(0), N->getOperand(1),
11161 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11162 else
11163 return SDValue();
11166 static SDValue PerformAddcSubcCombine(SDNode *N,
11167 TargetLowering::DAGCombinerInfo &DCI,
11168 const ARMSubtarget *Subtarget) {
11169 SelectionDAG &DAG(DCI.DAG);
11171 if (N->getOpcode() == ARMISD::SUBC) {
11172 // (SUBC (ADDE 0, 0, C), 1) -> C
11173 SDValue LHS = N->getOperand(0);
11174 SDValue RHS = N->getOperand(1);
11175 if (LHS->getOpcode() == ARMISD::ADDE &&
11176 isNullConstant(LHS->getOperand(0)) &&
11177 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11178 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11182 if (Subtarget->isThumb1Only()) {
11183 SDValue RHS = N->getOperand(1);
11184 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11185 int32_t imm = C->getSExtValue();
11186 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11187 SDLoc DL(N);
11188 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11189 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11190 : ARMISD::ADDC;
11191 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11196 return SDValue();
11199 static SDValue PerformAddeSubeCombine(SDNode *N,
11200 TargetLowering::DAGCombinerInfo &DCI,
11201 const ARMSubtarget *Subtarget) {
11202 if (Subtarget->isThumb1Only()) {
11203 SelectionDAG &DAG = DCI.DAG;
11204 SDValue RHS = N->getOperand(1);
11205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11206 int64_t imm = C->getSExtValue();
11207 if (imm < 0) {
11208 SDLoc DL(N);
11210 // The with-carry-in form matches bitwise not instead of the negation.
11211 // Effectively, the inverse interpretation of the carry flag already
11212 // accounts for part of the negation.
11213 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11215 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11216 : ARMISD::ADDE;
11217 return DAG.getNode(Opcode, DL, N->getVTList(),
11218 N->getOperand(0), RHS, N->getOperand(2));
11221 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11222 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11224 return SDValue();
11227 static SDValue PerformABSCombine(SDNode *N,
11228 TargetLowering::DAGCombinerInfo &DCI,
11229 const ARMSubtarget *Subtarget) {
11230 SDValue res;
11231 SelectionDAG &DAG = DCI.DAG;
11232 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11234 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11235 return SDValue();
11237 if (!TLI.expandABS(N, res, DAG))
11238 return SDValue();
11240 return res;
11243 /// PerformADDECombine - Target-specific dag combine transform from
11244 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11245 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11246 static SDValue PerformADDECombine(SDNode *N,
11247 TargetLowering::DAGCombinerInfo &DCI,
11248 const ARMSubtarget *Subtarget) {
11249 // Only ARM and Thumb2 support UMLAL/SMLAL.
11250 if (Subtarget->isThumb1Only())
11251 return PerformAddeSubeCombine(N, DCI, Subtarget);
11253 // Only perform the checks after legalize when the pattern is available.
11254 if (DCI.isBeforeLegalize()) return SDValue();
11256 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11259 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11260 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11261 /// called with the default operands, and if that fails, with commuted
11262 /// operands.
11263 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11264 TargetLowering::DAGCombinerInfo &DCI,
11265 const ARMSubtarget *Subtarget){
11266 // Attempt to create vpadd for this add.
11267 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11268 return Result;
11270 // Attempt to create vpaddl for this add.
11271 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11272 return Result;
11273 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11274 Subtarget))
11275 return Result;
11277 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11278 if (N0.getNode()->hasOneUse())
11279 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11280 return Result;
11281 return SDValue();
11284 bool
11285 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11286 CombineLevel Level) const {
11287 if (Level == BeforeLegalizeTypes)
11288 return true;
11290 if (N->getOpcode() != ISD::SHL)
11291 return true;
11293 if (Subtarget->isThumb1Only()) {
11294 // Avoid making expensive immediates by commuting shifts. (This logic
11295 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11296 // for free.)
11297 if (N->getOpcode() != ISD::SHL)
11298 return true;
11299 SDValue N1 = N->getOperand(0);
11300 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11301 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11302 return true;
11303 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11304 if (Const->getAPIntValue().ult(256))
11305 return false;
11306 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11307 Const->getAPIntValue().sgt(-256))
11308 return false;
11310 return true;
11313 // Turn off commute-with-shift transform after legalization, so it doesn't
11314 // conflict with PerformSHLSimplify. (We could try to detect when
11315 // PerformSHLSimplify would trigger more precisely, but it isn't
11316 // really necessary.)
11317 return false;
11320 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11321 const SDNode *N, CombineLevel Level) const {
11322 if (!Subtarget->isThumb1Only())
11323 return true;
11325 if (Level == BeforeLegalizeTypes)
11326 return true;
11328 return false;
11331 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11332 if (!Subtarget->hasNEON()) {
11333 if (Subtarget->isThumb1Only())
11334 return VT.getScalarSizeInBits() <= 32;
11335 return true;
11337 return VT.isScalarInteger();
11340 static SDValue PerformSHLSimplify(SDNode *N,
11341 TargetLowering::DAGCombinerInfo &DCI,
11342 const ARMSubtarget *ST) {
11343 // Allow the generic combiner to identify potential bswaps.
11344 if (DCI.isBeforeLegalize())
11345 return SDValue();
11347 // DAG combiner will fold:
11348 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11349 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11350 // Other code patterns that can be also be modified have the following form:
11351 // b + ((a << 1) | 510)
11352 // b + ((a << 1) & 510)
11353 // b + ((a << 1) ^ 510)
11354 // b + ((a << 1) + 510)
11356 // Many instructions can perform the shift for free, but it requires both
11357 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11358 // instruction will needed. So, unfold back to the original pattern if:
11359 // - if c1 and c2 are small enough that they don't require mov imms.
11360 // - the user(s) of the node can perform an shl
11362 // No shifted operands for 16-bit instructions.
11363 if (ST->isThumb() && ST->isThumb1Only())
11364 return SDValue();
11366 // Check that all the users could perform the shl themselves.
11367 for (auto U : N->uses()) {
11368 switch(U->getOpcode()) {
11369 default:
11370 return SDValue();
11371 case ISD::SUB:
11372 case ISD::ADD:
11373 case ISD::AND:
11374 case ISD::OR:
11375 case ISD::XOR:
11376 case ISD::SETCC:
11377 case ARMISD::CMP:
11378 // Check that the user isn't already using a constant because there
11379 // aren't any instructions that support an immediate operand and a
11380 // shifted operand.
11381 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11382 isa<ConstantSDNode>(U->getOperand(1)))
11383 return SDValue();
11385 // Check that it's not already using a shift.
11386 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11387 U->getOperand(1).getOpcode() == ISD::SHL)
11388 return SDValue();
11389 break;
11393 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11394 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11395 return SDValue();
11397 if (N->getOperand(0).getOpcode() != ISD::SHL)
11398 return SDValue();
11400 SDValue SHL = N->getOperand(0);
11402 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11403 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11404 if (!C1ShlC2 || !C2)
11405 return SDValue();
11407 APInt C2Int = C2->getAPIntValue();
11408 APInt C1Int = C1ShlC2->getAPIntValue();
11410 // Check that performing a lshr will not lose any information.
11411 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11412 C2Int.getBitWidth() - C2->getZExtValue());
11413 if ((C1Int & Mask) != C1Int)
11414 return SDValue();
11416 // Shift the first constant.
11417 C1Int.lshrInPlace(C2Int);
11419 // The immediates are encoded as an 8-bit value that can be rotated.
11420 auto LargeImm = [](const APInt &Imm) {
11421 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11422 return Imm.getBitWidth() - Zeros > 8;
11425 if (LargeImm(C1Int) || LargeImm(C2Int))
11426 return SDValue();
11428 SelectionDAG &DAG = DCI.DAG;
11429 SDLoc dl(N);
11430 SDValue X = SHL.getOperand(0);
11431 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11432 DAG.getConstant(C1Int, dl, MVT::i32));
11433 // Shift left to compensate for the lshr of C1Int.
11434 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11436 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11437 SHL.dump(); N->dump());
11438 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11439 return Res;
11443 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11445 static SDValue PerformADDCombine(SDNode *N,
11446 TargetLowering::DAGCombinerInfo &DCI,
11447 const ARMSubtarget *Subtarget) {
11448 SDValue N0 = N->getOperand(0);
11449 SDValue N1 = N->getOperand(1);
11451 // Only works one way, because it needs an immediate operand.
11452 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11453 return Result;
11455 // First try with the default operand order.
11456 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11457 return Result;
11459 // If that didn't work, try again with the operands commuted.
11460 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11463 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11465 static SDValue PerformSUBCombine(SDNode *N,
11466 TargetLowering::DAGCombinerInfo &DCI) {
11467 SDValue N0 = N->getOperand(0);
11468 SDValue N1 = N->getOperand(1);
11470 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11471 if (N1.getNode()->hasOneUse())
11472 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11473 return Result;
11475 return SDValue();
11478 /// PerformVMULCombine
11479 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11480 /// special multiplier accumulator forwarding.
11481 /// vmul d3, d0, d2
11482 /// vmla d3, d1, d2
11483 /// is faster than
11484 /// vadd d3, d0, d1
11485 /// vmul d3, d3, d2
11486 // However, for (A + B) * (A + B),
11487 // vadd d2, d0, d1
11488 // vmul d3, d0, d2
11489 // vmla d3, d1, d2
11490 // is slower than
11491 // vadd d2, d0, d1
11492 // vmul d3, d2, d2
11493 static SDValue PerformVMULCombine(SDNode *N,
11494 TargetLowering::DAGCombinerInfo &DCI,
11495 const ARMSubtarget *Subtarget) {
11496 if (!Subtarget->hasVMLxForwarding())
11497 return SDValue();
11499 SelectionDAG &DAG = DCI.DAG;
11500 SDValue N0 = N->getOperand(0);
11501 SDValue N1 = N->getOperand(1);
11502 unsigned Opcode = N0.getOpcode();
11503 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11504 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11505 Opcode = N1.getOpcode();
11506 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11507 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11508 return SDValue();
11509 std::swap(N0, N1);
11512 if (N0 == N1)
11513 return SDValue();
11515 EVT VT = N->getValueType(0);
11516 SDLoc DL(N);
11517 SDValue N00 = N0->getOperand(0);
11518 SDValue N01 = N0->getOperand(1);
11519 return DAG.getNode(Opcode, DL, VT,
11520 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11521 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11524 static SDValue PerformMULCombine(SDNode *N,
11525 TargetLowering::DAGCombinerInfo &DCI,
11526 const ARMSubtarget *Subtarget) {
11527 SelectionDAG &DAG = DCI.DAG;
11529 if (Subtarget->isThumb1Only())
11530 return SDValue();
11532 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11533 return SDValue();
11535 EVT VT = N->getValueType(0);
11536 if (VT.is64BitVector() || VT.is128BitVector())
11537 return PerformVMULCombine(N, DCI, Subtarget);
11538 if (VT != MVT::i32)
11539 return SDValue();
11541 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11542 if (!C)
11543 return SDValue();
11545 int64_t MulAmt = C->getSExtValue();
11546 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11548 ShiftAmt = ShiftAmt & (32 - 1);
11549 SDValue V = N->getOperand(0);
11550 SDLoc DL(N);
11552 SDValue Res;
11553 MulAmt >>= ShiftAmt;
11555 if (MulAmt >= 0) {
11556 if (isPowerOf2_32(MulAmt - 1)) {
11557 // (mul x, 2^N + 1) => (add (shl x, N), x)
11558 Res = DAG.getNode(ISD::ADD, DL, VT,
11560 DAG.getNode(ISD::SHL, DL, VT,
11562 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11563 MVT::i32)));
11564 } else if (isPowerOf2_32(MulAmt + 1)) {
11565 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11566 Res = DAG.getNode(ISD::SUB, DL, VT,
11567 DAG.getNode(ISD::SHL, DL, VT,
11569 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11570 MVT::i32)),
11572 } else
11573 return SDValue();
11574 } else {
11575 uint64_t MulAmtAbs = -MulAmt;
11576 if (isPowerOf2_32(MulAmtAbs + 1)) {
11577 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11578 Res = DAG.getNode(ISD::SUB, DL, VT,
11580 DAG.getNode(ISD::SHL, DL, VT,
11582 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11583 MVT::i32)));
11584 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11585 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11586 Res = DAG.getNode(ISD::ADD, DL, VT,
11588 DAG.getNode(ISD::SHL, DL, VT,
11590 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11591 MVT::i32)));
11592 Res = DAG.getNode(ISD::SUB, DL, VT,
11593 DAG.getConstant(0, DL, MVT::i32), Res);
11594 } else
11595 return SDValue();
11598 if (ShiftAmt != 0)
11599 Res = DAG.getNode(ISD::SHL, DL, VT,
11600 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11602 // Do not add new nodes to DAG combiner worklist.
11603 DCI.CombineTo(N, Res, false);
11604 return SDValue();
11607 static SDValue CombineANDShift(SDNode *N,
11608 TargetLowering::DAGCombinerInfo &DCI,
11609 const ARMSubtarget *Subtarget) {
11610 // Allow DAGCombine to pattern-match before we touch the canonical form.
11611 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11612 return SDValue();
11614 if (N->getValueType(0) != MVT::i32)
11615 return SDValue();
11617 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11618 if (!N1C)
11619 return SDValue();
11621 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11622 // Don't transform uxtb/uxth.
11623 if (C1 == 255 || C1 == 65535)
11624 return SDValue();
11626 SDNode *N0 = N->getOperand(0).getNode();
11627 if (!N0->hasOneUse())
11628 return SDValue();
11630 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11631 return SDValue();
11633 bool LeftShift = N0->getOpcode() == ISD::SHL;
11635 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11636 if (!N01C)
11637 return SDValue();
11639 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11640 if (!C2 || C2 >= 32)
11641 return SDValue();
11643 // Clear irrelevant bits in the mask.
11644 if (LeftShift)
11645 C1 &= (-1U << C2);
11646 else
11647 C1 &= (-1U >> C2);
11649 SelectionDAG &DAG = DCI.DAG;
11650 SDLoc DL(N);
11652 // We have a pattern of the form "(and (shl x, c2) c1)" or
11653 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11654 // transform to a pair of shifts, to save materializing c1.
11656 // First pattern: right shift, then mask off leading bits.
11657 // FIXME: Use demanded bits?
11658 if (!LeftShift && isMask_32(C1)) {
11659 uint32_t C3 = countLeadingZeros(C1);
11660 if (C2 < C3) {
11661 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11662 DAG.getConstant(C3 - C2, DL, MVT::i32));
11663 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11664 DAG.getConstant(C3, DL, MVT::i32));
11668 // First pattern, reversed: left shift, then mask off trailing bits.
11669 if (LeftShift && isMask_32(~C1)) {
11670 uint32_t C3 = countTrailingZeros(C1);
11671 if (C2 < C3) {
11672 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11673 DAG.getConstant(C3 - C2, DL, MVT::i32));
11674 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11675 DAG.getConstant(C3, DL, MVT::i32));
11679 // Second pattern: left shift, then mask off leading bits.
11680 // FIXME: Use demanded bits?
11681 if (LeftShift && isShiftedMask_32(C1)) {
11682 uint32_t Trailing = countTrailingZeros(C1);
11683 uint32_t C3 = countLeadingZeros(C1);
11684 if (Trailing == C2 && C2 + C3 < 32) {
11685 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11686 DAG.getConstant(C2 + C3, DL, MVT::i32));
11687 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11688 DAG.getConstant(C3, DL, MVT::i32));
11692 // Second pattern, reversed: right shift, then mask off trailing bits.
11693 // FIXME: Handle other patterns of known/demanded bits.
11694 if (!LeftShift && isShiftedMask_32(C1)) {
11695 uint32_t Leading = countLeadingZeros(C1);
11696 uint32_t C3 = countTrailingZeros(C1);
11697 if (Leading == C2 && C2 + C3 < 32) {
11698 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11699 DAG.getConstant(C2 + C3, DL, MVT::i32));
11700 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11701 DAG.getConstant(C3, DL, MVT::i32));
11705 // FIXME: Transform "(and (shl x, c2) c1)" ->
11706 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11707 // c1.
11708 return SDValue();
11711 static SDValue PerformANDCombine(SDNode *N,
11712 TargetLowering::DAGCombinerInfo &DCI,
11713 const ARMSubtarget *Subtarget) {
11714 // Attempt to use immediate-form VBIC
11715 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11716 SDLoc dl(N);
11717 EVT VT = N->getValueType(0);
11718 SelectionDAG &DAG = DCI.DAG;
11720 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11721 return SDValue();
11723 APInt SplatBits, SplatUndef;
11724 unsigned SplatBitSize;
11725 bool HasAnyUndefs;
11726 if (BVN && Subtarget->hasNEON() &&
11727 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11728 if (SplatBitSize <= 64) {
11729 EVT VbicVT;
11730 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11731 SplatUndef.getZExtValue(), SplatBitSize,
11732 DAG, dl, VbicVT, VT.is128BitVector(),
11733 OtherModImm);
11734 if (Val.getNode()) {
11735 SDValue Input =
11736 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11737 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11738 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11743 if (!Subtarget->isThumb1Only()) {
11744 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11745 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11746 return Result;
11748 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11749 return Result;
11752 if (Subtarget->isThumb1Only())
11753 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
11754 return Result;
11756 return SDValue();
11759 // Try combining OR nodes to SMULWB, SMULWT.
11760 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
11761 TargetLowering::DAGCombinerInfo &DCI,
11762 const ARMSubtarget *Subtarget) {
11763 if (!Subtarget->hasV6Ops() ||
11764 (Subtarget->isThumb() &&
11765 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
11766 return SDValue();
11768 SDValue SRL = OR->getOperand(0);
11769 SDValue SHL = OR->getOperand(1);
11771 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
11772 SRL = OR->getOperand(1);
11773 SHL = OR->getOperand(0);
11775 if (!isSRL16(SRL) || !isSHL16(SHL))
11776 return SDValue();
11778 // The first operands to the shifts need to be the two results from the
11779 // same smul_lohi node.
11780 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
11781 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
11782 return SDValue();
11784 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
11785 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
11786 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
11787 return SDValue();
11789 // Now we have:
11790 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
11791 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
11792 // For SMUWB the 16-bit value will signed extended somehow.
11793 // For SMULWT only the SRA is required.
11794 // Check both sides of SMUL_LOHI
11795 SDValue OpS16 = SMULLOHI->getOperand(0);
11796 SDValue OpS32 = SMULLOHI->getOperand(1);
11798 SelectionDAG &DAG = DCI.DAG;
11799 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
11800 OpS16 = OpS32;
11801 OpS32 = SMULLOHI->getOperand(0);
11804 SDLoc dl(OR);
11805 unsigned Opcode = 0;
11806 if (isS16(OpS16, DAG))
11807 Opcode = ARMISD::SMULWB;
11808 else if (isSRA16(OpS16)) {
11809 Opcode = ARMISD::SMULWT;
11810 OpS16 = OpS16->getOperand(0);
11812 else
11813 return SDValue();
11815 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11816 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11817 return SDValue(OR, 0);
11820 static SDValue PerformORCombineToBFI(SDNode *N,
11821 TargetLowering::DAGCombinerInfo &DCI,
11822 const ARMSubtarget *Subtarget) {
11823 // BFI is only available on V6T2+
11824 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11825 return SDValue();
11827 EVT VT = N->getValueType(0);
11828 SDValue N0 = N->getOperand(0);
11829 SDValue N1 = N->getOperand(1);
11830 SelectionDAG &DAG = DCI.DAG;
11831 SDLoc DL(N);
11832 // 1) or (and A, mask), val => ARMbfi A, val, mask
11833 // iff (val & mask) == val
11835 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11836 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
11837 // && mask == ~mask2
11838 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
11839 // && ~mask == mask2
11840 // (i.e., copy a bitfield value into another bitfield of the same width)
11842 if (VT != MVT::i32)
11843 return SDValue();
11845 SDValue N00 = N0.getOperand(0);
11847 // The value and the mask need to be constants so we can verify this is
11848 // actually a bitfield set. If the mask is 0xffff, we can do better
11849 // via a movt instruction, so don't use BFI in that case.
11850 SDValue MaskOp = N0.getOperand(1);
11851 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
11852 if (!MaskC)
11853 return SDValue();
11854 unsigned Mask = MaskC->getZExtValue();
11855 if (Mask == 0xffff)
11856 return SDValue();
11857 SDValue Res;
11858 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
11859 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11860 if (N1C) {
11861 unsigned Val = N1C->getZExtValue();
11862 if ((Val & ~Mask) != Val)
11863 return SDValue();
11865 if (ARM::isBitFieldInvertedMask(Mask)) {
11866 Val >>= countTrailingZeros(~Mask);
11868 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
11869 DAG.getConstant(Val, DL, MVT::i32),
11870 DAG.getConstant(Mask, DL, MVT::i32));
11872 DCI.CombineTo(N, Res, false);
11873 // Return value from the original node to inform the combiner than N is
11874 // now dead.
11875 return SDValue(N, 0);
11877 } else if (N1.getOpcode() == ISD::AND) {
11878 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11879 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11880 if (!N11C)
11881 return SDValue();
11882 unsigned Mask2 = N11C->getZExtValue();
11884 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
11885 // as is to match.
11886 if (ARM::isBitFieldInvertedMask(Mask) &&
11887 (Mask == ~Mask2)) {
11888 // The pack halfword instruction works better for masks that fit it,
11889 // so use that when it's available.
11890 if (Subtarget->hasDSP() &&
11891 (Mask == 0xffff || Mask == 0xffff0000))
11892 return SDValue();
11893 // 2a
11894 unsigned amt = countTrailingZeros(Mask2);
11895 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
11896 DAG.getConstant(amt, DL, MVT::i32));
11897 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
11898 DAG.getConstant(Mask, DL, MVT::i32));
11899 DCI.CombineTo(N, Res, false);
11900 // Return value from the original node to inform the combiner than N is
11901 // now dead.
11902 return SDValue(N, 0);
11903 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
11904 (~Mask == Mask2)) {
11905 // The pack halfword instruction works better for masks that fit it,
11906 // so use that when it's available.
11907 if (Subtarget->hasDSP() &&
11908 (Mask2 == 0xffff || Mask2 == 0xffff0000))
11909 return SDValue();
11910 // 2b
11911 unsigned lsb = countTrailingZeros(Mask);
11912 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
11913 DAG.getConstant(lsb, DL, MVT::i32));
11914 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
11915 DAG.getConstant(Mask2, DL, MVT::i32));
11916 DCI.CombineTo(N, Res, false);
11917 // Return value from the original node to inform the combiner than N is
11918 // now dead.
11919 return SDValue(N, 0);
11923 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
11924 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
11925 ARM::isBitFieldInvertedMask(~Mask)) {
11926 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
11927 // where lsb(mask) == #shamt and masked bits of B are known zero.
11928 SDValue ShAmt = N00.getOperand(1);
11929 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
11930 unsigned LSB = countTrailingZeros(Mask);
11931 if (ShAmtC != LSB)
11932 return SDValue();
11934 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11935 DAG.getConstant(~Mask, DL, MVT::i32));
11937 DCI.CombineTo(N, Res, false);
11938 // Return value from the original node to inform the combiner than N is
11939 // now dead.
11940 return SDValue(N, 0);
11943 return SDValue();
11946 static bool isValidMVECond(unsigned CC, bool IsFloat) {
11947 switch (CC) {
11948 case ARMCC::EQ:
11949 case ARMCC::NE:
11950 case ARMCC::LE:
11951 case ARMCC::GT:
11952 case ARMCC::GE:
11953 case ARMCC::LT:
11954 return true;
11955 case ARMCC::HS:
11956 case ARMCC::HI:
11957 return !IsFloat;
11958 default:
11959 return false;
11963 static SDValue PerformORCombine_i1(SDNode *N,
11964 TargetLowering::DAGCombinerInfo &DCI,
11965 const ARMSubtarget *Subtarget) {
11966 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
11967 // together with predicates
11968 EVT VT = N->getValueType(0);
11969 SDValue N0 = N->getOperand(0);
11970 SDValue N1 = N->getOperand(1);
11972 ARMCC::CondCodes CondCode0 = ARMCC::AL;
11973 ARMCC::CondCodes CondCode1 = ARMCC::AL;
11974 if (N0->getOpcode() == ARMISD::VCMP)
11975 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
11976 ->getZExtValue();
11977 else if (N0->getOpcode() == ARMISD::VCMPZ)
11978 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
11979 ->getZExtValue();
11980 if (N1->getOpcode() == ARMISD::VCMP)
11981 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
11982 ->getZExtValue();
11983 else if (N1->getOpcode() == ARMISD::VCMPZ)
11984 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
11985 ->getZExtValue();
11987 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
11988 return SDValue();
11990 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
11991 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
11993 if (!isValidMVECond(Opposite0,
11994 N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
11995 !isValidMVECond(Opposite1,
11996 N1->getOperand(0)->getValueType(0).isFloatingPoint()))
11997 return SDValue();
11999 SmallVector<SDValue, 4> Ops0;
12000 Ops0.push_back(N0->getOperand(0));
12001 if (N0->getOpcode() == ARMISD::VCMP)
12002 Ops0.push_back(N0->getOperand(1));
12003 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12004 SmallVector<SDValue, 4> Ops1;
12005 Ops1.push_back(N1->getOperand(0));
12006 if (N1->getOpcode() == ARMISD::VCMP)
12007 Ops1.push_back(N1->getOperand(1));
12008 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12010 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12011 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12012 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12013 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12014 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12017 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12018 static SDValue PerformORCombine(SDNode *N,
12019 TargetLowering::DAGCombinerInfo &DCI,
12020 const ARMSubtarget *Subtarget) {
12021 // Attempt to use immediate-form VORR
12022 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12023 SDLoc dl(N);
12024 EVT VT = N->getValueType(0);
12025 SelectionDAG &DAG = DCI.DAG;
12027 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12028 return SDValue();
12030 APInt SplatBits, SplatUndef;
12031 unsigned SplatBitSize;
12032 bool HasAnyUndefs;
12033 if (BVN && Subtarget->hasNEON() &&
12034 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12035 if (SplatBitSize <= 64) {
12036 EVT VorrVT;
12037 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
12038 SplatUndef.getZExtValue(), SplatBitSize,
12039 DAG, dl, VorrVT, VT.is128BitVector(),
12040 OtherModImm);
12041 if (Val.getNode()) {
12042 SDValue Input =
12043 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12044 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12045 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12050 if (!Subtarget->isThumb1Only()) {
12051 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12052 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12053 return Result;
12054 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12055 return Result;
12058 SDValue N0 = N->getOperand(0);
12059 SDValue N1 = N->getOperand(1);
12061 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12062 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12063 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12065 // The code below optimizes (or (and X, Y), Z).
12066 // The AND operand needs to have a single user to make these optimizations
12067 // profitable.
12068 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12069 return SDValue();
12071 APInt SplatUndef;
12072 unsigned SplatBitSize;
12073 bool HasAnyUndefs;
12075 APInt SplatBits0, SplatBits1;
12076 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12077 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12078 // Ensure that the second operand of both ands are constants
12079 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12080 HasAnyUndefs) && !HasAnyUndefs) {
12081 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12082 HasAnyUndefs) && !HasAnyUndefs) {
12083 // Ensure that the bit width of the constants are the same and that
12084 // the splat arguments are logical inverses as per the pattern we
12085 // are trying to simplify.
12086 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12087 SplatBits0 == ~SplatBits1) {
12088 // Canonicalize the vector type to make instruction selection
12089 // simpler.
12090 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12091 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12092 N0->getOperand(1),
12093 N0->getOperand(0),
12094 N1->getOperand(0));
12095 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12101 if (Subtarget->hasMVEIntegerOps() &&
12102 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12103 return PerformORCombine_i1(N, DCI, Subtarget);
12105 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12106 // reasonable.
12107 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12108 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12109 return Res;
12112 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12113 return Result;
12115 return SDValue();
12118 static SDValue PerformXORCombine(SDNode *N,
12119 TargetLowering::DAGCombinerInfo &DCI,
12120 const ARMSubtarget *Subtarget) {
12121 EVT VT = N->getValueType(0);
12122 SelectionDAG &DAG = DCI.DAG;
12124 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12125 return SDValue();
12127 if (!Subtarget->isThumb1Only()) {
12128 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12129 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12130 return Result;
12132 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12133 return Result;
12136 return SDValue();
12139 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12140 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12141 // their position in "to" (Rd).
12142 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12143 assert(N->getOpcode() == ARMISD::BFI);
12145 SDValue From = N->getOperand(1);
12146 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12147 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12149 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12150 // #C in the base of the SHR.
12151 if (From->getOpcode() == ISD::SRL &&
12152 isa<ConstantSDNode>(From->getOperand(1))) {
12153 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12154 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12155 FromMask <<= Shift.getLimitedValue(31);
12156 From = From->getOperand(0);
12159 return From;
12162 // If A and B contain one contiguous set of bits, does A | B == A . B?
12164 // Neither A nor B must be zero.
12165 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12166 unsigned LastActiveBitInA = A.countTrailingZeros();
12167 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12168 return LastActiveBitInA - 1 == FirstActiveBitInB;
12171 static SDValue FindBFIToCombineWith(SDNode *N) {
12172 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12173 // if one exists.
12174 APInt ToMask, FromMask;
12175 SDValue From = ParseBFI(N, ToMask, FromMask);
12176 SDValue To = N->getOperand(0);
12178 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12179 // aren't compatible, but not if they set the same bit in their destination as
12180 // we do (or that of any BFI we're going to combine with).
12181 SDValue V = To;
12182 APInt CombinedToMask = ToMask;
12183 while (V.getOpcode() == ARMISD::BFI) {
12184 APInt NewToMask, NewFromMask;
12185 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12186 if (NewFrom != From) {
12187 // This BFI has a different base. Keep going.
12188 CombinedToMask |= NewToMask;
12189 V = V.getOperand(0);
12190 continue;
12193 // Do the written bits conflict with any we've seen so far?
12194 if ((NewToMask & CombinedToMask).getBoolValue())
12195 // Conflicting bits - bail out because going further is unsafe.
12196 return SDValue();
12198 // Are the new bits contiguous when combined with the old bits?
12199 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12200 BitsProperlyConcatenate(FromMask, NewFromMask))
12201 return V;
12202 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12203 BitsProperlyConcatenate(NewFromMask, FromMask))
12204 return V;
12206 // We've seen a write to some bits, so track it.
12207 CombinedToMask |= NewToMask;
12208 // Keep going...
12209 V = V.getOperand(0);
12212 return SDValue();
12215 static SDValue PerformBFICombine(SDNode *N,
12216 TargetLowering::DAGCombinerInfo &DCI) {
12217 SDValue N1 = N->getOperand(1);
12218 if (N1.getOpcode() == ISD::AND) {
12219 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12220 // the bits being cleared by the AND are not demanded by the BFI.
12221 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12222 if (!N11C)
12223 return SDValue();
12224 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12225 unsigned LSB = countTrailingZeros(~InvMask);
12226 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12227 assert(Width <
12228 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12229 "undefined behavior");
12230 unsigned Mask = (1u << Width) - 1;
12231 unsigned Mask2 = N11C->getZExtValue();
12232 if ((Mask & (~Mask2)) == 0)
12233 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12234 N->getOperand(0), N1.getOperand(0),
12235 N->getOperand(2));
12236 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12237 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12238 // Keep track of any consecutive bits set that all come from the same base
12239 // value. We can combine these together into a single BFI.
12240 SDValue CombineBFI = FindBFIToCombineWith(N);
12241 if (CombineBFI == SDValue())
12242 return SDValue();
12244 // We've found a BFI.
12245 APInt ToMask1, FromMask1;
12246 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12248 APInt ToMask2, FromMask2;
12249 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12250 assert(From1 == From2);
12251 (void)From2;
12253 // First, unlink CombineBFI.
12254 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12255 // Then create a new BFI, combining the two together.
12256 APInt NewFromMask = FromMask1 | FromMask2;
12257 APInt NewToMask = ToMask1 | ToMask2;
12259 EVT VT = N->getValueType(0);
12260 SDLoc dl(N);
12262 if (NewFromMask[0] == 0)
12263 From1 = DCI.DAG.getNode(
12264 ISD::SRL, dl, VT, From1,
12265 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12266 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12267 DCI.DAG.getConstant(~NewToMask, dl, VT));
12269 return SDValue();
12272 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12273 /// ARMISD::VMOVRRD.
12274 static SDValue PerformVMOVRRDCombine(SDNode *N,
12275 TargetLowering::DAGCombinerInfo &DCI,
12276 const ARMSubtarget *Subtarget) {
12277 // vmovrrd(vmovdrr x, y) -> x,y
12278 SDValue InDouble = N->getOperand(0);
12279 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12280 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12282 // vmovrrd(load f64) -> (load i32), (load i32)
12283 SDNode *InNode = InDouble.getNode();
12284 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12285 InNode->getValueType(0) == MVT::f64 &&
12286 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12287 !cast<LoadSDNode>(InNode)->isVolatile()) {
12288 // TODO: Should this be done for non-FrameIndex operands?
12289 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12291 SelectionDAG &DAG = DCI.DAG;
12292 SDLoc DL(LD);
12293 SDValue BasePtr = LD->getBasePtr();
12294 SDValue NewLD1 =
12295 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12296 LD->getAlignment(), LD->getMemOperand()->getFlags());
12298 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12299 DAG.getConstant(4, DL, MVT::i32));
12301 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12302 LD->getPointerInfo().getWithOffset(4),
12303 std::min(4U, LD->getAlignment()),
12304 LD->getMemOperand()->getFlags());
12306 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12307 if (DCI.DAG.getDataLayout().isBigEndian())
12308 std::swap (NewLD1, NewLD2);
12309 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12310 return Result;
12313 return SDValue();
12316 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12317 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12318 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12319 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12320 SDValue Op0 = N->getOperand(0);
12321 SDValue Op1 = N->getOperand(1);
12322 if (Op0.getOpcode() == ISD::BITCAST)
12323 Op0 = Op0.getOperand(0);
12324 if (Op1.getOpcode() == ISD::BITCAST)
12325 Op1 = Op1.getOperand(0);
12326 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12327 Op0.getNode() == Op1.getNode() &&
12328 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12329 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12330 N->getValueType(0), Op0.getOperand(0));
12331 return SDValue();
12334 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12335 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12336 /// i64 vector to have f64 elements, since the value can then be loaded
12337 /// directly into a VFP register.
12338 static bool hasNormalLoadOperand(SDNode *N) {
12339 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12340 for (unsigned i = 0; i < NumElts; ++i) {
12341 SDNode *Elt = N->getOperand(i).getNode();
12342 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12343 return true;
12345 return false;
12348 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12349 /// ISD::BUILD_VECTOR.
12350 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12351 TargetLowering::DAGCombinerInfo &DCI,
12352 const ARMSubtarget *Subtarget) {
12353 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12354 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12355 // into a pair of GPRs, which is fine when the value is used as a scalar,
12356 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12357 SelectionDAG &DAG = DCI.DAG;
12358 if (N->getNumOperands() == 2)
12359 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12360 return RV;
12362 // Load i64 elements as f64 values so that type legalization does not split
12363 // them up into i32 values.
12364 EVT VT = N->getValueType(0);
12365 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12366 return SDValue();
12367 SDLoc dl(N);
12368 SmallVector<SDValue, 8> Ops;
12369 unsigned NumElts = VT.getVectorNumElements();
12370 for (unsigned i = 0; i < NumElts; ++i) {
12371 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12372 Ops.push_back(V);
12373 // Make the DAGCombiner fold the bitcast.
12374 DCI.AddToWorklist(V.getNode());
12376 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12377 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12378 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12381 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12382 static SDValue
12383 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12384 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12385 // At that time, we may have inserted bitcasts from integer to float.
12386 // If these bitcasts have survived DAGCombine, change the lowering of this
12387 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12388 // force to use floating point types.
12390 // Make sure we can change the type of the vector.
12391 // This is possible iff:
12392 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12393 // 1.1. Vector is used only once.
12394 // 1.2. Use is a bit convert to an integer type.
12395 // 2. The size of its operands are 32-bits (64-bits are not legal).
12396 EVT VT = N->getValueType(0);
12397 EVT EltVT = VT.getVectorElementType();
12399 // Check 1.1. and 2.
12400 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12401 return SDValue();
12403 // By construction, the input type must be float.
12404 assert(EltVT == MVT::f32 && "Unexpected type!");
12406 // Check 1.2.
12407 SDNode *Use = *N->use_begin();
12408 if (Use->getOpcode() != ISD::BITCAST ||
12409 Use->getValueType(0).isFloatingPoint())
12410 return SDValue();
12412 // Check profitability.
12413 // Model is, if more than half of the relevant operands are bitcast from
12414 // i32, turn the build_vector into a sequence of insert_vector_elt.
12415 // Relevant operands are everything that is not statically
12416 // (i.e., at compile time) bitcasted.
12417 unsigned NumOfBitCastedElts = 0;
12418 unsigned NumElts = VT.getVectorNumElements();
12419 unsigned NumOfRelevantElts = NumElts;
12420 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12421 SDValue Elt = N->getOperand(Idx);
12422 if (Elt->getOpcode() == ISD::BITCAST) {
12423 // Assume only bit cast to i32 will go away.
12424 if (Elt->getOperand(0).getValueType() == MVT::i32)
12425 ++NumOfBitCastedElts;
12426 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12427 // Constants are statically casted, thus do not count them as
12428 // relevant operands.
12429 --NumOfRelevantElts;
12432 // Check if more than half of the elements require a non-free bitcast.
12433 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12434 return SDValue();
12436 SelectionDAG &DAG = DCI.DAG;
12437 // Create the new vector type.
12438 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12439 // Check if the type is legal.
12440 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12441 if (!TLI.isTypeLegal(VecVT))
12442 return SDValue();
12444 // Combine:
12445 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12446 // => BITCAST INSERT_VECTOR_ELT
12447 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12448 // (BITCAST EN), N.
12449 SDValue Vec = DAG.getUNDEF(VecVT);
12450 SDLoc dl(N);
12451 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12452 SDValue V = N->getOperand(Idx);
12453 if (V.isUndef())
12454 continue;
12455 if (V.getOpcode() == ISD::BITCAST &&
12456 V->getOperand(0).getValueType() == MVT::i32)
12457 // Fold obvious case.
12458 V = V.getOperand(0);
12459 else {
12460 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12461 // Make the DAGCombiner fold the bitcasts.
12462 DCI.AddToWorklist(V.getNode());
12464 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12465 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12467 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12468 // Make the DAGCombiner fold the bitcasts.
12469 DCI.AddToWorklist(Vec.getNode());
12470 return Vec;
12473 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12474 /// ISD::INSERT_VECTOR_ELT.
12475 static SDValue PerformInsertEltCombine(SDNode *N,
12476 TargetLowering::DAGCombinerInfo &DCI) {
12477 // Bitcast an i64 load inserted into a vector to f64.
12478 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12479 EVT VT = N->getValueType(0);
12480 SDNode *Elt = N->getOperand(1).getNode();
12481 if (VT.getVectorElementType() != MVT::i64 ||
12482 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12483 return SDValue();
12485 SelectionDAG &DAG = DCI.DAG;
12486 SDLoc dl(N);
12487 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12488 VT.getVectorNumElements());
12489 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12490 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12491 // Make the DAGCombiner fold the bitcasts.
12492 DCI.AddToWorklist(Vec.getNode());
12493 DCI.AddToWorklist(V.getNode());
12494 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12495 Vec, V, N->getOperand(2));
12496 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12499 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12500 /// ISD::VECTOR_SHUFFLE.
12501 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12502 // The LLVM shufflevector instruction does not require the shuffle mask
12503 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12504 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12505 // operands do not match the mask length, they are extended by concatenating
12506 // them with undef vectors. That is probably the right thing for other
12507 // targets, but for NEON it is better to concatenate two double-register
12508 // size vector operands into a single quad-register size vector. Do that
12509 // transformation here:
12510 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12511 // shuffle(concat(v1, v2), undef)
12512 SDValue Op0 = N->getOperand(0);
12513 SDValue Op1 = N->getOperand(1);
12514 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12515 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12516 Op0.getNumOperands() != 2 ||
12517 Op1.getNumOperands() != 2)
12518 return SDValue();
12519 SDValue Concat0Op1 = Op0.getOperand(1);
12520 SDValue Concat1Op1 = Op1.getOperand(1);
12521 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12522 return SDValue();
12523 // Skip the transformation if any of the types are illegal.
12524 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12525 EVT VT = N->getValueType(0);
12526 if (!TLI.isTypeLegal(VT) ||
12527 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12528 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12529 return SDValue();
12531 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12532 Op0.getOperand(0), Op1.getOperand(0));
12533 // Translate the shuffle mask.
12534 SmallVector<int, 16> NewMask;
12535 unsigned NumElts = VT.getVectorNumElements();
12536 unsigned HalfElts = NumElts/2;
12537 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12538 for (unsigned n = 0; n < NumElts; ++n) {
12539 int MaskElt = SVN->getMaskElt(n);
12540 int NewElt = -1;
12541 if (MaskElt < (int)HalfElts)
12542 NewElt = MaskElt;
12543 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12544 NewElt = HalfElts + MaskElt - NumElts;
12545 NewMask.push_back(NewElt);
12547 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12548 DAG.getUNDEF(VT), NewMask);
12551 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12552 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12553 /// base address updates.
12554 /// For generic load/stores, the memory type is assumed to be a vector.
12555 /// The caller is assumed to have checked legality.
12556 static SDValue CombineBaseUpdate(SDNode *N,
12557 TargetLowering::DAGCombinerInfo &DCI) {
12558 SelectionDAG &DAG = DCI.DAG;
12559 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12560 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12561 const bool isStore = N->getOpcode() == ISD::STORE;
12562 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12563 SDValue Addr = N->getOperand(AddrOpIdx);
12564 MemSDNode *MemN = cast<MemSDNode>(N);
12565 SDLoc dl(N);
12567 // Search for a use of the address operand that is an increment.
12568 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12569 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12570 SDNode *User = *UI;
12571 if (User->getOpcode() != ISD::ADD ||
12572 UI.getUse().getResNo() != Addr.getResNo())
12573 continue;
12575 // Check that the add is independent of the load/store. Otherwise, folding
12576 // it would create a cycle. We can avoid searching through Addr as it's a
12577 // predecessor to both.
12578 SmallPtrSet<const SDNode *, 32> Visited;
12579 SmallVector<const SDNode *, 16> Worklist;
12580 Visited.insert(Addr.getNode());
12581 Worklist.push_back(N);
12582 Worklist.push_back(User);
12583 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12584 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12585 continue;
12587 // Find the new opcode for the updating load/store.
12588 bool isLoadOp = true;
12589 bool isLaneOp = false;
12590 unsigned NewOpc = 0;
12591 unsigned NumVecs = 0;
12592 if (isIntrinsic) {
12593 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12594 switch (IntNo) {
12595 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12596 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12597 NumVecs = 1; break;
12598 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12599 NumVecs = 2; break;
12600 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12601 NumVecs = 3; break;
12602 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12603 NumVecs = 4; break;
12604 case Intrinsic::arm_neon_vld2dup:
12605 case Intrinsic::arm_neon_vld3dup:
12606 case Intrinsic::arm_neon_vld4dup:
12607 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12608 // combining base updates for such intrinsics.
12609 continue;
12610 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12611 NumVecs = 2; isLaneOp = true; break;
12612 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12613 NumVecs = 3; isLaneOp = true; break;
12614 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12615 NumVecs = 4; isLaneOp = true; break;
12616 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12617 NumVecs = 1; isLoadOp = false; break;
12618 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12619 NumVecs = 2; isLoadOp = false; break;
12620 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12621 NumVecs = 3; isLoadOp = false; break;
12622 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12623 NumVecs = 4; isLoadOp = false; break;
12624 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12625 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12626 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12627 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12628 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12629 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12631 } else {
12632 isLaneOp = true;
12633 switch (N->getOpcode()) {
12634 default: llvm_unreachable("unexpected opcode for Neon base update");
12635 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12636 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12637 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12638 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12639 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12640 NumVecs = 1; isLaneOp = false; break;
12641 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12642 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12646 // Find the size of memory referenced by the load/store.
12647 EVT VecTy;
12648 if (isLoadOp) {
12649 VecTy = N->getValueType(0);
12650 } else if (isIntrinsic) {
12651 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12652 } else {
12653 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12654 VecTy = N->getOperand(1).getValueType();
12657 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12658 if (isLaneOp)
12659 NumBytes /= VecTy.getVectorNumElements();
12661 // If the increment is a constant, it must match the memory ref size.
12662 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12663 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12664 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12665 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12666 // separate instructions that make it harder to use a non-constant update.
12667 continue;
12670 // OK, we found an ADD we can fold into the base update.
12671 // Now, create a _UPD node, taking care of not breaking alignment.
12673 EVT AlignedVecTy = VecTy;
12674 unsigned Alignment = MemN->getAlignment();
12676 // If this is a less-than-standard-aligned load/store, change the type to
12677 // match the standard alignment.
12678 // The alignment is overlooked when selecting _UPD variants; and it's
12679 // easier to introduce bitcasts here than fix that.
12680 // There are 3 ways to get to this base-update combine:
12681 // - intrinsics: they are assumed to be properly aligned (to the standard
12682 // alignment of the memory type), so we don't need to do anything.
12683 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12684 // intrinsics, so, likewise, there's nothing to do.
12685 // - generic load/store instructions: the alignment is specified as an
12686 // explicit operand, rather than implicitly as the standard alignment
12687 // of the memory type (like the intrisics). We need to change the
12688 // memory type to match the explicit alignment. That way, we don't
12689 // generate non-standard-aligned ARMISD::VLDx nodes.
12690 if (isa<LSBaseSDNode>(N)) {
12691 if (Alignment == 0)
12692 Alignment = 1;
12693 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12694 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12695 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12696 assert(!isLaneOp && "Unexpected generic load/store lane.");
12697 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12698 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12700 // Don't set an explicit alignment on regular load/stores that we want
12701 // to transform to VLD/VST 1_UPD nodes.
12702 // This matches the behavior of regular load/stores, which only get an
12703 // explicit alignment if the MMO alignment is larger than the standard
12704 // alignment of the memory type.
12705 // Intrinsics, however, always get an explicit alignment, set to the
12706 // alignment of the MMO.
12707 Alignment = 1;
12710 // Create the new updating load/store node.
12711 // First, create an SDVTList for the new updating node's results.
12712 EVT Tys[6];
12713 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12714 unsigned n;
12715 for (n = 0; n < NumResultVecs; ++n)
12716 Tys[n] = AlignedVecTy;
12717 Tys[n++] = MVT::i32;
12718 Tys[n] = MVT::Other;
12719 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12721 // Then, gather the new node's operands.
12722 SmallVector<SDValue, 8> Ops;
12723 Ops.push_back(N->getOperand(0)); // incoming chain
12724 Ops.push_back(N->getOperand(AddrOpIdx));
12725 Ops.push_back(Inc);
12727 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12728 // Try to match the intrinsic's signature
12729 Ops.push_back(StN->getValue());
12730 } else {
12731 // Loads (and of course intrinsics) match the intrinsics' signature,
12732 // so just add all but the alignment operand.
12733 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12734 Ops.push_back(N->getOperand(i));
12737 // For all node types, the alignment operand is always the last one.
12738 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
12740 // If this is a non-standard-aligned STORE, the penultimate operand is the
12741 // stored value. Bitcast it to the aligned type.
12742 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
12743 SDValue &StVal = Ops[Ops.size()-2];
12744 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
12747 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
12748 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
12749 MemN->getMemOperand());
12751 // Update the uses.
12752 SmallVector<SDValue, 5> NewResults;
12753 for (unsigned i = 0; i < NumResultVecs; ++i)
12754 NewResults.push_back(SDValue(UpdN.getNode(), i));
12756 // If this is an non-standard-aligned LOAD, the first result is the loaded
12757 // value. Bitcast it to the expected result type.
12758 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
12759 SDValue &LdVal = NewResults[0];
12760 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
12763 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
12764 DCI.CombineTo(N, NewResults);
12765 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12767 break;
12769 return SDValue();
12772 static SDValue PerformVLDCombine(SDNode *N,
12773 TargetLowering::DAGCombinerInfo &DCI) {
12774 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12775 return SDValue();
12777 return CombineBaseUpdate(N, DCI);
12780 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
12781 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
12782 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
12783 /// return true.
12784 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12785 SelectionDAG &DAG = DCI.DAG;
12786 EVT VT = N->getValueType(0);
12787 // vldN-dup instructions only support 64-bit vectors for N > 1.
12788 if (!VT.is64BitVector())
12789 return false;
12791 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
12792 SDNode *VLD = N->getOperand(0).getNode();
12793 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
12794 return false;
12795 unsigned NumVecs = 0;
12796 unsigned NewOpc = 0;
12797 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
12798 if (IntNo == Intrinsic::arm_neon_vld2lane) {
12799 NumVecs = 2;
12800 NewOpc = ARMISD::VLD2DUP;
12801 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
12802 NumVecs = 3;
12803 NewOpc = ARMISD::VLD3DUP;
12804 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
12805 NumVecs = 4;
12806 NewOpc = ARMISD::VLD4DUP;
12807 } else {
12808 return false;
12811 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
12812 // numbers match the load.
12813 unsigned VLDLaneNo =
12814 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
12815 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12816 UI != UE; ++UI) {
12817 // Ignore uses of the chain result.
12818 if (UI.getUse().getResNo() == NumVecs)
12819 continue;
12820 SDNode *User = *UI;
12821 if (User->getOpcode() != ARMISD::VDUPLANE ||
12822 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
12823 return false;
12826 // Create the vldN-dup node.
12827 EVT Tys[5];
12828 unsigned n;
12829 for (n = 0; n < NumVecs; ++n)
12830 Tys[n] = VT;
12831 Tys[n] = MVT::Other;
12832 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
12833 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
12834 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
12835 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
12836 Ops, VLDMemInt->getMemoryVT(),
12837 VLDMemInt->getMemOperand());
12839 // Update the uses.
12840 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12841 UI != UE; ++UI) {
12842 unsigned ResNo = UI.getUse().getResNo();
12843 // Ignore uses of the chain result.
12844 if (ResNo == NumVecs)
12845 continue;
12846 SDNode *User = *UI;
12847 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
12850 // Now the vldN-lane intrinsic is dead except for its chain result.
12851 // Update uses of the chain.
12852 std::vector<SDValue> VLDDupResults;
12853 for (unsigned n = 0; n < NumVecs; ++n)
12854 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
12855 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
12856 DCI.CombineTo(VLD, VLDDupResults);
12858 return true;
12861 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
12862 /// ARMISD::VDUPLANE.
12863 static SDValue PerformVDUPLANECombine(SDNode *N,
12864 TargetLowering::DAGCombinerInfo &DCI) {
12865 SDValue Op = N->getOperand(0);
12867 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
12868 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
12869 if (CombineVLDDUP(N, DCI))
12870 return SDValue(N, 0);
12872 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
12873 // redundant. Ignore bit_converts for now; element sizes are checked below.
12874 while (Op.getOpcode() == ISD::BITCAST)
12875 Op = Op.getOperand(0);
12876 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
12877 return SDValue();
12879 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
12880 unsigned EltSize = Op.getScalarValueSizeInBits();
12881 // The canonical VMOV for a zero vector uses a 32-bit element size.
12882 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12883 unsigned EltBits;
12884 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
12885 EltSize = 8;
12886 EVT VT = N->getValueType(0);
12887 if (EltSize > VT.getScalarSizeInBits())
12888 return SDValue();
12890 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
12893 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
12894 static SDValue PerformVDUPCombine(SDNode *N,
12895 TargetLowering::DAGCombinerInfo &DCI,
12896 const ARMSubtarget *Subtarget) {
12897 SelectionDAG &DAG = DCI.DAG;
12898 SDValue Op = N->getOperand(0);
12900 if (!Subtarget->hasNEON())
12901 return SDValue();
12903 // Match VDUP(LOAD) -> VLD1DUP.
12904 // We match this pattern here rather than waiting for isel because the
12905 // transform is only legal for unindexed loads.
12906 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
12907 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
12908 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
12909 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
12910 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
12911 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
12912 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
12913 Ops, LD->getMemoryVT(),
12914 LD->getMemOperand());
12915 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
12916 return VLDDup;
12919 return SDValue();
12922 static SDValue PerformLOADCombine(SDNode *N,
12923 TargetLowering::DAGCombinerInfo &DCI) {
12924 EVT VT = N->getValueType(0);
12926 // If this is a legal vector load, try to combine it into a VLD1_UPD.
12927 if (ISD::isNormalLoad(N) && VT.isVector() &&
12928 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12929 return CombineBaseUpdate(N, DCI);
12931 return SDValue();
12934 /// PerformSTORECombine - Target-specific dag combine xforms for
12935 /// ISD::STORE.
12936 static SDValue PerformSTORECombine(SDNode *N,
12937 TargetLowering::DAGCombinerInfo &DCI) {
12938 StoreSDNode *St = cast<StoreSDNode>(N);
12939 if (St->isVolatile())
12940 return SDValue();
12942 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
12943 // pack all of the elements in one place. Next, store to memory in fewer
12944 // chunks.
12945 SDValue StVal = St->getValue();
12946 EVT VT = StVal.getValueType();
12947 if (St->isTruncatingStore() && VT.isVector()) {
12948 SelectionDAG &DAG = DCI.DAG;
12949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12950 EVT StVT = St->getMemoryVT();
12951 unsigned NumElems = VT.getVectorNumElements();
12952 assert(StVT != VT && "Cannot truncate to the same type");
12953 unsigned FromEltSz = VT.getScalarSizeInBits();
12954 unsigned ToEltSz = StVT.getScalarSizeInBits();
12956 // From, To sizes and ElemCount must be pow of two
12957 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
12959 // We are going to use the original vector elt for storing.
12960 // Accumulated smaller vector elements must be a multiple of the store size.
12961 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
12963 unsigned SizeRatio = FromEltSz / ToEltSz;
12964 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
12966 // Create a type on which we perform the shuffle.
12967 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
12968 NumElems*SizeRatio);
12969 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
12971 SDLoc DL(St);
12972 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
12973 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
12974 for (unsigned i = 0; i < NumElems; ++i)
12975 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
12976 ? (i + 1) * SizeRatio - 1
12977 : i * SizeRatio;
12979 // Can't shuffle using an illegal type.
12980 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
12982 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
12983 DAG.getUNDEF(WideVec.getValueType()),
12984 ShuffleVec);
12985 // At this point all of the data is stored at the bottom of the
12986 // register. We now need to save it to mem.
12988 // Find the largest store unit
12989 MVT StoreType = MVT::i8;
12990 for (MVT Tp : MVT::integer_valuetypes()) {
12991 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
12992 StoreType = Tp;
12994 // Didn't find a legal store type.
12995 if (!TLI.isTypeLegal(StoreType))
12996 return SDValue();
12998 // Bitcast the original vector into a vector of store-size units
12999 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13000 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13001 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13002 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13003 SmallVector<SDValue, 8> Chains;
13004 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13005 TLI.getPointerTy(DAG.getDataLayout()));
13006 SDValue BasePtr = St->getBasePtr();
13008 // Perform one or more big stores into memory.
13009 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
13010 for (unsigned I = 0; I < E; I++) {
13011 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
13012 StoreType, ShuffWide,
13013 DAG.getIntPtrConstant(I, DL));
13014 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
13015 St->getPointerInfo(), St->getAlignment(),
13016 St->getMemOperand()->getFlags());
13017 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
13018 Increment);
13019 Chains.push_back(Ch);
13021 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13024 if (!ISD::isNormalStore(St))
13025 return SDValue();
13027 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
13028 // ARM stores of arguments in the same cache line.
13029 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
13030 StVal.getNode()->hasOneUse()) {
13031 SelectionDAG &DAG = DCI.DAG;
13032 bool isBigEndian = DAG.getDataLayout().isBigEndian();
13033 SDLoc DL(St);
13034 SDValue BasePtr = St->getBasePtr();
13035 SDValue NewST1 = DAG.getStore(
13036 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
13037 BasePtr, St->getPointerInfo(), St->getAlignment(),
13038 St->getMemOperand()->getFlags());
13040 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13041 DAG.getConstant(4, DL, MVT::i32));
13042 return DAG.getStore(NewST1.getValue(0), DL,
13043 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
13044 OffsetPtr, St->getPointerInfo(),
13045 std::min(4U, St->getAlignment() / 2),
13046 St->getMemOperand()->getFlags());
13049 if (StVal.getValueType() == MVT::i64 &&
13050 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13052 // Bitcast an i64 store extracted from a vector to f64.
13053 // Otherwise, the i64 value will be legalized to a pair of i32 values.
13054 SelectionDAG &DAG = DCI.DAG;
13055 SDLoc dl(StVal);
13056 SDValue IntVec = StVal.getOperand(0);
13057 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13058 IntVec.getValueType().getVectorNumElements());
13059 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
13060 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13061 Vec, StVal.getOperand(1));
13062 dl = SDLoc(N);
13063 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
13064 // Make the DAGCombiner fold the bitcasts.
13065 DCI.AddToWorklist(Vec.getNode());
13066 DCI.AddToWorklist(ExtElt.getNode());
13067 DCI.AddToWorklist(V.getNode());
13068 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
13069 St->getPointerInfo(), St->getAlignment(),
13070 St->getMemOperand()->getFlags(), St->getAAInfo());
13073 // If this is a legal vector store, try to combine it into a VST1_UPD.
13074 if (ISD::isNormalStore(N) && VT.isVector() &&
13075 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13076 return CombineBaseUpdate(N, DCI);
13078 return SDValue();
13081 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
13082 /// can replace combinations of VMUL and VCVT (floating-point to integer)
13083 /// when the VMUL has a constant operand that is a power of 2.
13085 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13086 /// vmul.f32 d16, d17, d16
13087 /// vcvt.s32.f32 d16, d16
13088 /// becomes:
13089 /// vcvt.s32.f32 d16, d16, #3
13090 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
13091 const ARMSubtarget *Subtarget) {
13092 if (!Subtarget->hasNEON())
13093 return SDValue();
13095 SDValue Op = N->getOperand(0);
13096 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13097 Op.getOpcode() != ISD::FMUL)
13098 return SDValue();
13100 SDValue ConstVec = Op->getOperand(1);
13101 if (!isa<BuildVectorSDNode>(ConstVec))
13102 return SDValue();
13104 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13105 uint32_t FloatBits = FloatTy.getSizeInBits();
13106 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13107 uint32_t IntBits = IntTy.getSizeInBits();
13108 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13109 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13110 // These instructions only exist converting from f32 to i32. We can handle
13111 // smaller integers by generating an extra truncate, but larger ones would
13112 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13113 // these intructions only support v2i32/v4i32 types.
13114 return SDValue();
13117 BitVector UndefElements;
13118 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13119 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13120 if (C == -1 || C == 0 || C > 32)
13121 return SDValue();
13123 SDLoc dl(N);
13124 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
13125 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
13126 Intrinsic::arm_neon_vcvtfp2fxu;
13127 SDValue FixConv = DAG.getNode(
13128 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13129 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
13130 DAG.getConstant(C, dl, MVT::i32));
13132 if (IntBits < FloatBits)
13133 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
13135 return FixConv;
13138 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13139 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13140 /// when the VDIV has a constant operand that is a power of 2.
13142 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13143 /// vcvt.f32.s32 d16, d16
13144 /// vdiv.f32 d16, d17, d16
13145 /// becomes:
13146 /// vcvt.f32.s32 d16, d16, #3
13147 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13148 const ARMSubtarget *Subtarget) {
13149 if (!Subtarget->hasNEON())
13150 return SDValue();
13152 SDValue Op = N->getOperand(0);
13153 unsigned OpOpcode = Op.getNode()->getOpcode();
13154 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13155 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13156 return SDValue();
13158 SDValue ConstVec = N->getOperand(1);
13159 if (!isa<BuildVectorSDNode>(ConstVec))
13160 return SDValue();
13162 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13163 uint32_t FloatBits = FloatTy.getSizeInBits();
13164 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13165 uint32_t IntBits = IntTy.getSizeInBits();
13166 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13167 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13168 // These instructions only exist converting from i32 to f32. We can handle
13169 // smaller integers by generating an extra extend, but larger ones would
13170 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13171 // these intructions only support v2i32/v4i32 types.
13172 return SDValue();
13175 BitVector UndefElements;
13176 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13177 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13178 if (C == -1 || C == 0 || C > 32)
13179 return SDValue();
13181 SDLoc dl(N);
13182 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13183 SDValue ConvInput = Op.getOperand(0);
13184 if (IntBits < FloatBits)
13185 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13186 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13187 ConvInput);
13189 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13190 Intrinsic::arm_neon_vcvtfxu2fp;
13191 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13192 Op.getValueType(),
13193 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13194 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13197 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13198 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13199 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13200 switch (IntNo) {
13201 default:
13202 // Don't do anything for most intrinsics.
13203 break;
13205 // Vector shifts: check for immediate versions and lower them.
13206 // Note: This is done during DAG combining instead of DAG legalizing because
13207 // the build_vectors for 64-bit vector element shift counts are generally
13208 // not legal, and it is hard to see their values after they get legalized to
13209 // loads from a constant pool.
13210 case Intrinsic::arm_neon_vshifts:
13211 case Intrinsic::arm_neon_vshiftu:
13212 case Intrinsic::arm_neon_vrshifts:
13213 case Intrinsic::arm_neon_vrshiftu:
13214 case Intrinsic::arm_neon_vrshiftn:
13215 case Intrinsic::arm_neon_vqshifts:
13216 case Intrinsic::arm_neon_vqshiftu:
13217 case Intrinsic::arm_neon_vqshiftsu:
13218 case Intrinsic::arm_neon_vqshiftns:
13219 case Intrinsic::arm_neon_vqshiftnu:
13220 case Intrinsic::arm_neon_vqshiftnsu:
13221 case Intrinsic::arm_neon_vqrshiftns:
13222 case Intrinsic::arm_neon_vqrshiftnu:
13223 case Intrinsic::arm_neon_vqrshiftnsu: {
13224 EVT VT = N->getOperand(1).getValueType();
13225 int64_t Cnt;
13226 unsigned VShiftOpc = 0;
13228 switch (IntNo) {
13229 case Intrinsic::arm_neon_vshifts:
13230 case Intrinsic::arm_neon_vshiftu:
13231 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13232 VShiftOpc = ARMISD::VSHLIMM;
13233 break;
13235 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13236 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13237 : ARMISD::VSHRuIMM);
13238 break;
13240 return SDValue();
13242 case Intrinsic::arm_neon_vrshifts:
13243 case Intrinsic::arm_neon_vrshiftu:
13244 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13245 break;
13246 return SDValue();
13248 case Intrinsic::arm_neon_vqshifts:
13249 case Intrinsic::arm_neon_vqshiftu:
13250 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13251 break;
13252 return SDValue();
13254 case Intrinsic::arm_neon_vqshiftsu:
13255 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13256 break;
13257 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13259 case Intrinsic::arm_neon_vrshiftn:
13260 case Intrinsic::arm_neon_vqshiftns:
13261 case Intrinsic::arm_neon_vqshiftnu:
13262 case Intrinsic::arm_neon_vqshiftnsu:
13263 case Intrinsic::arm_neon_vqrshiftns:
13264 case Intrinsic::arm_neon_vqrshiftnu:
13265 case Intrinsic::arm_neon_vqrshiftnsu:
13266 // Narrowing shifts require an immediate right shift.
13267 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13268 break;
13269 llvm_unreachable("invalid shift count for narrowing vector shift "
13270 "intrinsic");
13272 default:
13273 llvm_unreachable("unhandled vector shift");
13276 switch (IntNo) {
13277 case Intrinsic::arm_neon_vshifts:
13278 case Intrinsic::arm_neon_vshiftu:
13279 // Opcode already set above.
13280 break;
13281 case Intrinsic::arm_neon_vrshifts:
13282 VShiftOpc = ARMISD::VRSHRsIMM;
13283 break;
13284 case Intrinsic::arm_neon_vrshiftu:
13285 VShiftOpc = ARMISD::VRSHRuIMM;
13286 break;
13287 case Intrinsic::arm_neon_vrshiftn:
13288 VShiftOpc = ARMISD::VRSHRNIMM;
13289 break;
13290 case Intrinsic::arm_neon_vqshifts:
13291 VShiftOpc = ARMISD::VQSHLsIMM;
13292 break;
13293 case Intrinsic::arm_neon_vqshiftu:
13294 VShiftOpc = ARMISD::VQSHLuIMM;
13295 break;
13296 case Intrinsic::arm_neon_vqshiftsu:
13297 VShiftOpc = ARMISD::VQSHLsuIMM;
13298 break;
13299 case Intrinsic::arm_neon_vqshiftns:
13300 VShiftOpc = ARMISD::VQSHRNsIMM;
13301 break;
13302 case Intrinsic::arm_neon_vqshiftnu:
13303 VShiftOpc = ARMISD::VQSHRNuIMM;
13304 break;
13305 case Intrinsic::arm_neon_vqshiftnsu:
13306 VShiftOpc = ARMISD::VQSHRNsuIMM;
13307 break;
13308 case Intrinsic::arm_neon_vqrshiftns:
13309 VShiftOpc = ARMISD::VQRSHRNsIMM;
13310 break;
13311 case Intrinsic::arm_neon_vqrshiftnu:
13312 VShiftOpc = ARMISD::VQRSHRNuIMM;
13313 break;
13314 case Intrinsic::arm_neon_vqrshiftnsu:
13315 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13316 break;
13319 SDLoc dl(N);
13320 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13321 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13324 case Intrinsic::arm_neon_vshiftins: {
13325 EVT VT = N->getOperand(1).getValueType();
13326 int64_t Cnt;
13327 unsigned VShiftOpc = 0;
13329 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13330 VShiftOpc = ARMISD::VSLIIMM;
13331 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13332 VShiftOpc = ARMISD::VSRIIMM;
13333 else {
13334 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13337 SDLoc dl(N);
13338 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13339 N->getOperand(1), N->getOperand(2),
13340 DAG.getConstant(Cnt, dl, MVT::i32));
13343 case Intrinsic::arm_neon_vqrshifts:
13344 case Intrinsic::arm_neon_vqrshiftu:
13345 // No immediate versions of these to check for.
13346 break;
13349 return SDValue();
13352 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13353 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13354 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13355 /// vector element shift counts are generally not legal, and it is hard to see
13356 /// their values after they get legalized to loads from a constant pool.
13357 static SDValue PerformShiftCombine(SDNode *N,
13358 TargetLowering::DAGCombinerInfo &DCI,
13359 const ARMSubtarget *ST) {
13360 SelectionDAG &DAG = DCI.DAG;
13361 EVT VT = N->getValueType(0);
13362 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13363 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13364 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13365 SDValue N1 = N->getOperand(1);
13366 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13367 SDValue N0 = N->getOperand(0);
13368 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13369 DAG.MaskedValueIsZero(N0.getOperand(0),
13370 APInt::getHighBitsSet(32, 16)))
13371 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13375 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13376 N->getOperand(0)->getOpcode() == ISD::AND &&
13377 N->getOperand(0)->hasOneUse()) {
13378 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13379 return SDValue();
13380 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13381 // usually show up because instcombine prefers to canonicalize it to
13382 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13383 // out of GEP lowering in some cases.
13384 SDValue N0 = N->getOperand(0);
13385 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13386 if (!ShiftAmtNode)
13387 return SDValue();
13388 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13389 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13390 if (!AndMaskNode)
13391 return SDValue();
13392 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13393 // Don't transform uxtb/uxth.
13394 if (AndMask == 255 || AndMask == 65535)
13395 return SDValue();
13396 if (isMask_32(AndMask)) {
13397 uint32_t MaskedBits = countLeadingZeros(AndMask);
13398 if (MaskedBits > ShiftAmt) {
13399 SDLoc DL(N);
13400 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13401 DAG.getConstant(MaskedBits, DL, MVT::i32));
13402 return DAG.getNode(
13403 ISD::SRL, DL, MVT::i32, SHL,
13404 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13409 // Nothing to be done for scalar shifts.
13410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13411 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13412 return SDValue();
13413 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13414 return SDValue();
13416 int64_t Cnt;
13418 switch (N->getOpcode()) {
13419 default: llvm_unreachable("unexpected shift opcode");
13421 case ISD::SHL:
13422 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13423 SDLoc dl(N);
13424 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13425 DAG.getConstant(Cnt, dl, MVT::i32));
13427 break;
13429 case ISD::SRA:
13430 case ISD::SRL:
13431 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13432 unsigned VShiftOpc =
13433 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13434 SDLoc dl(N);
13435 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13436 DAG.getConstant(Cnt, dl, MVT::i32));
13439 return SDValue();
13442 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13443 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13444 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13445 const ARMSubtarget *ST) {
13446 SDValue N0 = N->getOperand(0);
13448 // Check for sign- and zero-extensions of vector extract operations of 8-
13449 // and 16-bit vector elements. NEON supports these directly. They are
13450 // handled during DAG combining because type legalization will promote them
13451 // to 32-bit types and it is messy to recognize the operations after that.
13452 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13453 SDValue Vec = N0.getOperand(0);
13454 SDValue Lane = N0.getOperand(1);
13455 EVT VT = N->getValueType(0);
13456 EVT EltVT = N0.getValueType();
13457 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13459 if (VT == MVT::i32 &&
13460 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13461 TLI.isTypeLegal(Vec.getValueType()) &&
13462 isa<ConstantSDNode>(Lane)) {
13464 unsigned Opc = 0;
13465 switch (N->getOpcode()) {
13466 default: llvm_unreachable("unexpected opcode");
13467 case ISD::SIGN_EXTEND:
13468 Opc = ARMISD::VGETLANEs;
13469 break;
13470 case ISD::ZERO_EXTEND:
13471 case ISD::ANY_EXTEND:
13472 Opc = ARMISD::VGETLANEu;
13473 break;
13475 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13479 return SDValue();
13482 static const APInt *isPowerOf2Constant(SDValue V) {
13483 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13484 if (!C)
13485 return nullptr;
13486 const APInt *CV = &C->getAPIntValue();
13487 return CV->isPowerOf2() ? CV : nullptr;
13490 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13491 // If we have a CMOV, OR and AND combination such as:
13492 // if (x & CN)
13493 // y |= CM;
13495 // And:
13496 // * CN is a single bit;
13497 // * All bits covered by CM are known zero in y
13499 // Then we can convert this into a sequence of BFI instructions. This will
13500 // always be a win if CM is a single bit, will always be no worse than the
13501 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13502 // three bits (due to the extra IT instruction).
13504 SDValue Op0 = CMOV->getOperand(0);
13505 SDValue Op1 = CMOV->getOperand(1);
13506 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13507 auto CC = CCNode->getAPIntValue().getLimitedValue();
13508 SDValue CmpZ = CMOV->getOperand(4);
13510 // The compare must be against zero.
13511 if (!isNullConstant(CmpZ->getOperand(1)))
13512 return SDValue();
13514 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13515 SDValue And = CmpZ->getOperand(0);
13516 if (And->getOpcode() != ISD::AND)
13517 return SDValue();
13518 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13519 if (!AndC)
13520 return SDValue();
13521 SDValue X = And->getOperand(0);
13523 if (CC == ARMCC::EQ) {
13524 // We're performing an "equal to zero" compare. Swap the operands so we
13525 // canonicalize on a "not equal to zero" compare.
13526 std::swap(Op0, Op1);
13527 } else {
13528 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13531 if (Op1->getOpcode() != ISD::OR)
13532 return SDValue();
13534 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13535 if (!OrC)
13536 return SDValue();
13537 SDValue Y = Op1->getOperand(0);
13539 if (Op0 != Y)
13540 return SDValue();
13542 // Now, is it profitable to continue?
13543 APInt OrCI = OrC->getAPIntValue();
13544 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13545 if (OrCI.countPopulation() > Heuristic)
13546 return SDValue();
13548 // Lastly, can we determine that the bits defined by OrCI
13549 // are zero in Y?
13550 KnownBits Known = DAG.computeKnownBits(Y);
13551 if ((OrCI & Known.Zero) != OrCI)
13552 return SDValue();
13554 // OK, we can do the combine.
13555 SDValue V = Y;
13556 SDLoc dl(X);
13557 EVT VT = X.getValueType();
13558 unsigned BitInX = AndC->logBase2();
13560 if (BitInX != 0) {
13561 // We must shift X first.
13562 X = DAG.getNode(ISD::SRL, dl, VT, X,
13563 DAG.getConstant(BitInX, dl, VT));
13566 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13567 BitInY < NumActiveBits; ++BitInY) {
13568 if (OrCI[BitInY] == 0)
13569 continue;
13570 APInt Mask(VT.getSizeInBits(), 0);
13571 Mask.setBit(BitInY);
13572 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13573 // Confusingly, the operand is an *inverted* mask.
13574 DAG.getConstant(~Mask, dl, VT));
13577 return V;
13580 // Given N, the value controlling the conditional branch, search for the loop
13581 // intrinsic, returning it, along with how the value is used. We need to handle
13582 // patterns such as the following:
13583 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13584 // (brcond (setcc (loop.decrement), 0, eq), exit)
13585 // (brcond (setcc (loop.decrement), 0, ne), header)
13586 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13587 bool &Negate) {
13588 switch (N->getOpcode()) {
13589 default:
13590 break;
13591 case ISD::XOR: {
13592 if (!isa<ConstantSDNode>(N.getOperand(1)))
13593 return SDValue();
13594 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13595 return SDValue();
13596 Negate = !Negate;
13597 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
13599 case ISD::SETCC: {
13600 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
13601 if (!Const)
13602 return SDValue();
13603 if (Const->isNullValue())
13604 Imm = 0;
13605 else if (Const->isOne())
13606 Imm = 1;
13607 else
13608 return SDValue();
13609 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
13610 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
13612 case ISD::INTRINSIC_W_CHAIN: {
13613 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
13614 if (IntOp != Intrinsic::test_set_loop_iterations &&
13615 IntOp != Intrinsic::loop_decrement_reg)
13616 return SDValue();
13617 return N;
13620 return SDValue();
13623 static SDValue PerformHWLoopCombine(SDNode *N,
13624 TargetLowering::DAGCombinerInfo &DCI,
13625 const ARMSubtarget *ST) {
13627 // The hwloop intrinsics that we're interested are used for control-flow,
13628 // either for entering or exiting the loop:
13629 // - test.set.loop.iterations will test whether its operand is zero. If it
13630 // is zero, the proceeding branch should not enter the loop.
13631 // - loop.decrement.reg also tests whether its operand is zero. If it is
13632 // zero, the proceeding branch should not branch back to the beginning of
13633 // the loop.
13634 // So here, we need to check that how the brcond is using the result of each
13635 // of the intrinsics to ensure that we're branching to the right place at the
13636 // right time.
13638 ISD::CondCode CC;
13639 SDValue Cond;
13640 int Imm = 1;
13641 bool Negate = false;
13642 SDValue Chain = N->getOperand(0);
13643 SDValue Dest;
13645 if (N->getOpcode() == ISD::BRCOND) {
13646 CC = ISD::SETEQ;
13647 Cond = N->getOperand(1);
13648 Dest = N->getOperand(2);
13649 } else {
13650 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
13651 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13652 Cond = N->getOperand(2);
13653 Dest = N->getOperand(4);
13654 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
13655 if (!Const->isOne() && !Const->isNullValue())
13656 return SDValue();
13657 Imm = Const->getZExtValue();
13658 } else
13659 return SDValue();
13662 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
13663 if (!Int)
13664 return SDValue();
13666 if (Negate)
13667 CC = ISD::getSetCCInverse(CC, true);
13669 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
13670 return (CC == ISD::SETEQ && Imm == 0) ||
13671 (CC == ISD::SETNE && Imm == 1) ||
13672 (CC == ISD::SETLT && Imm == 1) ||
13673 (CC == ISD::SETULT && Imm == 1);
13676 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
13677 return (CC == ISD::SETEQ && Imm == 1) ||
13678 (CC == ISD::SETNE && Imm == 0) ||
13679 (CC == ISD::SETGT && Imm == 0) ||
13680 (CC == ISD::SETUGT && Imm == 0) ||
13681 (CC == ISD::SETGE && Imm == 1) ||
13682 (CC == ISD::SETUGE && Imm == 1);
13685 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
13686 "unsupported condition");
13688 SDLoc dl(Int);
13689 SelectionDAG &DAG = DCI.DAG;
13690 SDValue Elements = Int.getOperand(2);
13691 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
13692 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
13693 && "expected single br user");
13694 SDNode *Br = *N->use_begin();
13695 SDValue OtherTarget = Br->getOperand(1);
13697 // Update the unconditional branch to branch to the given Dest.
13698 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
13699 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
13700 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
13701 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
13704 if (IntOp == Intrinsic::test_set_loop_iterations) {
13705 SDValue Res;
13706 // We expect this 'instruction' to branch when the counter is zero.
13707 if (IsTrueIfZero(CC, Imm)) {
13708 SDValue Ops[] = { Chain, Elements, Dest };
13709 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13710 } else {
13711 // The logic is the reverse of what we need for WLS, so find the other
13712 // basic block target: the target of the proceeding br.
13713 UpdateUncondBr(Br, Dest, DAG);
13715 SDValue Ops[] = { Chain, Elements, OtherTarget };
13716 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13718 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
13719 return Res;
13720 } else {
13721 SDValue Size = DAG.getTargetConstant(
13722 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
13723 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
13724 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
13725 DAG.getVTList(MVT::i32, MVT::Other), Args);
13726 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
13728 // We expect this instruction to branch when the count is not zero.
13729 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
13731 // Update the unconditional branch to target the loop preheader if we've
13732 // found the condition has been reversed.
13733 if (Target == OtherTarget)
13734 UpdateUncondBr(Br, Dest, DAG);
13736 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13737 SDValue(LoopDec.getNode(), 1), Chain);
13739 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
13740 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
13742 return SDValue();
13745 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
13746 SDValue
13747 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
13748 SDValue Cmp = N->getOperand(4);
13749 if (Cmp.getOpcode() != ARMISD::CMPZ)
13750 // Only looking at NE cases.
13751 return SDValue();
13753 EVT VT = N->getValueType(0);
13754 SDLoc dl(N);
13755 SDValue LHS = Cmp.getOperand(0);
13756 SDValue RHS = Cmp.getOperand(1);
13757 SDValue Chain = N->getOperand(0);
13758 SDValue BB = N->getOperand(1);
13759 SDValue ARMcc = N->getOperand(2);
13760 ARMCC::CondCodes CC =
13761 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13763 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
13764 // -> (brcond Chain BB CC CPSR Cmp)
13765 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
13766 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
13767 LHS->getOperand(0)->hasOneUse()) {
13768 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
13769 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
13770 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13771 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13772 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
13773 (LHS01C && LHS01C->getZExtValue() == 1) &&
13774 (LHS1C && LHS1C->getZExtValue() == 1) &&
13775 (RHSC && RHSC->getZExtValue() == 0)) {
13776 return DAG.getNode(
13777 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
13778 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
13782 return SDValue();
13785 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
13786 SDValue
13787 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
13788 SDValue Cmp = N->getOperand(4);
13789 if (Cmp.getOpcode() != ARMISD::CMPZ)
13790 // Only looking at EQ and NE cases.
13791 return SDValue();
13793 EVT VT = N->getValueType(0);
13794 SDLoc dl(N);
13795 SDValue LHS = Cmp.getOperand(0);
13796 SDValue RHS = Cmp.getOperand(1);
13797 SDValue FalseVal = N->getOperand(0);
13798 SDValue TrueVal = N->getOperand(1);
13799 SDValue ARMcc = N->getOperand(2);
13800 ARMCC::CondCodes CC =
13801 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13803 // BFI is only available on V6T2+.
13804 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
13805 SDValue R = PerformCMOVToBFICombine(N, DAG);
13806 if (R)
13807 return R;
13810 // Simplify
13811 // mov r1, r0
13812 // cmp r1, x
13813 // mov r0, y
13814 // moveq r0, x
13815 // to
13816 // cmp r0, x
13817 // movne r0, y
13819 // mov r1, r0
13820 // cmp r1, x
13821 // mov r0, x
13822 // movne r0, y
13823 // to
13824 // cmp r0, x
13825 // movne r0, y
13826 /// FIXME: Turn this into a target neutral optimization?
13827 SDValue Res;
13828 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
13829 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
13830 N->getOperand(3), Cmp);
13831 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
13832 SDValue ARMcc;
13833 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
13834 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
13835 N->getOperand(3), NewCmp);
13838 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
13839 // -> (cmov F T CC CPSR Cmp)
13840 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
13841 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
13842 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13843 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13844 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
13845 (LHS1C && LHS1C->getZExtValue() == 1) &&
13846 (RHSC && RHSC->getZExtValue() == 0)) {
13847 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
13848 LHS->getOperand(2), LHS->getOperand(3),
13849 LHS->getOperand(4));
13853 if (!VT.isInteger())
13854 return SDValue();
13856 // Materialize a boolean comparison for integers so we can avoid branching.
13857 if (isNullConstant(FalseVal)) {
13858 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
13859 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
13860 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
13861 // right 5 bits will make that 32 be 1, otherwise it will be 0.
13862 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
13863 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13864 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
13865 DAG.getConstant(5, dl, MVT::i32));
13866 } else {
13867 // CMOV 0, 1, ==, (CMPZ x, y) ->
13868 // (ADDCARRY (SUB x, y), t:0, t:1)
13869 // where t = (SUBCARRY 0, (SUB x, y), 0)
13871 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
13872 // x != y. In other words, a carry C == 1 when x == y, C == 0
13873 // otherwise.
13874 // The final ADDCARRY computes
13875 // x - y + (0 - (x - y)) + C == C
13876 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13877 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13878 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
13879 // ISD::SUBCARRY returns a borrow but we want the carry here
13880 // actually.
13881 SDValue Carry =
13882 DAG.getNode(ISD::SUB, dl, MVT::i32,
13883 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
13884 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
13886 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
13887 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
13888 // This seems pointless but will allow us to combine it further below.
13889 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13890 SDValue Sub =
13891 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13892 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13893 Sub.getValue(1), SDValue());
13894 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
13895 N->getOperand(3), CPSRGlue.getValue(1));
13896 FalseVal = Sub;
13898 } else if (isNullConstant(TrueVal)) {
13899 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
13900 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
13901 // This seems pointless but will allow us to combine it further below
13902 // Note that we change == for != as this is the dual for the case above.
13903 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13904 SDValue Sub =
13905 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13906 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13907 Sub.getValue(1), SDValue());
13908 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
13909 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
13910 N->getOperand(3), CPSRGlue.getValue(1));
13911 FalseVal = Sub;
13915 // On Thumb1, the DAG above may be further combined if z is a power of 2
13916 // (z == 2 ^ K).
13917 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
13918 // t1 = (USUBO (SUB x, y), 1)
13919 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
13920 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13922 // This also handles the special case of comparing against zero; it's
13923 // essentially, the same pattern, except there's no SUBS:
13924 // CMOV x, z, !=, (CMPZ x, 0) ->
13925 // t1 = (USUBO x, 1)
13926 // t2 = (SUBCARRY x, t1:0, t1:1)
13927 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13928 const APInt *TrueConst;
13929 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
13930 ((FalseVal.getOpcode() == ARMISD::SUBS &&
13931 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
13932 (FalseVal == LHS && isNullConstant(RHS))) &&
13933 (TrueConst = isPowerOf2Constant(TrueVal))) {
13934 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13935 unsigned ShiftAmount = TrueConst->logBase2();
13936 if (ShiftAmount)
13937 TrueVal = DAG.getConstant(1, dl, VT);
13938 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
13939 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
13941 if (ShiftAmount)
13942 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
13943 DAG.getConstant(ShiftAmount, dl, MVT::i32));
13946 if (Res.getNode()) {
13947 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
13948 // Capture demanded bits information that would be otherwise lost.
13949 if (Known.Zero == 0xfffffffe)
13950 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13951 DAG.getValueType(MVT::i1));
13952 else if (Known.Zero == 0xffffff00)
13953 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13954 DAG.getValueType(MVT::i8));
13955 else if (Known.Zero == 0xffff0000)
13956 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13957 DAG.getValueType(MVT::i16));
13960 return Res;
13963 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
13964 DAGCombinerInfo &DCI) const {
13965 switch (N->getOpcode()) {
13966 default: break;
13967 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
13968 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
13969 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
13970 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
13971 case ISD::SUB: return PerformSUBCombine(N, DCI);
13972 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
13973 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
13974 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
13975 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
13976 case ISD::BRCOND:
13977 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
13978 case ARMISD::ADDC:
13979 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
13980 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
13981 case ARMISD::BFI: return PerformBFICombine(N, DCI);
13982 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
13983 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
13984 case ISD::STORE: return PerformSTORECombine(N, DCI);
13985 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
13986 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
13987 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
13988 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
13989 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
13990 case ISD::FP_TO_SINT:
13991 case ISD::FP_TO_UINT:
13992 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
13993 case ISD::FDIV:
13994 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
13995 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
13996 case ISD::SHL:
13997 case ISD::SRA:
13998 case ISD::SRL:
13999 return PerformShiftCombine(N, DCI, Subtarget);
14000 case ISD::SIGN_EXTEND:
14001 case ISD::ZERO_EXTEND:
14002 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
14003 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
14004 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
14005 case ISD::LOAD: return PerformLOADCombine(N, DCI);
14006 case ARMISD::VLD1DUP:
14007 case ARMISD::VLD2DUP:
14008 case ARMISD::VLD3DUP:
14009 case ARMISD::VLD4DUP:
14010 return PerformVLDCombine(N, DCI);
14011 case ARMISD::BUILD_VECTOR:
14012 return PerformARMBUILD_VECTORCombine(N, DCI);
14013 case ARMISD::SMULWB: {
14014 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14015 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14016 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14017 return SDValue();
14018 break;
14020 case ARMISD::SMULWT: {
14021 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14022 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14023 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14024 return SDValue();
14025 break;
14027 case ARMISD::SMLALBB: {
14028 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14029 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14030 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14031 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14032 return SDValue();
14033 break;
14035 case ARMISD::SMLALBT: {
14036 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
14037 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14038 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
14039 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14040 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
14041 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
14042 return SDValue();
14043 break;
14045 case ARMISD::SMLALTB: {
14046 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
14047 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14048 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
14049 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14050 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
14051 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
14052 return SDValue();
14053 break;
14055 case ARMISD::SMLALTT: {
14056 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14057 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14058 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14059 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14060 return SDValue();
14061 break;
14063 case ISD::INTRINSIC_VOID:
14064 case ISD::INTRINSIC_W_CHAIN:
14065 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14066 case Intrinsic::arm_neon_vld1:
14067 case Intrinsic::arm_neon_vld1x2:
14068 case Intrinsic::arm_neon_vld1x3:
14069 case Intrinsic::arm_neon_vld1x4:
14070 case Intrinsic::arm_neon_vld2:
14071 case Intrinsic::arm_neon_vld3:
14072 case Intrinsic::arm_neon_vld4:
14073 case Intrinsic::arm_neon_vld2lane:
14074 case Intrinsic::arm_neon_vld3lane:
14075 case Intrinsic::arm_neon_vld4lane:
14076 case Intrinsic::arm_neon_vld2dup:
14077 case Intrinsic::arm_neon_vld3dup:
14078 case Intrinsic::arm_neon_vld4dup:
14079 case Intrinsic::arm_neon_vst1:
14080 case Intrinsic::arm_neon_vst1x2:
14081 case Intrinsic::arm_neon_vst1x3:
14082 case Intrinsic::arm_neon_vst1x4:
14083 case Intrinsic::arm_neon_vst2:
14084 case Intrinsic::arm_neon_vst3:
14085 case Intrinsic::arm_neon_vst4:
14086 case Intrinsic::arm_neon_vst2lane:
14087 case Intrinsic::arm_neon_vst3lane:
14088 case Intrinsic::arm_neon_vst4lane:
14089 return PerformVLDCombine(N, DCI);
14090 default: break;
14092 break;
14094 return SDValue();
14097 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
14098 EVT VT) const {
14099 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
14102 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
14103 unsigned Alignment,
14104 MachineMemOperand::Flags,
14105 bool *Fast) const {
14106 // Depends what it gets converted into if the type is weird.
14107 if (!VT.isSimple())
14108 return false;
14110 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
14111 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
14112 auto Ty = VT.getSimpleVT().SimpleTy;
14114 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
14115 // Unaligned access can use (for example) LRDB, LRDH, LDR
14116 if (AllowsUnaligned) {
14117 if (Fast)
14118 *Fast = Subtarget->hasV7Ops();
14119 return true;
14123 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
14124 // For any little-endian targets with neon, we can support unaligned ld/st
14125 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
14126 // A big-endian target may also explicitly support unaligned accesses
14127 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
14128 if (Fast)
14129 *Fast = true;
14130 return true;
14134 if (!Subtarget->hasMVEIntegerOps())
14135 return false;
14137 // These are for predicates
14138 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14139 if (Fast)
14140 *Fast = true;
14141 return true;
14144 // These are for truncated stores/narrowing loads. They are fine so long as
14145 // the alignment is at least the size of the item being loaded
14146 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
14147 Alignment >= VT.getScalarSizeInBits() / 8) {
14148 if (Fast)
14149 *Fast = true;
14150 return true;
14153 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
14154 // VSTRW.U32 all store the vector register in exactly the same format, and
14155 // differ only in the range of their immediate offset field and the required
14156 // alignment. So there is always a store that can be used, regardless of
14157 // actual type.
14159 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
14160 // VREV64.8) pair and get the same effect. This will likely be better than
14161 // aligning the vector through the stack.
14162 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
14163 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
14164 Ty == MVT::v2f64) {
14165 if (Fast)
14166 *Fast = true;
14167 return true;
14170 return false;
14173 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14174 unsigned AlignCheck) {
14175 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14176 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14179 EVT ARMTargetLowering::getOptimalMemOpType(
14180 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14181 bool ZeroMemset, bool MemcpyStrSrc,
14182 const AttributeList &FuncAttributes) const {
14183 // See if we can use NEON instructions for this...
14184 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14185 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14186 bool Fast;
14187 if (Size >= 16 &&
14188 (memOpAlign(SrcAlign, DstAlign, 16) ||
14189 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14190 MachineMemOperand::MONone, &Fast) &&
14191 Fast))) {
14192 return MVT::v2f64;
14193 } else if (Size >= 8 &&
14194 (memOpAlign(SrcAlign, DstAlign, 8) ||
14195 (allowsMisalignedMemoryAccesses(
14196 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14197 Fast))) {
14198 return MVT::f64;
14202 // Let the target-independent logic figure it out.
14203 return MVT::Other;
14206 // 64-bit integers are split into their high and low parts and held in two
14207 // different registers, so the trunc is free since the low register can just
14208 // be used.
14209 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14210 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14211 return false;
14212 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14213 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14214 return (SrcBits == 64 && DestBits == 32);
14217 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14218 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14219 !DstVT.isInteger())
14220 return false;
14221 unsigned SrcBits = SrcVT.getSizeInBits();
14222 unsigned DestBits = DstVT.getSizeInBits();
14223 return (SrcBits == 64 && DestBits == 32);
14226 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14227 if (Val.getOpcode() != ISD::LOAD)
14228 return false;
14230 EVT VT1 = Val.getValueType();
14231 if (!VT1.isSimple() || !VT1.isInteger() ||
14232 !VT2.isSimple() || !VT2.isInteger())
14233 return false;
14235 switch (VT1.getSimpleVT().SimpleTy) {
14236 default: break;
14237 case MVT::i1:
14238 case MVT::i8:
14239 case MVT::i16:
14240 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14241 return true;
14244 return false;
14247 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14248 if (!VT.isSimple())
14249 return false;
14251 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14252 // negate values directly (fneg is free). So, we don't want to let the DAG
14253 // combiner rewrite fneg into xors and some other instructions. For f16 and
14254 // FullFP16 argument passing, some bitcast nodes may be introduced,
14255 // triggering this DAG combine rewrite, so we are avoiding that with this.
14256 switch (VT.getSimpleVT().SimpleTy) {
14257 default: break;
14258 case MVT::f16:
14259 return Subtarget->hasFullFP16();
14262 return false;
14265 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14266 /// of the vector elements.
14267 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14268 auto areExtDoubled = [](Instruction *Ext) {
14269 return Ext->getType()->getScalarSizeInBits() ==
14270 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14273 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14274 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14275 !areExtDoubled(cast<Instruction>(Ext1)) ||
14276 !areExtDoubled(cast<Instruction>(Ext2)))
14277 return false;
14279 return true;
14282 /// Check if sinking \p I's operands to I's basic block is profitable, because
14283 /// the operands can be folded into a target instruction, e.g.
14284 /// sext/zext can be folded into vsubl.
14285 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14286 SmallVectorImpl<Use *> &Ops) const {
14287 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy())
14288 return false;
14290 switch (I->getOpcode()) {
14291 case Instruction::Sub:
14292 case Instruction::Add: {
14293 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14294 return false;
14295 Ops.push_back(&I->getOperandUse(0));
14296 Ops.push_back(&I->getOperandUse(1));
14297 return true;
14299 default:
14300 return false;
14302 return false;
14305 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14306 EVT VT = ExtVal.getValueType();
14308 if (!isTypeLegal(VT))
14309 return false;
14311 // Don't create a loadext if we can fold the extension into a wide/long
14312 // instruction.
14313 // If there's more than one user instruction, the loadext is desirable no
14314 // matter what. There can be two uses by the same instruction.
14315 if (ExtVal->use_empty() ||
14316 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14317 return true;
14319 SDNode *U = *ExtVal->use_begin();
14320 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14321 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14322 return false;
14324 return true;
14327 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14328 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14329 return false;
14331 if (!isTypeLegal(EVT::getEVT(Ty1)))
14332 return false;
14334 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14336 // Assuming the caller doesn't have a zeroext or signext return parameter,
14337 // truncation all the way down to i1 is valid.
14338 return true;
14341 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14342 const AddrMode &AM, Type *Ty,
14343 unsigned AS) const {
14344 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14345 if (Subtarget->hasFPAO())
14346 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14347 return 0;
14349 return -1;
14352 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14353 if (V < 0)
14354 return false;
14356 unsigned Scale = 1;
14357 switch (VT.getSimpleVT().SimpleTy) {
14358 case MVT::i1:
14359 case MVT::i8:
14360 // Scale == 1;
14361 break;
14362 case MVT::i16:
14363 // Scale == 2;
14364 Scale = 2;
14365 break;
14366 default:
14367 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14368 // Scale == 4;
14369 Scale = 4;
14370 break;
14373 if ((V & (Scale - 1)) != 0)
14374 return false;
14375 return isUInt<5>(V / Scale);
14378 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14379 const ARMSubtarget *Subtarget) {
14380 if (!VT.isInteger() && !VT.isFloatingPoint())
14381 return false;
14382 if (VT.isVector() && Subtarget->hasNEON())
14383 return false;
14384 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14385 !Subtarget->hasMVEFloatOps())
14386 return false;
14388 bool IsNeg = false;
14389 if (V < 0) {
14390 IsNeg = true;
14391 V = -V;
14394 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14396 // MVE: size * imm7
14397 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14398 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14399 case MVT::i32:
14400 case MVT::f32:
14401 return isShiftedUInt<7,2>(V);
14402 case MVT::i16:
14403 case MVT::f16:
14404 return isShiftedUInt<7,1>(V);
14405 case MVT::i8:
14406 return isUInt<7>(V);
14407 default:
14408 return false;
14412 // half VLDR: 2 * imm8
14413 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14414 return isShiftedUInt<8, 1>(V);
14415 // VLDR and LDRD: 4 * imm8
14416 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14417 return isShiftedUInt<8, 2>(V);
14419 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14420 // + imm12 or - imm8
14421 if (IsNeg)
14422 return isUInt<8>(V);
14423 return isUInt<12>(V);
14426 return false;
14429 /// isLegalAddressImmediate - Return true if the integer value can be used
14430 /// as the offset of the target addressing mode for load / store of the
14431 /// given type.
14432 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14433 const ARMSubtarget *Subtarget) {
14434 if (V == 0)
14435 return true;
14437 if (!VT.isSimple())
14438 return false;
14440 if (Subtarget->isThumb1Only())
14441 return isLegalT1AddressImmediate(V, VT);
14442 else if (Subtarget->isThumb2())
14443 return isLegalT2AddressImmediate(V, VT, Subtarget);
14445 // ARM mode.
14446 if (V < 0)
14447 V = - V;
14448 switch (VT.getSimpleVT().SimpleTy) {
14449 default: return false;
14450 case MVT::i1:
14451 case MVT::i8:
14452 case MVT::i32:
14453 // +- imm12
14454 return isUInt<12>(V);
14455 case MVT::i16:
14456 // +- imm8
14457 return isUInt<8>(V);
14458 case MVT::f32:
14459 case MVT::f64:
14460 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14461 return false;
14462 return isShiftedUInt<8, 2>(V);
14466 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14467 EVT VT) const {
14468 int Scale = AM.Scale;
14469 if (Scale < 0)
14470 return false;
14472 switch (VT.getSimpleVT().SimpleTy) {
14473 default: return false;
14474 case MVT::i1:
14475 case MVT::i8:
14476 case MVT::i16:
14477 case MVT::i32:
14478 if (Scale == 1)
14479 return true;
14480 // r + r << imm
14481 Scale = Scale & ~1;
14482 return Scale == 2 || Scale == 4 || Scale == 8;
14483 case MVT::i64:
14484 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14485 // version in Thumb mode.
14486 // r + r
14487 if (Scale == 1)
14488 return true;
14489 // r * 2 (this can be lowered to r + r).
14490 if (!AM.HasBaseReg && Scale == 2)
14491 return true;
14492 return false;
14493 case MVT::isVoid:
14494 // Note, we allow "void" uses (basically, uses that aren't loads or
14495 // stores), because arm allows folding a scale into many arithmetic
14496 // operations. This should be made more precise and revisited later.
14498 // Allow r << imm, but the imm has to be a multiple of two.
14499 if (Scale & 1) return false;
14500 return isPowerOf2_32(Scale);
14504 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14505 EVT VT) const {
14506 const int Scale = AM.Scale;
14508 // Negative scales are not supported in Thumb1.
14509 if (Scale < 0)
14510 return false;
14512 // Thumb1 addressing modes do not support register scaling excepting the
14513 // following cases:
14514 // 1. Scale == 1 means no scaling.
14515 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14516 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14519 /// isLegalAddressingMode - Return true if the addressing mode represented
14520 /// by AM is legal for this target, for a load/store of the specified type.
14521 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14522 const AddrMode &AM, Type *Ty,
14523 unsigned AS, Instruction *I) const {
14524 EVT VT = getValueType(DL, Ty, true);
14525 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14526 return false;
14528 // Can never fold addr of global into load/store.
14529 if (AM.BaseGV)
14530 return false;
14532 switch (AM.Scale) {
14533 case 0: // no scale reg, must be "r+i" or "r", or "i".
14534 break;
14535 default:
14536 // ARM doesn't support any R+R*scale+imm addr modes.
14537 if (AM.BaseOffs)
14538 return false;
14540 if (!VT.isSimple())
14541 return false;
14543 if (Subtarget->isThumb1Only())
14544 return isLegalT1ScaledAddressingMode(AM, VT);
14546 if (Subtarget->isThumb2())
14547 return isLegalT2ScaledAddressingMode(AM, VT);
14549 int Scale = AM.Scale;
14550 switch (VT.getSimpleVT().SimpleTy) {
14551 default: return false;
14552 case MVT::i1:
14553 case MVT::i8:
14554 case MVT::i32:
14555 if (Scale < 0) Scale = -Scale;
14556 if (Scale == 1)
14557 return true;
14558 // r + r << imm
14559 return isPowerOf2_32(Scale & ~1);
14560 case MVT::i16:
14561 case MVT::i64:
14562 // r +/- r
14563 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
14564 return true;
14565 // r * 2 (this can be lowered to r + r).
14566 if (!AM.HasBaseReg && Scale == 2)
14567 return true;
14568 return false;
14570 case MVT::isVoid:
14571 // Note, we allow "void" uses (basically, uses that aren't loads or
14572 // stores), because arm allows folding a scale into many arithmetic
14573 // operations. This should be made more precise and revisited later.
14575 // Allow r << imm, but the imm has to be a multiple of two.
14576 if (Scale & 1) return false;
14577 return isPowerOf2_32(Scale);
14580 return true;
14583 /// isLegalICmpImmediate - Return true if the specified immediate is legal
14584 /// icmp immediate, that is the target has icmp instructions which can compare
14585 /// a register against the immediate without having to materialize the
14586 /// immediate into a register.
14587 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14588 // Thumb2 and ARM modes can use cmn for negative immediates.
14589 if (!Subtarget->isThumb())
14590 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
14591 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
14592 if (Subtarget->isThumb2())
14593 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
14594 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
14595 // Thumb1 doesn't have cmn, and only 8-bit immediates.
14596 return Imm >= 0 && Imm <= 255;
14599 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
14600 /// *or sub* immediate, that is the target has add or sub instructions which can
14601 /// add a register with the immediate without having to materialize the
14602 /// immediate into a register.
14603 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14604 // Same encoding for add/sub, just flip the sign.
14605 int64_t AbsImm = std::abs(Imm);
14606 if (!Subtarget->isThumb())
14607 return ARM_AM::getSOImmVal(AbsImm) != -1;
14608 if (Subtarget->isThumb2())
14609 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
14610 // Thumb1 only has 8-bit unsigned immediate.
14611 return AbsImm >= 0 && AbsImm <= 255;
14614 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
14615 bool isSEXTLoad, SDValue &Base,
14616 SDValue &Offset, bool &isInc,
14617 SelectionDAG &DAG) {
14618 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14619 return false;
14621 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
14622 // AddressingMode 3
14623 Base = Ptr->getOperand(0);
14624 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14625 int RHSC = (int)RHS->getZExtValue();
14626 if (RHSC < 0 && RHSC > -256) {
14627 assert(Ptr->getOpcode() == ISD::ADD);
14628 isInc = false;
14629 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14630 return true;
14633 isInc = (Ptr->getOpcode() == ISD::ADD);
14634 Offset = Ptr->getOperand(1);
14635 return true;
14636 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
14637 // AddressingMode 2
14638 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14639 int RHSC = (int)RHS->getZExtValue();
14640 if (RHSC < 0 && RHSC > -0x1000) {
14641 assert(Ptr->getOpcode() == ISD::ADD);
14642 isInc = false;
14643 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14644 Base = Ptr->getOperand(0);
14645 return true;
14649 if (Ptr->getOpcode() == ISD::ADD) {
14650 isInc = true;
14651 ARM_AM::ShiftOpc ShOpcVal=
14652 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
14653 if (ShOpcVal != ARM_AM::no_shift) {
14654 Base = Ptr->getOperand(1);
14655 Offset = Ptr->getOperand(0);
14656 } else {
14657 Base = Ptr->getOperand(0);
14658 Offset = Ptr->getOperand(1);
14660 return true;
14663 isInc = (Ptr->getOpcode() == ISD::ADD);
14664 Base = Ptr->getOperand(0);
14665 Offset = Ptr->getOperand(1);
14666 return true;
14669 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
14670 return false;
14673 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
14674 bool isSEXTLoad, SDValue &Base,
14675 SDValue &Offset, bool &isInc,
14676 SelectionDAG &DAG) {
14677 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14678 return false;
14680 Base = Ptr->getOperand(0);
14681 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14682 int RHSC = (int)RHS->getZExtValue();
14683 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
14684 assert(Ptr->getOpcode() == ISD::ADD);
14685 isInc = false;
14686 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14687 return true;
14688 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
14689 isInc = Ptr->getOpcode() == ISD::ADD;
14690 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14691 return true;
14695 return false;
14698 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
14699 bool isSEXTLoad, bool isLE, SDValue &Base,
14700 SDValue &Offset, bool &isInc,
14701 SelectionDAG &DAG) {
14702 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14703 return false;
14704 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
14705 return false;
14707 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
14708 int RHSC = (int)RHS->getZExtValue();
14710 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
14711 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
14712 assert(Ptr->getOpcode() == ISD::ADD);
14713 isInc = false;
14714 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14715 return true;
14716 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
14717 isInc = Ptr->getOpcode() == ISD::ADD;
14718 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14719 return true;
14721 return false;
14724 // Try to find a matching instruction based on s/zext, Alignment, Offset and
14725 // (in BE) type.
14726 Base = Ptr->getOperand(0);
14727 if (VT == MVT::v4i16) {
14728 if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
14729 return true;
14730 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
14731 if (IsInRange(RHSC, 0x80, 1))
14732 return true;
14733 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) &&
14734 IsInRange(RHSC, 0x80, 4))
14735 return true;
14736 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) &&
14737 IsInRange(RHSC, 0x80, 2))
14738 return true;
14739 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
14740 return true;
14741 return false;
14744 /// getPreIndexedAddressParts - returns true by value, base pointer and
14745 /// offset pointer and addressing mode by reference if the node's address
14746 /// can be legally represented as pre-indexed load / store address.
14747 bool
14748 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14749 SDValue &Offset,
14750 ISD::MemIndexedMode &AM,
14751 SelectionDAG &DAG) const {
14752 if (Subtarget->isThumb1Only())
14753 return false;
14755 EVT VT;
14756 SDValue Ptr;
14757 unsigned Align;
14758 bool isSEXTLoad = false;
14759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14760 Ptr = LD->getBasePtr();
14761 VT = LD->getMemoryVT();
14762 Align = LD->getAlignment();
14763 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14764 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14765 Ptr = ST->getBasePtr();
14766 VT = ST->getMemoryVT();
14767 Align = ST->getAlignment();
14768 } else
14769 return false;
14771 bool isInc;
14772 bool isLegal = false;
14773 if (VT.isVector())
14774 isLegal = Subtarget->hasMVEIntegerOps() &&
14775 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
14776 Subtarget->isLittle(), Base, Offset,
14777 isInc, DAG);
14778 else {
14779 if (Subtarget->isThumb2())
14780 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14781 Offset, isInc, DAG);
14782 else
14783 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14784 Offset, isInc, DAG);
14786 if (!isLegal)
14787 return false;
14789 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
14790 return true;
14793 /// getPostIndexedAddressParts - returns true by value, base pointer and
14794 /// offset pointer and addressing mode by reference if this node can be
14795 /// combined with a load / store to form a post-indexed load / store.
14796 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
14797 SDValue &Base,
14798 SDValue &Offset,
14799 ISD::MemIndexedMode &AM,
14800 SelectionDAG &DAG) const {
14801 EVT VT;
14802 SDValue Ptr;
14803 unsigned Align;
14804 bool isSEXTLoad = false, isNonExt;
14805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14806 VT = LD->getMemoryVT();
14807 Ptr = LD->getBasePtr();
14808 Align = LD->getAlignment();
14809 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14810 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
14811 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14812 VT = ST->getMemoryVT();
14813 Ptr = ST->getBasePtr();
14814 Align = ST->getAlignment();
14815 isNonExt = !ST->isTruncatingStore();
14816 } else
14817 return false;
14819 if (Subtarget->isThumb1Only()) {
14820 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
14821 // must be non-extending/truncating, i32, with an offset of 4.
14822 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
14823 if (Op->getOpcode() != ISD::ADD || !isNonExt)
14824 return false;
14825 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14826 if (!RHS || RHS->getZExtValue() != 4)
14827 return false;
14829 Offset = Op->getOperand(1);
14830 Base = Op->getOperand(0);
14831 AM = ISD::POST_INC;
14832 return true;
14835 bool isInc;
14836 bool isLegal = false;
14837 if (VT.isVector())
14838 isLegal = Subtarget->hasMVEIntegerOps() &&
14839 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad,
14840 Subtarget->isLittle(), Base, Offset,
14841 isInc, DAG);
14842 else {
14843 if (Subtarget->isThumb2())
14844 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14845 isInc, DAG);
14846 else
14847 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14848 isInc, DAG);
14850 if (!isLegal)
14851 return false;
14853 if (Ptr != Base) {
14854 // Swap base ptr and offset to catch more post-index load / store when
14855 // it's legal. In Thumb2 mode, offset must be an immediate.
14856 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
14857 !Subtarget->isThumb2())
14858 std::swap(Base, Offset);
14860 // Post-indexed load / store update the base pointer.
14861 if (Ptr != Base)
14862 return false;
14865 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
14866 return true;
14869 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14870 KnownBits &Known,
14871 const APInt &DemandedElts,
14872 const SelectionDAG &DAG,
14873 unsigned Depth) const {
14874 unsigned BitWidth = Known.getBitWidth();
14875 Known.resetAll();
14876 switch (Op.getOpcode()) {
14877 default: break;
14878 case ARMISD::ADDC:
14879 case ARMISD::ADDE:
14880 case ARMISD::SUBC:
14881 case ARMISD::SUBE:
14882 // Special cases when we convert a carry to a boolean.
14883 if (Op.getResNo() == 0) {
14884 SDValue LHS = Op.getOperand(0);
14885 SDValue RHS = Op.getOperand(1);
14886 // (ADDE 0, 0, C) will give us a single bit.
14887 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
14888 isNullConstant(RHS)) {
14889 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14890 return;
14893 break;
14894 case ARMISD::CMOV: {
14895 // Bits are known zero/one if known on the LHS and RHS.
14896 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
14897 if (Known.isUnknown())
14898 return;
14900 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
14901 Known.Zero &= KnownRHS.Zero;
14902 Known.One &= KnownRHS.One;
14903 return;
14905 case ISD::INTRINSIC_W_CHAIN: {
14906 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
14907 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14908 switch (IntID) {
14909 default: return;
14910 case Intrinsic::arm_ldaex:
14911 case Intrinsic::arm_ldrex: {
14912 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
14913 unsigned MemBits = VT.getScalarSizeInBits();
14914 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
14915 return;
14919 case ARMISD::BFI: {
14920 // Conservatively, we can recurse down the first operand
14921 // and just mask out all affected bits.
14922 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
14924 // The operand to BFI is already a mask suitable for removing the bits it
14925 // sets.
14926 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
14927 const APInt &Mask = CI->getAPIntValue();
14928 Known.Zero &= Mask;
14929 Known.One &= Mask;
14930 return;
14932 case ARMISD::VGETLANEs:
14933 case ARMISD::VGETLANEu: {
14934 const SDValue &SrcSV = Op.getOperand(0);
14935 EVT VecVT = SrcSV.getValueType();
14936 assert(VecVT.isVector() && "VGETLANE expected a vector type");
14937 const unsigned NumSrcElts = VecVT.getVectorNumElements();
14938 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
14939 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
14940 "VGETLANE index out of bounds");
14941 unsigned Idx = Pos->getZExtValue();
14942 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
14943 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
14945 EVT VT = Op.getValueType();
14946 const unsigned DstSz = VT.getScalarSizeInBits();
14947 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
14948 (void)SrcSz;
14949 assert(SrcSz == Known.getBitWidth());
14950 assert(DstSz > SrcSz);
14951 if (Op.getOpcode() == ARMISD::VGETLANEs)
14952 Known = Known.sext(DstSz);
14953 else {
14954 Known = Known.zext(DstSz, true /* extended bits are known zero */);
14956 assert(DstSz == Known.getBitWidth());
14957 break;
14962 bool
14963 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
14964 const APInt &DemandedAPInt,
14965 TargetLoweringOpt &TLO) const {
14966 // Delay optimization, so we don't have to deal with illegal types, or block
14967 // optimizations.
14968 if (!TLO.LegalOps)
14969 return false;
14971 // Only optimize AND for now.
14972 if (Op.getOpcode() != ISD::AND)
14973 return false;
14975 EVT VT = Op.getValueType();
14977 // Ignore vectors.
14978 if (VT.isVector())
14979 return false;
14981 assert(VT == MVT::i32 && "Unexpected integer type");
14983 // Make sure the RHS really is a constant.
14984 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14985 if (!C)
14986 return false;
14988 unsigned Mask = C->getZExtValue();
14990 unsigned Demanded = DemandedAPInt.getZExtValue();
14991 unsigned ShrunkMask = Mask & Demanded;
14992 unsigned ExpandedMask = Mask | ~Demanded;
14994 // If the mask is all zeros, let the target-independent code replace the
14995 // result with zero.
14996 if (ShrunkMask == 0)
14997 return false;
14999 // If the mask is all ones, erase the AND. (Currently, the target-independent
15000 // code won't do this, so we have to do it explicitly to avoid an infinite
15001 // loop in obscure cases.)
15002 if (ExpandedMask == ~0U)
15003 return TLO.CombineTo(Op, Op.getOperand(0));
15005 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
15006 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
15008 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
15009 if (NewMask == Mask)
15010 return true;
15011 SDLoc DL(Op);
15012 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
15013 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
15014 return TLO.CombineTo(Op, NewOp);
15017 // Prefer uxtb mask.
15018 if (IsLegalMask(0xFF))
15019 return UseMask(0xFF);
15021 // Prefer uxth mask.
15022 if (IsLegalMask(0xFFFF))
15023 return UseMask(0xFFFF);
15025 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
15026 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15027 if (ShrunkMask < 256)
15028 return UseMask(ShrunkMask);
15030 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
15031 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15032 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
15033 return UseMask(ExpandedMask);
15035 // Potential improvements:
15037 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
15038 // We could try to prefer Thumb1 immediates which can be lowered to a
15039 // two-instruction sequence.
15040 // We could try to recognize more legal ARM/Thumb2 immediates here.
15042 return false;
15046 //===----------------------------------------------------------------------===//
15047 // ARM Inline Assembly Support
15048 //===----------------------------------------------------------------------===//
15050 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
15051 // Looking for "rev" which is V6+.
15052 if (!Subtarget->hasV6Ops())
15053 return false;
15055 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15056 std::string AsmStr = IA->getAsmString();
15057 SmallVector<StringRef, 4> AsmPieces;
15058 SplitString(AsmStr, AsmPieces, ";\n");
15060 switch (AsmPieces.size()) {
15061 default: return false;
15062 case 1:
15063 AsmStr = AsmPieces[0];
15064 AsmPieces.clear();
15065 SplitString(AsmStr, AsmPieces, " \t,");
15067 // rev $0, $1
15068 if (AsmPieces.size() == 3 &&
15069 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
15070 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
15071 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15072 if (Ty && Ty->getBitWidth() == 32)
15073 return IntrinsicLowering::LowerToByteSwap(CI);
15075 break;
15078 return false;
15081 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
15082 // At this point, we have to lower this constraint to something else, so we
15083 // lower it to an "r" or "w". However, by doing this we will force the result
15084 // to be in register, while the X constraint is much more permissive.
15086 // Although we are correct (we are free to emit anything, without
15087 // constraints), we might break use cases that would expect us to be more
15088 // efficient and emit something else.
15089 if (!Subtarget->hasVFP2Base())
15090 return "r";
15091 if (ConstraintVT.isFloatingPoint())
15092 return "w";
15093 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
15094 (ConstraintVT.getSizeInBits() == 64 ||
15095 ConstraintVT.getSizeInBits() == 128))
15096 return "w";
15098 return "r";
15101 /// getConstraintType - Given a constraint letter, return the type of
15102 /// constraint it is for this target.
15103 ARMTargetLowering::ConstraintType
15104 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
15105 unsigned S = Constraint.size();
15106 if (S == 1) {
15107 switch (Constraint[0]) {
15108 default: break;
15109 case 'l': return C_RegisterClass;
15110 case 'w': return C_RegisterClass;
15111 case 'h': return C_RegisterClass;
15112 case 'x': return C_RegisterClass;
15113 case 't': return C_RegisterClass;
15114 case 'j': return C_Immediate; // Constant for movw.
15115 // An address with a single base register. Due to the way we
15116 // currently handle addresses it is the same as an 'r' memory constraint.
15117 case 'Q': return C_Memory;
15119 } else if (S == 2) {
15120 switch (Constraint[0]) {
15121 default: break;
15122 case 'T': return C_RegisterClass;
15123 // All 'U+' constraints are addresses.
15124 case 'U': return C_Memory;
15127 return TargetLowering::getConstraintType(Constraint);
15130 /// Examine constraint type and operand type and determine a weight value.
15131 /// This object must already have been set up with the operand type
15132 /// and the current alternative constraint selected.
15133 TargetLowering::ConstraintWeight
15134 ARMTargetLowering::getSingleConstraintMatchWeight(
15135 AsmOperandInfo &info, const char *constraint) const {
15136 ConstraintWeight weight = CW_Invalid;
15137 Value *CallOperandVal = info.CallOperandVal;
15138 // If we don't have a value, we can't do a match,
15139 // but allow it at the lowest weight.
15140 if (!CallOperandVal)
15141 return CW_Default;
15142 Type *type = CallOperandVal->getType();
15143 // Look at the constraint type.
15144 switch (*constraint) {
15145 default:
15146 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15147 break;
15148 case 'l':
15149 if (type->isIntegerTy()) {
15150 if (Subtarget->isThumb())
15151 weight = CW_SpecificReg;
15152 else
15153 weight = CW_Register;
15155 break;
15156 case 'w':
15157 if (type->isFloatingPointTy())
15158 weight = CW_Register;
15159 break;
15161 return weight;
15164 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
15166 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
15167 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
15168 switch (Constraint.size()) {
15169 case 1:
15170 // GCC ARM Constraint Letters
15171 switch (Constraint[0]) {
15172 case 'l': // Low regs or general regs.
15173 if (Subtarget->isThumb())
15174 return RCPair(0U, &ARM::tGPRRegClass);
15175 return RCPair(0U, &ARM::GPRRegClass);
15176 case 'h': // High regs or no regs.
15177 if (Subtarget->isThumb())
15178 return RCPair(0U, &ARM::hGPRRegClass);
15179 break;
15180 case 'r':
15181 if (Subtarget->isThumb1Only())
15182 return RCPair(0U, &ARM::tGPRRegClass);
15183 return RCPair(0U, &ARM::GPRRegClass);
15184 case 'w':
15185 if (VT == MVT::Other)
15186 break;
15187 if (VT == MVT::f32)
15188 return RCPair(0U, &ARM::SPRRegClass);
15189 if (VT.getSizeInBits() == 64)
15190 return RCPair(0U, &ARM::DPRRegClass);
15191 if (VT.getSizeInBits() == 128)
15192 return RCPair(0U, &ARM::QPRRegClass);
15193 break;
15194 case 'x':
15195 if (VT == MVT::Other)
15196 break;
15197 if (VT == MVT::f32)
15198 return RCPair(0U, &ARM::SPR_8RegClass);
15199 if (VT.getSizeInBits() == 64)
15200 return RCPair(0U, &ARM::DPR_8RegClass);
15201 if (VT.getSizeInBits() == 128)
15202 return RCPair(0U, &ARM::QPR_8RegClass);
15203 break;
15204 case 't':
15205 if (VT == MVT::Other)
15206 break;
15207 if (VT == MVT::f32 || VT == MVT::i32)
15208 return RCPair(0U, &ARM::SPRRegClass);
15209 if (VT.getSizeInBits() == 64)
15210 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15211 if (VT.getSizeInBits() == 128)
15212 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15213 break;
15215 break;
15217 case 2:
15218 if (Constraint[0] == 'T') {
15219 switch (Constraint[1]) {
15220 default:
15221 break;
15222 case 'e':
15223 return RCPair(0U, &ARM::tGPREvenRegClass);
15224 case 'o':
15225 return RCPair(0U, &ARM::tGPROddRegClass);
15228 break;
15230 default:
15231 break;
15234 if (StringRef("{cc}").equals_lower(Constraint))
15235 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15237 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15240 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15241 /// vector. If it is invalid, don't add anything to Ops.
15242 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15243 std::string &Constraint,
15244 std::vector<SDValue>&Ops,
15245 SelectionDAG &DAG) const {
15246 SDValue Result;
15248 // Currently only support length 1 constraints.
15249 if (Constraint.length() != 1) return;
15251 char ConstraintLetter = Constraint[0];
15252 switch (ConstraintLetter) {
15253 default: break;
15254 case 'j':
15255 case 'I': case 'J': case 'K': case 'L':
15256 case 'M': case 'N': case 'O':
15257 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15258 if (!C)
15259 return;
15261 int64_t CVal64 = C->getSExtValue();
15262 int CVal = (int) CVal64;
15263 // None of these constraints allow values larger than 32 bits. Check
15264 // that the value fits in an int.
15265 if (CVal != CVal64)
15266 return;
15268 switch (ConstraintLetter) {
15269 case 'j':
15270 // Constant suitable for movw, must be between 0 and
15271 // 65535.
15272 if (Subtarget->hasV6T2Ops())
15273 if (CVal >= 0 && CVal <= 65535)
15274 break;
15275 return;
15276 case 'I':
15277 if (Subtarget->isThumb1Only()) {
15278 // This must be a constant between 0 and 255, for ADD
15279 // immediates.
15280 if (CVal >= 0 && CVal <= 255)
15281 break;
15282 } else if (Subtarget->isThumb2()) {
15283 // A constant that can be used as an immediate value in a
15284 // data-processing instruction.
15285 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15286 break;
15287 } else {
15288 // A constant that can be used as an immediate value in a
15289 // data-processing instruction.
15290 if (ARM_AM::getSOImmVal(CVal) != -1)
15291 break;
15293 return;
15295 case 'J':
15296 if (Subtarget->isThumb1Only()) {
15297 // This must be a constant between -255 and -1, for negated ADD
15298 // immediates. This can be used in GCC with an "n" modifier that
15299 // prints the negated value, for use with SUB instructions. It is
15300 // not useful otherwise but is implemented for compatibility.
15301 if (CVal >= -255 && CVal <= -1)
15302 break;
15303 } else {
15304 // This must be a constant between -4095 and 4095. It is not clear
15305 // what this constraint is intended for. Implemented for
15306 // compatibility with GCC.
15307 if (CVal >= -4095 && CVal <= 4095)
15308 break;
15310 return;
15312 case 'K':
15313 if (Subtarget->isThumb1Only()) {
15314 // A 32-bit value where only one byte has a nonzero value. Exclude
15315 // zero to match GCC. This constraint is used by GCC internally for
15316 // constants that can be loaded with a move/shift combination.
15317 // It is not useful otherwise but is implemented for compatibility.
15318 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15319 break;
15320 } else if (Subtarget->isThumb2()) {
15321 // A constant whose bitwise inverse can be used as an immediate
15322 // value in a data-processing instruction. This can be used in GCC
15323 // with a "B" modifier that prints the inverted value, for use with
15324 // BIC and MVN instructions. It is not useful otherwise but is
15325 // implemented for compatibility.
15326 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15327 break;
15328 } else {
15329 // A constant whose bitwise inverse can be used as an immediate
15330 // value in a data-processing instruction. This can be used in GCC
15331 // with a "B" modifier that prints the inverted value, for use with
15332 // BIC and MVN instructions. It is not useful otherwise but is
15333 // implemented for compatibility.
15334 if (ARM_AM::getSOImmVal(~CVal) != -1)
15335 break;
15337 return;
15339 case 'L':
15340 if (Subtarget->isThumb1Only()) {
15341 // This must be a constant between -7 and 7,
15342 // for 3-operand ADD/SUB immediate instructions.
15343 if (CVal >= -7 && CVal < 7)
15344 break;
15345 } else if (Subtarget->isThumb2()) {
15346 // A constant whose negation can be used as an immediate value in a
15347 // data-processing instruction. This can be used in GCC with an "n"
15348 // modifier that prints the negated value, for use with SUB
15349 // instructions. It is not useful otherwise but is implemented for
15350 // compatibility.
15351 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15352 break;
15353 } else {
15354 // A constant whose negation can be used as an immediate value in a
15355 // data-processing instruction. This can be used in GCC with an "n"
15356 // modifier that prints the negated value, for use with SUB
15357 // instructions. It is not useful otherwise but is implemented for
15358 // compatibility.
15359 if (ARM_AM::getSOImmVal(-CVal) != -1)
15360 break;
15362 return;
15364 case 'M':
15365 if (Subtarget->isThumb1Only()) {
15366 // This must be a multiple of 4 between 0 and 1020, for
15367 // ADD sp + immediate.
15368 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15369 break;
15370 } else {
15371 // A power of two or a constant between 0 and 32. This is used in
15372 // GCC for the shift amount on shifted register operands, but it is
15373 // useful in general for any shift amounts.
15374 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15375 break;
15377 return;
15379 case 'N':
15380 if (Subtarget->isThumb()) { // FIXME thumb2
15381 // This must be a constant between 0 and 31, for shift amounts.
15382 if (CVal >= 0 && CVal <= 31)
15383 break;
15385 return;
15387 case 'O':
15388 if (Subtarget->isThumb()) { // FIXME thumb2
15389 // This must be a multiple of 4 between -508 and 508, for
15390 // ADD/SUB sp = sp + immediate.
15391 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15392 break;
15394 return;
15396 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15397 break;
15400 if (Result.getNode()) {
15401 Ops.push_back(Result);
15402 return;
15404 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15407 static RTLIB::Libcall getDivRemLibcall(
15408 const SDNode *N, MVT::SimpleValueType SVT) {
15409 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15410 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15411 "Unhandled Opcode in getDivRemLibcall");
15412 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15413 N->getOpcode() == ISD::SREM;
15414 RTLIB::Libcall LC;
15415 switch (SVT) {
15416 default: llvm_unreachable("Unexpected request for libcall!");
15417 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15418 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15419 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15420 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15422 return LC;
15425 static TargetLowering::ArgListTy getDivRemArgList(
15426 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15427 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15428 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15429 "Unhandled Opcode in getDivRemArgList");
15430 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15431 N->getOpcode() == ISD::SREM;
15432 TargetLowering::ArgListTy Args;
15433 TargetLowering::ArgListEntry Entry;
15434 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15435 EVT ArgVT = N->getOperand(i).getValueType();
15436 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15437 Entry.Node = N->getOperand(i);
15438 Entry.Ty = ArgTy;
15439 Entry.IsSExt = isSigned;
15440 Entry.IsZExt = !isSigned;
15441 Args.push_back(Entry);
15443 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15444 std::swap(Args[0], Args[1]);
15445 return Args;
15448 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15449 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15450 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15451 Subtarget->isTargetWindows()) &&
15452 "Register-based DivRem lowering only");
15453 unsigned Opcode = Op->getOpcode();
15454 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15455 "Invalid opcode for Div/Rem lowering");
15456 bool isSigned = (Opcode == ISD::SDIVREM);
15457 EVT VT = Op->getValueType(0);
15458 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15459 SDLoc dl(Op);
15461 // If the target has hardware divide, use divide + multiply + subtract:
15462 // div = a / b
15463 // rem = a - b * div
15464 // return {div, rem}
15465 // This should be lowered into UDIV/SDIV + MLS later on.
15466 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15467 : Subtarget->hasDivideInARMMode();
15468 if (hasDivide && Op->getValueType(0).isSimple() &&
15469 Op->getSimpleValueType(0) == MVT::i32) {
15470 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15471 const SDValue Dividend = Op->getOperand(0);
15472 const SDValue Divisor = Op->getOperand(1);
15473 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15474 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15475 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15477 SDValue Values[2] = {Div, Rem};
15478 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15481 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15482 VT.getSimpleVT().SimpleTy);
15483 SDValue InChain = DAG.getEntryNode();
15485 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15486 DAG.getContext(),
15487 Subtarget);
15489 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15490 getPointerTy(DAG.getDataLayout()));
15492 Type *RetTy = StructType::get(Ty, Ty);
15494 if (Subtarget->isTargetWindows())
15495 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15497 TargetLowering::CallLoweringInfo CLI(DAG);
15498 CLI.setDebugLoc(dl).setChain(InChain)
15499 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15500 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15502 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15503 return CallInfo.first;
15506 // Lowers REM using divmod helpers
15507 // see RTABI section 4.2/4.3
15508 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15509 // Build return types (div and rem)
15510 std::vector<Type*> RetTyParams;
15511 Type *RetTyElement;
15513 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15514 default: llvm_unreachable("Unexpected request for libcall!");
15515 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15516 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15517 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15518 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15521 RetTyParams.push_back(RetTyElement);
15522 RetTyParams.push_back(RetTyElement);
15523 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15524 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15526 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15527 SimpleTy);
15528 SDValue InChain = DAG.getEntryNode();
15529 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15530 Subtarget);
15531 bool isSigned = N->getOpcode() == ISD::SREM;
15532 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15533 getPointerTy(DAG.getDataLayout()));
15535 if (Subtarget->isTargetWindows())
15536 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15538 // Lower call
15539 CallLoweringInfo CLI(DAG);
15540 CLI.setChain(InChain)
15541 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
15542 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
15543 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
15545 // Return second (rem) result operand (first contains div)
15546 SDNode *ResNode = CallResult.first.getNode();
15547 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
15548 return ResNode->getOperand(1);
15551 SDValue
15552 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
15553 assert(Subtarget->isTargetWindows() && "unsupported target platform");
15554 SDLoc DL(Op);
15556 // Get the inputs.
15557 SDValue Chain = Op.getOperand(0);
15558 SDValue Size = Op.getOperand(1);
15560 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
15561 "no-stack-arg-probe")) {
15562 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15563 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15564 Chain = SP.getValue(1);
15565 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
15566 if (Align)
15567 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
15568 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
15569 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
15570 SDValue Ops[2] = { SP, Chain };
15571 return DAG.getMergeValues(Ops, DL);
15574 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
15575 DAG.getConstant(2, DL, MVT::i32));
15577 SDValue Flag;
15578 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
15579 Flag = Chain.getValue(1);
15581 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15582 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
15584 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15585 Chain = NewSP.getValue(1);
15587 SDValue Ops[2] = { NewSP, Chain };
15588 return DAG.getMergeValues(Ops, DL);
15591 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
15592 SDValue SrcVal = Op.getOperand(0);
15593 const unsigned DstSz = Op.getValueType().getSizeInBits();
15594 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
15595 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
15596 "Unexpected type for custom-lowering FP_EXTEND");
15598 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15599 "With both FP DP and 16, any FP conversion is legal!");
15601 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
15602 "With FP16, 16 to 32 conversion is legal!");
15604 // Either we are converting from 16 -> 64, without FP16 and/or
15605 // FP.double-precision or without Armv8-fp. So we must do it in two
15606 // steps.
15607 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
15608 // without FP16. So we must do a function call.
15609 SDLoc Loc(Op);
15610 RTLIB::Libcall LC;
15611 MakeLibCallOptions CallOptions;
15612 if (SrcSz == 16) {
15613 // Instruction from 16 -> 32
15614 if (Subtarget->hasFP16())
15615 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
15616 // Lib call from 16 -> 32
15617 else {
15618 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
15619 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15620 "Unexpected type for custom-lowering FP_EXTEND");
15621 SrcVal =
15622 makeLibCall(DAG, LC, MVT::f32, SrcVal, CallOptions, Loc).first;
15626 if (DstSz != 64)
15627 return SrcVal;
15628 // For sure now SrcVal is 32 bits
15629 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
15630 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
15632 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
15633 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15634 "Unexpected type for custom-lowering FP_EXTEND");
15635 return makeLibCall(DAG, LC, MVT::f64, SrcVal, CallOptions, Loc).first;
15638 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
15639 SDValue SrcVal = Op.getOperand(0);
15640 EVT SrcVT = SrcVal.getValueType();
15641 EVT DstVT = Op.getValueType();
15642 const unsigned DstSz = Op.getValueType().getSizeInBits();
15643 const unsigned SrcSz = SrcVT.getSizeInBits();
15644 (void)DstSz;
15645 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
15646 "Unexpected type for custom-lowering FP_ROUND");
15648 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15649 "With both FP DP and 16, any FP conversion is legal!");
15651 SDLoc Loc(Op);
15653 // Instruction from 32 -> 16 if hasFP16 is valid
15654 if (SrcSz == 32 && Subtarget->hasFP16())
15655 return Op;
15657 // Lib call from 32 -> 16 / 64 -> [32, 16]
15658 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
15659 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15660 "Unexpected type for custom-lowering FP_ROUND");
15661 MakeLibCallOptions CallOptions;
15662 return makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, Loc).first;
15665 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
15666 SelectionDAG &DAG) const {
15667 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
15668 MVT HalfT = MVT::i32;
15669 SDLoc dl(N);
15670 SDValue Hi, Lo, Tmp;
15672 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
15673 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
15674 return ;
15676 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
15677 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
15679 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15680 DAG.getConstant(0, dl, HalfT));
15681 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15682 DAG.getConstant(1, dl, HalfT));
15684 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
15685 DAG.getConstant(OpTypeBits - 1, dl,
15686 getShiftAmountTy(HalfT, DAG.getDataLayout())));
15687 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
15688 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
15689 SDValue(Lo.getNode(), 1));
15690 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
15691 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
15693 Results.push_back(Lo);
15694 Results.push_back(Hi);
15697 bool
15698 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15699 // The ARM target isn't yet aware of offsets.
15700 return false;
15703 bool ARM::isBitFieldInvertedMask(unsigned v) {
15704 if (v == 0xffffffff)
15705 return false;
15707 // there can be 1's on either or both "outsides", all the "inside"
15708 // bits must be 0's
15709 return isShiftedMask_32(~v);
15712 /// isFPImmLegal - Returns true if the target can instruction select the
15713 /// specified FP immediate natively. If false, the legalizer will
15714 /// materialize the FP immediate as a load from a constant pool.
15715 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15716 bool ForCodeSize) const {
15717 if (!Subtarget->hasVFP3Base())
15718 return false;
15719 if (VT == MVT::f16 && Subtarget->hasFullFP16())
15720 return ARM_AM::getFP16Imm(Imm) != -1;
15721 if (VT == MVT::f32)
15722 return ARM_AM::getFP32Imm(Imm) != -1;
15723 if (VT == MVT::f64 && Subtarget->hasFP64())
15724 return ARM_AM::getFP64Imm(Imm) != -1;
15725 return false;
15728 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
15729 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
15730 /// specified in the intrinsic calls.
15731 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15732 const CallInst &I,
15733 MachineFunction &MF,
15734 unsigned Intrinsic) const {
15735 switch (Intrinsic) {
15736 case Intrinsic::arm_neon_vld1:
15737 case Intrinsic::arm_neon_vld2:
15738 case Intrinsic::arm_neon_vld3:
15739 case Intrinsic::arm_neon_vld4:
15740 case Intrinsic::arm_neon_vld2lane:
15741 case Intrinsic::arm_neon_vld3lane:
15742 case Intrinsic::arm_neon_vld4lane:
15743 case Intrinsic::arm_neon_vld2dup:
15744 case Intrinsic::arm_neon_vld3dup:
15745 case Intrinsic::arm_neon_vld4dup: {
15746 Info.opc = ISD::INTRINSIC_W_CHAIN;
15747 // Conservatively set memVT to the entire set of vectors loaded.
15748 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15749 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15750 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15751 Info.ptrVal = I.getArgOperand(0);
15752 Info.offset = 0;
15753 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15754 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15755 // volatile loads with NEON intrinsics not supported
15756 Info.flags = MachineMemOperand::MOLoad;
15757 return true;
15759 case Intrinsic::arm_neon_vld1x2:
15760 case Intrinsic::arm_neon_vld1x3:
15761 case Intrinsic::arm_neon_vld1x4: {
15762 Info.opc = ISD::INTRINSIC_W_CHAIN;
15763 // Conservatively set memVT to the entire set of vectors loaded.
15764 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15765 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15766 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15767 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
15768 Info.offset = 0;
15769 Info.align.reset();
15770 // volatile loads with NEON intrinsics not supported
15771 Info.flags = MachineMemOperand::MOLoad;
15772 return true;
15774 case Intrinsic::arm_neon_vst1:
15775 case Intrinsic::arm_neon_vst2:
15776 case Intrinsic::arm_neon_vst3:
15777 case Intrinsic::arm_neon_vst4:
15778 case Intrinsic::arm_neon_vst2lane:
15779 case Intrinsic::arm_neon_vst3lane:
15780 case Intrinsic::arm_neon_vst4lane: {
15781 Info.opc = ISD::INTRINSIC_VOID;
15782 // Conservatively set memVT to the entire set of vectors stored.
15783 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15784 unsigned NumElts = 0;
15785 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15786 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15787 if (!ArgTy->isVectorTy())
15788 break;
15789 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15791 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15792 Info.ptrVal = I.getArgOperand(0);
15793 Info.offset = 0;
15794 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15795 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15796 // volatile stores with NEON intrinsics not supported
15797 Info.flags = MachineMemOperand::MOStore;
15798 return true;
15800 case Intrinsic::arm_neon_vst1x2:
15801 case Intrinsic::arm_neon_vst1x3:
15802 case Intrinsic::arm_neon_vst1x4: {
15803 Info.opc = ISD::INTRINSIC_VOID;
15804 // Conservatively set memVT to the entire set of vectors stored.
15805 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15806 unsigned NumElts = 0;
15807 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15808 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15809 if (!ArgTy->isVectorTy())
15810 break;
15811 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15813 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15814 Info.ptrVal = I.getArgOperand(0);
15815 Info.offset = 0;
15816 Info.align.reset();
15817 // volatile stores with NEON intrinsics not supported
15818 Info.flags = MachineMemOperand::MOStore;
15819 return true;
15821 case Intrinsic::arm_ldaex:
15822 case Intrinsic::arm_ldrex: {
15823 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15824 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
15825 Info.opc = ISD::INTRINSIC_W_CHAIN;
15826 Info.memVT = MVT::getVT(PtrTy->getElementType());
15827 Info.ptrVal = I.getArgOperand(0);
15828 Info.offset = 0;
15829 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
15830 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15831 return true;
15833 case Intrinsic::arm_stlex:
15834 case Intrinsic::arm_strex: {
15835 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15836 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
15837 Info.opc = ISD::INTRINSIC_W_CHAIN;
15838 Info.memVT = MVT::getVT(PtrTy->getElementType());
15839 Info.ptrVal = I.getArgOperand(1);
15840 Info.offset = 0;
15841 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
15842 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15843 return true;
15845 case Intrinsic::arm_stlexd:
15846 case Intrinsic::arm_strexd:
15847 Info.opc = ISD::INTRINSIC_W_CHAIN;
15848 Info.memVT = MVT::i64;
15849 Info.ptrVal = I.getArgOperand(2);
15850 Info.offset = 0;
15851 Info.align = Align(8);
15852 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15853 return true;
15855 case Intrinsic::arm_ldaexd:
15856 case Intrinsic::arm_ldrexd:
15857 Info.opc = ISD::INTRINSIC_W_CHAIN;
15858 Info.memVT = MVT::i64;
15859 Info.ptrVal = I.getArgOperand(0);
15860 Info.offset = 0;
15861 Info.align = Align(8);
15862 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15863 return true;
15865 default:
15866 break;
15869 return false;
15872 /// Returns true if it is beneficial to convert a load of a constant
15873 /// to just the constant itself.
15874 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15875 Type *Ty) const {
15876 assert(Ty->isIntegerTy());
15878 unsigned Bits = Ty->getPrimitiveSizeInBits();
15879 if (Bits == 0 || Bits > 32)
15880 return false;
15881 return true;
15884 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
15885 unsigned Index) const {
15886 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
15887 return false;
15889 return (Index == 0 || Index == ResVT.getVectorNumElements());
15892 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
15893 ARM_MB::MemBOpt Domain) const {
15894 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15896 // First, if the target has no DMB, see what fallback we can use.
15897 if (!Subtarget->hasDataBarrier()) {
15898 // Some ARMv6 cpus can support data barriers with an mcr instruction.
15899 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
15900 // here.
15901 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
15902 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
15903 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
15904 Builder.getInt32(0), Builder.getInt32(7),
15905 Builder.getInt32(10), Builder.getInt32(5)};
15906 return Builder.CreateCall(MCR, args);
15907 } else {
15908 // Instead of using barriers, atomic accesses on these subtargets use
15909 // libcalls.
15910 llvm_unreachable("makeDMB on a target so old that it has no barriers");
15912 } else {
15913 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
15914 // Only a full system barrier exists in the M-class architectures.
15915 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
15916 Constant *CDomain = Builder.getInt32(Domain);
15917 return Builder.CreateCall(DMB, CDomain);
15921 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
15922 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
15923 Instruction *Inst,
15924 AtomicOrdering Ord) const {
15925 switch (Ord) {
15926 case AtomicOrdering::NotAtomic:
15927 case AtomicOrdering::Unordered:
15928 llvm_unreachable("Invalid fence: unordered/non-atomic");
15929 case AtomicOrdering::Monotonic:
15930 case AtomicOrdering::Acquire:
15931 return nullptr; // Nothing to do
15932 case AtomicOrdering::SequentiallyConsistent:
15933 if (!Inst->hasAtomicStore())
15934 return nullptr; // Nothing to do
15935 LLVM_FALLTHROUGH;
15936 case AtomicOrdering::Release:
15937 case AtomicOrdering::AcquireRelease:
15938 if (Subtarget->preferISHSTBarriers())
15939 return makeDMB(Builder, ARM_MB::ISHST);
15940 // FIXME: add a comment with a link to documentation justifying this.
15941 else
15942 return makeDMB(Builder, ARM_MB::ISH);
15944 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
15947 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
15948 Instruction *Inst,
15949 AtomicOrdering Ord) const {
15950 switch (Ord) {
15951 case AtomicOrdering::NotAtomic:
15952 case AtomicOrdering::Unordered:
15953 llvm_unreachable("Invalid fence: unordered/not-atomic");
15954 case AtomicOrdering::Monotonic:
15955 case AtomicOrdering::Release:
15956 return nullptr; // Nothing to do
15957 case AtomicOrdering::Acquire:
15958 case AtomicOrdering::AcquireRelease:
15959 case AtomicOrdering::SequentiallyConsistent:
15960 return makeDMB(Builder, ARM_MB::ISH);
15962 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
15965 // Loads and stores less than 64-bits are already atomic; ones above that
15966 // are doomed anyway, so defer to the default libcall and blame the OS when
15967 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
15968 // anything for those.
15969 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
15970 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
15971 return (Size == 64) && !Subtarget->isMClass();
15974 // Loads and stores less than 64-bits are already atomic; ones above that
15975 // are doomed anyway, so defer to the default libcall and blame the OS when
15976 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
15977 // anything for those.
15978 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
15979 // guarantee, see DDI0406C ARM architecture reference manual,
15980 // sections A8.8.72-74 LDRD)
15981 TargetLowering::AtomicExpansionKind
15982 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
15983 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
15984 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
15985 : AtomicExpansionKind::None;
15988 // For the real atomic operations, we have ldrex/strex up to 32 bits,
15989 // and up to 64 bits on the non-M profiles
15990 TargetLowering::AtomicExpansionKind
15991 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
15992 if (AI->isFloatingPointOperation())
15993 return AtomicExpansionKind::CmpXChg;
15995 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
15996 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
15997 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
15998 ? AtomicExpansionKind::LLSC
15999 : AtomicExpansionKind::None;
16002 TargetLowering::AtomicExpansionKind
16003 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
16004 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16005 // implement cmpxchg without spilling. If the address being exchanged is also
16006 // on the stack and close enough to the spill slot, this can lead to a
16007 // situation where the monitor always gets cleared and the atomic operation
16008 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16009 bool HasAtomicCmpXchg =
16010 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16011 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
16012 return AtomicExpansionKind::LLSC;
16013 return AtomicExpansionKind::None;
16016 bool ARMTargetLowering::shouldInsertFencesForAtomic(
16017 const Instruction *I) const {
16018 return InsertFencesForAtomic;
16021 // This has so far only been implemented for MachO.
16022 bool ARMTargetLowering::useLoadStackGuardNode() const {
16023 return Subtarget->isTargetMachO();
16026 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
16027 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16028 return TargetLowering::insertSSPDeclarations(M);
16030 // MSVC CRT has a global variable holding security cookie.
16031 M.getOrInsertGlobal("__security_cookie",
16032 Type::getInt8PtrTy(M.getContext()));
16034 // MSVC CRT has a function to validate security cookie.
16035 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16036 "__security_check_cookie", Type::getVoidTy(M.getContext()),
16037 Type::getInt8PtrTy(M.getContext()));
16038 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
16039 F->addAttribute(1, Attribute::AttrKind::InReg);
16042 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
16043 // MSVC CRT has a global variable holding security cookie.
16044 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16045 return M.getGlobalVariable("__security_cookie");
16046 return TargetLowering::getSDagStackGuard(M);
16049 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
16050 // MSVC CRT has a function to validate security cookie.
16051 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16052 return M.getFunction("__security_check_cookie");
16053 return TargetLowering::getSSPStackGuardCheck(M);
16056 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
16057 unsigned &Cost) const {
16058 // If we do not have NEON, vector types are not natively supported.
16059 if (!Subtarget->hasNEON())
16060 return false;
16062 // Floating point values and vector values map to the same register file.
16063 // Therefore, although we could do a store extract of a vector type, this is
16064 // better to leave at float as we have more freedom in the addressing mode for
16065 // those.
16066 if (VectorTy->isFPOrFPVectorTy())
16067 return false;
16069 // If the index is unknown at compile time, this is very expensive to lower
16070 // and it is not possible to combine the store with the extract.
16071 if (!isa<ConstantInt>(Idx))
16072 return false;
16074 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
16075 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
16076 // We can do a store + vector extract on any vector that fits perfectly in a D
16077 // or Q register.
16078 if (BitWidth == 64 || BitWidth == 128) {
16079 Cost = 0;
16080 return true;
16082 return false;
16085 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
16086 return Subtarget->hasV6T2Ops();
16089 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
16090 return Subtarget->hasV6T2Ops();
16093 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
16094 return !Subtarget->hasMinSize();
16097 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16098 AtomicOrdering Ord) const {
16099 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16100 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16101 bool IsAcquire = isAcquireOrStronger(Ord);
16103 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
16104 // intrinsic must return {i32, i32} and we have to recombine them into a
16105 // single i64 here.
16106 if (ValTy->getPrimitiveSizeInBits() == 64) {
16107 Intrinsic::ID Int =
16108 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
16109 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
16111 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16112 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
16114 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16115 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16116 if (!Subtarget->isLittle())
16117 std::swap (Lo, Hi);
16118 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16119 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16120 return Builder.CreateOr(
16121 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
16124 Type *Tys[] = { Addr->getType() };
16125 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
16126 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
16128 return Builder.CreateTruncOrBitCast(
16129 Builder.CreateCall(Ldrex, Addr),
16130 cast<PointerType>(Addr->getType())->getElementType());
16133 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16134 IRBuilder<> &Builder) const {
16135 if (!Subtarget->hasV7Ops())
16136 return;
16137 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16138 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
16141 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
16142 Value *Addr,
16143 AtomicOrdering Ord) const {
16144 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16145 bool IsRelease = isReleaseOrStronger(Ord);
16147 // Since the intrinsics must have legal type, the i64 intrinsics take two
16148 // parameters: "i32, i32". We must marshal Val into the appropriate form
16149 // before the call.
16150 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
16151 Intrinsic::ID Int =
16152 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
16153 Function *Strex = Intrinsic::getDeclaration(M, Int);
16154 Type *Int32Ty = Type::getInt32Ty(M->getContext());
16156 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
16157 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
16158 if (!Subtarget->isLittle())
16159 std::swap(Lo, Hi);
16160 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16161 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
16164 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
16165 Type *Tys[] = { Addr->getType() };
16166 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
16168 return Builder.CreateCall(
16169 Strex, {Builder.CreateZExtOrBitCast(
16170 Val, Strex->getFunctionType()->getParamType(0)),
16171 Addr});
16175 bool ARMTargetLowering::alignLoopsWithOptSize() const {
16176 return Subtarget->isMClass();
16179 /// A helper function for determining the number of interleaved accesses we
16180 /// will generate when lowering accesses of the given type.
16181 unsigned
16182 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
16183 const DataLayout &DL) const {
16184 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
16187 bool ARMTargetLowering::isLegalInterleavedAccessType(
16188 VectorType *VecTy, const DataLayout &DL) const {
16190 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16191 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16193 // Ensure the vector doesn't have f16 elements. Even though we could do an
16194 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16195 // f32.
16196 if (VecTy->getElementType()->isHalfTy())
16197 return false;
16199 // Ensure the number of vector elements is greater than 1.
16200 if (VecTy->getNumElements() < 2)
16201 return false;
16203 // Ensure the element type is legal.
16204 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16205 return false;
16207 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16208 // 128 will be split into multiple interleaved accesses.
16209 return VecSize == 64 || VecSize % 128 == 0;
16212 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
16213 if (Subtarget->hasNEON())
16214 return 4;
16215 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
16218 /// Lower an interleaved load into a vldN intrinsic.
16220 /// E.g. Lower an interleaved load (Factor = 2):
16221 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16222 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16223 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16225 /// Into:
16226 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16227 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16228 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16229 bool ARMTargetLowering::lowerInterleavedLoad(
16230 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16231 ArrayRef<unsigned> Indices, unsigned Factor) const {
16232 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16233 "Invalid interleave factor");
16234 assert(!Shuffles.empty() && "Empty shufflevector input");
16235 assert(Shuffles.size() == Indices.size() &&
16236 "Unmatched number of shufflevectors and indices");
16238 VectorType *VecTy = Shuffles[0]->getType();
16239 Type *EltTy = VecTy->getVectorElementType();
16241 const DataLayout &DL = LI->getModule()->getDataLayout();
16243 // Skip if we do not have NEON and skip illegal vector types. We can
16244 // "legalize" wide vector types into multiple interleaved accesses as long as
16245 // the vector types are divisible by 128.
16246 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16247 return false;
16249 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16251 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16252 // load integer vectors first and then convert to pointer vectors.
16253 if (EltTy->isPointerTy())
16254 VecTy =
16255 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16257 IRBuilder<> Builder(LI);
16259 // The base address of the load.
16260 Value *BaseAddr = LI->getPointerOperand();
16262 if (NumLoads > 1) {
16263 // If we're going to generate more than one load, reset the sub-vector type
16264 // to something legal.
16265 VecTy = VectorType::get(VecTy->getVectorElementType(),
16266 VecTy->getVectorNumElements() / NumLoads);
16268 // We will compute the pointer operand of each load from the original base
16269 // address using GEPs. Cast the base address to a pointer to the scalar
16270 // element type.
16271 BaseAddr = Builder.CreateBitCast(
16272 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16273 LI->getPointerAddressSpace()));
16276 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16278 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16279 Type *Tys[] = {VecTy, Int8Ptr};
16280 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16281 Intrinsic::arm_neon_vld3,
16282 Intrinsic::arm_neon_vld4};
16283 Function *VldnFunc =
16284 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16286 // Holds sub-vectors extracted from the load intrinsic return values. The
16287 // sub-vectors are associated with the shufflevector instructions they will
16288 // replace.
16289 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16291 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16292 // If we're generating more than one load, compute the base address of
16293 // subsequent loads as an offset from the previous.
16294 if (LoadCount > 0)
16295 BaseAddr =
16296 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16297 VecTy->getVectorNumElements() * Factor);
16299 SmallVector<Value *, 2> Ops;
16300 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16301 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16303 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16305 // Replace uses of each shufflevector with the corresponding vector loaded
16306 // by ldN.
16307 for (unsigned i = 0; i < Shuffles.size(); i++) {
16308 ShuffleVectorInst *SV = Shuffles[i];
16309 unsigned Index = Indices[i];
16311 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16313 // Convert the integer vector to pointer vector if the element is pointer.
16314 if (EltTy->isPointerTy())
16315 SubVec = Builder.CreateIntToPtr(
16316 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16317 VecTy->getVectorNumElements()));
16319 SubVecs[SV].push_back(SubVec);
16323 // Replace uses of the shufflevector instructions with the sub-vectors
16324 // returned by the load intrinsic. If a shufflevector instruction is
16325 // associated with more than one sub-vector, those sub-vectors will be
16326 // concatenated into a single wide vector.
16327 for (ShuffleVectorInst *SVI : Shuffles) {
16328 auto &SubVec = SubVecs[SVI];
16329 auto *WideVec =
16330 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16331 SVI->replaceAllUsesWith(WideVec);
16334 return true;
16337 /// Lower an interleaved store into a vstN intrinsic.
16339 /// E.g. Lower an interleaved store (Factor = 3):
16340 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16341 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16342 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16344 /// Into:
16345 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16346 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16347 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16348 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16350 /// Note that the new shufflevectors will be removed and we'll only generate one
16351 /// vst3 instruction in CodeGen.
16353 /// Example for a more general valid mask (Factor 3). Lower:
16354 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16355 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16356 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16358 /// Into:
16359 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16360 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16361 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16362 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16363 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16364 ShuffleVectorInst *SVI,
16365 unsigned Factor) const {
16366 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16367 "Invalid interleave factor");
16369 VectorType *VecTy = SVI->getType();
16370 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16371 "Invalid interleaved store");
16373 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16374 Type *EltTy = VecTy->getVectorElementType();
16375 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16377 const DataLayout &DL = SI->getModule()->getDataLayout();
16379 // Skip if we do not have NEON and skip illegal vector types. We can
16380 // "legalize" wide vector types into multiple interleaved accesses as long as
16381 // the vector types are divisible by 128.
16382 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16383 return false;
16385 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16387 Value *Op0 = SVI->getOperand(0);
16388 Value *Op1 = SVI->getOperand(1);
16389 IRBuilder<> Builder(SI);
16391 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16392 // vectors to integer vectors.
16393 if (EltTy->isPointerTy()) {
16394 Type *IntTy = DL.getIntPtrType(EltTy);
16396 // Convert to the corresponding integer vector.
16397 Type *IntVecTy =
16398 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16399 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16400 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16402 SubVecTy = VectorType::get(IntTy, LaneLen);
16405 // The base address of the store.
16406 Value *BaseAddr = SI->getPointerOperand();
16408 if (NumStores > 1) {
16409 // If we're going to generate more than one store, reset the lane length
16410 // and sub-vector type to something legal.
16411 LaneLen /= NumStores;
16412 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16414 // We will compute the pointer operand of each store from the original base
16415 // address using GEPs. Cast the base address to a pointer to the scalar
16416 // element type.
16417 BaseAddr = Builder.CreateBitCast(
16418 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16419 SI->getPointerAddressSpace()));
16422 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16424 auto Mask = SVI->getShuffleMask();
16426 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16427 Type *Tys[] = {Int8Ptr, SubVecTy};
16428 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16429 Intrinsic::arm_neon_vst3,
16430 Intrinsic::arm_neon_vst4};
16432 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16433 // If we generating more than one store, we compute the base address of
16434 // subsequent stores as an offset from the previous.
16435 if (StoreCount > 0)
16436 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16437 BaseAddr, LaneLen * Factor);
16439 SmallVector<Value *, 6> Ops;
16440 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16442 Function *VstNFunc =
16443 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16445 // Split the shufflevector operands into sub vectors for the new vstN call.
16446 for (unsigned i = 0; i < Factor; i++) {
16447 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16448 if (Mask[IdxI] >= 0) {
16449 Ops.push_back(Builder.CreateShuffleVector(
16450 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16451 } else {
16452 unsigned StartMask = 0;
16453 for (unsigned j = 1; j < LaneLen; j++) {
16454 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16455 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16456 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16457 break;
16460 // Note: If all elements in a chunk are undefs, StartMask=0!
16461 // Note: Filling undef gaps with random elements is ok, since
16462 // those elements were being written anyway (with undefs).
16463 // In the case of all undefs we're defaulting to using elems from 0
16464 // Note: StartMask cannot be negative, it's checked in
16465 // isReInterleaveMask
16466 Ops.push_back(Builder.CreateShuffleVector(
16467 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16471 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16472 Builder.CreateCall(VstNFunc, Ops);
16474 return true;
16477 enum HABaseType {
16478 HA_UNKNOWN = 0,
16479 HA_FLOAT,
16480 HA_DOUBLE,
16481 HA_VECT64,
16482 HA_VECT128
16485 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16486 uint64_t &Members) {
16487 if (auto *ST = dyn_cast<StructType>(Ty)) {
16488 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16489 uint64_t SubMembers = 0;
16490 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16491 return false;
16492 Members += SubMembers;
16494 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16495 uint64_t SubMembers = 0;
16496 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16497 return false;
16498 Members += SubMembers * AT->getNumElements();
16499 } else if (Ty->isFloatTy()) {
16500 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16501 return false;
16502 Members = 1;
16503 Base = HA_FLOAT;
16504 } else if (Ty->isDoubleTy()) {
16505 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16506 return false;
16507 Members = 1;
16508 Base = HA_DOUBLE;
16509 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16510 Members = 1;
16511 switch (Base) {
16512 case HA_FLOAT:
16513 case HA_DOUBLE:
16514 return false;
16515 case HA_VECT64:
16516 return VT->getBitWidth() == 64;
16517 case HA_VECT128:
16518 return VT->getBitWidth() == 128;
16519 case HA_UNKNOWN:
16520 switch (VT->getBitWidth()) {
16521 case 64:
16522 Base = HA_VECT64;
16523 return true;
16524 case 128:
16525 Base = HA_VECT128;
16526 return true;
16527 default:
16528 return false;
16533 return (Members > 0 && Members <= 4);
16536 /// Return the correct alignment for the current calling convention.
16537 unsigned
16538 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16539 DataLayout DL) const {
16540 if (!ArgTy->isVectorTy())
16541 return DL.getABITypeAlignment(ArgTy);
16543 // Avoid over-aligning vector parameters. It would require realigning the
16544 // stack and waste space for no real benefit.
16545 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
16548 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
16549 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
16550 /// passing according to AAPCS rules.
16551 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
16552 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
16553 if (getEffectiveCallingConv(CallConv, isVarArg) !=
16554 CallingConv::ARM_AAPCS_VFP)
16555 return false;
16557 HABaseType Base = HA_UNKNOWN;
16558 uint64_t Members = 0;
16559 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
16560 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
16562 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
16563 return IsHA || IsIntArray;
16566 unsigned ARMTargetLowering::getExceptionPointerRegister(
16567 const Constant *PersonalityFn) const {
16568 // Platforms which do not use SjLj EH may return values in these registers
16569 // via the personality function.
16570 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
16573 unsigned ARMTargetLowering::getExceptionSelectorRegister(
16574 const Constant *PersonalityFn) const {
16575 // Platforms which do not use SjLj EH may return values in these registers
16576 // via the personality function.
16577 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
16580 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
16581 // Update IsSplitCSR in ARMFunctionInfo.
16582 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
16583 AFI->setIsSplitCSR(true);
16586 void ARMTargetLowering::insertCopiesSplitCSR(
16587 MachineBasicBlock *Entry,
16588 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
16589 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
16590 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
16591 if (!IStart)
16592 return;
16594 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
16595 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
16596 MachineBasicBlock::iterator MBBI = Entry->begin();
16597 for (const MCPhysReg *I = IStart; *I; ++I) {
16598 const TargetRegisterClass *RC = nullptr;
16599 if (ARM::GPRRegClass.contains(*I))
16600 RC = &ARM::GPRRegClass;
16601 else if (ARM::DPRRegClass.contains(*I))
16602 RC = &ARM::DPRRegClass;
16603 else
16604 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
16606 Register NewVR = MRI->createVirtualRegister(RC);
16607 // Create copy from CSR to a virtual register.
16608 // FIXME: this currently does not emit CFI pseudo-instructions, it works
16609 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
16610 // nounwind. If we want to generalize this later, we may need to emit
16611 // CFI pseudo-instructions.
16612 assert(Entry->getParent()->getFunction().hasFnAttribute(
16613 Attribute::NoUnwind) &&
16614 "Function should be nounwind in insertCopiesSplitCSR!");
16615 Entry->addLiveIn(*I);
16616 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
16617 .addReg(*I);
16619 // Insert the copy-back instructions right before the terminator.
16620 for (auto *Exit : Exits)
16621 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
16622 TII->get(TargetOpcode::COPY), *I)
16623 .addReg(NewVR);
16627 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
16628 MF.getFrameInfo().computeMaxCallFrameSize(MF);
16629 TargetLoweringBase::finalizeLowering(MF);