[Alignment][NFC] Use Align with TargetLowering::setMinFunctionAlignment
[llvm-complete.git] / lib / Target / ARM / ARMISelLowering.cpp
blob5c298e5238823f54df348fcbe82d07dd8897d188
1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
12 //===----------------------------------------------------------------------===//
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "Utils/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/RuntimeLibcalls.h"
56 #include "llvm/CodeGen/SelectionDAG.h"
57 #include "llvm/CodeGen/SelectionDAGNodes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCInstrDesc.h"
87 #include "llvm/MC/MCInstrItineraries.h"
88 #include "llvm/MC/MCRegisterInfo.h"
89 #include "llvm/MC/MCSchedule.h"
90 #include "llvm/Support/AtomicOrdering.h"
91 #include "llvm/Support/BranchProbability.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CodeGen.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/KnownBits.h"
99 #include "llvm/Support/MachineValueType.h"
100 #include "llvm/Support/MathExtras.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
115 using namespace llvm;
116 using namespace llvm::PatternMatch;
118 #define DEBUG_TYPE "arm-isel"
120 STATISTIC(NumTailCalls, "Number of tail calls");
121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
123 STATISTIC(NumConstpoolPromoted,
124 "Number of constants with their storage promoted into constant pools");
126 static cl::opt<bool>
127 ARMInterworking("arm-interworking", cl::Hidden,
128 cl::desc("Enable / disable ARM interworking (for debugging only)"),
129 cl::init(true));
131 static cl::opt<bool> EnableConstpoolPromotion(
132 "arm-promote-constant", cl::Hidden,
133 cl::desc("Enable / disable promotion of unnamed_addr constants into "
134 "constant pools"),
135 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
136 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
137 "arm-promote-constant-max-size", cl::Hidden,
138 cl::desc("Maximum size of constant to promote into a constant pool"),
139 cl::init(64));
140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
141 "arm-promote-constant-max-total", cl::Hidden,
142 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
143 cl::init(128));
145 // The APCS parameter registers.
146 static const MCPhysReg GPRArgRegs[] = {
147 ARM::R0, ARM::R1, ARM::R2, ARM::R3
150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
151 MVT PromotedBitwiseVT) {
152 if (VT != PromotedLdStVT) {
153 setOperationAction(ISD::LOAD, VT, Promote);
154 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
156 setOperationAction(ISD::STORE, VT, Promote);
157 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
160 MVT ElemTy = VT.getVectorElementType();
161 if (ElemTy != MVT::f64)
162 setOperationAction(ISD::SETCC, VT, Custom);
163 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
164 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
165 if (ElemTy == MVT::i32) {
166 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
167 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
168 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
169 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
170 } else {
171 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
172 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
173 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
174 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
176 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
177 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
178 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
179 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
180 setOperationAction(ISD::SELECT, VT, Expand);
181 setOperationAction(ISD::SELECT_CC, VT, Expand);
182 setOperationAction(ISD::VSELECT, VT, Expand);
183 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
184 if (VT.isInteger()) {
185 setOperationAction(ISD::SHL, VT, Custom);
186 setOperationAction(ISD::SRA, VT, Custom);
187 setOperationAction(ISD::SRL, VT, Custom);
190 // Promote all bit-wise operations.
191 if (VT.isInteger() && VT != PromotedBitwiseVT) {
192 setOperationAction(ISD::AND, VT, Promote);
193 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
194 setOperationAction(ISD::OR, VT, Promote);
195 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
196 setOperationAction(ISD::XOR, VT, Promote);
197 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
200 // Neon does not support vector divide/remainder operations.
201 setOperationAction(ISD::SDIV, VT, Expand);
202 setOperationAction(ISD::UDIV, VT, Expand);
203 setOperationAction(ISD::FDIV, VT, Expand);
204 setOperationAction(ISD::SREM, VT, Expand);
205 setOperationAction(ISD::UREM, VT, Expand);
206 setOperationAction(ISD::FREM, VT, Expand);
208 if (!VT.isFloatingPoint() &&
209 VT != MVT::v2i64 && VT != MVT::v1i64)
210 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
211 setOperationAction(Opcode, VT, Legal);
214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
215 addRegisterClass(VT, &ARM::DPRRegClass);
216 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
220 addRegisterClass(VT, &ARM::DPairRegClass);
221 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
224 void ARMTargetLowering::setAllExpand(MVT VT) {
225 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
226 setOperationAction(Opc, VT, Expand);
228 // We support these really simple operations even on types where all
229 // the actual arithmetic has to be broken down into simpler
230 // operations or turned into library calls.
231 setOperationAction(ISD::BITCAST, VT, Legal);
232 setOperationAction(ISD::LOAD, VT, Legal);
233 setOperationAction(ISD::STORE, VT, Legal);
234 setOperationAction(ISD::UNDEF, VT, Legal);
237 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
238 LegalizeAction Action) {
239 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
240 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
241 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
244 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
245 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
247 for (auto VT : IntTypes) {
248 addRegisterClass(VT, &ARM::MQPRRegClass);
249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
250 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
251 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
252 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
253 setOperationAction(ISD::SHL, VT, Custom);
254 setOperationAction(ISD::SRA, VT, Custom);
255 setOperationAction(ISD::SRL, VT, Custom);
256 setOperationAction(ISD::SMIN, VT, Legal);
257 setOperationAction(ISD::SMAX, VT, Legal);
258 setOperationAction(ISD::UMIN, VT, Legal);
259 setOperationAction(ISD::UMAX, VT, Legal);
260 setOperationAction(ISD::ABS, VT, Legal);
261 setOperationAction(ISD::SETCC, VT, Custom);
263 // No native support for these.
264 setOperationAction(ISD::UDIV, VT, Expand);
265 setOperationAction(ISD::SDIV, VT, Expand);
266 setOperationAction(ISD::UREM, VT, Expand);
267 setOperationAction(ISD::SREM, VT, Expand);
268 setOperationAction(ISD::CTPOP, VT, Expand);
270 // Vector reductions
271 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
273 if (!HasMVEFP) {
274 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
275 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
276 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
277 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
280 // Pre and Post inc are supported on loads and stores
281 for (unsigned im = (unsigned)ISD::PRE_INC;
282 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
283 setIndexedLoadAction(im, VT, Legal);
284 setIndexedStoreAction(im, VT, Legal);
288 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
289 for (auto VT : FloatTypes) {
290 addRegisterClass(VT, &ARM::MQPRRegClass);
291 if (!HasMVEFP)
292 setAllExpand(VT);
294 // These are legal or custom whether we have MVE.fp or not
295 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
296 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
297 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
298 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
299 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
300 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
301 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
302 setOperationAction(ISD::SETCC, VT, Custom);
304 // Pre and Post inc are supported on loads and stores
305 for (unsigned im = (unsigned)ISD::PRE_INC;
306 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
307 setIndexedLoadAction(im, VT, Legal);
308 setIndexedStoreAction(im, VT, Legal);
311 if (HasMVEFP) {
312 setOperationAction(ISD::FMINNUM, VT, Legal);
313 setOperationAction(ISD::FMAXNUM, VT, Legal);
314 setOperationAction(ISD::FROUND, VT, Legal);
316 // No native support for these.
317 setOperationAction(ISD::FDIV, VT, Expand);
318 setOperationAction(ISD::FREM, VT, Expand);
319 setOperationAction(ISD::FSQRT, VT, Expand);
320 setOperationAction(ISD::FSIN, VT, Expand);
321 setOperationAction(ISD::FCOS, VT, Expand);
322 setOperationAction(ISD::FPOW, VT, Expand);
323 setOperationAction(ISD::FLOG, VT, Expand);
324 setOperationAction(ISD::FLOG2, VT, Expand);
325 setOperationAction(ISD::FLOG10, VT, Expand);
326 setOperationAction(ISD::FEXP, VT, Expand);
327 setOperationAction(ISD::FEXP2, VT, Expand);
328 setOperationAction(ISD::FNEARBYINT, VT, Expand);
332 // We 'support' these types up to bitcast/load/store level, regardless of
333 // MVE integer-only / float support. Only doing FP data processing on the FP
334 // vector types is inhibited at integer-only level.
335 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
336 for (auto VT : LongTypes) {
337 addRegisterClass(VT, &ARM::MQPRRegClass);
338 setAllExpand(VT);
339 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
340 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
341 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
343 // We can do bitwise operations on v2i64 vectors
344 setOperationAction(ISD::AND, MVT::v2i64, Legal);
345 setOperationAction(ISD::OR, MVT::v2i64, Legal);
346 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
348 // It is legal to extload from v4i8 to v4i16 or v4i32.
349 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
350 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
351 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
353 // Some truncating stores are legal too.
354 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
355 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
356 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
358 // Pre and Post inc on these are legal, given the correct extends
359 for (unsigned im = (unsigned)ISD::PRE_INC;
360 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
361 setIndexedLoadAction(im, MVT::v8i8, Legal);
362 setIndexedStoreAction(im, MVT::v8i8, Legal);
363 setIndexedLoadAction(im, MVT::v4i8, Legal);
364 setIndexedStoreAction(im, MVT::v4i8, Legal);
365 setIndexedLoadAction(im, MVT::v4i16, Legal);
366 setIndexedStoreAction(im, MVT::v4i16, Legal);
369 // Predicate types
370 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
371 for (auto VT : pTypes) {
372 addRegisterClass(VT, &ARM::VCCRRegClass);
373 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
374 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
375 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
376 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
377 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
378 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
379 setOperationAction(ISD::SETCC, VT, Custom);
380 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
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 setPrefLoopLogAlignment(Subtarget->getPrefLoopLogAlignment());
1424 setMinFunctionAlignment(Subtarget->isThumb() ? llvm::Align(2)
1425 : llvm::Align(4));
1427 if (Subtarget->isThumb() || Subtarget->isThumb2())
1428 setTargetDAGCombine(ISD::ABS);
1431 bool ARMTargetLowering::useSoftFloat() const {
1432 return Subtarget->useSoftFloat();
1435 // FIXME: It might make sense to define the representative register class as the
1436 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1437 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1438 // SPR's representative would be DPR_VFP2. This should work well if register
1439 // pressure tracking were modified such that a register use would increment the
1440 // pressure of the register class's representative and all of it's super
1441 // classes' representatives transitively. We have not implemented this because
1442 // of the difficulty prior to coalescing of modeling operand register classes
1443 // due to the common occurrence of cross class copies and subregister insertions
1444 // and extractions.
1445 std::pair<const TargetRegisterClass *, uint8_t>
1446 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1447 MVT VT) const {
1448 const TargetRegisterClass *RRC = nullptr;
1449 uint8_t Cost = 1;
1450 switch (VT.SimpleTy) {
1451 default:
1452 return TargetLowering::findRepresentativeClass(TRI, VT);
1453 // Use DPR as representative register class for all floating point
1454 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1455 // the cost is 1 for both f32 and f64.
1456 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1457 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1458 RRC = &ARM::DPRRegClass;
1459 // When NEON is used for SP, only half of the register file is available
1460 // because operations that define both SP and DP results will be constrained
1461 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1462 // coalescing by double-counting the SP regs. See the FIXME above.
1463 if (Subtarget->useNEONForSinglePrecisionFP())
1464 Cost = 2;
1465 break;
1466 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1467 case MVT::v4f32: case MVT::v2f64:
1468 RRC = &ARM::DPRRegClass;
1469 Cost = 2;
1470 break;
1471 case MVT::v4i64:
1472 RRC = &ARM::DPRRegClass;
1473 Cost = 4;
1474 break;
1475 case MVT::v8i64:
1476 RRC = &ARM::DPRRegClass;
1477 Cost = 8;
1478 break;
1480 return std::make_pair(RRC, Cost);
1483 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1484 switch ((ARMISD::NodeType)Opcode) {
1485 case ARMISD::FIRST_NUMBER: break;
1486 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1487 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1488 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1489 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1490 case ARMISD::CALL: return "ARMISD::CALL";
1491 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1492 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1493 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1494 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1495 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1496 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1497 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1498 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1499 case ARMISD::CMP: return "ARMISD::CMP";
1500 case ARMISD::CMN: return "ARMISD::CMN";
1501 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1502 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1503 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1504 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1505 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1507 case ARMISD::CMOV: return "ARMISD::CMOV";
1508 case ARMISD::SUBS: return "ARMISD::SUBS";
1510 case ARMISD::SSAT: return "ARMISD::SSAT";
1511 case ARMISD::USAT: return "ARMISD::USAT";
1513 case ARMISD::ASRL: return "ARMISD::ASRL";
1514 case ARMISD::LSRL: return "ARMISD::LSRL";
1515 case ARMISD::LSLL: return "ARMISD::LSLL";
1517 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1518 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1519 case ARMISD::RRX: return "ARMISD::RRX";
1521 case ARMISD::ADDC: return "ARMISD::ADDC";
1522 case ARMISD::ADDE: return "ARMISD::ADDE";
1523 case ARMISD::SUBC: return "ARMISD::SUBC";
1524 case ARMISD::SUBE: return "ARMISD::SUBE";
1525 case ARMISD::LSLS: return "ARMISD::LSLS";
1527 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1528 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1529 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1530 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1531 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1533 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1534 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1535 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1537 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1539 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1541 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1543 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1545 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1547 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1548 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1550 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1551 case ARMISD::VCMP: return "ARMISD::VCMP";
1552 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1553 case ARMISD::VTST: return "ARMISD::VTST";
1555 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1556 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1557 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1558 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1559 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1560 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1561 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1562 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1563 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1564 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1565 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1566 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1567 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1568 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1569 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1570 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1571 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1572 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1573 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1574 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1575 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1576 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1577 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1578 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1579 case ARMISD::VDUP: return "ARMISD::VDUP";
1580 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1581 case ARMISD::VEXT: return "ARMISD::VEXT";
1582 case ARMISD::VREV64: return "ARMISD::VREV64";
1583 case ARMISD::VREV32: return "ARMISD::VREV32";
1584 case ARMISD::VREV16: return "ARMISD::VREV16";
1585 case ARMISD::VZIP: return "ARMISD::VZIP";
1586 case ARMISD::VUZP: return "ARMISD::VUZP";
1587 case ARMISD::VTRN: return "ARMISD::VTRN";
1588 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1589 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1590 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1591 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1592 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1593 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1594 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1595 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1596 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1597 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1598 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1599 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1600 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1601 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1602 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1603 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1604 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1605 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1606 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1607 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1608 case ARMISD::BFI: return "ARMISD::BFI";
1609 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1610 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1611 case ARMISD::VBSL: return "ARMISD::VBSL";
1612 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1613 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1614 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1615 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1616 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1617 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1618 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1619 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1620 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1621 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1622 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1623 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1624 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1625 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1626 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1627 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1628 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1629 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1630 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1631 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1632 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1633 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1634 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1635 case ARMISD::WLS: return "ARMISD::WLS";
1636 case ARMISD::LE: return "ARMISD::LE";
1637 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1638 case ARMISD::CSINV: return "ARMISD::CSINV";
1639 case ARMISD::CSNEG: return "ARMISD::CSNEG";
1640 case ARMISD::CSINC: return "ARMISD::CSINC";
1642 return nullptr;
1645 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1646 EVT VT) const {
1647 if (!VT.isVector())
1648 return getPointerTy(DL);
1650 // MVE has a predicate register.
1651 if (Subtarget->hasMVEIntegerOps() &&
1652 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1653 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1654 return VT.changeVectorElementTypeToInteger();
1657 /// getRegClassFor - Return the register class that should be used for the
1658 /// specified value type.
1659 const TargetRegisterClass *
1660 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1661 (void)isDivergent;
1662 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1663 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1664 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1665 // MVE Q registers.
1666 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1667 if (VT == MVT::v4i64)
1668 return &ARM::QQPRRegClass;
1669 if (VT == MVT::v8i64)
1670 return &ARM::QQQQPRRegClass;
1672 return TargetLowering::getRegClassFor(VT);
1675 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1676 // source/dest is aligned and the copy size is large enough. We therefore want
1677 // to align such objects passed to memory intrinsics.
1678 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1679 unsigned &PrefAlign) const {
1680 if (!isa<MemIntrinsic>(CI))
1681 return false;
1682 MinSize = 8;
1683 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1684 // cycle faster than 4-byte aligned LDM.
1685 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1686 return true;
1689 // Create a fast isel object.
1690 FastISel *
1691 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1692 const TargetLibraryInfo *libInfo) const {
1693 return ARM::createFastISel(funcInfo, libInfo);
1696 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1697 unsigned NumVals = N->getNumValues();
1698 if (!NumVals)
1699 return Sched::RegPressure;
1701 for (unsigned i = 0; i != NumVals; ++i) {
1702 EVT VT = N->getValueType(i);
1703 if (VT == MVT::Glue || VT == MVT::Other)
1704 continue;
1705 if (VT.isFloatingPoint() || VT.isVector())
1706 return Sched::ILP;
1709 if (!N->isMachineOpcode())
1710 return Sched::RegPressure;
1712 // Load are scheduled for latency even if there instruction itinerary
1713 // is not available.
1714 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1715 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1717 if (MCID.getNumDefs() == 0)
1718 return Sched::RegPressure;
1719 if (!Itins->isEmpty() &&
1720 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1721 return Sched::ILP;
1723 return Sched::RegPressure;
1726 //===----------------------------------------------------------------------===//
1727 // Lowering Code
1728 //===----------------------------------------------------------------------===//
1730 static bool isSRL16(const SDValue &Op) {
1731 if (Op.getOpcode() != ISD::SRL)
1732 return false;
1733 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1734 return Const->getZExtValue() == 16;
1735 return false;
1738 static bool isSRA16(const SDValue &Op) {
1739 if (Op.getOpcode() != ISD::SRA)
1740 return false;
1741 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1742 return Const->getZExtValue() == 16;
1743 return false;
1746 static bool isSHL16(const SDValue &Op) {
1747 if (Op.getOpcode() != ISD::SHL)
1748 return false;
1749 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1750 return Const->getZExtValue() == 16;
1751 return false;
1754 // Check for a signed 16-bit value. We special case SRA because it makes it
1755 // more simple when also looking for SRAs that aren't sign extending a
1756 // smaller value. Without the check, we'd need to take extra care with
1757 // checking order for some operations.
1758 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1759 if (isSRA16(Op))
1760 return isSHL16(Op.getOperand(0));
1761 return DAG.ComputeNumSignBits(Op) == 17;
1764 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1765 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1766 switch (CC) {
1767 default: llvm_unreachable("Unknown condition code!");
1768 case ISD::SETNE: return ARMCC::NE;
1769 case ISD::SETEQ: return ARMCC::EQ;
1770 case ISD::SETGT: return ARMCC::GT;
1771 case ISD::SETGE: return ARMCC::GE;
1772 case ISD::SETLT: return ARMCC::LT;
1773 case ISD::SETLE: return ARMCC::LE;
1774 case ISD::SETUGT: return ARMCC::HI;
1775 case ISD::SETUGE: return ARMCC::HS;
1776 case ISD::SETULT: return ARMCC::LO;
1777 case ISD::SETULE: return ARMCC::LS;
1781 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1782 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1783 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1784 CondCode2 = ARMCC::AL;
1785 InvalidOnQNaN = true;
1786 switch (CC) {
1787 default: llvm_unreachable("Unknown FP condition!");
1788 case ISD::SETEQ:
1789 case ISD::SETOEQ:
1790 CondCode = ARMCC::EQ;
1791 InvalidOnQNaN = false;
1792 break;
1793 case ISD::SETGT:
1794 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1795 case ISD::SETGE:
1796 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1797 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1798 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1799 case ISD::SETONE:
1800 CondCode = ARMCC::MI;
1801 CondCode2 = ARMCC::GT;
1802 InvalidOnQNaN = false;
1803 break;
1804 case ISD::SETO: CondCode = ARMCC::VC; break;
1805 case ISD::SETUO: CondCode = ARMCC::VS; break;
1806 case ISD::SETUEQ:
1807 CondCode = ARMCC::EQ;
1808 CondCode2 = ARMCC::VS;
1809 InvalidOnQNaN = false;
1810 break;
1811 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1812 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1813 case ISD::SETLT:
1814 case ISD::SETULT: CondCode = ARMCC::LT; break;
1815 case ISD::SETLE:
1816 case ISD::SETULE: CondCode = ARMCC::LE; break;
1817 case ISD::SETNE:
1818 case ISD::SETUNE:
1819 CondCode = ARMCC::NE;
1820 InvalidOnQNaN = false;
1821 break;
1825 //===----------------------------------------------------------------------===//
1826 // Calling Convention Implementation
1827 //===----------------------------------------------------------------------===//
1829 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1830 /// account presence of floating point hardware and calling convention
1831 /// limitations, such as support for variadic functions.
1832 CallingConv::ID
1833 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1834 bool isVarArg) const {
1835 switch (CC) {
1836 default:
1837 report_fatal_error("Unsupported calling convention");
1838 case CallingConv::ARM_AAPCS:
1839 case CallingConv::ARM_APCS:
1840 case CallingConv::GHC:
1841 return CC;
1842 case CallingConv::PreserveMost:
1843 return CallingConv::PreserveMost;
1844 case CallingConv::ARM_AAPCS_VFP:
1845 case CallingConv::Swift:
1846 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1847 case CallingConv::C:
1848 if (!Subtarget->isAAPCS_ABI())
1849 return CallingConv::ARM_APCS;
1850 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1851 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1852 !isVarArg)
1853 return CallingConv::ARM_AAPCS_VFP;
1854 else
1855 return CallingConv::ARM_AAPCS;
1856 case CallingConv::Fast:
1857 case CallingConv::CXX_FAST_TLS:
1858 if (!Subtarget->isAAPCS_ABI()) {
1859 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1860 return CallingConv::Fast;
1861 return CallingConv::ARM_APCS;
1862 } else if (Subtarget->hasVFP2Base() &&
1863 !Subtarget->isThumb1Only() && !isVarArg)
1864 return CallingConv::ARM_AAPCS_VFP;
1865 else
1866 return CallingConv::ARM_AAPCS;
1870 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1871 bool isVarArg) const {
1872 return CCAssignFnForNode(CC, false, isVarArg);
1875 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1876 bool isVarArg) const {
1877 return CCAssignFnForNode(CC, true, isVarArg);
1880 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1881 /// CallingConvention.
1882 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1883 bool Return,
1884 bool isVarArg) const {
1885 switch (getEffectiveCallingConv(CC, isVarArg)) {
1886 default:
1887 report_fatal_error("Unsupported calling convention");
1888 case CallingConv::ARM_APCS:
1889 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1890 case CallingConv::ARM_AAPCS:
1891 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1892 case CallingConv::ARM_AAPCS_VFP:
1893 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1894 case CallingConv::Fast:
1895 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1896 case CallingConv::GHC:
1897 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1898 case CallingConv::PreserveMost:
1899 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1903 /// LowerCallResult - Lower the result values of a call into the
1904 /// appropriate copies out of appropriate physical registers.
1905 SDValue ARMTargetLowering::LowerCallResult(
1906 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1907 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1908 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1909 SDValue ThisVal) const {
1910 // Assign locations to each value returned by this call.
1911 SmallVector<CCValAssign, 16> RVLocs;
1912 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1913 *DAG.getContext());
1914 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1916 // Copy all of the result registers out of their specified physreg.
1917 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1918 CCValAssign VA = RVLocs[i];
1920 // Pass 'this' value directly from the argument to return value, to avoid
1921 // reg unit interference
1922 if (i == 0 && isThisReturn) {
1923 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1924 "unexpected return calling convention register assignment");
1925 InVals.push_back(ThisVal);
1926 continue;
1929 SDValue Val;
1930 if (VA.needsCustom()) {
1931 // Handle f64 or half of a v2f64.
1932 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1933 InFlag);
1934 Chain = Lo.getValue(1);
1935 InFlag = Lo.getValue(2);
1936 VA = RVLocs[++i]; // skip ahead to next loc
1937 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1938 InFlag);
1939 Chain = Hi.getValue(1);
1940 InFlag = Hi.getValue(2);
1941 if (!Subtarget->isLittle())
1942 std::swap (Lo, Hi);
1943 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1945 if (VA.getLocVT() == MVT::v2f64) {
1946 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1947 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1948 DAG.getConstant(0, dl, MVT::i32));
1950 VA = RVLocs[++i]; // skip ahead to next loc
1951 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1952 Chain = Lo.getValue(1);
1953 InFlag = Lo.getValue(2);
1954 VA = RVLocs[++i]; // skip ahead to next loc
1955 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1956 Chain = Hi.getValue(1);
1957 InFlag = Hi.getValue(2);
1958 if (!Subtarget->isLittle())
1959 std::swap (Lo, Hi);
1960 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1961 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1962 DAG.getConstant(1, dl, MVT::i32));
1964 } else {
1965 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1966 InFlag);
1967 Chain = Val.getValue(1);
1968 InFlag = Val.getValue(2);
1971 switch (VA.getLocInfo()) {
1972 default: llvm_unreachable("Unknown loc info!");
1973 case CCValAssign::Full: break;
1974 case CCValAssign::BCvt:
1975 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1976 break;
1979 InVals.push_back(Val);
1982 return Chain;
1985 /// LowerMemOpCallTo - Store the argument to the stack.
1986 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1987 SDValue Arg, const SDLoc &dl,
1988 SelectionDAG &DAG,
1989 const CCValAssign &VA,
1990 ISD::ArgFlagsTy Flags) const {
1991 unsigned LocMemOffset = VA.getLocMemOffset();
1992 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1993 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1994 StackPtr, PtrOff);
1995 return DAG.getStore(
1996 Chain, dl, Arg, PtrOff,
1997 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2000 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2001 SDValue Chain, SDValue &Arg,
2002 RegsToPassVector &RegsToPass,
2003 CCValAssign &VA, CCValAssign &NextVA,
2004 SDValue &StackPtr,
2005 SmallVectorImpl<SDValue> &MemOpChains,
2006 ISD::ArgFlagsTy Flags) const {
2007 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2008 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2009 unsigned id = Subtarget->isLittle() ? 0 : 1;
2010 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2012 if (NextVA.isRegLoc())
2013 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2014 else {
2015 assert(NextVA.isMemLoc());
2016 if (!StackPtr.getNode())
2017 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2018 getPointerTy(DAG.getDataLayout()));
2020 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2021 dl, DAG, NextVA,
2022 Flags));
2026 /// LowerCall - Lowering a call into a callseq_start <-
2027 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2028 /// nodes.
2029 SDValue
2030 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2031 SmallVectorImpl<SDValue> &InVals) const {
2032 SelectionDAG &DAG = CLI.DAG;
2033 SDLoc &dl = CLI.DL;
2034 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2035 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2036 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2037 SDValue Chain = CLI.Chain;
2038 SDValue Callee = CLI.Callee;
2039 bool &isTailCall = CLI.IsTailCall;
2040 CallingConv::ID CallConv = CLI.CallConv;
2041 bool doesNotRet = CLI.DoesNotReturn;
2042 bool isVarArg = CLI.IsVarArg;
2044 MachineFunction &MF = DAG.getMachineFunction();
2045 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2046 bool isThisReturn = false;
2047 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2048 bool PreferIndirect = false;
2050 // Disable tail calls if they're not supported.
2051 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2052 isTailCall = false;
2054 if (isa<GlobalAddressSDNode>(Callee)) {
2055 // If we're optimizing for minimum size and the function is called three or
2056 // more times in this block, we can improve codesize by calling indirectly
2057 // as BLXr has a 16-bit encoding.
2058 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2059 if (CLI.CS) {
2060 auto *BB = CLI.CS.getParent();
2061 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2062 count_if(GV->users(), [&BB](const User *U) {
2063 return isa<Instruction>(U) &&
2064 cast<Instruction>(U)->getParent() == BB;
2065 }) > 2;
2068 if (isTailCall) {
2069 // Check if it's really possible to do a tail call.
2070 isTailCall = IsEligibleForTailCallOptimization(
2071 Callee, CallConv, isVarArg, isStructRet,
2072 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2073 PreferIndirect);
2074 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2075 report_fatal_error("failed to perform tail call elimination on a call "
2076 "site marked musttail");
2077 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2078 // detected sibcalls.
2079 if (isTailCall)
2080 ++NumTailCalls;
2083 // Analyze operands of the call, assigning locations to each operand.
2084 SmallVector<CCValAssign, 16> ArgLocs;
2085 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2086 *DAG.getContext());
2087 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2089 // Get a count of how many bytes are to be pushed on the stack.
2090 unsigned NumBytes = CCInfo.getNextStackOffset();
2092 if (isTailCall) {
2093 // For tail calls, memory operands are available in our caller's stack.
2094 NumBytes = 0;
2095 } else {
2096 // Adjust the stack pointer for the new arguments...
2097 // These operations are automatically eliminated by the prolog/epilog pass
2098 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2101 SDValue StackPtr =
2102 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2104 RegsToPassVector RegsToPass;
2105 SmallVector<SDValue, 8> MemOpChains;
2107 // Walk the register/memloc assignments, inserting copies/loads. In the case
2108 // of tail call optimization, arguments are handled later.
2109 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2110 i != e;
2111 ++i, ++realArgIdx) {
2112 CCValAssign &VA = ArgLocs[i];
2113 SDValue Arg = OutVals[realArgIdx];
2114 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2115 bool isByVal = Flags.isByVal();
2117 // Promote the value if needed.
2118 switch (VA.getLocInfo()) {
2119 default: llvm_unreachable("Unknown loc info!");
2120 case CCValAssign::Full: break;
2121 case CCValAssign::SExt:
2122 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2123 break;
2124 case CCValAssign::ZExt:
2125 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2126 break;
2127 case CCValAssign::AExt:
2128 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2129 break;
2130 case CCValAssign::BCvt:
2131 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2132 break;
2135 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2136 if (VA.needsCustom()) {
2137 if (VA.getLocVT() == MVT::v2f64) {
2138 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2139 DAG.getConstant(0, dl, MVT::i32));
2140 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2141 DAG.getConstant(1, dl, MVT::i32));
2143 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2144 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2146 VA = ArgLocs[++i]; // skip ahead to next loc
2147 if (VA.isRegLoc()) {
2148 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2149 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2150 } else {
2151 assert(VA.isMemLoc());
2153 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2154 dl, DAG, VA, Flags));
2156 } else {
2157 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2158 StackPtr, MemOpChains, Flags);
2160 } else if (VA.isRegLoc()) {
2161 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2162 Outs[0].VT == MVT::i32) {
2163 assert(VA.getLocVT() == MVT::i32 &&
2164 "unexpected calling convention register assignment");
2165 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2166 "unexpected use of 'returned'");
2167 isThisReturn = true;
2169 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2170 } else if (isByVal) {
2171 assert(VA.isMemLoc());
2172 unsigned offset = 0;
2174 // True if this byval aggregate will be split between registers
2175 // and memory.
2176 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2177 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2179 if (CurByValIdx < ByValArgsCount) {
2181 unsigned RegBegin, RegEnd;
2182 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2184 EVT PtrVT =
2185 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2186 unsigned int i, j;
2187 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2188 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2189 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2190 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2191 MachinePointerInfo(),
2192 DAG.InferPtrAlignment(AddArg));
2193 MemOpChains.push_back(Load.getValue(1));
2194 RegsToPass.push_back(std::make_pair(j, Load));
2197 // If parameter size outsides register area, "offset" value
2198 // helps us to calculate stack slot for remained part properly.
2199 offset = RegEnd - RegBegin;
2201 CCInfo.nextInRegsParam();
2204 if (Flags.getByValSize() > 4*offset) {
2205 auto PtrVT = getPointerTy(DAG.getDataLayout());
2206 unsigned LocMemOffset = VA.getLocMemOffset();
2207 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2208 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2209 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2210 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2211 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2212 MVT::i32);
2213 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2214 MVT::i32);
2216 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2217 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2218 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2219 Ops));
2221 } else if (!isTailCall) {
2222 assert(VA.isMemLoc());
2224 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2225 dl, DAG, VA, Flags));
2229 if (!MemOpChains.empty())
2230 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2232 // Build a sequence of copy-to-reg nodes chained together with token chain
2233 // and flag operands which copy the outgoing args into the appropriate regs.
2234 SDValue InFlag;
2235 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2236 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2237 RegsToPass[i].second, InFlag);
2238 InFlag = Chain.getValue(1);
2241 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2242 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2243 // node so that legalize doesn't hack it.
2244 bool isDirect = false;
2246 const TargetMachine &TM = getTargetMachine();
2247 const Module *Mod = MF.getFunction().getParent();
2248 const GlobalValue *GV = nullptr;
2249 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2250 GV = G->getGlobal();
2251 bool isStub =
2252 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2254 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2255 bool isLocalARMFunc = false;
2256 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2257 auto PtrVt = getPointerTy(DAG.getDataLayout());
2259 if (Subtarget->genLongCalls()) {
2260 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2261 "long-calls codegen is not position independent!");
2262 // Handle a global address or an external symbol. If it's not one of
2263 // those, the target's already in a register, so we don't need to do
2264 // anything extra.
2265 if (isa<GlobalAddressSDNode>(Callee)) {
2266 // Create a constant pool entry for the callee address
2267 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2268 ARMConstantPoolValue *CPV =
2269 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2271 // Get the address of the callee into a register
2272 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2273 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2274 Callee = DAG.getLoad(
2275 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2276 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2277 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2278 const char *Sym = S->getSymbol();
2280 // Create a constant pool entry for the callee address
2281 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2282 ARMConstantPoolValue *CPV =
2283 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2284 ARMPCLabelIndex, 0);
2285 // Get the address of the callee into a register
2286 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2287 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2288 Callee = DAG.getLoad(
2289 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2290 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2292 } else if (isa<GlobalAddressSDNode>(Callee)) {
2293 if (!PreferIndirect) {
2294 isDirect = true;
2295 bool isDef = GV->isStrongDefinitionForLinker();
2297 // ARM call to a local ARM function is predicable.
2298 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2299 // tBX takes a register source operand.
2300 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2301 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2302 Callee = DAG.getNode(
2303 ARMISD::WrapperPIC, dl, PtrVt,
2304 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2305 Callee = DAG.getLoad(
2306 PtrVt, dl, DAG.getEntryNode(), Callee,
2307 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2308 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2309 MachineMemOperand::MOInvariant);
2310 } else if (Subtarget->isTargetCOFF()) {
2311 assert(Subtarget->isTargetWindows() &&
2312 "Windows is the only supported COFF target");
2313 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2314 ? ARMII::MO_DLLIMPORT
2315 : ARMII::MO_NO_FLAG;
2316 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2317 TargetFlags);
2318 if (GV->hasDLLImportStorageClass())
2319 Callee =
2320 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2321 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2322 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2323 } else {
2324 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2327 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2328 isDirect = true;
2329 // tBX takes a register source operand.
2330 const char *Sym = S->getSymbol();
2331 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2332 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2333 ARMConstantPoolValue *CPV =
2334 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2335 ARMPCLabelIndex, 4);
2336 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2337 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2338 Callee = DAG.getLoad(
2339 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2340 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2341 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2342 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2343 } else {
2344 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2348 // FIXME: handle tail calls differently.
2349 unsigned CallOpc;
2350 if (Subtarget->isThumb()) {
2351 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2352 CallOpc = ARMISD::CALL_NOLINK;
2353 else
2354 CallOpc = ARMISD::CALL;
2355 } else {
2356 if (!isDirect && !Subtarget->hasV5TOps())
2357 CallOpc = ARMISD::CALL_NOLINK;
2358 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2359 // Emit regular call when code size is the priority
2360 !Subtarget->hasMinSize())
2361 // "mov lr, pc; b _foo" to avoid confusing the RSP
2362 CallOpc = ARMISD::CALL_NOLINK;
2363 else
2364 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2367 std::vector<SDValue> Ops;
2368 Ops.push_back(Chain);
2369 Ops.push_back(Callee);
2371 // Add argument registers to the end of the list so that they are known live
2372 // into the call.
2373 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2374 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2375 RegsToPass[i].second.getValueType()));
2377 // Add a register mask operand representing the call-preserved registers.
2378 if (!isTailCall) {
2379 const uint32_t *Mask;
2380 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2381 if (isThisReturn) {
2382 // For 'this' returns, use the R0-preserving mask if applicable
2383 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2384 if (!Mask) {
2385 // Set isThisReturn to false if the calling convention is not one that
2386 // allows 'returned' to be modeled in this way, so LowerCallResult does
2387 // not try to pass 'this' straight through
2388 isThisReturn = false;
2389 Mask = ARI->getCallPreservedMask(MF, CallConv);
2391 } else
2392 Mask = ARI->getCallPreservedMask(MF, CallConv);
2394 assert(Mask && "Missing call preserved mask for calling convention");
2395 Ops.push_back(DAG.getRegisterMask(Mask));
2398 if (InFlag.getNode())
2399 Ops.push_back(InFlag);
2401 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2402 if (isTailCall) {
2403 MF.getFrameInfo().setHasTailCall();
2404 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2407 // Returns a chain and a flag for retval copy to use.
2408 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2409 InFlag = Chain.getValue(1);
2411 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2412 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2413 if (!Ins.empty())
2414 InFlag = Chain.getValue(1);
2416 // Handle result values, copying them out of physregs into vregs that we
2417 // return.
2418 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2419 InVals, isThisReturn,
2420 isThisReturn ? OutVals[0] : SDValue());
2423 /// HandleByVal - Every parameter *after* a byval parameter is passed
2424 /// on the stack. Remember the next parameter register to allocate,
2425 /// and then confiscate the rest of the parameter registers to insure
2426 /// this.
2427 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2428 unsigned Align) const {
2429 // Byval (as with any stack) slots are always at least 4 byte aligned.
2430 Align = std::max(Align, 4U);
2432 unsigned Reg = State->AllocateReg(GPRArgRegs);
2433 if (!Reg)
2434 return;
2436 unsigned AlignInRegs = Align / 4;
2437 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2438 for (unsigned i = 0; i < Waste; ++i)
2439 Reg = State->AllocateReg(GPRArgRegs);
2441 if (!Reg)
2442 return;
2444 unsigned Excess = 4 * (ARM::R4 - Reg);
2446 // Special case when NSAA != SP and parameter size greater than size of
2447 // all remained GPR regs. In that case we can't split parameter, we must
2448 // send it to stack. We also must set NCRN to R4, so waste all
2449 // remained registers.
2450 const unsigned NSAAOffset = State->getNextStackOffset();
2451 if (NSAAOffset != 0 && Size > Excess) {
2452 while (State->AllocateReg(GPRArgRegs))
2454 return;
2457 // First register for byval parameter is the first register that wasn't
2458 // allocated before this method call, so it would be "reg".
2459 // If parameter is small enough to be saved in range [reg, r4), then
2460 // the end (first after last) register would be reg + param-size-in-regs,
2461 // else parameter would be splitted between registers and stack,
2462 // end register would be r4 in this case.
2463 unsigned ByValRegBegin = Reg;
2464 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2465 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2466 // Note, first register is allocated in the beginning of function already,
2467 // allocate remained amount of registers we need.
2468 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2469 State->AllocateReg(GPRArgRegs);
2470 // A byval parameter that is split between registers and memory needs its
2471 // size truncated here.
2472 // In the case where the entire structure fits in registers, we set the
2473 // size in memory to zero.
2474 Size = std::max<int>(Size - Excess, 0);
2477 /// MatchingStackOffset - Return true if the given stack call argument is
2478 /// already available in the same position (relatively) of the caller's
2479 /// incoming argument stack.
2480 static
2481 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2482 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2483 const TargetInstrInfo *TII) {
2484 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2485 int FI = std::numeric_limits<int>::max();
2486 if (Arg.getOpcode() == ISD::CopyFromReg) {
2487 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2488 if (!Register::isVirtualRegister(VR))
2489 return false;
2490 MachineInstr *Def = MRI->getVRegDef(VR);
2491 if (!Def)
2492 return false;
2493 if (!Flags.isByVal()) {
2494 if (!TII->isLoadFromStackSlot(*Def, FI))
2495 return false;
2496 } else {
2497 return false;
2499 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2500 if (Flags.isByVal())
2501 // ByVal argument is passed in as a pointer but it's now being
2502 // dereferenced. e.g.
2503 // define @foo(%struct.X* %A) {
2504 // tail call @bar(%struct.X* byval %A)
2505 // }
2506 return false;
2507 SDValue Ptr = Ld->getBasePtr();
2508 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2509 if (!FINode)
2510 return false;
2511 FI = FINode->getIndex();
2512 } else
2513 return false;
2515 assert(FI != std::numeric_limits<int>::max());
2516 if (!MFI.isFixedObjectIndex(FI))
2517 return false;
2518 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2521 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2522 /// for tail call optimization. Targets which want to do tail call
2523 /// optimization should implement this function.
2524 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2525 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2526 bool isCalleeStructRet, bool isCallerStructRet,
2527 const SmallVectorImpl<ISD::OutputArg> &Outs,
2528 const SmallVectorImpl<SDValue> &OutVals,
2529 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2530 const bool isIndirect) const {
2531 MachineFunction &MF = DAG.getMachineFunction();
2532 const Function &CallerF = MF.getFunction();
2533 CallingConv::ID CallerCC = CallerF.getCallingConv();
2535 assert(Subtarget->supportsTailCall());
2537 // Indirect tail calls cannot be optimized for Thumb1 if the args
2538 // to the call take up r0-r3. The reason is that there are no legal registers
2539 // left to hold the pointer to the function to be called.
2540 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2541 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2542 return false;
2544 // Look for obvious safe cases to perform tail call optimization that do not
2545 // require ABI changes. This is what gcc calls sibcall.
2547 // Exception-handling functions need a special set of instructions to indicate
2548 // a return to the hardware. Tail-calling another function would probably
2549 // break this.
2550 if (CallerF.hasFnAttribute("interrupt"))
2551 return false;
2553 // Also avoid sibcall optimization if either caller or callee uses struct
2554 // return semantics.
2555 if (isCalleeStructRet || isCallerStructRet)
2556 return false;
2558 // Externally-defined functions with weak linkage should not be
2559 // tail-called on ARM when the OS does not support dynamic
2560 // pre-emption of symbols, as the AAELF spec requires normal calls
2561 // to undefined weak functions to be replaced with a NOP or jump to the
2562 // next instruction. The behaviour of branch instructions in this
2563 // situation (as used for tail calls) is implementation-defined, so we
2564 // cannot rely on the linker replacing the tail call with a return.
2565 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2566 const GlobalValue *GV = G->getGlobal();
2567 const Triple &TT = getTargetMachine().getTargetTriple();
2568 if (GV->hasExternalWeakLinkage() &&
2569 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2570 return false;
2573 // Check that the call results are passed in the same way.
2574 LLVMContext &C = *DAG.getContext();
2575 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2576 CCAssignFnForReturn(CalleeCC, isVarArg),
2577 CCAssignFnForReturn(CallerCC, isVarArg)))
2578 return false;
2579 // The callee has to preserve all registers the caller needs to preserve.
2580 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2581 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2582 if (CalleeCC != CallerCC) {
2583 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2584 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2585 return false;
2588 // If Caller's vararg or byval argument has been split between registers and
2589 // stack, do not perform tail call, since part of the argument is in caller's
2590 // local frame.
2591 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2592 if (AFI_Caller->getArgRegsSaveSize())
2593 return false;
2595 // If the callee takes no arguments then go on to check the results of the
2596 // call.
2597 if (!Outs.empty()) {
2598 // Check if stack adjustment is needed. For now, do not do this if any
2599 // argument is passed on the stack.
2600 SmallVector<CCValAssign, 16> ArgLocs;
2601 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2602 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2603 if (CCInfo.getNextStackOffset()) {
2604 // Check if the arguments are already laid out in the right way as
2605 // the caller's fixed stack objects.
2606 MachineFrameInfo &MFI = MF.getFrameInfo();
2607 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2608 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2609 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2610 i != e;
2611 ++i, ++realArgIdx) {
2612 CCValAssign &VA = ArgLocs[i];
2613 EVT RegVT = VA.getLocVT();
2614 SDValue Arg = OutVals[realArgIdx];
2615 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2616 if (VA.getLocInfo() == CCValAssign::Indirect)
2617 return false;
2618 if (VA.needsCustom()) {
2619 // f64 and vector types are split into multiple registers or
2620 // register/stack-slot combinations. The types will not match
2621 // the registers; give up on memory f64 refs until we figure
2622 // out what to do about this.
2623 if (!VA.isRegLoc())
2624 return false;
2625 if (!ArgLocs[++i].isRegLoc())
2626 return false;
2627 if (RegVT == MVT::v2f64) {
2628 if (!ArgLocs[++i].isRegLoc())
2629 return false;
2630 if (!ArgLocs[++i].isRegLoc())
2631 return false;
2633 } else if (!VA.isRegLoc()) {
2634 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2635 MFI, MRI, TII))
2636 return false;
2641 const MachineRegisterInfo &MRI = MF.getRegInfo();
2642 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2643 return false;
2646 return true;
2649 bool
2650 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2651 MachineFunction &MF, bool isVarArg,
2652 const SmallVectorImpl<ISD::OutputArg> &Outs,
2653 LLVMContext &Context) const {
2654 SmallVector<CCValAssign, 16> RVLocs;
2655 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2656 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2659 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2660 const SDLoc &DL, SelectionDAG &DAG) {
2661 const MachineFunction &MF = DAG.getMachineFunction();
2662 const Function &F = MF.getFunction();
2664 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2666 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2667 // version of the "preferred return address". These offsets affect the return
2668 // instruction if this is a return from PL1 without hypervisor extensions.
2669 // IRQ/FIQ: +4 "subs pc, lr, #4"
2670 // SWI: 0 "subs pc, lr, #0"
2671 // ABORT: +4 "subs pc, lr, #4"
2672 // UNDEF: +4/+2 "subs pc, lr, #0"
2673 // UNDEF varies depending on where the exception came from ARM or Thumb
2674 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2676 int64_t LROffset;
2677 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2678 IntKind == "ABORT")
2679 LROffset = 4;
2680 else if (IntKind == "SWI" || IntKind == "UNDEF")
2681 LROffset = 0;
2682 else
2683 report_fatal_error("Unsupported interrupt attribute. If present, value "
2684 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2686 RetOps.insert(RetOps.begin() + 1,
2687 DAG.getConstant(LROffset, DL, MVT::i32, false));
2689 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2692 SDValue
2693 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2694 bool isVarArg,
2695 const SmallVectorImpl<ISD::OutputArg> &Outs,
2696 const SmallVectorImpl<SDValue> &OutVals,
2697 const SDLoc &dl, SelectionDAG &DAG) const {
2698 // CCValAssign - represent the assignment of the return value to a location.
2699 SmallVector<CCValAssign, 16> RVLocs;
2701 // CCState - Info about the registers and stack slots.
2702 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2703 *DAG.getContext());
2705 // Analyze outgoing return values.
2706 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2708 SDValue Flag;
2709 SmallVector<SDValue, 4> RetOps;
2710 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2711 bool isLittleEndian = Subtarget->isLittle();
2713 MachineFunction &MF = DAG.getMachineFunction();
2714 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2715 AFI->setReturnRegsCount(RVLocs.size());
2717 // Copy the result values into the output registers.
2718 for (unsigned i = 0, realRVLocIdx = 0;
2719 i != RVLocs.size();
2720 ++i, ++realRVLocIdx) {
2721 CCValAssign &VA = RVLocs[i];
2722 assert(VA.isRegLoc() && "Can only return in registers!");
2724 SDValue Arg = OutVals[realRVLocIdx];
2725 bool ReturnF16 = false;
2727 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2728 // Half-precision return values can be returned like this:
2730 // t11 f16 = fadd ...
2731 // t12: i16 = bitcast t11
2732 // t13: i32 = zero_extend t12
2733 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2735 // to avoid code generation for bitcasts, we simply set Arg to the node
2736 // that produces the f16 value, t11 in this case.
2738 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2739 SDValue ZE = Arg.getOperand(0);
2740 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2741 SDValue BC = ZE.getOperand(0);
2742 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2743 Arg = BC.getOperand(0);
2744 ReturnF16 = true;
2750 switch (VA.getLocInfo()) {
2751 default: llvm_unreachable("Unknown loc info!");
2752 case CCValAssign::Full: break;
2753 case CCValAssign::BCvt:
2754 if (!ReturnF16)
2755 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2756 break;
2759 if (VA.needsCustom()) {
2760 if (VA.getLocVT() == MVT::v2f64) {
2761 // Extract the first half and return it in two registers.
2762 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2763 DAG.getConstant(0, dl, MVT::i32));
2764 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2765 DAG.getVTList(MVT::i32, MVT::i32), Half);
2767 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2768 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2769 Flag);
2770 Flag = Chain.getValue(1);
2771 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2772 VA = RVLocs[++i]; // skip ahead to next loc
2773 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2774 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2775 Flag);
2776 Flag = Chain.getValue(1);
2777 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2778 VA = RVLocs[++i]; // skip ahead to next loc
2780 // Extract the 2nd half and fall through to handle it as an f64 value.
2781 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2782 DAG.getConstant(1, dl, MVT::i32));
2784 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2785 // available.
2786 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2787 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2788 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2789 fmrrd.getValue(isLittleEndian ? 0 : 1),
2790 Flag);
2791 Flag = Chain.getValue(1);
2792 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2793 VA = RVLocs[++i]; // skip ahead to next loc
2794 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2795 fmrrd.getValue(isLittleEndian ? 1 : 0),
2796 Flag);
2797 } else
2798 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2800 // Guarantee that all emitted copies are
2801 // stuck together, avoiding something bad.
2802 Flag = Chain.getValue(1);
2803 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2804 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2806 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2807 const MCPhysReg *I =
2808 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2809 if (I) {
2810 for (; *I; ++I) {
2811 if (ARM::GPRRegClass.contains(*I))
2812 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2813 else if (ARM::DPRRegClass.contains(*I))
2814 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2815 else
2816 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2820 // Update chain and glue.
2821 RetOps[0] = Chain;
2822 if (Flag.getNode())
2823 RetOps.push_back(Flag);
2825 // CPUs which aren't M-class use a special sequence to return from
2826 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2827 // though we use "subs pc, lr, #N").
2829 // M-class CPUs actually use a normal return sequence with a special
2830 // (hardware-provided) value in LR, so the normal code path works.
2831 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2832 !Subtarget->isMClass()) {
2833 if (Subtarget->isThumb1Only())
2834 report_fatal_error("interrupt attribute is not supported in Thumb1");
2835 return LowerInterruptReturn(RetOps, dl, DAG);
2838 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2841 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2842 if (N->getNumValues() != 1)
2843 return false;
2844 if (!N->hasNUsesOfValue(1, 0))
2845 return false;
2847 SDValue TCChain = Chain;
2848 SDNode *Copy = *N->use_begin();
2849 if (Copy->getOpcode() == ISD::CopyToReg) {
2850 // If the copy has a glue operand, we conservatively assume it isn't safe to
2851 // perform a tail call.
2852 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2853 return false;
2854 TCChain = Copy->getOperand(0);
2855 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2856 SDNode *VMov = Copy;
2857 // f64 returned in a pair of GPRs.
2858 SmallPtrSet<SDNode*, 2> Copies;
2859 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2860 UI != UE; ++UI) {
2861 if (UI->getOpcode() != ISD::CopyToReg)
2862 return false;
2863 Copies.insert(*UI);
2865 if (Copies.size() > 2)
2866 return false;
2868 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2869 UI != UE; ++UI) {
2870 SDValue UseChain = UI->getOperand(0);
2871 if (Copies.count(UseChain.getNode()))
2872 // Second CopyToReg
2873 Copy = *UI;
2874 else {
2875 // We are at the top of this chain.
2876 // If the copy has a glue operand, we conservatively assume it
2877 // isn't safe to perform a tail call.
2878 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2879 return false;
2880 // First CopyToReg
2881 TCChain = UseChain;
2884 } else if (Copy->getOpcode() == ISD::BITCAST) {
2885 // f32 returned in a single GPR.
2886 if (!Copy->hasOneUse())
2887 return false;
2888 Copy = *Copy->use_begin();
2889 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2890 return false;
2891 // If the copy has a glue operand, we conservatively assume it isn't safe to
2892 // perform a tail call.
2893 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2894 return false;
2895 TCChain = Copy->getOperand(0);
2896 } else {
2897 return false;
2900 bool HasRet = false;
2901 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2902 UI != UE; ++UI) {
2903 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2904 UI->getOpcode() != ARMISD::INTRET_FLAG)
2905 return false;
2906 HasRet = true;
2909 if (!HasRet)
2910 return false;
2912 Chain = TCChain;
2913 return true;
2916 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2917 if (!Subtarget->supportsTailCall())
2918 return false;
2920 auto Attr =
2921 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2922 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2923 return false;
2925 return true;
2928 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2929 // and pass the lower and high parts through.
2930 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2931 SDLoc DL(Op);
2932 SDValue WriteValue = Op->getOperand(2);
2934 // This function is only supposed to be called for i64 type argument.
2935 assert(WriteValue.getValueType() == MVT::i64
2936 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2938 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2939 DAG.getConstant(0, DL, MVT::i32));
2940 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2941 DAG.getConstant(1, DL, MVT::i32));
2942 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2943 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2946 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2947 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2948 // one of the above mentioned nodes. It has to be wrapped because otherwise
2949 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2950 // be used to form addressing mode. These wrapped nodes will be selected
2951 // into MOVi.
2952 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2953 SelectionDAG &DAG) const {
2954 EVT PtrVT = Op.getValueType();
2955 // FIXME there is no actual debug info here
2956 SDLoc dl(Op);
2957 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2958 SDValue Res;
2960 // When generating execute-only code Constant Pools must be promoted to the
2961 // global data section. It's a bit ugly that we can't share them across basic
2962 // blocks, but this way we guarantee that execute-only behaves correct with
2963 // position-independent addressing modes.
2964 if (Subtarget->genExecuteOnly()) {
2965 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2966 auto T = const_cast<Type*>(CP->getType());
2967 auto C = const_cast<Constant*>(CP->getConstVal());
2968 auto M = const_cast<Module*>(DAG.getMachineFunction().
2969 getFunction().getParent());
2970 auto GV = new GlobalVariable(
2971 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2972 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2973 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2974 Twine(AFI->createPICLabelUId())
2976 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2977 dl, PtrVT);
2978 return LowerGlobalAddress(GA, DAG);
2981 if (CP->isMachineConstantPoolEntry())
2982 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2983 CP->getAlignment());
2984 else
2985 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2986 CP->getAlignment());
2987 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2990 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2991 return MachineJumpTableInfo::EK_Inline;
2994 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2995 SelectionDAG &DAG) const {
2996 MachineFunction &MF = DAG.getMachineFunction();
2997 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2998 unsigned ARMPCLabelIndex = 0;
2999 SDLoc DL(Op);
3000 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3001 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3002 SDValue CPAddr;
3003 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3004 if (!IsPositionIndependent) {
3005 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3006 } else {
3007 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3008 ARMPCLabelIndex = AFI->createPICLabelUId();
3009 ARMConstantPoolValue *CPV =
3010 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3011 ARMCP::CPBlockAddress, PCAdj);
3012 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3014 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3015 SDValue Result = DAG.getLoad(
3016 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3017 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3018 if (!IsPositionIndependent)
3019 return Result;
3020 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3021 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3024 /// Convert a TLS address reference into the correct sequence of loads
3025 /// and calls to compute the variable's address for Darwin, and return an
3026 /// SDValue containing the final node.
3028 /// Darwin only has one TLS scheme which must be capable of dealing with the
3029 /// fully general situation, in the worst case. This means:
3030 /// + "extern __thread" declaration.
3031 /// + Defined in a possibly unknown dynamic library.
3033 /// The general system is that each __thread variable has a [3 x i32] descriptor
3034 /// which contains information used by the runtime to calculate the address. The
3035 /// only part of this the compiler needs to know about is the first word, which
3036 /// contains a function pointer that must be called with the address of the
3037 /// entire descriptor in "r0".
3039 /// Since this descriptor may be in a different unit, in general access must
3040 /// proceed along the usual ARM rules. A common sequence to produce is:
3042 /// movw rT1, :lower16:_var$non_lazy_ptr
3043 /// movt rT1, :upper16:_var$non_lazy_ptr
3044 /// ldr r0, [rT1]
3045 /// ldr rT2, [r0]
3046 /// blx rT2
3047 /// [...address now in r0...]
3048 SDValue
3049 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3050 SelectionDAG &DAG) const {
3051 assert(Subtarget->isTargetDarwin() &&
3052 "This function expects a Darwin target");
3053 SDLoc DL(Op);
3055 // First step is to get the address of the actua global symbol. This is where
3056 // the TLS descriptor lives.
3057 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3059 // The first entry in the descriptor is a function pointer that we must call
3060 // to obtain the address of the variable.
3061 SDValue Chain = DAG.getEntryNode();
3062 SDValue FuncTLVGet = DAG.getLoad(
3063 MVT::i32, DL, Chain, DescAddr,
3064 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3065 /* Alignment = */ 4,
3066 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3067 MachineMemOperand::MOInvariant);
3068 Chain = FuncTLVGet.getValue(1);
3070 MachineFunction &F = DAG.getMachineFunction();
3071 MachineFrameInfo &MFI = F.getFrameInfo();
3072 MFI.setAdjustsStack(true);
3074 // TLS calls preserve all registers except those that absolutely must be
3075 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3076 // silly).
3077 auto TRI =
3078 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3079 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3080 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3082 // Finally, we can make the call. This is just a degenerate version of a
3083 // normal AArch64 call node: r0 takes the address of the descriptor, and
3084 // returns the address of the variable in this thread.
3085 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3086 Chain =
3087 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3088 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3089 DAG.getRegisterMask(Mask), Chain.getValue(1));
3090 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3093 SDValue
3094 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3095 SelectionDAG &DAG) const {
3096 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3098 SDValue Chain = DAG.getEntryNode();
3099 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3100 SDLoc DL(Op);
3102 // Load the current TEB (thread environment block)
3103 SDValue Ops[] = {Chain,
3104 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3105 DAG.getConstant(15, DL, MVT::i32),
3106 DAG.getConstant(0, DL, MVT::i32),
3107 DAG.getConstant(13, DL, MVT::i32),
3108 DAG.getConstant(0, DL, MVT::i32),
3109 DAG.getConstant(2, DL, MVT::i32)};
3110 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3111 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3113 SDValue TEB = CurrentTEB.getValue(0);
3114 Chain = CurrentTEB.getValue(1);
3116 // Load the ThreadLocalStoragePointer from the TEB
3117 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3118 SDValue TLSArray =
3119 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3120 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3122 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3123 // offset into the TLSArray.
3125 // Load the TLS index from the C runtime
3126 SDValue TLSIndex =
3127 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3128 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3129 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3131 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3132 DAG.getConstant(2, DL, MVT::i32));
3133 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3134 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3135 MachinePointerInfo());
3137 // Get the offset of the start of the .tls section (section base)
3138 const auto *GA = cast<GlobalAddressSDNode>(Op);
3139 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3140 SDValue Offset = DAG.getLoad(
3141 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3142 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3143 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3145 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3148 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3149 SDValue
3150 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3151 SelectionDAG &DAG) const {
3152 SDLoc dl(GA);
3153 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3154 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3155 MachineFunction &MF = DAG.getMachineFunction();
3156 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3157 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3158 ARMConstantPoolValue *CPV =
3159 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3160 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3161 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3162 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3163 Argument = DAG.getLoad(
3164 PtrVT, dl, DAG.getEntryNode(), Argument,
3165 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3166 SDValue Chain = Argument.getValue(1);
3168 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3169 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3171 // call __tls_get_addr.
3172 ArgListTy Args;
3173 ArgListEntry Entry;
3174 Entry.Node = Argument;
3175 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3176 Args.push_back(Entry);
3178 // FIXME: is there useful debug info available here?
3179 TargetLowering::CallLoweringInfo CLI(DAG);
3180 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3181 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3182 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3184 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3185 return CallResult.first;
3188 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3189 // "local exec" model.
3190 SDValue
3191 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3192 SelectionDAG &DAG,
3193 TLSModel::Model model) const {
3194 const GlobalValue *GV = GA->getGlobal();
3195 SDLoc dl(GA);
3196 SDValue Offset;
3197 SDValue Chain = DAG.getEntryNode();
3198 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3199 // Get the Thread Pointer
3200 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3202 if (model == TLSModel::InitialExec) {
3203 MachineFunction &MF = DAG.getMachineFunction();
3204 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3205 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3206 // Initial exec model.
3207 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3208 ARMConstantPoolValue *CPV =
3209 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3210 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3211 true);
3212 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3213 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3214 Offset = DAG.getLoad(
3215 PtrVT, dl, Chain, Offset,
3216 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3217 Chain = Offset.getValue(1);
3219 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3220 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3222 Offset = DAG.getLoad(
3223 PtrVT, dl, Chain, Offset,
3224 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3225 } else {
3226 // local exec model
3227 assert(model == TLSModel::LocalExec);
3228 ARMConstantPoolValue *CPV =
3229 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3230 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3231 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3232 Offset = DAG.getLoad(
3233 PtrVT, dl, Chain, Offset,
3234 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3237 // The address of the thread local variable is the add of the thread
3238 // pointer with the offset of the variable.
3239 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3242 SDValue
3243 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3244 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3245 if (DAG.getTarget().useEmulatedTLS())
3246 return LowerToTLSEmulatedModel(GA, DAG);
3248 if (Subtarget->isTargetDarwin())
3249 return LowerGlobalTLSAddressDarwin(Op, DAG);
3251 if (Subtarget->isTargetWindows())
3252 return LowerGlobalTLSAddressWindows(Op, DAG);
3254 // TODO: implement the "local dynamic" model
3255 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3256 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3258 switch (model) {
3259 case TLSModel::GeneralDynamic:
3260 case TLSModel::LocalDynamic:
3261 return LowerToTLSGeneralDynamicModel(GA, DAG);
3262 case TLSModel::InitialExec:
3263 case TLSModel::LocalExec:
3264 return LowerToTLSExecModels(GA, DAG, model);
3266 llvm_unreachable("bogus TLS model");
3269 /// Return true if all users of V are within function F, looking through
3270 /// ConstantExprs.
3271 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3272 SmallVector<const User*,4> Worklist;
3273 for (auto *U : V->users())
3274 Worklist.push_back(U);
3275 while (!Worklist.empty()) {
3276 auto *U = Worklist.pop_back_val();
3277 if (isa<ConstantExpr>(U)) {
3278 for (auto *UU : U->users())
3279 Worklist.push_back(UU);
3280 continue;
3283 auto *I = dyn_cast<Instruction>(U);
3284 if (!I || I->getParent()->getParent() != F)
3285 return false;
3287 return true;
3290 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3291 const GlobalValue *GV, SelectionDAG &DAG,
3292 EVT PtrVT, const SDLoc &dl) {
3293 // If we're creating a pool entry for a constant global with unnamed address,
3294 // and the global is small enough, we can emit it inline into the constant pool
3295 // to save ourselves an indirection.
3297 // This is a win if the constant is only used in one function (so it doesn't
3298 // need to be duplicated) or duplicating the constant wouldn't increase code
3299 // size (implying the constant is no larger than 4 bytes).
3300 const Function &F = DAG.getMachineFunction().getFunction();
3302 // We rely on this decision to inline being idemopotent and unrelated to the
3303 // use-site. We know that if we inline a variable at one use site, we'll
3304 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3305 // doesn't know about this optimization, so bail out if it's enabled else
3306 // we could decide to inline here (and thus never emit the GV) but require
3307 // the GV from fast-isel generated code.
3308 if (!EnableConstpoolPromotion ||
3309 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3310 return SDValue();
3312 auto *GVar = dyn_cast<GlobalVariable>(GV);
3313 if (!GVar || !GVar->hasInitializer() ||
3314 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3315 !GVar->hasLocalLinkage())
3316 return SDValue();
3318 // If we inline a value that contains relocations, we move the relocations
3319 // from .data to .text. This is not allowed in position-independent code.
3320 auto *Init = GVar->getInitializer();
3321 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3322 Init->needsRelocation())
3323 return SDValue();
3325 // The constant islands pass can only really deal with alignment requests
3326 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3327 // any type wanting greater alignment requirements than 4 bytes. We also
3328 // can only promote constants that are multiples of 4 bytes in size or
3329 // are paddable to a multiple of 4. Currently we only try and pad constants
3330 // that are strings for simplicity.
3331 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3332 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3333 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3334 unsigned RequiredPadding = 4 - (Size % 4);
3335 bool PaddingPossible =
3336 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3337 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3338 Size == 0)
3339 return SDValue();
3341 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3342 MachineFunction &MF = DAG.getMachineFunction();
3343 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3345 // We can't bloat the constant pool too much, else the ConstantIslands pass
3346 // may fail to converge. If we haven't promoted this global yet (it may have
3347 // multiple uses), and promoting it would increase the constant pool size (Sz
3348 // > 4), ensure we have space to do so up to MaxTotal.
3349 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3350 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3351 ConstpoolPromotionMaxTotal)
3352 return SDValue();
3354 // This is only valid if all users are in a single function; we can't clone
3355 // the constant in general. The LLVM IR unnamed_addr allows merging
3356 // constants, but not cloning them.
3358 // We could potentially allow cloning if we could prove all uses of the
3359 // constant in the current function don't care about the address, like
3360 // printf format strings. But that isn't implemented for now.
3361 if (!allUsersAreInFunction(GVar, &F))
3362 return SDValue();
3364 // We're going to inline this global. Pad it out if needed.
3365 if (RequiredPadding != 4) {
3366 StringRef S = CDAInit->getAsString();
3368 SmallVector<uint8_t,16> V(S.size());
3369 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3370 while (RequiredPadding--)
3371 V.push_back(0);
3372 Init = ConstantDataArray::get(*DAG.getContext(), V);
3375 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3376 SDValue CPAddr =
3377 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3378 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3379 AFI->markGlobalAsPromotedToConstantPool(GVar);
3380 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3381 PaddedSize - 4);
3383 ++NumConstpoolPromoted;
3384 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3387 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3388 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3389 if (!(GV = GA->getBaseObject()))
3390 return false;
3391 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3392 return V->isConstant();
3393 return isa<Function>(GV);
3396 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3397 SelectionDAG &DAG) const {
3398 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3399 default: llvm_unreachable("unknown object format");
3400 case Triple::COFF:
3401 return LowerGlobalAddressWindows(Op, DAG);
3402 case Triple::ELF:
3403 return LowerGlobalAddressELF(Op, DAG);
3404 case Triple::MachO:
3405 return LowerGlobalAddressDarwin(Op, DAG);
3409 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3410 SelectionDAG &DAG) const {
3411 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3412 SDLoc dl(Op);
3413 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3414 const TargetMachine &TM = getTargetMachine();
3415 bool IsRO = isReadOnly(GV);
3417 // promoteToConstantPool only if not generating XO text section
3418 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3419 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3420 return V;
3422 if (isPositionIndependent()) {
3423 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3424 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3425 UseGOT_PREL ? ARMII::MO_GOT : 0);
3426 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3427 if (UseGOT_PREL)
3428 Result =
3429 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3430 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3431 return Result;
3432 } else if (Subtarget->isROPI() && IsRO) {
3433 // PC-relative.
3434 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3435 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3436 return Result;
3437 } else if (Subtarget->isRWPI() && !IsRO) {
3438 // SB-relative.
3439 SDValue RelAddr;
3440 if (Subtarget->useMovt()) {
3441 ++NumMovwMovt;
3442 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3443 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3444 } else { // use literal pool for address constant
3445 ARMConstantPoolValue *CPV =
3446 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3447 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3448 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3449 RelAddr = DAG.getLoad(
3450 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3451 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3453 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3454 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3455 return Result;
3458 // If we have T2 ops, we can materialize the address directly via movt/movw
3459 // pair. This is always cheaper.
3460 if (Subtarget->useMovt()) {
3461 ++NumMovwMovt;
3462 // FIXME: Once remat is capable of dealing with instructions with register
3463 // operands, expand this into two nodes.
3464 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3465 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3466 } else {
3467 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3468 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3469 return DAG.getLoad(
3470 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3471 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3475 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3476 SelectionDAG &DAG) const {
3477 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3478 "ROPI/RWPI not currently supported for Darwin");
3479 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3480 SDLoc dl(Op);
3481 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3483 if (Subtarget->useMovt())
3484 ++NumMovwMovt;
3486 // FIXME: Once remat is capable of dealing with instructions with register
3487 // operands, expand this into multiple nodes
3488 unsigned Wrapper =
3489 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3491 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3492 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3494 if (Subtarget->isGVIndirectSymbol(GV))
3495 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3496 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3497 return Result;
3500 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3501 SelectionDAG &DAG) const {
3502 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3503 assert(Subtarget->useMovt() &&
3504 "Windows on ARM expects to use movw/movt");
3505 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3506 "ROPI/RWPI not currently supported for Windows");
3508 const TargetMachine &TM = getTargetMachine();
3509 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3510 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3511 if (GV->hasDLLImportStorageClass())
3512 TargetFlags = ARMII::MO_DLLIMPORT;
3513 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3514 TargetFlags = ARMII::MO_COFFSTUB;
3515 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3516 SDValue Result;
3517 SDLoc DL(Op);
3519 ++NumMovwMovt;
3521 // FIXME: Once remat is capable of dealing with instructions with register
3522 // operands, expand this into two nodes.
3523 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3524 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3525 TargetFlags));
3526 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3527 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3528 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3529 return Result;
3532 SDValue
3533 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3534 SDLoc dl(Op);
3535 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3536 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3537 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3538 Op.getOperand(1), Val);
3541 SDValue
3542 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3543 SDLoc dl(Op);
3544 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3545 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3548 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3549 SelectionDAG &DAG) const {
3550 SDLoc dl(Op);
3551 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3552 Op.getOperand(0));
3555 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3556 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3557 unsigned IntNo =
3558 cast<ConstantSDNode>(
3559 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3560 ->getZExtValue();
3561 switch (IntNo) {
3562 default:
3563 return SDValue(); // Don't custom lower most intrinsics.
3564 case Intrinsic::arm_gnu_eabi_mcount: {
3565 MachineFunction &MF = DAG.getMachineFunction();
3566 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3567 SDLoc dl(Op);
3568 SDValue Chain = Op.getOperand(0);
3569 // call "\01__gnu_mcount_nc"
3570 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3571 const uint32_t *Mask =
3572 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3573 assert(Mask && "Missing call preserved mask for calling convention");
3574 // Mark LR an implicit live-in.
3575 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3576 SDValue ReturnAddress =
3577 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3578 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue};
3579 SDValue Callee =
3580 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3581 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3582 if (Subtarget->isThumb())
3583 return SDValue(
3584 DAG.getMachineNode(
3585 ARM::tBL_PUSHLR, dl, ResultTys,
3586 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3587 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3589 return SDValue(
3590 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3591 {ReturnAddress, Callee, RegisterMask, Chain}),
3597 SDValue
3598 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3599 const ARMSubtarget *Subtarget) const {
3600 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3601 SDLoc dl(Op);
3602 switch (IntNo) {
3603 default: return SDValue(); // Don't custom lower most intrinsics.
3604 case Intrinsic::thread_pointer: {
3605 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3606 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3608 case Intrinsic::eh_sjlj_lsda: {
3609 MachineFunction &MF = DAG.getMachineFunction();
3610 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3611 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3612 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3613 SDValue CPAddr;
3614 bool IsPositionIndependent = isPositionIndependent();
3615 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3616 ARMConstantPoolValue *CPV =
3617 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3618 ARMCP::CPLSDA, PCAdj);
3619 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3620 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3621 SDValue Result = DAG.getLoad(
3622 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3623 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3625 if (IsPositionIndependent) {
3626 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3627 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3629 return Result;
3631 case Intrinsic::arm_neon_vabs:
3632 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3633 Op.getOperand(1));
3634 case Intrinsic::arm_neon_vmulls:
3635 case Intrinsic::arm_neon_vmullu: {
3636 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3637 ? ARMISD::VMULLs : ARMISD::VMULLu;
3638 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3639 Op.getOperand(1), Op.getOperand(2));
3641 case Intrinsic::arm_neon_vminnm:
3642 case Intrinsic::arm_neon_vmaxnm: {
3643 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3644 ? ISD::FMINNUM : ISD::FMAXNUM;
3645 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3646 Op.getOperand(1), Op.getOperand(2));
3648 case Intrinsic::arm_neon_vminu:
3649 case Intrinsic::arm_neon_vmaxu: {
3650 if (Op.getValueType().isFloatingPoint())
3651 return SDValue();
3652 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3653 ? ISD::UMIN : ISD::UMAX;
3654 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3655 Op.getOperand(1), Op.getOperand(2));
3657 case Intrinsic::arm_neon_vmins:
3658 case Intrinsic::arm_neon_vmaxs: {
3659 // v{min,max}s is overloaded between signed integers and floats.
3660 if (!Op.getValueType().isFloatingPoint()) {
3661 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3662 ? ISD::SMIN : ISD::SMAX;
3663 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3664 Op.getOperand(1), Op.getOperand(2));
3666 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3667 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3668 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3669 Op.getOperand(1), Op.getOperand(2));
3671 case Intrinsic::arm_neon_vtbl1:
3672 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3673 Op.getOperand(1), Op.getOperand(2));
3674 case Intrinsic::arm_neon_vtbl2:
3675 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3676 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3680 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3681 const ARMSubtarget *Subtarget) {
3682 SDLoc dl(Op);
3683 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3684 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3685 if (SSID == SyncScope::SingleThread)
3686 return Op;
3688 if (!Subtarget->hasDataBarrier()) {
3689 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3690 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3691 // here.
3692 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3693 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3694 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3695 DAG.getConstant(0, dl, MVT::i32));
3698 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3699 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3700 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3701 if (Subtarget->isMClass()) {
3702 // Only a full system barrier exists in the M-class architectures.
3703 Domain = ARM_MB::SY;
3704 } else if (Subtarget->preferISHSTBarriers() &&
3705 Ord == AtomicOrdering::Release) {
3706 // Swift happens to implement ISHST barriers in a way that's compatible with
3707 // Release semantics but weaker than ISH so we'd be fools not to use
3708 // it. Beware: other processors probably don't!
3709 Domain = ARM_MB::ISHST;
3712 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3713 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3714 DAG.getConstant(Domain, dl, MVT::i32));
3717 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3718 const ARMSubtarget *Subtarget) {
3719 // ARM pre v5TE and Thumb1 does not have preload instructions.
3720 if (!(Subtarget->isThumb2() ||
3721 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3722 // Just preserve the chain.
3723 return Op.getOperand(0);
3725 SDLoc dl(Op);
3726 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3727 if (!isRead &&
3728 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3729 // ARMv7 with MP extension has PLDW.
3730 return Op.getOperand(0);
3732 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3733 if (Subtarget->isThumb()) {
3734 // Invert the bits.
3735 isRead = ~isRead & 1;
3736 isData = ~isData & 1;
3739 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3740 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3741 DAG.getConstant(isData, dl, MVT::i32));
3744 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3745 MachineFunction &MF = DAG.getMachineFunction();
3746 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3748 // vastart just stores the address of the VarArgsFrameIndex slot into the
3749 // memory location argument.
3750 SDLoc dl(Op);
3751 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3752 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3753 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3754 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3755 MachinePointerInfo(SV));
3758 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3759 CCValAssign &NextVA,
3760 SDValue &Root,
3761 SelectionDAG &DAG,
3762 const SDLoc &dl) const {
3763 MachineFunction &MF = DAG.getMachineFunction();
3764 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3766 const TargetRegisterClass *RC;
3767 if (AFI->isThumb1OnlyFunction())
3768 RC = &ARM::tGPRRegClass;
3769 else
3770 RC = &ARM::GPRRegClass;
3772 // Transform the arguments stored in physical registers into virtual ones.
3773 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3774 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3776 SDValue ArgValue2;
3777 if (NextVA.isMemLoc()) {
3778 MachineFrameInfo &MFI = MF.getFrameInfo();
3779 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3781 // Create load node to retrieve arguments from the stack.
3782 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3783 ArgValue2 = DAG.getLoad(
3784 MVT::i32, dl, Root, FIN,
3785 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3786 } else {
3787 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3788 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3790 if (!Subtarget->isLittle())
3791 std::swap (ArgValue, ArgValue2);
3792 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3795 // The remaining GPRs hold either the beginning of variable-argument
3796 // data, or the beginning of an aggregate passed by value (usually
3797 // byval). Either way, we allocate stack slots adjacent to the data
3798 // provided by our caller, and store the unallocated registers there.
3799 // If this is a variadic function, the va_list pointer will begin with
3800 // these values; otherwise, this reassembles a (byval) structure that
3801 // was split between registers and memory.
3802 // Return: The frame index registers were stored into.
3803 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3804 const SDLoc &dl, SDValue &Chain,
3805 const Value *OrigArg,
3806 unsigned InRegsParamRecordIdx,
3807 int ArgOffset, unsigned ArgSize) const {
3808 // Currently, two use-cases possible:
3809 // Case #1. Non-var-args function, and we meet first byval parameter.
3810 // Setup first unallocated register as first byval register;
3811 // eat all remained registers
3812 // (these two actions are performed by HandleByVal method).
3813 // Then, here, we initialize stack frame with
3814 // "store-reg" instructions.
3815 // Case #2. Var-args function, that doesn't contain byval parameters.
3816 // The same: eat all remained unallocated registers,
3817 // initialize stack frame.
3819 MachineFunction &MF = DAG.getMachineFunction();
3820 MachineFrameInfo &MFI = MF.getFrameInfo();
3821 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3822 unsigned RBegin, REnd;
3823 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3824 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3825 } else {
3826 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3827 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3828 REnd = ARM::R4;
3831 if (REnd != RBegin)
3832 ArgOffset = -4 * (ARM::R4 - RBegin);
3834 auto PtrVT = getPointerTy(DAG.getDataLayout());
3835 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3836 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3838 SmallVector<SDValue, 4> MemOps;
3839 const TargetRegisterClass *RC =
3840 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3842 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3843 unsigned VReg = MF.addLiveIn(Reg, RC);
3844 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3845 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3846 MachinePointerInfo(OrigArg, 4 * i));
3847 MemOps.push_back(Store);
3848 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3851 if (!MemOps.empty())
3852 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3853 return FrameIndex;
3856 // Setup stack frame, the va_list pointer will start from.
3857 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3858 const SDLoc &dl, SDValue &Chain,
3859 unsigned ArgOffset,
3860 unsigned TotalArgRegsSaveSize,
3861 bool ForceMutable) const {
3862 MachineFunction &MF = DAG.getMachineFunction();
3863 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3865 // Try to store any remaining integer argument regs
3866 // to their spots on the stack so that they may be loaded by dereferencing
3867 // the result of va_next.
3868 // If there is no regs to be stored, just point address after last
3869 // argument passed via stack.
3870 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3871 CCInfo.getInRegsParamsCount(),
3872 CCInfo.getNextStackOffset(),
3873 std::max(4U, TotalArgRegsSaveSize));
3874 AFI->setVarArgsFrameIndex(FrameIndex);
3877 SDValue ARMTargetLowering::LowerFormalArguments(
3878 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3879 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3880 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3881 MachineFunction &MF = DAG.getMachineFunction();
3882 MachineFrameInfo &MFI = MF.getFrameInfo();
3884 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3886 // Assign locations to all of the incoming arguments.
3887 SmallVector<CCValAssign, 16> ArgLocs;
3888 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3889 *DAG.getContext());
3890 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3892 SmallVector<SDValue, 16> ArgValues;
3893 SDValue ArgValue;
3894 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3895 unsigned CurArgIdx = 0;
3897 // Initially ArgRegsSaveSize is zero.
3898 // Then we increase this value each time we meet byval parameter.
3899 // We also increase this value in case of varargs function.
3900 AFI->setArgRegsSaveSize(0);
3902 // Calculate the amount of stack space that we need to allocate to store
3903 // byval and variadic arguments that are passed in registers.
3904 // We need to know this before we allocate the first byval or variadic
3905 // argument, as they will be allocated a stack slot below the CFA (Canonical
3906 // Frame Address, the stack pointer at entry to the function).
3907 unsigned ArgRegBegin = ARM::R4;
3908 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3909 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3910 break;
3912 CCValAssign &VA = ArgLocs[i];
3913 unsigned Index = VA.getValNo();
3914 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3915 if (!Flags.isByVal())
3916 continue;
3918 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3919 unsigned RBegin, REnd;
3920 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3921 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3923 CCInfo.nextInRegsParam();
3925 CCInfo.rewindByValRegsInfo();
3927 int lastInsIndex = -1;
3928 if (isVarArg && MFI.hasVAStart()) {
3929 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3930 if (RegIdx != array_lengthof(GPRArgRegs))
3931 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3934 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3935 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3936 auto PtrVT = getPointerTy(DAG.getDataLayout());
3938 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3939 CCValAssign &VA = ArgLocs[i];
3940 if (Ins[VA.getValNo()].isOrigArg()) {
3941 std::advance(CurOrigArg,
3942 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3943 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3945 // Arguments stored in registers.
3946 if (VA.isRegLoc()) {
3947 EVT RegVT = VA.getLocVT();
3949 if (VA.needsCustom()) {
3950 // f64 and vector types are split up into multiple registers or
3951 // combinations of registers and stack slots.
3952 if (VA.getLocVT() == MVT::v2f64) {
3953 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3954 Chain, DAG, dl);
3955 VA = ArgLocs[++i]; // skip ahead to next loc
3956 SDValue ArgValue2;
3957 if (VA.isMemLoc()) {
3958 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3959 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3960 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3961 MachinePointerInfo::getFixedStack(
3962 DAG.getMachineFunction(), FI));
3963 } else {
3964 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3965 Chain, DAG, dl);
3967 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3968 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3969 ArgValue, ArgValue1,
3970 DAG.getIntPtrConstant(0, dl));
3971 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3972 ArgValue, ArgValue2,
3973 DAG.getIntPtrConstant(1, dl));
3974 } else
3975 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3976 } else {
3977 const TargetRegisterClass *RC;
3980 if (RegVT == MVT::f16)
3981 RC = &ARM::HPRRegClass;
3982 else if (RegVT == MVT::f32)
3983 RC = &ARM::SPRRegClass;
3984 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3985 RC = &ARM::DPRRegClass;
3986 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3987 RC = &ARM::QPRRegClass;
3988 else if (RegVT == MVT::i32)
3989 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3990 : &ARM::GPRRegClass;
3991 else
3992 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3994 // Transform the arguments in physical registers into virtual ones.
3995 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3996 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3998 // If this value is passed in r0 and has the returned attribute (e.g.
3999 // C++ 'structors), record this fact for later use.
4000 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4001 AFI->setPreservesR0();
4005 // If this is an 8 or 16-bit value, it is really passed promoted
4006 // to 32 bits. Insert an assert[sz]ext to capture this, then
4007 // truncate to the right size.
4008 switch (VA.getLocInfo()) {
4009 default: llvm_unreachable("Unknown loc info!");
4010 case CCValAssign::Full: break;
4011 case CCValAssign::BCvt:
4012 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4013 break;
4014 case CCValAssign::SExt:
4015 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4016 DAG.getValueType(VA.getValVT()));
4017 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4018 break;
4019 case CCValAssign::ZExt:
4020 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4021 DAG.getValueType(VA.getValVT()));
4022 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4023 break;
4026 InVals.push_back(ArgValue);
4027 } else { // VA.isRegLoc()
4028 // sanity check
4029 assert(VA.isMemLoc());
4030 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4032 int index = VA.getValNo();
4034 // Some Ins[] entries become multiple ArgLoc[] entries.
4035 // Process them only once.
4036 if (index != lastInsIndex)
4038 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4039 // FIXME: For now, all byval parameter objects are marked mutable.
4040 // This can be changed with more analysis.
4041 // In case of tail call optimization mark all arguments mutable.
4042 // Since they could be overwritten by lowering of arguments in case of
4043 // a tail call.
4044 if (Flags.isByVal()) {
4045 assert(Ins[index].isOrigArg() &&
4046 "Byval arguments cannot be implicit");
4047 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4049 int FrameIndex = StoreByValRegs(
4050 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4051 VA.getLocMemOffset(), Flags.getByValSize());
4052 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4053 CCInfo.nextInRegsParam();
4054 } else {
4055 unsigned FIOffset = VA.getLocMemOffset();
4056 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4057 FIOffset, true);
4059 // Create load nodes to retrieve arguments from the stack.
4060 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4061 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4062 MachinePointerInfo::getFixedStack(
4063 DAG.getMachineFunction(), FI)));
4065 lastInsIndex = index;
4070 // varargs
4071 if (isVarArg && MFI.hasVAStart())
4072 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4073 CCInfo.getNextStackOffset(),
4074 TotalArgRegsSaveSize);
4076 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4078 return Chain;
4081 /// isFloatingPointZero - Return true if this is +0.0.
4082 static bool isFloatingPointZero(SDValue Op) {
4083 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4084 return CFP->getValueAPF().isPosZero();
4085 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4086 // Maybe this has already been legalized into the constant pool?
4087 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4088 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4089 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4090 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4091 return CFP->getValueAPF().isPosZero();
4093 } else if (Op->getOpcode() == ISD::BITCAST &&
4094 Op->getValueType(0) == MVT::f64) {
4095 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4096 // created by LowerConstantFP().
4097 SDValue BitcastOp = Op->getOperand(0);
4098 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4099 isNullConstant(BitcastOp->getOperand(0)))
4100 return true;
4102 return false;
4105 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4106 /// the given operands.
4107 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4108 SDValue &ARMcc, SelectionDAG &DAG,
4109 const SDLoc &dl) const {
4110 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4111 unsigned C = RHSC->getZExtValue();
4112 if (!isLegalICmpImmediate((int32_t)C)) {
4113 // Constant does not fit, try adjusting it by one.
4114 switch (CC) {
4115 default: break;
4116 case ISD::SETLT:
4117 case ISD::SETGE:
4118 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4119 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4120 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4122 break;
4123 case ISD::SETULT:
4124 case ISD::SETUGE:
4125 if (C != 0 && isLegalICmpImmediate(C-1)) {
4126 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4127 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4129 break;
4130 case ISD::SETLE:
4131 case ISD::SETGT:
4132 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4133 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4134 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4136 break;
4137 case ISD::SETULE:
4138 case ISD::SETUGT:
4139 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4140 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4141 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4143 break;
4146 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4147 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4148 // In ARM and Thumb-2, the compare instructions can shift their second
4149 // operand.
4150 CC = ISD::getSetCCSwappedOperands(CC);
4151 std::swap(LHS, RHS);
4154 // Thumb1 has very limited immediate modes, so turning an "and" into a
4155 // shift can save multiple instructions.
4157 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4158 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4159 // own. If it's the operand to an unsigned comparison with an immediate,
4160 // we can eliminate one of the shifts: we transform
4161 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4163 // We avoid transforming cases which aren't profitable due to encoding
4164 // details:
4166 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4167 // would not; in that case, we're essentially trading one immediate load for
4168 // another.
4169 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4170 // 3. C2 is zero; we have other code for this special case.
4172 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4173 // instruction, since the AND is always one instruction anyway, but we could
4174 // use narrow instructions in some cases.
4175 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4176 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4177 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4178 !isSignedIntSetCC(CC)) {
4179 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4180 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4181 uint64_t RHSV = RHSC->getZExtValue();
4182 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4183 unsigned ShiftBits = countLeadingZeros(Mask);
4184 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4185 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4186 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4187 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4192 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4193 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4194 // way a cmp would.
4195 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4196 // some tweaks to the heuristics for the previous and->shift transform.
4197 // FIXME: Optimize cases where the LHS isn't a shift.
4198 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4199 isa<ConstantSDNode>(RHS) &&
4200 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4201 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4202 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4203 unsigned ShiftAmt =
4204 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4205 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4206 DAG.getVTList(MVT::i32, MVT::i32),
4207 LHS.getOperand(0),
4208 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4209 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4210 Shift.getValue(1), SDValue());
4211 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4212 return Chain.getValue(1);
4215 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4217 // If the RHS is a constant zero then the V (overflow) flag will never be
4218 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4219 // simpler for other passes (like the peephole optimiser) to deal with.
4220 if (isNullConstant(RHS)) {
4221 switch (CondCode) {
4222 default: break;
4223 case ARMCC::GE:
4224 CondCode = ARMCC::PL;
4225 break;
4226 case ARMCC::LT:
4227 CondCode = ARMCC::MI;
4228 break;
4232 ARMISD::NodeType CompareType;
4233 switch (CondCode) {
4234 default:
4235 CompareType = ARMISD::CMP;
4236 break;
4237 case ARMCC::EQ:
4238 case ARMCC::NE:
4239 // Uses only Z Flag
4240 CompareType = ARMISD::CMPZ;
4241 break;
4243 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4244 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4247 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4248 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4249 SelectionDAG &DAG, const SDLoc &dl,
4250 bool InvalidOnQNaN) const {
4251 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4252 SDValue Cmp;
4253 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
4254 if (!isFloatingPointZero(RHS))
4255 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
4256 else
4257 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
4258 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4261 /// duplicateCmp - Glue values can have only one use, so this function
4262 /// duplicates a comparison node.
4263 SDValue
4264 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4265 unsigned Opc = Cmp.getOpcode();
4266 SDLoc DL(Cmp);
4267 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4268 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4270 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4271 Cmp = Cmp.getOperand(0);
4272 Opc = Cmp.getOpcode();
4273 if (Opc == ARMISD::CMPFP)
4274 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4275 Cmp.getOperand(1), Cmp.getOperand(2));
4276 else {
4277 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4278 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4279 Cmp.getOperand(1));
4281 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4284 // This function returns three things: the arithmetic computation itself
4285 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4286 // comparison and the condition code define the case in which the arithmetic
4287 // computation *does not* overflow.
4288 std::pair<SDValue, SDValue>
4289 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4290 SDValue &ARMcc) const {
4291 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4293 SDValue Value, OverflowCmp;
4294 SDValue LHS = Op.getOperand(0);
4295 SDValue RHS = Op.getOperand(1);
4296 SDLoc dl(Op);
4298 // FIXME: We are currently always generating CMPs because we don't support
4299 // generating CMN through the backend. This is not as good as the natural
4300 // CMP case because it causes a register dependency and cannot be folded
4301 // later.
4303 switch (Op.getOpcode()) {
4304 default:
4305 llvm_unreachable("Unknown overflow instruction!");
4306 case ISD::SADDO:
4307 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4308 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4309 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4310 break;
4311 case ISD::UADDO:
4312 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4313 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4314 // We do not use it in the USUBO case as Value may not be used.
4315 Value = DAG.getNode(ARMISD::ADDC, dl,
4316 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4317 .getValue(0);
4318 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4319 break;
4320 case ISD::SSUBO:
4321 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4322 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4323 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4324 break;
4325 case ISD::USUBO:
4326 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4327 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4328 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4329 break;
4330 case ISD::UMULO:
4331 // We generate a UMUL_LOHI and then check if the high word is 0.
4332 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4333 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4334 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4335 LHS, RHS);
4336 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4337 DAG.getConstant(0, dl, MVT::i32));
4338 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4339 break;
4340 case ISD::SMULO:
4341 // We generate a SMUL_LOHI and then check if all the bits of the high word
4342 // are the same as the sign bit of the low word.
4343 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4344 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4345 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4346 LHS, RHS);
4347 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4348 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4349 Value.getValue(0),
4350 DAG.getConstant(31, dl, MVT::i32)));
4351 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4352 break;
4353 } // switch (...)
4355 return std::make_pair(Value, OverflowCmp);
4358 SDValue
4359 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4360 // Let legalize expand this if it isn't a legal type yet.
4361 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4362 return SDValue();
4364 SDValue Value, OverflowCmp;
4365 SDValue ARMcc;
4366 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4367 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4368 SDLoc dl(Op);
4369 // We use 0 and 1 as false and true values.
4370 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4371 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4372 EVT VT = Op.getValueType();
4374 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4375 ARMcc, CCR, OverflowCmp);
4377 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4378 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4381 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4382 SelectionDAG &DAG) {
4383 SDLoc DL(BoolCarry);
4384 EVT CarryVT = BoolCarry.getValueType();
4386 // This converts the boolean value carry into the carry flag by doing
4387 // ARMISD::SUBC Carry, 1
4388 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4389 DAG.getVTList(CarryVT, MVT::i32),
4390 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4391 return Carry.getValue(1);
4394 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4395 SelectionDAG &DAG) {
4396 SDLoc DL(Flags);
4398 // Now convert the carry flag into a boolean carry. We do this
4399 // using ARMISD:ADDE 0, 0, Carry
4400 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4401 DAG.getConstant(0, DL, MVT::i32),
4402 DAG.getConstant(0, DL, MVT::i32), Flags);
4405 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4406 SelectionDAG &DAG) const {
4407 // Let legalize expand this if it isn't a legal type yet.
4408 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4409 return SDValue();
4411 SDValue LHS = Op.getOperand(0);
4412 SDValue RHS = Op.getOperand(1);
4413 SDLoc dl(Op);
4415 EVT VT = Op.getValueType();
4416 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4417 SDValue Value;
4418 SDValue Overflow;
4419 switch (Op.getOpcode()) {
4420 default:
4421 llvm_unreachable("Unknown overflow instruction!");
4422 case ISD::UADDO:
4423 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4424 // Convert the carry flag into a boolean value.
4425 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4426 break;
4427 case ISD::USUBO: {
4428 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4429 // Convert the carry flag into a boolean value.
4430 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4431 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4432 // value. So compute 1 - C.
4433 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4434 DAG.getConstant(1, dl, MVT::i32), Overflow);
4435 break;
4439 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4442 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4443 SDValue Cond = Op.getOperand(0);
4444 SDValue SelectTrue = Op.getOperand(1);
4445 SDValue SelectFalse = Op.getOperand(2);
4446 SDLoc dl(Op);
4447 unsigned Opc = Cond.getOpcode();
4449 if (Cond.getResNo() == 1 &&
4450 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4451 Opc == ISD::USUBO)) {
4452 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4453 return SDValue();
4455 SDValue Value, OverflowCmp;
4456 SDValue ARMcc;
4457 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4458 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4459 EVT VT = Op.getValueType();
4461 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4462 OverflowCmp, DAG);
4465 // Convert:
4467 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4468 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4470 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4471 const ConstantSDNode *CMOVTrue =
4472 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4473 const ConstantSDNode *CMOVFalse =
4474 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4476 if (CMOVTrue && CMOVFalse) {
4477 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4478 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4480 SDValue True;
4481 SDValue False;
4482 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4483 True = SelectTrue;
4484 False = SelectFalse;
4485 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4486 True = SelectFalse;
4487 False = SelectTrue;
4490 if (True.getNode() && False.getNode()) {
4491 EVT VT = Op.getValueType();
4492 SDValue ARMcc = Cond.getOperand(2);
4493 SDValue CCR = Cond.getOperand(3);
4494 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4495 assert(True.getValueType() == VT);
4496 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4501 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4502 // undefined bits before doing a full-word comparison with zero.
4503 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4504 DAG.getConstant(1, dl, Cond.getValueType()));
4506 return DAG.getSelectCC(dl, Cond,
4507 DAG.getConstant(0, dl, Cond.getValueType()),
4508 SelectTrue, SelectFalse, ISD::SETNE);
4511 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4512 bool &swpCmpOps, bool &swpVselOps) {
4513 // Start by selecting the GE condition code for opcodes that return true for
4514 // 'equality'
4515 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4516 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4517 CondCode = ARMCC::GE;
4519 // and GT for opcodes that return false for 'equality'.
4520 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4521 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4522 CondCode = ARMCC::GT;
4524 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4525 // to swap the compare operands.
4526 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4527 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4528 swpCmpOps = true;
4530 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4531 // If we have an unordered opcode, we need to swap the operands to the VSEL
4532 // instruction (effectively negating the condition).
4534 // This also has the effect of swapping which one of 'less' or 'greater'
4535 // returns true, so we also swap the compare operands. It also switches
4536 // whether we return true for 'equality', so we compensate by picking the
4537 // opposite condition code to our original choice.
4538 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4539 CC == ISD::SETUGT) {
4540 swpCmpOps = !swpCmpOps;
4541 swpVselOps = !swpVselOps;
4542 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4545 // 'ordered' is 'anything but unordered', so use the VS condition code and
4546 // swap the VSEL operands.
4547 if (CC == ISD::SETO) {
4548 CondCode = ARMCC::VS;
4549 swpVselOps = true;
4552 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4553 // code and swap the VSEL operands. Also do this if we don't care about the
4554 // unordered case.
4555 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4556 CondCode = ARMCC::EQ;
4557 swpVselOps = true;
4561 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4562 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4563 SDValue Cmp, SelectionDAG &DAG) const {
4564 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4565 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4566 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4567 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4568 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4570 SDValue TrueLow = TrueVal.getValue(0);
4571 SDValue TrueHigh = TrueVal.getValue(1);
4572 SDValue FalseLow = FalseVal.getValue(0);
4573 SDValue FalseHigh = FalseVal.getValue(1);
4575 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4576 ARMcc, CCR, Cmp);
4577 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4578 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4580 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4581 } else {
4582 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4583 Cmp);
4587 static bool isGTorGE(ISD::CondCode CC) {
4588 return CC == ISD::SETGT || CC == ISD::SETGE;
4591 static bool isLTorLE(ISD::CondCode CC) {
4592 return CC == ISD::SETLT || CC == ISD::SETLE;
4595 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4596 // All of these conditions (and their <= and >= counterparts) will do:
4597 // x < k ? k : x
4598 // x > k ? x : k
4599 // k < x ? x : k
4600 // k > x ? k : x
4601 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4602 const SDValue TrueVal, const SDValue FalseVal,
4603 const ISD::CondCode CC, const SDValue K) {
4604 return (isGTorGE(CC) &&
4605 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4606 (isLTorLE(CC) &&
4607 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4610 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4611 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4612 const SDValue TrueVal, const SDValue FalseVal,
4613 const ISD::CondCode CC, const SDValue K) {
4614 return (isGTorGE(CC) &&
4615 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4616 (isLTorLE(CC) &&
4617 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4620 // Check if two chained conditionals could be converted into SSAT or USAT.
4622 // SSAT can replace a set of two conditional selectors that bound a number to an
4623 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4625 // x < -k ? -k : (x > k ? k : x)
4626 // x < -k ? -k : (x < k ? x : k)
4627 // x > -k ? (x > k ? k : x) : -k
4628 // x < k ? (x < -k ? -k : x) : k
4629 // etc.
4631 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4632 // a power of 2.
4634 // It returns true if the conversion can be done, false otherwise.
4635 // Additionally, the variable is returned in parameter V, the constant in K and
4636 // usat is set to true if the conditional represents an unsigned saturation
4637 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4638 uint64_t &K, bool &usat) {
4639 SDValue LHS1 = Op.getOperand(0);
4640 SDValue RHS1 = Op.getOperand(1);
4641 SDValue TrueVal1 = Op.getOperand(2);
4642 SDValue FalseVal1 = Op.getOperand(3);
4643 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4645 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4646 if (Op2.getOpcode() != ISD::SELECT_CC)
4647 return false;
4649 SDValue LHS2 = Op2.getOperand(0);
4650 SDValue RHS2 = Op2.getOperand(1);
4651 SDValue TrueVal2 = Op2.getOperand(2);
4652 SDValue FalseVal2 = Op2.getOperand(3);
4653 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4655 // Find out which are the constants and which are the variables
4656 // in each conditional
4657 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4658 ? &RHS1
4659 : nullptr;
4660 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4661 ? &RHS2
4662 : nullptr;
4663 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4664 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4665 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4666 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4668 // We must detect cases where the original operations worked with 16- or
4669 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4670 // must work with sign-extended values but the select operations return
4671 // the original non-extended value.
4672 SDValue V2TmpReg = V2Tmp;
4673 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4674 V2TmpReg = V2Tmp->getOperand(0);
4676 // Check that the registers and the constants have the correct values
4677 // in both conditionals
4678 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4679 V2TmpReg != V2)
4680 return false;
4682 // Figure out which conditional is saturating the lower/upper bound.
4683 const SDValue *LowerCheckOp =
4684 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4685 ? &Op
4686 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4687 ? &Op2
4688 : nullptr;
4689 const SDValue *UpperCheckOp =
4690 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4691 ? &Op
4692 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4693 ? &Op2
4694 : nullptr;
4696 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4697 return false;
4699 // Check that the constant in the lower-bound check is
4700 // the opposite of the constant in the upper-bound check
4701 // in 1's complement.
4702 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4703 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4704 int64_t PosVal = std::max(Val1, Val2);
4705 int64_t NegVal = std::min(Val1, Val2);
4707 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4708 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4709 isPowerOf2_64(PosVal + 1)) {
4711 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4712 if (Val1 == ~Val2)
4713 usat = false;
4714 else if (NegVal == 0)
4715 usat = true;
4716 else
4717 return false;
4719 V = V2;
4720 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4722 return true;
4725 return false;
4728 // Check if a condition of the type x < k ? k : x can be converted into a
4729 // bit operation instead of conditional moves.
4730 // Currently this is allowed given:
4731 // - The conditions and values match up
4732 // - k is 0 or -1 (all ones)
4733 // This function will not check the last condition, thats up to the caller
4734 // It returns true if the transformation can be made, and in such case
4735 // returns x in V, and k in SatK.
4736 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4737 SDValue &SatK)
4739 SDValue LHS = Op.getOperand(0);
4740 SDValue RHS = Op.getOperand(1);
4741 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4742 SDValue TrueVal = Op.getOperand(2);
4743 SDValue FalseVal = Op.getOperand(3);
4745 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4746 ? &RHS
4747 : nullptr;
4749 // No constant operation in comparison, early out
4750 if (!K)
4751 return false;
4753 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4754 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4755 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4757 // If the constant on left and right side, or variable on left and right,
4758 // does not match, early out
4759 if (*K != KTmp || V != VTmp)
4760 return false;
4762 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4763 SatK = *K;
4764 return true;
4767 return false;
4770 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4771 if (VT == MVT::f32)
4772 return !Subtarget->hasVFP2Base();
4773 if (VT == MVT::f64)
4774 return !Subtarget->hasFP64();
4775 if (VT == MVT::f16)
4776 return !Subtarget->hasFullFP16();
4777 return false;
4780 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4781 EVT VT = Op.getValueType();
4782 SDLoc dl(Op);
4784 // Try to convert two saturating conditional selects into a single SSAT
4785 SDValue SatValue;
4786 uint64_t SatConstant;
4787 bool SatUSat;
4788 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4789 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4790 if (SatUSat)
4791 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4792 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4793 else
4794 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4795 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4798 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4799 // into more efficient bit operations, which is possible when k is 0 or -1
4800 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4801 // single instructions. On Thumb the shift and the bit operation will be two
4802 // instructions.
4803 // Only allow this transformation on full-width (32-bit) operations
4804 SDValue LowerSatConstant;
4805 if (VT == MVT::i32 &&
4806 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4807 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4808 DAG.getConstant(31, dl, VT));
4809 if (isNullConstant(LowerSatConstant)) {
4810 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4811 DAG.getAllOnesConstant(dl, VT));
4812 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4813 } else if (isAllOnesConstant(LowerSatConstant))
4814 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4817 SDValue LHS = Op.getOperand(0);
4818 SDValue RHS = Op.getOperand(1);
4819 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4820 SDValue TrueVal = Op.getOperand(2);
4821 SDValue FalseVal = Op.getOperand(3);
4822 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
4823 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
4825 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
4826 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
4827 unsigned TVal = CTVal->getZExtValue();
4828 unsigned FVal = CFVal->getZExtValue();
4829 unsigned Opcode = 0;
4831 if (TVal == ~FVal) {
4832 Opcode = ARMISD::CSINV;
4833 } else if (TVal == ~FVal + 1) {
4834 Opcode = ARMISD::CSNEG;
4835 } else if (TVal + 1 == FVal) {
4836 Opcode = ARMISD::CSINC;
4837 } else if (TVal == FVal + 1) {
4838 Opcode = ARMISD::CSINC;
4839 std::swap(TrueVal, FalseVal);
4840 std::swap(TVal, FVal);
4841 CC = ISD::getSetCCInverse(CC, true);
4844 if (Opcode) {
4845 // If one of the constants is cheaper than another, materialise the
4846 // cheaper one and let the csel generate the other.
4847 if (Opcode != ARMISD::CSINC &&
4848 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
4849 std::swap(TrueVal, FalseVal);
4850 std::swap(TVal, FVal);
4851 CC = ISD::getSetCCInverse(CC, true);
4854 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
4855 // to get there. CSINC not is invertable like the other two (~(~a) == a,
4856 // -(-a) == a, but (a+1)+1 != a).
4857 if (FVal == 0 && Opcode != ARMISD::CSINC) {
4858 std::swap(TrueVal, FalseVal);
4859 std::swap(TVal, FVal);
4860 CC = ISD::getSetCCInverse(CC, true);
4862 if (TVal == 0)
4863 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
4865 // Drops F's value because we can get it by inverting/negating TVal.
4866 FalseVal = TrueVal;
4868 SDValue ARMcc;
4869 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4870 EVT VT = TrueVal.getValueType();
4871 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
4875 if (isUnsupportedFloatingType(LHS.getValueType())) {
4876 DAG.getTargetLoweringInfo().softenSetCCOperands(
4877 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
4879 // If softenSetCCOperands only returned one value, we should compare it to
4880 // zero.
4881 if (!RHS.getNode()) {
4882 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4883 CC = ISD::SETNE;
4887 if (LHS.getValueType() == MVT::i32) {
4888 // Try to generate VSEL on ARMv8.
4889 // The VSEL instruction can't use all the usual ARM condition
4890 // codes: it only has two bits to select the condition code, so it's
4891 // constrained to use only GE, GT, VS and EQ.
4893 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4894 // swap the operands of the previous compare instruction (effectively
4895 // inverting the compare condition, swapping 'less' and 'greater') and
4896 // sometimes need to swap the operands to the VSEL (which inverts the
4897 // condition in the sense of firing whenever the previous condition didn't)
4898 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4899 TrueVal.getValueType() == MVT::f32 ||
4900 TrueVal.getValueType() == MVT::f64)) {
4901 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4902 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4903 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4904 CC = ISD::getSetCCInverse(CC, true);
4905 std::swap(TrueVal, FalseVal);
4909 SDValue ARMcc;
4910 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4911 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4912 // Choose GE over PL, which vsel does now support
4913 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4914 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4915 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4918 ARMCC::CondCodes CondCode, CondCode2;
4919 bool InvalidOnQNaN;
4920 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4922 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4923 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4924 // must use VSEL (limited condition codes), due to not having conditional f16
4925 // moves.
4926 if (Subtarget->hasFPARMv8Base() &&
4927 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4928 (TrueVal.getValueType() == MVT::f16 ||
4929 TrueVal.getValueType() == MVT::f32 ||
4930 TrueVal.getValueType() == MVT::f64)) {
4931 bool swpCmpOps = false;
4932 bool swpVselOps = false;
4933 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4935 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4936 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4937 if (swpCmpOps)
4938 std::swap(LHS, RHS);
4939 if (swpVselOps)
4940 std::swap(TrueVal, FalseVal);
4944 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4945 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4946 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4947 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4948 if (CondCode2 != ARMCC::AL) {
4949 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4950 // FIXME: Needs another CMP because flag can have but one use.
4951 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4952 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4954 return Result;
4957 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4958 /// to morph to an integer compare sequence.
4959 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4960 const ARMSubtarget *Subtarget) {
4961 SDNode *N = Op.getNode();
4962 if (!N->hasOneUse())
4963 // Otherwise it requires moving the value from fp to integer registers.
4964 return false;
4965 if (!N->getNumValues())
4966 return false;
4967 EVT VT = Op.getValueType();
4968 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4969 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4970 // vmrs are very slow, e.g. cortex-a8.
4971 return false;
4973 if (isFloatingPointZero(Op)) {
4974 SeenZero = true;
4975 return true;
4977 return ISD::isNormalLoad(N);
4980 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4981 if (isFloatingPointZero(Op))
4982 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4984 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4985 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4986 Ld->getPointerInfo(), Ld->getAlignment(),
4987 Ld->getMemOperand()->getFlags());
4989 llvm_unreachable("Unknown VFP cmp argument!");
4992 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4993 SDValue &RetVal1, SDValue &RetVal2) {
4994 SDLoc dl(Op);
4996 if (isFloatingPointZero(Op)) {
4997 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4998 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4999 return;
5002 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5003 SDValue Ptr = Ld->getBasePtr();
5004 RetVal1 =
5005 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5006 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5008 EVT PtrType = Ptr.getValueType();
5009 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5010 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5011 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5012 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5013 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5014 Ld->getMemOperand()->getFlags());
5015 return;
5018 llvm_unreachable("Unknown VFP cmp argument!");
5021 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5022 /// f32 and even f64 comparisons to integer ones.
5023 SDValue
5024 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5025 SDValue Chain = Op.getOperand(0);
5026 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5027 SDValue LHS = Op.getOperand(2);
5028 SDValue RHS = Op.getOperand(3);
5029 SDValue Dest = Op.getOperand(4);
5030 SDLoc dl(Op);
5032 bool LHSSeenZero = false;
5033 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5034 bool RHSSeenZero = false;
5035 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5036 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5037 // If unsafe fp math optimization is enabled and there are no other uses of
5038 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5039 // to an integer comparison.
5040 if (CC == ISD::SETOEQ)
5041 CC = ISD::SETEQ;
5042 else if (CC == ISD::SETUNE)
5043 CC = ISD::SETNE;
5045 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5046 SDValue ARMcc;
5047 if (LHS.getValueType() == MVT::f32) {
5048 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5049 bitcastf32Toi32(LHS, DAG), Mask);
5050 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5051 bitcastf32Toi32(RHS, DAG), Mask);
5052 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5053 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5054 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5055 Chain, Dest, ARMcc, CCR, Cmp);
5058 SDValue LHS1, LHS2;
5059 SDValue RHS1, RHS2;
5060 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5061 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5062 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5063 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5064 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5065 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5066 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5067 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5068 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5071 return SDValue();
5074 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5075 SDValue Chain = Op.getOperand(0);
5076 SDValue Cond = Op.getOperand(1);
5077 SDValue Dest = Op.getOperand(2);
5078 SDLoc dl(Op);
5080 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5081 // instruction.
5082 unsigned Opc = Cond.getOpcode();
5083 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5084 !Subtarget->isThumb1Only();
5085 if (Cond.getResNo() == 1 &&
5086 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5087 Opc == ISD::USUBO || OptimizeMul)) {
5088 // Only lower legal XALUO ops.
5089 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5090 return SDValue();
5092 // The actual operation with overflow check.
5093 SDValue Value, OverflowCmp;
5094 SDValue ARMcc;
5095 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5097 // Reverse the condition code.
5098 ARMCC::CondCodes CondCode =
5099 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5100 CondCode = ARMCC::getOppositeCondition(CondCode);
5101 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5102 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5104 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5105 OverflowCmp);
5108 return SDValue();
5111 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5112 SDValue Chain = Op.getOperand(0);
5113 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5114 SDValue LHS = Op.getOperand(2);
5115 SDValue RHS = Op.getOperand(3);
5116 SDValue Dest = Op.getOperand(4);
5117 SDLoc dl(Op);
5119 if (isUnsupportedFloatingType(LHS.getValueType())) {
5120 DAG.getTargetLoweringInfo().softenSetCCOperands(
5121 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5123 // If softenSetCCOperands only returned one value, we should compare it to
5124 // zero.
5125 if (!RHS.getNode()) {
5126 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5127 CC = ISD::SETNE;
5131 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5132 // instruction.
5133 unsigned Opc = LHS.getOpcode();
5134 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5135 !Subtarget->isThumb1Only();
5136 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5137 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5138 Opc == ISD::USUBO || OptimizeMul) &&
5139 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5140 // Only lower legal XALUO ops.
5141 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5142 return SDValue();
5144 // The actual operation with overflow check.
5145 SDValue Value, OverflowCmp;
5146 SDValue ARMcc;
5147 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5149 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5150 // Reverse the condition code.
5151 ARMCC::CondCodes CondCode =
5152 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5153 CondCode = ARMCC::getOppositeCondition(CondCode);
5154 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5156 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5158 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5159 OverflowCmp);
5162 if (LHS.getValueType() == MVT::i32) {
5163 SDValue ARMcc;
5164 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5165 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5166 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5167 Chain, Dest, ARMcc, CCR, Cmp);
5170 if (getTargetMachine().Options.UnsafeFPMath &&
5171 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5172 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5173 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5174 return Result;
5177 ARMCC::CondCodes CondCode, CondCode2;
5178 bool InvalidOnQNaN;
5179 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
5181 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5182 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
5183 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5184 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5185 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5186 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5187 if (CondCode2 != ARMCC::AL) {
5188 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5189 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5190 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5192 return Res;
5195 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5196 SDValue Chain = Op.getOperand(0);
5197 SDValue Table = Op.getOperand(1);
5198 SDValue Index = Op.getOperand(2);
5199 SDLoc dl(Op);
5201 EVT PTy = getPointerTy(DAG.getDataLayout());
5202 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5203 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5204 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5205 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5206 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5207 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5208 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5209 // which does another jump to the destination. This also makes it easier
5210 // to translate it to TBB / TBH later (Thumb2 only).
5211 // FIXME: This might not work if the function is extremely large.
5212 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5213 Addr, Op.getOperand(2), JTI);
5215 if (isPositionIndependent() || Subtarget->isROPI()) {
5216 Addr =
5217 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5218 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5219 Chain = Addr.getValue(1);
5220 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5221 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5222 } else {
5223 Addr =
5224 DAG.getLoad(PTy, dl, Chain, Addr,
5225 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5226 Chain = Addr.getValue(1);
5227 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5231 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5232 EVT VT = Op.getValueType();
5233 SDLoc dl(Op);
5235 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5236 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5237 return Op;
5238 return DAG.UnrollVectorOp(Op.getNode());
5241 const bool HasFullFP16 =
5242 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5244 EVT NewTy;
5245 const EVT OpTy = Op.getOperand(0).getValueType();
5246 if (OpTy == MVT::v4f32)
5247 NewTy = MVT::v4i32;
5248 else if (OpTy == MVT::v4f16 && HasFullFP16)
5249 NewTy = MVT::v4i16;
5250 else if (OpTy == MVT::v8f16 && HasFullFP16)
5251 NewTy = MVT::v8i16;
5252 else
5253 llvm_unreachable("Invalid type for custom lowering!");
5255 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5256 return DAG.UnrollVectorOp(Op.getNode());
5258 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5259 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5262 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5263 EVT VT = Op.getValueType();
5264 if (VT.isVector())
5265 return LowerVectorFP_TO_INT(Op, DAG);
5266 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5267 RTLIB::Libcall LC;
5268 if (Op.getOpcode() == ISD::FP_TO_SINT)
5269 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5270 Op.getValueType());
5271 else
5272 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5273 Op.getValueType());
5274 MakeLibCallOptions CallOptions;
5275 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5276 CallOptions, SDLoc(Op)).first;
5279 return Op;
5282 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5283 EVT VT = Op.getValueType();
5284 SDLoc dl(Op);
5286 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5287 if (VT.getVectorElementType() == MVT::f32)
5288 return Op;
5289 return DAG.UnrollVectorOp(Op.getNode());
5292 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5293 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5294 "Invalid type for custom lowering!");
5296 const bool HasFullFP16 =
5297 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5299 EVT DestVecType;
5300 if (VT == MVT::v4f32)
5301 DestVecType = MVT::v4i32;
5302 else if (VT == MVT::v4f16 && HasFullFP16)
5303 DestVecType = MVT::v4i16;
5304 else if (VT == MVT::v8f16 && HasFullFP16)
5305 DestVecType = MVT::v8i16;
5306 else
5307 return DAG.UnrollVectorOp(Op.getNode());
5309 unsigned CastOpc;
5310 unsigned Opc;
5311 switch (Op.getOpcode()) {
5312 default: llvm_unreachable("Invalid opcode!");
5313 case ISD::SINT_TO_FP:
5314 CastOpc = ISD::SIGN_EXTEND;
5315 Opc = ISD::SINT_TO_FP;
5316 break;
5317 case ISD::UINT_TO_FP:
5318 CastOpc = ISD::ZERO_EXTEND;
5319 Opc = ISD::UINT_TO_FP;
5320 break;
5323 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5324 return DAG.getNode(Opc, dl, VT, Op);
5327 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5328 EVT VT = Op.getValueType();
5329 if (VT.isVector())
5330 return LowerVectorINT_TO_FP(Op, DAG);
5331 if (isUnsupportedFloatingType(VT)) {
5332 RTLIB::Libcall LC;
5333 if (Op.getOpcode() == ISD::SINT_TO_FP)
5334 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5335 Op.getValueType());
5336 else
5337 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5338 Op.getValueType());
5339 MakeLibCallOptions CallOptions;
5340 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5341 CallOptions, SDLoc(Op)).first;
5344 return Op;
5347 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5348 // Implement fcopysign with a fabs and a conditional fneg.
5349 SDValue Tmp0 = Op.getOperand(0);
5350 SDValue Tmp1 = Op.getOperand(1);
5351 SDLoc dl(Op);
5352 EVT VT = Op.getValueType();
5353 EVT SrcVT = Tmp1.getValueType();
5354 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5355 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5356 bool UseNEON = !InGPR && Subtarget->hasNEON();
5358 if (UseNEON) {
5359 // Use VBSL to copy the sign bit.
5360 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5361 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5362 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5363 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5364 if (VT == MVT::f64)
5365 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5366 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5367 DAG.getConstant(32, dl, MVT::i32));
5368 else /*if (VT == MVT::f32)*/
5369 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5370 if (SrcVT == MVT::f32) {
5371 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5372 if (VT == MVT::f64)
5373 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5374 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5375 DAG.getConstant(32, dl, MVT::i32));
5376 } else if (VT == MVT::f32)
5377 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5378 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5379 DAG.getConstant(32, dl, MVT::i32));
5380 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5381 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5383 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5384 dl, MVT::i32);
5385 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5386 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5387 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5389 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5390 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5391 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5392 if (VT == MVT::f32) {
5393 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5394 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5395 DAG.getConstant(0, dl, MVT::i32));
5396 } else {
5397 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5400 return Res;
5403 // Bitcast operand 1 to i32.
5404 if (SrcVT == MVT::f64)
5405 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5406 Tmp1).getValue(1);
5407 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5409 // Or in the signbit with integer operations.
5410 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5411 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5412 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5413 if (VT == MVT::f32) {
5414 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5415 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5416 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5417 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5420 // f64: Or the high part with signbit and then combine two parts.
5421 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5422 Tmp0);
5423 SDValue Lo = Tmp0.getValue(0);
5424 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5425 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5426 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5429 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5430 MachineFunction &MF = DAG.getMachineFunction();
5431 MachineFrameInfo &MFI = MF.getFrameInfo();
5432 MFI.setReturnAddressIsTaken(true);
5434 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5435 return SDValue();
5437 EVT VT = Op.getValueType();
5438 SDLoc dl(Op);
5439 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5440 if (Depth) {
5441 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5442 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5443 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5444 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5445 MachinePointerInfo());
5448 // Return LR, which contains the return address. Mark it an implicit live-in.
5449 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5450 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5453 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5454 const ARMBaseRegisterInfo &ARI =
5455 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5456 MachineFunction &MF = DAG.getMachineFunction();
5457 MachineFrameInfo &MFI = MF.getFrameInfo();
5458 MFI.setFrameAddressIsTaken(true);
5460 EVT VT = Op.getValueType();
5461 SDLoc dl(Op); // FIXME probably not meaningful
5462 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5463 Register FrameReg = ARI.getFrameRegister(MF);
5464 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5465 while (Depth--)
5466 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5467 MachinePointerInfo());
5468 return FrameAddr;
5471 // FIXME? Maybe this could be a TableGen attribute on some registers and
5472 // this table could be generated automatically from RegInfo.
5473 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5474 SelectionDAG &DAG) const {
5475 unsigned Reg = StringSwitch<unsigned>(RegName)
5476 .Case("sp", ARM::SP)
5477 .Default(0);
5478 if (Reg)
5479 return Reg;
5480 report_fatal_error(Twine("Invalid register name \""
5481 + StringRef(RegName) + "\"."));
5484 // Result is 64 bit value so split into two 32 bit values and return as a
5485 // pair of values.
5486 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5487 SelectionDAG &DAG) {
5488 SDLoc DL(N);
5490 // This function is only supposed to be called for i64 type destination.
5491 assert(N->getValueType(0) == MVT::i64
5492 && "ExpandREAD_REGISTER called for non-i64 type result.");
5494 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5495 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5496 N->getOperand(0),
5497 N->getOperand(1));
5499 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5500 Read.getValue(1)));
5501 Results.push_back(Read.getOperand(0));
5504 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5505 /// When \p DstVT, the destination type of \p BC, is on the vector
5506 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5507 /// it might be possible to combine them, such that everything stays on the
5508 /// vector register bank.
5509 /// \p return The node that would replace \p BT, if the combine
5510 /// is possible.
5511 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5512 SelectionDAG &DAG) {
5513 SDValue Op = BC->getOperand(0);
5514 EVT DstVT = BC->getValueType(0);
5516 // The only vector instruction that can produce a scalar (remember,
5517 // since the bitcast was about to be turned into VMOVDRR, the source
5518 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5519 // Moreover, we can do this combine only if there is one use.
5520 // Finally, if the destination type is not a vector, there is not
5521 // much point on forcing everything on the vector bank.
5522 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5523 !Op.hasOneUse())
5524 return SDValue();
5526 // If the index is not constant, we will introduce an additional
5527 // multiply that will stick.
5528 // Give up in that case.
5529 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5530 if (!Index)
5531 return SDValue();
5532 unsigned DstNumElt = DstVT.getVectorNumElements();
5534 // Compute the new index.
5535 const APInt &APIntIndex = Index->getAPIntValue();
5536 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5537 NewIndex *= APIntIndex;
5538 // Check if the new constant index fits into i32.
5539 if (NewIndex.getBitWidth() > 32)
5540 return SDValue();
5542 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5543 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5544 SDLoc dl(Op);
5545 SDValue ExtractSrc = Op.getOperand(0);
5546 EVT VecVT = EVT::getVectorVT(
5547 *DAG.getContext(), DstVT.getScalarType(),
5548 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5549 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5550 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5551 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5554 /// ExpandBITCAST - If the target supports VFP, this function is called to
5555 /// expand a bit convert where either the source or destination type is i64 to
5556 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5557 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5558 /// vectors), since the legalizer won't know what to do with that.
5559 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5560 const ARMSubtarget *Subtarget) {
5561 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5562 SDLoc dl(N);
5563 SDValue Op = N->getOperand(0);
5565 // This function is only supposed to be called for i64 types, either as the
5566 // source or destination of the bit convert.
5567 EVT SrcVT = Op.getValueType();
5568 EVT DstVT = N->getValueType(0);
5569 const bool HasFullFP16 = Subtarget->hasFullFP16();
5571 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5572 // FullFP16: half values are passed in S-registers, and we don't
5573 // need any of the bitcast and moves:
5575 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5576 // t5: i32 = bitcast t2
5577 // t18: f16 = ARMISD::VMOVhr t5
5578 if (Op.getOpcode() != ISD::CopyFromReg ||
5579 Op.getValueType() != MVT::f32)
5580 return SDValue();
5582 auto Move = N->use_begin();
5583 if (Move->getOpcode() != ARMISD::VMOVhr)
5584 return SDValue();
5586 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5587 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5588 DAG.ReplaceAllUsesWith(*Move, &Copy);
5589 return Copy;
5592 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5593 if (!HasFullFP16)
5594 return SDValue();
5595 // SoftFP: read half-precision arguments:
5597 // t2: i32,ch = ...
5598 // t7: i16 = truncate t2 <~~~~ Op
5599 // t8: f16 = bitcast t7 <~~~~ N
5601 if (Op.getOperand(0).getValueType() == MVT::i32)
5602 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5603 MVT::f16, Op.getOperand(0));
5605 return SDValue();
5608 // Half-precision return values
5609 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5610 if (!HasFullFP16)
5611 return SDValue();
5613 // t11: f16 = fadd t8, t10
5614 // t12: i16 = bitcast t11 <~~~ SDNode N
5615 // t13: i32 = zero_extend t12
5616 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5617 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5619 // transform this into:
5621 // t20: i32 = ARMISD::VMOVrh t11
5622 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5624 auto ZeroExtend = N->use_begin();
5625 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5626 ZeroExtend->getValueType(0) != MVT::i32)
5627 return SDValue();
5629 auto Copy = ZeroExtend->use_begin();
5630 if (Copy->getOpcode() == ISD::CopyToReg &&
5631 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5632 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5633 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5634 return Cvt;
5636 return SDValue();
5639 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5640 return SDValue();
5642 // Turn i64->f64 into VMOVDRR.
5643 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5644 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5645 // if we can combine the bitcast with its source.
5646 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5647 return Val;
5649 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5650 DAG.getConstant(0, dl, MVT::i32));
5651 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5652 DAG.getConstant(1, dl, MVT::i32));
5653 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5654 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5657 // Turn f64->i64 into VMOVRRD.
5658 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5659 SDValue Cvt;
5660 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5661 SrcVT.getVectorNumElements() > 1)
5662 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5663 DAG.getVTList(MVT::i32, MVT::i32),
5664 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5665 else
5666 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5667 DAG.getVTList(MVT::i32, MVT::i32), Op);
5668 // Merge the pieces into a single i64 value.
5669 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5672 return SDValue();
5675 /// getZeroVector - Returns a vector of specified type with all zero elements.
5676 /// Zero vectors are used to represent vector negation and in those cases
5677 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5678 /// not support i64 elements, so sometimes the zero vectors will need to be
5679 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5680 /// zero vector.
5681 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5682 assert(VT.isVector() && "Expected a vector type");
5683 // The canonical modified immediate encoding of a zero vector is....0!
5684 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5685 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5686 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5687 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5690 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5691 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5692 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5693 SelectionDAG &DAG) const {
5694 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5695 EVT VT = Op.getValueType();
5696 unsigned VTBits = VT.getSizeInBits();
5697 SDLoc dl(Op);
5698 SDValue ShOpLo = Op.getOperand(0);
5699 SDValue ShOpHi = Op.getOperand(1);
5700 SDValue ShAmt = Op.getOperand(2);
5701 SDValue ARMcc;
5702 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5703 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5705 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5707 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5708 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5709 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5710 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5711 DAG.getConstant(VTBits, dl, MVT::i32));
5712 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5713 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5714 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5715 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5716 ISD::SETGE, ARMcc, DAG, dl);
5717 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5718 ARMcc, CCR, CmpLo);
5720 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5721 SDValue HiBigShift = Opc == ISD::SRA
5722 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5723 DAG.getConstant(VTBits - 1, dl, VT))
5724 : DAG.getConstant(0, dl, VT);
5725 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5726 ISD::SETGE, ARMcc, DAG, dl);
5727 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5728 ARMcc, CCR, CmpHi);
5730 SDValue Ops[2] = { Lo, Hi };
5731 return DAG.getMergeValues(Ops, dl);
5734 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5735 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5736 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5737 SelectionDAG &DAG) const {
5738 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5739 EVT VT = Op.getValueType();
5740 unsigned VTBits = VT.getSizeInBits();
5741 SDLoc dl(Op);
5742 SDValue ShOpLo = Op.getOperand(0);
5743 SDValue ShOpHi = Op.getOperand(1);
5744 SDValue ShAmt = Op.getOperand(2);
5745 SDValue ARMcc;
5746 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5748 assert(Op.getOpcode() == ISD::SHL_PARTS);
5749 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5750 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5751 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5752 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5753 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5755 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5756 DAG.getConstant(VTBits, dl, MVT::i32));
5757 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5758 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5759 ISD::SETGE, ARMcc, DAG, dl);
5760 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5761 ARMcc, CCR, CmpHi);
5763 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5764 ISD::SETGE, ARMcc, DAG, dl);
5765 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5766 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5767 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5769 SDValue Ops[2] = { Lo, Hi };
5770 return DAG.getMergeValues(Ops, dl);
5773 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5774 SelectionDAG &DAG) const {
5775 // The rounding mode is in bits 23:22 of the FPSCR.
5776 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5777 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5778 // so that the shift + and get folded into a bitfield extract.
5779 SDLoc dl(Op);
5780 SDValue Ops[] = { DAG.getEntryNode(),
5781 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5783 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5784 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5785 DAG.getConstant(1U << 22, dl, MVT::i32));
5786 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5787 DAG.getConstant(22, dl, MVT::i32));
5788 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5789 DAG.getConstant(3, dl, MVT::i32));
5792 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5793 const ARMSubtarget *ST) {
5794 SDLoc dl(N);
5795 EVT VT = N->getValueType(0);
5796 if (VT.isVector()) {
5797 assert(ST->hasNEON());
5799 // Compute the least significant set bit: LSB = X & -X
5800 SDValue X = N->getOperand(0);
5801 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5802 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5804 EVT ElemTy = VT.getVectorElementType();
5806 if (ElemTy == MVT::i8) {
5807 // Compute with: cttz(x) = ctpop(lsb - 1)
5808 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5809 DAG.getTargetConstant(1, dl, ElemTy));
5810 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5811 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5814 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5815 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5816 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5817 unsigned NumBits = ElemTy.getSizeInBits();
5818 SDValue WidthMinus1 =
5819 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5820 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5821 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5822 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5825 // Compute with: cttz(x) = ctpop(lsb - 1)
5827 // Compute LSB - 1.
5828 SDValue Bits;
5829 if (ElemTy == MVT::i64) {
5830 // Load constant 0xffff'ffff'ffff'ffff to register.
5831 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5832 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5833 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5834 } else {
5835 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5836 DAG.getTargetConstant(1, dl, ElemTy));
5837 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5839 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5842 if (!ST->hasV6T2Ops())
5843 return SDValue();
5845 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5846 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5849 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5850 const ARMSubtarget *ST) {
5851 EVT VT = N->getValueType(0);
5852 SDLoc DL(N);
5854 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5855 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5856 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5857 "Unexpected type for custom ctpop lowering");
5859 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5860 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5861 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5862 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5864 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5865 unsigned EltSize = 8;
5866 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5867 while (EltSize != VT.getScalarSizeInBits()) {
5868 SmallVector<SDValue, 8> Ops;
5869 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5870 TLI.getPointerTy(DAG.getDataLayout())));
5871 Ops.push_back(Res);
5873 EltSize *= 2;
5874 NumElts /= 2;
5875 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5876 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5879 return Res;
5882 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5883 /// operand of a vector shift operation, where all the elements of the
5884 /// build_vector must have the same constant integer value.
5885 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5886 // Ignore bit_converts.
5887 while (Op.getOpcode() == ISD::BITCAST)
5888 Op = Op.getOperand(0);
5889 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5890 APInt SplatBits, SplatUndef;
5891 unsigned SplatBitSize;
5892 bool HasAnyUndefs;
5893 if (!BVN ||
5894 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5895 ElementBits) ||
5896 SplatBitSize > ElementBits)
5897 return false;
5898 Cnt = SplatBits.getSExtValue();
5899 return true;
5902 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5903 /// operand of a vector shift left operation. That value must be in the range:
5904 /// 0 <= Value < ElementBits for a left shift; or
5905 /// 0 <= Value <= ElementBits for a long left shift.
5906 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5907 assert(VT.isVector() && "vector shift count is not a vector type");
5908 int64_t ElementBits = VT.getScalarSizeInBits();
5909 if (!getVShiftImm(Op, ElementBits, Cnt))
5910 return false;
5911 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5914 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5915 /// operand of a vector shift right operation. For a shift opcode, the value
5916 /// is positive, but for an intrinsic the value count must be negative. The
5917 /// absolute value must be in the range:
5918 /// 1 <= |Value| <= ElementBits for a right shift; or
5919 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5920 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5921 int64_t &Cnt) {
5922 assert(VT.isVector() && "vector shift count is not a vector type");
5923 int64_t ElementBits = VT.getScalarSizeInBits();
5924 if (!getVShiftImm(Op, ElementBits, Cnt))
5925 return false;
5926 if (!isIntrinsic)
5927 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5928 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5929 Cnt = -Cnt;
5930 return true;
5932 return false;
5935 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5936 const ARMSubtarget *ST) {
5937 EVT VT = N->getValueType(0);
5938 SDLoc dl(N);
5939 int64_t Cnt;
5941 if (!VT.isVector())
5942 return SDValue();
5944 // We essentially have two forms here. Shift by an immediate and shift by a
5945 // vector register (there are also shift by a gpr, but that is just handled
5946 // with a tablegen pattern). We cannot easily match shift by an immediate in
5947 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5948 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5949 // signed or unsigned, and a negative shift indicates a shift right).
5950 if (N->getOpcode() == ISD::SHL) {
5951 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5952 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5953 DAG.getConstant(Cnt, dl, MVT::i32));
5954 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
5955 N->getOperand(1));
5958 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
5959 "unexpected vector shift opcode");
5961 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
5962 unsigned VShiftOpc =
5963 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
5964 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
5965 DAG.getConstant(Cnt, dl, MVT::i32));
5968 // Other right shifts we don't have operations for (we use a shift left by a
5969 // negative number).
5970 EVT ShiftVT = N->getOperand(1).getValueType();
5971 SDValue NegatedCount = DAG.getNode(
5972 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
5973 unsigned VShiftOpc =
5974 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
5975 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
5978 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5979 const ARMSubtarget *ST) {
5980 EVT VT = N->getValueType(0);
5981 SDLoc dl(N);
5983 // We can get here for a node like i32 = ISD::SHL i32, i64
5984 if (VT != MVT::i64)
5985 return SDValue();
5987 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
5988 N->getOpcode() == ISD::SHL) &&
5989 "Unknown shift to lower!");
5991 unsigned ShOpc = N->getOpcode();
5992 if (ST->hasMVEIntegerOps()) {
5993 SDValue ShAmt = N->getOperand(1);
5994 unsigned ShPartsOpc = ARMISD::LSLL;
5995 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
5997 // If the shift amount is greater than 32 or has a greater bitwidth than 64
5998 // then do the default optimisation
5999 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6000 (Con && Con->getZExtValue() >= 32))
6001 return SDValue();
6003 // Extract the lower 32 bits of the shift amount if it's not an i32
6004 if (ShAmt->getValueType(0) != MVT::i32)
6005 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6007 if (ShOpc == ISD::SRL) {
6008 if (!Con)
6009 // There is no t2LSRLr instruction so negate and perform an lsll if the
6010 // shift amount is in a register, emulating a right shift.
6011 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6012 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6013 else
6014 // Else generate an lsrl on the immediate shift amount
6015 ShPartsOpc = ARMISD::LSRL;
6016 } else if (ShOpc == ISD::SRA)
6017 ShPartsOpc = ARMISD::ASRL;
6019 // Lower 32 bits of the destination/source
6020 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6021 DAG.getConstant(0, dl, MVT::i32));
6022 // Upper 32 bits of the destination/source
6023 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6024 DAG.getConstant(1, dl, MVT::i32));
6026 // Generate the shift operation as computed above
6027 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6028 ShAmt);
6029 // The upper 32 bits come from the second return value of lsll
6030 Hi = SDValue(Lo.getNode(), 1);
6031 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6034 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6035 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6036 return SDValue();
6038 // If we are in thumb mode, we don't have RRX.
6039 if (ST->isThumb1Only())
6040 return SDValue();
6042 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6043 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6044 DAG.getConstant(0, dl, MVT::i32));
6045 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6046 DAG.getConstant(1, dl, MVT::i32));
6048 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6049 // captures the result into a carry flag.
6050 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6051 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6053 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6054 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6056 // Merge the pieces into a single i64 value.
6057 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6060 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6061 const ARMSubtarget *ST) {
6062 bool Invert = false;
6063 bool Swap = false;
6064 unsigned Opc = ARMCC::AL;
6066 SDValue Op0 = Op.getOperand(0);
6067 SDValue Op1 = Op.getOperand(1);
6068 SDValue CC = Op.getOperand(2);
6069 EVT VT = Op.getValueType();
6070 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6071 SDLoc dl(Op);
6073 EVT CmpVT;
6074 if (ST->hasNEON())
6075 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6076 else {
6077 assert(ST->hasMVEIntegerOps() &&
6078 "No hardware support for integer vector comparison!");
6080 if (Op.getValueType().getVectorElementType() != MVT::i1)
6081 return SDValue();
6083 // Make sure we expand floating point setcc to scalar if we do not have
6084 // mve.fp, so that we can handle them from there.
6085 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6086 return SDValue();
6088 CmpVT = VT;
6091 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6092 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6093 // Special-case integer 64-bit equality comparisons. They aren't legal,
6094 // but they can be lowered with a few vector instructions.
6095 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6096 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6097 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6098 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6099 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6100 DAG.getCondCode(ISD::SETEQ));
6101 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6102 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6103 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6104 if (SetCCOpcode == ISD::SETNE)
6105 Merged = DAG.getNOT(dl, Merged, CmpVT);
6106 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6107 return Merged;
6110 if (CmpVT.getVectorElementType() == MVT::i64)
6111 // 64-bit comparisons are not legal in general.
6112 return SDValue();
6114 if (Op1.getValueType().isFloatingPoint()) {
6115 switch (SetCCOpcode) {
6116 default: llvm_unreachable("Illegal FP comparison");
6117 case ISD::SETUNE:
6118 case ISD::SETNE:
6119 if (ST->hasMVEFloatOps()) {
6120 Opc = ARMCC::NE; break;
6121 } else {
6122 Invert = true; LLVM_FALLTHROUGH;
6124 case ISD::SETOEQ:
6125 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6126 case ISD::SETOLT:
6127 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6128 case ISD::SETOGT:
6129 case ISD::SETGT: Opc = ARMCC::GT; break;
6130 case ISD::SETOLE:
6131 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6132 case ISD::SETOGE:
6133 case ISD::SETGE: Opc = ARMCC::GE; break;
6134 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6135 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6136 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6137 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6138 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6139 case ISD::SETONE: {
6140 // Expand this to (OLT | OGT).
6141 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6142 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6143 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6144 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6145 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6146 if (Invert)
6147 Result = DAG.getNOT(dl, Result, VT);
6148 return Result;
6150 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6151 case ISD::SETO: {
6152 // Expand this to (OLT | OGE).
6153 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6154 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6155 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6156 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6157 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6158 if (Invert)
6159 Result = DAG.getNOT(dl, Result, VT);
6160 return Result;
6163 } else {
6164 // Integer comparisons.
6165 switch (SetCCOpcode) {
6166 default: llvm_unreachable("Illegal integer comparison");
6167 case ISD::SETNE:
6168 if (ST->hasMVEIntegerOps()) {
6169 Opc = ARMCC::NE; break;
6170 } else {
6171 Invert = true; LLVM_FALLTHROUGH;
6173 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6174 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6175 case ISD::SETGT: Opc = ARMCC::GT; break;
6176 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6177 case ISD::SETGE: Opc = ARMCC::GE; break;
6178 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6179 case ISD::SETUGT: Opc = ARMCC::HI; break;
6180 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6181 case ISD::SETUGE: Opc = ARMCC::HS; break;
6184 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6185 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6186 SDValue AndOp;
6187 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6188 AndOp = Op0;
6189 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6190 AndOp = Op1;
6192 // Ignore bitconvert.
6193 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6194 AndOp = AndOp.getOperand(0);
6196 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6197 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6198 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6199 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6200 if (!Invert)
6201 Result = DAG.getNOT(dl, Result, VT);
6202 return Result;
6207 if (Swap)
6208 std::swap(Op0, Op1);
6210 // If one of the operands is a constant vector zero, attempt to fold the
6211 // comparison to a specialized compare-against-zero form.
6212 SDValue SingleOp;
6213 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6214 SingleOp = Op0;
6215 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6216 if (Opc == ARMCC::GE)
6217 Opc = ARMCC::LE;
6218 else if (Opc == ARMCC::GT)
6219 Opc = ARMCC::LT;
6220 SingleOp = Op1;
6223 SDValue Result;
6224 if (SingleOp.getNode()) {
6225 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6226 DAG.getConstant(Opc, dl, MVT::i32));
6227 } else {
6228 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6229 DAG.getConstant(Opc, dl, MVT::i32));
6232 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6234 if (Invert)
6235 Result = DAG.getNOT(dl, Result, VT);
6237 return Result;
6240 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6241 SDValue LHS = Op.getOperand(0);
6242 SDValue RHS = Op.getOperand(1);
6243 SDValue Carry = Op.getOperand(2);
6244 SDValue Cond = Op.getOperand(3);
6245 SDLoc DL(Op);
6247 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6249 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6250 // have to invert the carry first.
6251 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6252 DAG.getConstant(1, DL, MVT::i32), Carry);
6253 // This converts the boolean value carry into the carry flag.
6254 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6256 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6257 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6259 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6260 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6261 SDValue ARMcc = DAG.getConstant(
6262 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6263 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6264 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6265 Cmp.getValue(1), SDValue());
6266 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6267 CCR, Chain.getValue(1));
6270 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6271 /// valid vector constant for a NEON or MVE instruction with a "modified
6272 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6273 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6274 unsigned SplatBitSize, SelectionDAG &DAG,
6275 const SDLoc &dl, EVT &VT, bool is128Bits,
6276 VMOVModImmType type) {
6277 unsigned OpCmode, Imm;
6279 // SplatBitSize is set to the smallest size that splats the vector, so a
6280 // zero vector will always have SplatBitSize == 8. However, NEON modified
6281 // immediate instructions others than VMOV do not support the 8-bit encoding
6282 // of a zero vector, and the default encoding of zero is supposed to be the
6283 // 32-bit version.
6284 if (SplatBits == 0)
6285 SplatBitSize = 32;
6287 switch (SplatBitSize) {
6288 case 8:
6289 if (type != VMOVModImm)
6290 return SDValue();
6291 // Any 1-byte value is OK. Op=0, Cmode=1110.
6292 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6293 OpCmode = 0xe;
6294 Imm = SplatBits;
6295 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6296 break;
6298 case 16:
6299 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6300 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6301 if ((SplatBits & ~0xff) == 0) {
6302 // Value = 0x00nn: Op=x, Cmode=100x.
6303 OpCmode = 0x8;
6304 Imm = SplatBits;
6305 break;
6307 if ((SplatBits & ~0xff00) == 0) {
6308 // Value = 0xnn00: Op=x, Cmode=101x.
6309 OpCmode = 0xa;
6310 Imm = SplatBits >> 8;
6311 break;
6313 return SDValue();
6315 case 32:
6316 // NEON's 32-bit VMOV supports splat values where:
6317 // * only one byte is nonzero, or
6318 // * the least significant byte is 0xff and the second byte is nonzero, or
6319 // * the least significant 2 bytes are 0xff and the third is nonzero.
6320 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6321 if ((SplatBits & ~0xff) == 0) {
6322 // Value = 0x000000nn: Op=x, Cmode=000x.
6323 OpCmode = 0;
6324 Imm = SplatBits;
6325 break;
6327 if ((SplatBits & ~0xff00) == 0) {
6328 // Value = 0x0000nn00: Op=x, Cmode=001x.
6329 OpCmode = 0x2;
6330 Imm = SplatBits >> 8;
6331 break;
6333 if ((SplatBits & ~0xff0000) == 0) {
6334 // Value = 0x00nn0000: Op=x, Cmode=010x.
6335 OpCmode = 0x4;
6336 Imm = SplatBits >> 16;
6337 break;
6339 if ((SplatBits & ~0xff000000) == 0) {
6340 // Value = 0xnn000000: Op=x, Cmode=011x.
6341 OpCmode = 0x6;
6342 Imm = SplatBits >> 24;
6343 break;
6346 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6347 if (type == OtherModImm) return SDValue();
6349 if ((SplatBits & ~0xffff) == 0 &&
6350 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6351 // Value = 0x0000nnff: Op=x, Cmode=1100.
6352 OpCmode = 0xc;
6353 Imm = SplatBits >> 8;
6354 break;
6357 // cmode == 0b1101 is not supported for MVE VMVN
6358 if (type == MVEVMVNModImm)
6359 return SDValue();
6361 if ((SplatBits & ~0xffffff) == 0 &&
6362 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6363 // Value = 0x00nnffff: Op=x, Cmode=1101.
6364 OpCmode = 0xd;
6365 Imm = SplatBits >> 16;
6366 break;
6369 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6370 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6371 // VMOV.I32. A (very) minor optimization would be to replicate the value
6372 // and fall through here to test for a valid 64-bit splat. But, then the
6373 // caller would also need to check and handle the change in size.
6374 return SDValue();
6376 case 64: {
6377 if (type != VMOVModImm)
6378 return SDValue();
6379 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6380 uint64_t BitMask = 0xff;
6381 uint64_t Val = 0;
6382 unsigned ImmMask = 1;
6383 Imm = 0;
6384 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6385 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6386 Val |= BitMask;
6387 Imm |= ImmMask;
6388 } else if ((SplatBits & BitMask) != 0) {
6389 return SDValue();
6391 BitMask <<= 8;
6392 ImmMask <<= 1;
6395 if (DAG.getDataLayout().isBigEndian())
6396 // swap higher and lower 32 bit word
6397 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6399 // Op=1, Cmode=1110.
6400 OpCmode = 0x1e;
6401 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6402 break;
6405 default:
6406 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6409 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6410 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6413 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6414 const ARMSubtarget *ST) const {
6415 EVT VT = Op.getValueType();
6416 bool IsDouble = (VT == MVT::f64);
6417 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6418 const APFloat &FPVal = CFP->getValueAPF();
6420 // Prevent floating-point constants from using literal loads
6421 // when execute-only is enabled.
6422 if (ST->genExecuteOnly()) {
6423 // If we can represent the constant as an immediate, don't lower it
6424 if (isFPImmLegal(FPVal, VT))
6425 return Op;
6426 // Otherwise, construct as integer, and move to float register
6427 APInt INTVal = FPVal.bitcastToAPInt();
6428 SDLoc DL(CFP);
6429 switch (VT.getSimpleVT().SimpleTy) {
6430 default:
6431 llvm_unreachable("Unknown floating point type!");
6432 break;
6433 case MVT::f64: {
6434 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6435 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6436 if (!ST->isLittle())
6437 std::swap(Lo, Hi);
6438 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6440 case MVT::f32:
6441 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6442 DAG.getConstant(INTVal, DL, MVT::i32));
6446 if (!ST->hasVFP3Base())
6447 return SDValue();
6449 // Use the default (constant pool) lowering for double constants when we have
6450 // an SP-only FPU
6451 if (IsDouble && !Subtarget->hasFP64())
6452 return SDValue();
6454 // Try splatting with a VMOV.f32...
6455 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6457 if (ImmVal != -1) {
6458 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6459 // We have code in place to select a valid ConstantFP already, no need to
6460 // do any mangling.
6461 return Op;
6464 // It's a float and we are trying to use NEON operations where
6465 // possible. Lower it to a splat followed by an extract.
6466 SDLoc DL(Op);
6467 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6468 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6469 NewVal);
6470 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6471 DAG.getConstant(0, DL, MVT::i32));
6474 // The rest of our options are NEON only, make sure that's allowed before
6475 // proceeding..
6476 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6477 return SDValue();
6479 EVT VMovVT;
6480 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6482 // It wouldn't really be worth bothering for doubles except for one very
6483 // important value, which does happen to match: 0.0. So make sure we don't do
6484 // anything stupid.
6485 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6486 return SDValue();
6488 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6489 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6490 VMovVT, false, VMOVModImm);
6491 if (NewVal != SDValue()) {
6492 SDLoc DL(Op);
6493 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6494 NewVal);
6495 if (IsDouble)
6496 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6498 // It's a float: cast and extract a vector element.
6499 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6500 VecConstant);
6501 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6502 DAG.getConstant(0, DL, MVT::i32));
6505 // Finally, try a VMVN.i32
6506 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6507 false, VMVNModImm);
6508 if (NewVal != SDValue()) {
6509 SDLoc DL(Op);
6510 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6512 if (IsDouble)
6513 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6515 // It's a float: cast and extract a vector element.
6516 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6517 VecConstant);
6518 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6519 DAG.getConstant(0, DL, MVT::i32));
6522 return SDValue();
6525 // check if an VEXT instruction can handle the shuffle mask when the
6526 // vector sources of the shuffle are the same.
6527 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6528 unsigned NumElts = VT.getVectorNumElements();
6530 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6531 if (M[0] < 0)
6532 return false;
6534 Imm = M[0];
6536 // If this is a VEXT shuffle, the immediate value is the index of the first
6537 // element. The other shuffle indices must be the successive elements after
6538 // the first one.
6539 unsigned ExpectedElt = Imm;
6540 for (unsigned i = 1; i < NumElts; ++i) {
6541 // Increment the expected index. If it wraps around, just follow it
6542 // back to index zero and keep going.
6543 ++ExpectedElt;
6544 if (ExpectedElt == NumElts)
6545 ExpectedElt = 0;
6547 if (M[i] < 0) continue; // ignore UNDEF indices
6548 if (ExpectedElt != static_cast<unsigned>(M[i]))
6549 return false;
6552 return true;
6555 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6556 bool &ReverseVEXT, unsigned &Imm) {
6557 unsigned NumElts = VT.getVectorNumElements();
6558 ReverseVEXT = false;
6560 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6561 if (M[0] < 0)
6562 return false;
6564 Imm = M[0];
6566 // If this is a VEXT shuffle, the immediate value is the index of the first
6567 // element. The other shuffle indices must be the successive elements after
6568 // the first one.
6569 unsigned ExpectedElt = Imm;
6570 for (unsigned i = 1; i < NumElts; ++i) {
6571 // Increment the expected index. If it wraps around, it may still be
6572 // a VEXT but the source vectors must be swapped.
6573 ExpectedElt += 1;
6574 if (ExpectedElt == NumElts * 2) {
6575 ExpectedElt = 0;
6576 ReverseVEXT = true;
6579 if (M[i] < 0) continue; // ignore UNDEF indices
6580 if (ExpectedElt != static_cast<unsigned>(M[i]))
6581 return false;
6584 // Adjust the index value if the source operands will be swapped.
6585 if (ReverseVEXT)
6586 Imm -= NumElts;
6588 return true;
6591 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6592 /// instruction with the specified blocksize. (The order of the elements
6593 /// within each block of the vector is reversed.)
6594 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6595 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6596 "Only possible block sizes for VREV are: 16, 32, 64");
6598 unsigned EltSz = VT.getScalarSizeInBits();
6599 if (EltSz == 64)
6600 return false;
6602 unsigned NumElts = VT.getVectorNumElements();
6603 unsigned BlockElts = M[0] + 1;
6604 // If the first shuffle index is UNDEF, be optimistic.
6605 if (M[0] < 0)
6606 BlockElts = BlockSize / EltSz;
6608 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6609 return false;
6611 for (unsigned i = 0; i < NumElts; ++i) {
6612 if (M[i] < 0) continue; // ignore UNDEF indices
6613 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6614 return false;
6617 return true;
6620 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6621 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6622 // range, then 0 is placed into the resulting vector. So pretty much any mask
6623 // of 8 elements can work here.
6624 return VT == MVT::v8i8 && M.size() == 8;
6627 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6628 unsigned Index) {
6629 if (Mask.size() == Elements * 2)
6630 return Index / Elements;
6631 return Mask[Index] == 0 ? 0 : 1;
6634 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6635 // checking that pairs of elements in the shuffle mask represent the same index
6636 // in each vector, incrementing the expected index by 2 at each step.
6637 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6638 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6639 // v2={e,f,g,h}
6640 // WhichResult gives the offset for each element in the mask based on which
6641 // of the two results it belongs to.
6643 // The transpose can be represented either as:
6644 // result1 = shufflevector v1, v2, result1_shuffle_mask
6645 // result2 = shufflevector v1, v2, result2_shuffle_mask
6646 // where v1/v2 and the shuffle masks have the same number of elements
6647 // (here WhichResult (see below) indicates which result is being checked)
6649 // or as:
6650 // results = shufflevector v1, v2, shuffle_mask
6651 // where both results are returned in one vector and the shuffle mask has twice
6652 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6653 // want to check the low half and high half of the shuffle mask as if it were
6654 // the other case
6655 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6656 unsigned EltSz = VT.getScalarSizeInBits();
6657 if (EltSz == 64)
6658 return false;
6660 unsigned NumElts = VT.getVectorNumElements();
6661 if (M.size() != NumElts && M.size() != NumElts*2)
6662 return false;
6664 // If the mask is twice as long as the input vector then we need to check the
6665 // upper and lower parts of the mask with a matching value for WhichResult
6666 // FIXME: A mask with only even values will be rejected in case the first
6667 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6668 // M[0] is used to determine WhichResult
6669 for (unsigned i = 0; i < M.size(); i += NumElts) {
6670 WhichResult = SelectPairHalf(NumElts, M, i);
6671 for (unsigned j = 0; j < NumElts; j += 2) {
6672 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6673 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6674 return false;
6678 if (M.size() == NumElts*2)
6679 WhichResult = 0;
6681 return true;
6684 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6685 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6686 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6687 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6688 unsigned EltSz = VT.getScalarSizeInBits();
6689 if (EltSz == 64)
6690 return false;
6692 unsigned NumElts = VT.getVectorNumElements();
6693 if (M.size() != NumElts && M.size() != NumElts*2)
6694 return false;
6696 for (unsigned i = 0; i < M.size(); i += NumElts) {
6697 WhichResult = SelectPairHalf(NumElts, M, i);
6698 for (unsigned j = 0; j < NumElts; j += 2) {
6699 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6700 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6701 return false;
6705 if (M.size() == NumElts*2)
6706 WhichResult = 0;
6708 return true;
6711 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6712 // that the mask elements are either all even and in steps of size 2 or all odd
6713 // and in steps of size 2.
6714 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6715 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6716 // v2={e,f,g,h}
6717 // Requires similar checks to that of isVTRNMask with
6718 // respect the how results are returned.
6719 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6720 unsigned EltSz = VT.getScalarSizeInBits();
6721 if (EltSz == 64)
6722 return false;
6724 unsigned NumElts = VT.getVectorNumElements();
6725 if (M.size() != NumElts && M.size() != NumElts*2)
6726 return false;
6728 for (unsigned i = 0; i < M.size(); i += NumElts) {
6729 WhichResult = SelectPairHalf(NumElts, M, i);
6730 for (unsigned j = 0; j < NumElts; ++j) {
6731 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6732 return false;
6736 if (M.size() == NumElts*2)
6737 WhichResult = 0;
6739 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6740 if (VT.is64BitVector() && EltSz == 32)
6741 return false;
6743 return true;
6746 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6747 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6748 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6749 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6750 unsigned EltSz = VT.getScalarSizeInBits();
6751 if (EltSz == 64)
6752 return false;
6754 unsigned NumElts = VT.getVectorNumElements();
6755 if (M.size() != NumElts && M.size() != NumElts*2)
6756 return false;
6758 unsigned Half = NumElts / 2;
6759 for (unsigned i = 0; i < M.size(); i += NumElts) {
6760 WhichResult = SelectPairHalf(NumElts, M, i);
6761 for (unsigned j = 0; j < NumElts; j += Half) {
6762 unsigned Idx = WhichResult;
6763 for (unsigned k = 0; k < Half; ++k) {
6764 int MIdx = M[i + j + k];
6765 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6766 return false;
6767 Idx += 2;
6772 if (M.size() == NumElts*2)
6773 WhichResult = 0;
6775 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6776 if (VT.is64BitVector() && EltSz == 32)
6777 return false;
6779 return true;
6782 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6783 // that pairs of elements of the shufflemask represent the same index in each
6784 // vector incrementing sequentially through the vectors.
6785 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6786 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6787 // v2={e,f,g,h}
6788 // Requires similar checks to that of isVTRNMask with respect the how results
6789 // are returned.
6790 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6791 unsigned EltSz = VT.getScalarSizeInBits();
6792 if (EltSz == 64)
6793 return false;
6795 unsigned NumElts = VT.getVectorNumElements();
6796 if (M.size() != NumElts && M.size() != NumElts*2)
6797 return false;
6799 for (unsigned i = 0; i < M.size(); i += NumElts) {
6800 WhichResult = SelectPairHalf(NumElts, M, i);
6801 unsigned Idx = WhichResult * NumElts / 2;
6802 for (unsigned j = 0; j < NumElts; j += 2) {
6803 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6804 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6805 return false;
6806 Idx += 1;
6810 if (M.size() == NumElts*2)
6811 WhichResult = 0;
6813 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6814 if (VT.is64BitVector() && EltSz == 32)
6815 return false;
6817 return true;
6820 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6821 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6822 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6823 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6824 unsigned EltSz = VT.getScalarSizeInBits();
6825 if (EltSz == 64)
6826 return false;
6828 unsigned NumElts = VT.getVectorNumElements();
6829 if (M.size() != NumElts && M.size() != NumElts*2)
6830 return false;
6832 for (unsigned i = 0; i < M.size(); i += NumElts) {
6833 WhichResult = SelectPairHalf(NumElts, M, i);
6834 unsigned Idx = WhichResult * NumElts / 2;
6835 for (unsigned j = 0; j < NumElts; j += 2) {
6836 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6837 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6838 return false;
6839 Idx += 1;
6843 if (M.size() == NumElts*2)
6844 WhichResult = 0;
6846 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6847 if (VT.is64BitVector() && EltSz == 32)
6848 return false;
6850 return true;
6853 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6854 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6855 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6856 unsigned &WhichResult,
6857 bool &isV_UNDEF) {
6858 isV_UNDEF = false;
6859 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6860 return ARMISD::VTRN;
6861 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6862 return ARMISD::VUZP;
6863 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6864 return ARMISD::VZIP;
6866 isV_UNDEF = true;
6867 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6868 return ARMISD::VTRN;
6869 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6870 return ARMISD::VUZP;
6871 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6872 return ARMISD::VZIP;
6874 return 0;
6877 /// \return true if this is a reverse operation on an vector.
6878 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6879 unsigned NumElts = VT.getVectorNumElements();
6880 // Make sure the mask has the right size.
6881 if (NumElts != M.size())
6882 return false;
6884 // Look for <15, ..., 3, -1, 1, 0>.
6885 for (unsigned i = 0; i != NumElts; ++i)
6886 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6887 return false;
6889 return true;
6892 // If N is an integer constant that can be moved into a register in one
6893 // instruction, return an SDValue of such a constant (will become a MOV
6894 // instruction). Otherwise return null.
6895 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6896 const ARMSubtarget *ST, const SDLoc &dl) {
6897 uint64_t Val;
6898 if (!isa<ConstantSDNode>(N))
6899 return SDValue();
6900 Val = cast<ConstantSDNode>(N)->getZExtValue();
6902 if (ST->isThumb1Only()) {
6903 if (Val <= 255 || ~Val <= 255)
6904 return DAG.getConstant(Val, dl, MVT::i32);
6905 } else {
6906 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6907 return DAG.getConstant(Val, dl, MVT::i32);
6909 return SDValue();
6912 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6913 const ARMSubtarget *ST) {
6914 SDLoc dl(Op);
6915 EVT VT = Op.getValueType();
6917 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6919 unsigned NumElts = VT.getVectorNumElements();
6920 unsigned BoolMask;
6921 unsigned BitsPerBool;
6922 if (NumElts == 4) {
6923 BitsPerBool = 4;
6924 BoolMask = 0xf;
6925 } else if (NumElts == 8) {
6926 BitsPerBool = 2;
6927 BoolMask = 0x3;
6928 } else if (NumElts == 16) {
6929 BitsPerBool = 1;
6930 BoolMask = 0x1;
6931 } else
6932 return SDValue();
6934 // First create base with bits set where known
6935 unsigned Bits32 = 0;
6936 for (unsigned i = 0; i < NumElts; ++i) {
6937 SDValue V = Op.getOperand(i);
6938 if (!isa<ConstantSDNode>(V) && !V.isUndef())
6939 continue;
6940 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
6941 if (BitSet)
6942 Bits32 |= BoolMask << (i * BitsPerBool);
6945 // Add in unknown nodes
6946 // FIXME: Handle splats of the same value better.
6947 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
6948 DAG.getConstant(Bits32, dl, MVT::i32));
6949 for (unsigned i = 0; i < NumElts; ++i) {
6950 SDValue V = Op.getOperand(i);
6951 if (isa<ConstantSDNode>(V) || V.isUndef())
6952 continue;
6953 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
6954 DAG.getConstant(i, dl, MVT::i32));
6957 return Base;
6960 // If this is a case we can't handle, return null and let the default
6961 // expansion code take care of it.
6962 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6963 const ARMSubtarget *ST) const {
6964 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6965 SDLoc dl(Op);
6966 EVT VT = Op.getValueType();
6968 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
6969 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
6971 APInt SplatBits, SplatUndef;
6972 unsigned SplatBitSize;
6973 bool HasAnyUndefs;
6974 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6975 if (SplatUndef.isAllOnesValue())
6976 return DAG.getUNDEF(VT);
6978 if ((ST->hasNEON() && SplatBitSize <= 64) ||
6979 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
6980 // Check if an immediate VMOV works.
6981 EVT VmovVT;
6982 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
6983 SplatUndef.getZExtValue(), SplatBitSize,
6984 DAG, dl, VmovVT, VT.is128BitVector(),
6985 VMOVModImm);
6987 if (Val.getNode()) {
6988 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6989 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6992 // Try an immediate VMVN.
6993 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6994 Val = isVMOVModifiedImm(
6995 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
6996 DAG, dl, VmovVT, VT.is128BitVector(),
6997 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
6998 if (Val.getNode()) {
6999 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7000 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7003 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7004 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7005 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7006 if (ImmVal != -1) {
7007 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7008 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7014 // Scan through the operands to see if only one value is used.
7016 // As an optimisation, even if more than one value is used it may be more
7017 // profitable to splat with one value then change some lanes.
7019 // Heuristically we decide to do this if the vector has a "dominant" value,
7020 // defined as splatted to more than half of the lanes.
7021 unsigned NumElts = VT.getVectorNumElements();
7022 bool isOnlyLowElement = true;
7023 bool usesOnlyOneValue = true;
7024 bool hasDominantValue = false;
7025 bool isConstant = true;
7027 // Map of the number of times a particular SDValue appears in the
7028 // element list.
7029 DenseMap<SDValue, unsigned> ValueCounts;
7030 SDValue Value;
7031 for (unsigned i = 0; i < NumElts; ++i) {
7032 SDValue V = Op.getOperand(i);
7033 if (V.isUndef())
7034 continue;
7035 if (i > 0)
7036 isOnlyLowElement = false;
7037 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7038 isConstant = false;
7040 ValueCounts.insert(std::make_pair(V, 0));
7041 unsigned &Count = ValueCounts[V];
7043 // Is this value dominant? (takes up more than half of the lanes)
7044 if (++Count > (NumElts / 2)) {
7045 hasDominantValue = true;
7046 Value = V;
7049 if (ValueCounts.size() != 1)
7050 usesOnlyOneValue = false;
7051 if (!Value.getNode() && !ValueCounts.empty())
7052 Value = ValueCounts.begin()->first;
7054 if (ValueCounts.empty())
7055 return DAG.getUNDEF(VT);
7057 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7058 // Keep going if we are hitting this case.
7059 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7060 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7062 unsigned EltSize = VT.getScalarSizeInBits();
7064 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7065 // i32 and try again.
7066 if (hasDominantValue && EltSize <= 32) {
7067 if (!isConstant) {
7068 SDValue N;
7070 // If we are VDUPing a value that comes directly from a vector, that will
7071 // cause an unnecessary move to and from a GPR, where instead we could
7072 // just use VDUPLANE. We can only do this if the lane being extracted
7073 // is at a constant index, as the VDUP from lane instructions only have
7074 // constant-index forms.
7075 ConstantSDNode *constIndex;
7076 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7077 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7078 // We need to create a new undef vector to use for the VDUPLANE if the
7079 // size of the vector from which we get the value is different than the
7080 // size of the vector that we need to create. We will insert the element
7081 // such that the register coalescer will remove unnecessary copies.
7082 if (VT != Value->getOperand(0).getValueType()) {
7083 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7084 VT.getVectorNumElements();
7085 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7086 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7087 Value, DAG.getConstant(index, dl, MVT::i32)),
7088 DAG.getConstant(index, dl, MVT::i32));
7089 } else
7090 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7091 Value->getOperand(0), Value->getOperand(1));
7092 } else
7093 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7095 if (!usesOnlyOneValue) {
7096 // The dominant value was splatted as 'N', but we now have to insert
7097 // all differing elements.
7098 for (unsigned I = 0; I < NumElts; ++I) {
7099 if (Op.getOperand(I) == Value)
7100 continue;
7101 SmallVector<SDValue, 3> Ops;
7102 Ops.push_back(N);
7103 Ops.push_back(Op.getOperand(I));
7104 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7105 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7108 return N;
7110 if (VT.getVectorElementType().isFloatingPoint()) {
7111 SmallVector<SDValue, 8> Ops;
7112 MVT FVT = VT.getVectorElementType().getSimpleVT();
7113 assert(FVT == MVT::f32 || FVT == MVT::f16);
7114 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7115 for (unsigned i = 0; i < NumElts; ++i)
7116 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7117 Op.getOperand(i)));
7118 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7119 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7120 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7121 if (Val.getNode())
7122 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7124 if (usesOnlyOneValue) {
7125 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7126 if (isConstant && Val.getNode())
7127 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7131 // If all elements are constants and the case above didn't get hit, fall back
7132 // to the default expansion, which will generate a load from the constant
7133 // pool.
7134 if (isConstant)
7135 return SDValue();
7137 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7138 if (NumElts >= 4) {
7139 SDValue shuffle = ReconstructShuffle(Op, DAG);
7140 if (shuffle != SDValue())
7141 return shuffle;
7144 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7145 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7146 // into two 64-bit vectors; we might discover a better way to lower it.
7147 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7148 EVT ExtVT = VT.getVectorElementType();
7149 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7150 SDValue Lower =
7151 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7152 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7153 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7154 SDValue Upper = DAG.getBuildVector(
7155 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7156 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7157 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7158 if (Lower && Upper)
7159 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7162 // Vectors with 32- or 64-bit elements can be built by directly assigning
7163 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7164 // will be legalized.
7165 if (EltSize >= 32) {
7166 // Do the expansion with floating-point types, since that is what the VFP
7167 // registers are defined to use, and since i64 is not legal.
7168 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7169 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7170 SmallVector<SDValue, 8> Ops;
7171 for (unsigned i = 0; i < NumElts; ++i)
7172 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7173 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7174 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7177 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7178 // know the default expansion would otherwise fall back on something even
7179 // worse. For a vector with one or two non-undef values, that's
7180 // scalar_to_vector for the elements followed by a shuffle (provided the
7181 // shuffle is valid for the target) and materialization element by element
7182 // on the stack followed by a load for everything else.
7183 if (!isConstant && !usesOnlyOneValue) {
7184 SDValue Vec = DAG.getUNDEF(VT);
7185 for (unsigned i = 0 ; i < NumElts; ++i) {
7186 SDValue V = Op.getOperand(i);
7187 if (V.isUndef())
7188 continue;
7189 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7190 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7192 return Vec;
7195 return SDValue();
7198 // Gather data to see if the operation can be modelled as a
7199 // shuffle in combination with VEXTs.
7200 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7201 SelectionDAG &DAG) const {
7202 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7203 SDLoc dl(Op);
7204 EVT VT = Op.getValueType();
7205 unsigned NumElts = VT.getVectorNumElements();
7207 struct ShuffleSourceInfo {
7208 SDValue Vec;
7209 unsigned MinElt = std::numeric_limits<unsigned>::max();
7210 unsigned MaxElt = 0;
7212 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7213 // be compatible with the shuffle we intend to construct. As a result
7214 // ShuffleVec will be some sliding window into the original Vec.
7215 SDValue ShuffleVec;
7217 // Code should guarantee that element i in Vec starts at element "WindowBase
7218 // + i * WindowScale in ShuffleVec".
7219 int WindowBase = 0;
7220 int WindowScale = 1;
7222 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7224 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7227 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7228 // node.
7229 SmallVector<ShuffleSourceInfo, 2> Sources;
7230 for (unsigned i = 0; i < NumElts; ++i) {
7231 SDValue V = Op.getOperand(i);
7232 if (V.isUndef())
7233 continue;
7234 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7235 // A shuffle can only come from building a vector from various
7236 // elements of other vectors.
7237 return SDValue();
7238 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7239 // Furthermore, shuffles require a constant mask, whereas extractelts
7240 // accept variable indices.
7241 return SDValue();
7244 // Add this element source to the list if it's not already there.
7245 SDValue SourceVec = V.getOperand(0);
7246 auto Source = llvm::find(Sources, SourceVec);
7247 if (Source == Sources.end())
7248 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7250 // Update the minimum and maximum lane number seen.
7251 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7252 Source->MinElt = std::min(Source->MinElt, EltNo);
7253 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7256 // Currently only do something sane when at most two source vectors
7257 // are involved.
7258 if (Sources.size() > 2)
7259 return SDValue();
7261 // Find out the smallest element size among result and two sources, and use
7262 // it as element size to build the shuffle_vector.
7263 EVT SmallestEltTy = VT.getVectorElementType();
7264 for (auto &Source : Sources) {
7265 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7266 if (SrcEltTy.bitsLT(SmallestEltTy))
7267 SmallestEltTy = SrcEltTy;
7269 unsigned ResMultiplier =
7270 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7271 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7272 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7274 // If the source vector is too wide or too narrow, we may nevertheless be able
7275 // to construct a compatible shuffle either by concatenating it with UNDEF or
7276 // extracting a suitable range of elements.
7277 for (auto &Src : Sources) {
7278 EVT SrcVT = Src.ShuffleVec.getValueType();
7280 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7281 continue;
7283 // This stage of the search produces a source with the same element type as
7284 // the original, but with a total width matching the BUILD_VECTOR output.
7285 EVT EltVT = SrcVT.getVectorElementType();
7286 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7287 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7289 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7290 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7291 return SDValue();
7292 // We can pad out the smaller vector for free, so if it's part of a
7293 // shuffle...
7294 Src.ShuffleVec =
7295 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7296 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7297 continue;
7300 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7301 return SDValue();
7303 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7304 // Span too large for a VEXT to cope
7305 return SDValue();
7308 if (Src.MinElt >= NumSrcElts) {
7309 // The extraction can just take the second half
7310 Src.ShuffleVec =
7311 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7312 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7313 Src.WindowBase = -NumSrcElts;
7314 } else if (Src.MaxElt < NumSrcElts) {
7315 // The extraction can just take the first half
7316 Src.ShuffleVec =
7317 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7318 DAG.getConstant(0, dl, MVT::i32));
7319 } else {
7320 // An actual VEXT is needed
7321 SDValue VEXTSrc1 =
7322 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7323 DAG.getConstant(0, dl, MVT::i32));
7324 SDValue VEXTSrc2 =
7325 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7326 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7328 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7329 VEXTSrc2,
7330 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7331 Src.WindowBase = -Src.MinElt;
7335 // Another possible incompatibility occurs from the vector element types. We
7336 // can fix this by bitcasting the source vectors to the same type we intend
7337 // for the shuffle.
7338 for (auto &Src : Sources) {
7339 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7340 if (SrcEltTy == SmallestEltTy)
7341 continue;
7342 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7343 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7344 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7345 Src.WindowBase *= Src.WindowScale;
7348 // Final sanity check before we try to actually produce a shuffle.
7349 LLVM_DEBUG(for (auto Src
7350 : Sources)
7351 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7353 // The stars all align, our next step is to produce the mask for the shuffle.
7354 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7355 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7356 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7357 SDValue Entry = Op.getOperand(i);
7358 if (Entry.isUndef())
7359 continue;
7361 auto Src = llvm::find(Sources, Entry.getOperand(0));
7362 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7364 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7365 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7366 // segment.
7367 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7368 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7369 VT.getScalarSizeInBits());
7370 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7372 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7373 // starting at the appropriate offset.
7374 int *LaneMask = &Mask[i * ResMultiplier];
7376 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7377 ExtractBase += NumElts * (Src - Sources.begin());
7378 for (int j = 0; j < LanesDefined; ++j)
7379 LaneMask[j] = ExtractBase + j;
7383 // We can't handle more than two sources. This should have already
7384 // been checked before this point.
7385 assert(Sources.size() <= 2 && "Too many sources!");
7387 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7388 for (unsigned i = 0; i < Sources.size(); ++i)
7389 ShuffleOps[i] = Sources[i].ShuffleVec;
7391 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7392 ShuffleOps[1], Mask, DAG);
7393 if (!Shuffle)
7394 return SDValue();
7395 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7398 enum ShuffleOpCodes {
7399 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7400 OP_VREV,
7401 OP_VDUP0,
7402 OP_VDUP1,
7403 OP_VDUP2,
7404 OP_VDUP3,
7405 OP_VEXT1,
7406 OP_VEXT2,
7407 OP_VEXT3,
7408 OP_VUZPL, // VUZP, left result
7409 OP_VUZPR, // VUZP, right result
7410 OP_VZIPL, // VZIP, left result
7411 OP_VZIPR, // VZIP, right result
7412 OP_VTRNL, // VTRN, left result
7413 OP_VTRNR // VTRN, right result
7416 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7417 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7418 switch (OpNum) {
7419 case OP_COPY:
7420 case OP_VREV:
7421 case OP_VDUP0:
7422 case OP_VDUP1:
7423 case OP_VDUP2:
7424 case OP_VDUP3:
7425 return true;
7427 return false;
7430 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7431 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7432 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7433 /// are assumed to be legal.
7434 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7435 if (VT.getVectorNumElements() == 4 &&
7436 (VT.is128BitVector() || VT.is64BitVector())) {
7437 unsigned PFIndexes[4];
7438 for (unsigned i = 0; i != 4; ++i) {
7439 if (M[i] < 0)
7440 PFIndexes[i] = 8;
7441 else
7442 PFIndexes[i] = M[i];
7445 // Compute the index in the perfect shuffle table.
7446 unsigned PFTableIndex =
7447 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7448 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7449 unsigned Cost = (PFEntry >> 30);
7451 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7452 return true;
7455 bool ReverseVEXT, isV_UNDEF;
7456 unsigned Imm, WhichResult;
7458 unsigned EltSize = VT.getScalarSizeInBits();
7459 if (EltSize >= 32 ||
7460 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7461 isVREVMask(M, VT, 64) ||
7462 isVREVMask(M, VT, 32) ||
7463 isVREVMask(M, VT, 16))
7464 return true;
7465 else if (Subtarget->hasNEON() &&
7466 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7467 isVTBLMask(M, VT) ||
7468 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7469 return true;
7470 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7471 isReverseMask(M, VT))
7472 return true;
7473 else
7474 return false;
7477 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7478 /// the specified operations to build the shuffle.
7479 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7480 SDValue RHS, SelectionDAG &DAG,
7481 const SDLoc &dl) {
7482 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7483 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7484 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7486 if (OpNum == OP_COPY) {
7487 if (LHSID == (1*9+2)*9+3) return LHS;
7488 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7489 return RHS;
7492 SDValue OpLHS, OpRHS;
7493 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7494 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7495 EVT VT = OpLHS.getValueType();
7497 switch (OpNum) {
7498 default: llvm_unreachable("Unknown shuffle opcode!");
7499 case OP_VREV:
7500 // VREV divides the vector in half and swaps within the half.
7501 if (VT.getVectorElementType() == MVT::i32 ||
7502 VT.getVectorElementType() == MVT::f32)
7503 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7504 // vrev <4 x i16> -> VREV32
7505 if (VT.getVectorElementType() == MVT::i16)
7506 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7507 // vrev <4 x i8> -> VREV16
7508 assert(VT.getVectorElementType() == MVT::i8);
7509 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7510 case OP_VDUP0:
7511 case OP_VDUP1:
7512 case OP_VDUP2:
7513 case OP_VDUP3:
7514 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7515 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7516 case OP_VEXT1:
7517 case OP_VEXT2:
7518 case OP_VEXT3:
7519 return DAG.getNode(ARMISD::VEXT, dl, VT,
7520 OpLHS, OpRHS,
7521 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7522 case OP_VUZPL:
7523 case OP_VUZPR:
7524 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7525 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7526 case OP_VZIPL:
7527 case OP_VZIPR:
7528 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7529 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7530 case OP_VTRNL:
7531 case OP_VTRNR:
7532 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7533 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7537 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7538 ArrayRef<int> ShuffleMask,
7539 SelectionDAG &DAG) {
7540 // Check to see if we can use the VTBL instruction.
7541 SDValue V1 = Op.getOperand(0);
7542 SDValue V2 = Op.getOperand(1);
7543 SDLoc DL(Op);
7545 SmallVector<SDValue, 8> VTBLMask;
7546 for (ArrayRef<int>::iterator
7547 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7548 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7550 if (V2.getNode()->isUndef())
7551 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7552 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7554 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7555 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7558 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7559 SelectionDAG &DAG) {
7560 SDLoc DL(Op);
7561 SDValue OpLHS = Op.getOperand(0);
7562 EVT VT = OpLHS.getValueType();
7564 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7565 "Expect an v8i16/v16i8 type");
7566 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7567 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7568 // extract the first 8 bytes into the top double word and the last 8 bytes
7569 // into the bottom double word. The v8i16 case is similar.
7570 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7571 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7572 DAG.getConstant(ExtractNum, DL, MVT::i32));
7575 static EVT getVectorTyFromPredicateVector(EVT VT) {
7576 switch (VT.getSimpleVT().SimpleTy) {
7577 case MVT::v4i1:
7578 return MVT::v4i32;
7579 case MVT::v8i1:
7580 return MVT::v8i16;
7581 case MVT::v16i1:
7582 return MVT::v16i8;
7583 default:
7584 llvm_unreachable("Unexpected vector predicate type");
7588 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7589 SelectionDAG &DAG) {
7590 // Converting from boolean predicates to integers involves creating a vector
7591 // of all ones or all zeroes and selecting the lanes based upon the real
7592 // predicate.
7593 SDValue AllOnes =
7594 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7595 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7597 SDValue AllZeroes =
7598 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7599 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7601 // Get full vector type from predicate type
7602 EVT NewVT = getVectorTyFromPredicateVector(VT);
7604 SDValue RecastV1;
7605 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7606 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7607 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7608 // since we know in hardware the sizes are really the same.
7609 if (VT != MVT::v16i1)
7610 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7611 else
7612 RecastV1 = Pred;
7614 // Select either all ones or zeroes depending upon the real predicate bits.
7615 SDValue PredAsVector =
7616 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7618 // Recast our new predicate-as-integer v16i8 vector into something
7619 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7620 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7623 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7624 const ARMSubtarget *ST) {
7625 EVT VT = Op.getValueType();
7626 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7627 ArrayRef<int> ShuffleMask = SVN->getMask();
7629 assert(ST->hasMVEIntegerOps() &&
7630 "No support for vector shuffle of boolean predicates");
7632 SDValue V1 = Op.getOperand(0);
7633 SDLoc dl(Op);
7634 if (isReverseMask(ShuffleMask, VT)) {
7635 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7636 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7637 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7638 DAG.getConstant(16, dl, MVT::i32));
7639 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7642 // Until we can come up with optimised cases for every single vector
7643 // shuffle in existence we have chosen the least painful strategy. This is
7644 // to essentially promote the boolean predicate to a 8-bit integer, where
7645 // each predicate represents a byte. Then we fall back on a normal integer
7646 // vector shuffle and convert the result back into a predicate vector. In
7647 // many cases the generated code might be even better than scalar code
7648 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7649 // fields in a register into 8 other arbitrary 2-bit fields!
7650 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7651 EVT NewVT = PredAsVector.getValueType();
7653 // Do the shuffle!
7654 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7655 DAG.getUNDEF(NewVT), ShuffleMask);
7657 // Now return the result of comparing the shuffled vector with zero,
7658 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7659 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7660 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7663 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7664 const ARMSubtarget *ST) {
7665 SDValue V1 = Op.getOperand(0);
7666 SDValue V2 = Op.getOperand(1);
7667 SDLoc dl(Op);
7668 EVT VT = Op.getValueType();
7669 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7670 unsigned EltSize = VT.getScalarSizeInBits();
7672 if (ST->hasMVEIntegerOps() && EltSize == 1)
7673 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7675 // Convert shuffles that are directly supported on NEON to target-specific
7676 // DAG nodes, instead of keeping them as shuffles and matching them again
7677 // during code selection. This is more efficient and avoids the possibility
7678 // of inconsistencies between legalization and selection.
7679 // FIXME: floating-point vectors should be canonicalized to integer vectors
7680 // of the same time so that they get CSEd properly.
7681 ArrayRef<int> ShuffleMask = SVN->getMask();
7683 if (EltSize <= 32) {
7684 if (SVN->isSplat()) {
7685 int Lane = SVN->getSplatIndex();
7686 // If this is undef splat, generate it via "just" vdup, if possible.
7687 if (Lane == -1) Lane = 0;
7689 // Test if V1 is a SCALAR_TO_VECTOR.
7690 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7691 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7693 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7694 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7695 // reaches it).
7696 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7697 !isa<ConstantSDNode>(V1.getOperand(0))) {
7698 bool IsScalarToVector = true;
7699 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7700 if (!V1.getOperand(i).isUndef()) {
7701 IsScalarToVector = false;
7702 break;
7704 if (IsScalarToVector)
7705 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7707 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7708 DAG.getConstant(Lane, dl, MVT::i32));
7711 bool ReverseVEXT = false;
7712 unsigned Imm = 0;
7713 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7714 if (ReverseVEXT)
7715 std::swap(V1, V2);
7716 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7717 DAG.getConstant(Imm, dl, MVT::i32));
7720 if (isVREVMask(ShuffleMask, VT, 64))
7721 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7722 if (isVREVMask(ShuffleMask, VT, 32))
7723 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7724 if (isVREVMask(ShuffleMask, VT, 16))
7725 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7727 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7728 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7729 DAG.getConstant(Imm, dl, MVT::i32));
7732 // Check for Neon shuffles that modify both input vectors in place.
7733 // If both results are used, i.e., if there are two shuffles with the same
7734 // source operands and with masks corresponding to both results of one of
7735 // these operations, DAG memoization will ensure that a single node is
7736 // used for both shuffles.
7737 unsigned WhichResult = 0;
7738 bool isV_UNDEF = false;
7739 if (ST->hasNEON()) {
7740 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7741 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7742 if (isV_UNDEF)
7743 V2 = V1;
7744 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7745 .getValue(WhichResult);
7749 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7750 // shuffles that produce a result larger than their operands with:
7751 // shuffle(concat(v1, undef), concat(v2, undef))
7752 // ->
7753 // shuffle(concat(v1, v2), undef)
7754 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7756 // This is useful in the general case, but there are special cases where
7757 // native shuffles produce larger results: the two-result ops.
7759 // Look through the concat when lowering them:
7760 // shuffle(concat(v1, v2), undef)
7761 // ->
7762 // concat(VZIP(v1, v2):0, :1)
7764 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7765 SDValue SubV1 = V1->getOperand(0);
7766 SDValue SubV2 = V1->getOperand(1);
7767 EVT SubVT = SubV1.getValueType();
7769 // We expect these to have been canonicalized to -1.
7770 assert(llvm::all_of(ShuffleMask, [&](int i) {
7771 return i < (int)VT.getVectorNumElements();
7772 }) && "Unexpected shuffle index into UNDEF operand!");
7774 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7775 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7776 if (isV_UNDEF)
7777 SubV2 = SubV1;
7778 assert((WhichResult == 0) &&
7779 "In-place shuffle of concat can only have one result!");
7780 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7781 SubV1, SubV2);
7782 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7783 Res.getValue(1));
7788 // If the shuffle is not directly supported and it has 4 elements, use
7789 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7790 unsigned NumElts = VT.getVectorNumElements();
7791 if (NumElts == 4) {
7792 unsigned PFIndexes[4];
7793 for (unsigned i = 0; i != 4; ++i) {
7794 if (ShuffleMask[i] < 0)
7795 PFIndexes[i] = 8;
7796 else
7797 PFIndexes[i] = ShuffleMask[i];
7800 // Compute the index in the perfect shuffle table.
7801 unsigned PFTableIndex =
7802 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7803 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7804 unsigned Cost = (PFEntry >> 30);
7806 if (Cost <= 4) {
7807 if (ST->hasNEON())
7808 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7809 else if (isLegalMVEShuffleOp(PFEntry)) {
7810 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7811 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7812 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7813 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7814 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7815 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7820 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7821 if (EltSize >= 32) {
7822 // Do the expansion with floating-point types, since that is what the VFP
7823 // registers are defined to use, and since i64 is not legal.
7824 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7825 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7826 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7827 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7828 SmallVector<SDValue, 8> Ops;
7829 for (unsigned i = 0; i < NumElts; ++i) {
7830 if (ShuffleMask[i] < 0)
7831 Ops.push_back(DAG.getUNDEF(EltVT));
7832 else
7833 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7834 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7835 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7836 dl, MVT::i32)));
7838 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7839 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7842 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7843 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7845 if (ST->hasNEON() && VT == MVT::v8i8)
7846 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7847 return NewOp;
7849 return SDValue();
7852 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7853 const ARMSubtarget *ST) {
7854 EVT VecVT = Op.getOperand(0).getValueType();
7855 SDLoc dl(Op);
7857 assert(ST->hasMVEIntegerOps() &&
7858 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7860 SDValue Conv =
7861 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7862 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7863 unsigned LaneWidth =
7864 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7865 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7866 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7867 Op.getOperand(1), DAG.getValueType(MVT::i1));
7868 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7869 DAG.getConstant(~Mask, dl, MVT::i32));
7870 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7873 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7874 SelectionDAG &DAG) const {
7875 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7876 SDValue Lane = Op.getOperand(2);
7877 if (!isa<ConstantSDNode>(Lane))
7878 return SDValue();
7880 SDValue Elt = Op.getOperand(1);
7881 EVT EltVT = Elt.getValueType();
7883 if (Subtarget->hasMVEIntegerOps() &&
7884 Op.getValueType().getScalarSizeInBits() == 1)
7885 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7887 if (getTypeAction(*DAG.getContext(), EltVT) ==
7888 TargetLowering::TypePromoteFloat) {
7889 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7890 // but the type system will try to do that if we don't intervene.
7891 // Reinterpret any such vector-element insertion as one with the
7892 // corresponding integer types.
7894 SDLoc dl(Op);
7896 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7897 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7898 TargetLowering::TypePromoteFloat);
7900 SDValue VecIn = Op.getOperand(0);
7901 EVT VecVT = VecIn.getValueType();
7902 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7903 VecVT.getVectorNumElements());
7905 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7906 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7907 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7908 IVecIn, IElt, Lane);
7909 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
7912 return Op;
7915 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7916 const ARMSubtarget *ST) {
7917 EVT VecVT = Op.getOperand(0).getValueType();
7918 SDLoc dl(Op);
7920 assert(ST->hasMVEIntegerOps() &&
7921 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7923 SDValue Conv =
7924 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7925 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7926 unsigned LaneWidth =
7927 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7928 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
7929 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
7930 return Shift;
7933 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
7934 const ARMSubtarget *ST) {
7935 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7936 SDValue Lane = Op.getOperand(1);
7937 if (!isa<ConstantSDNode>(Lane))
7938 return SDValue();
7940 SDValue Vec = Op.getOperand(0);
7941 EVT VT = Vec.getValueType();
7943 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7944 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
7946 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7947 SDLoc dl(Op);
7948 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7951 return Op;
7954 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
7955 const ARMSubtarget *ST) {
7956 SDValue V1 = Op.getOperand(0);
7957 SDValue V2 = Op.getOperand(1);
7958 SDLoc dl(Op);
7959 EVT VT = Op.getValueType();
7960 EVT Op1VT = V1.getValueType();
7961 EVT Op2VT = V2.getValueType();
7962 unsigned NumElts = VT.getVectorNumElements();
7964 assert(Op1VT == Op2VT && "Operand types don't match!");
7965 assert(VT.getScalarSizeInBits() == 1 &&
7966 "Unexpected custom CONCAT_VECTORS lowering");
7967 assert(ST->hasMVEIntegerOps() &&
7968 "CONCAT_VECTORS lowering only supported for MVE");
7970 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7971 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
7973 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
7974 // promoted to v8i16, etc.
7976 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7978 // Extract the vector elements from Op1 and Op2 one by one and truncate them
7979 // to be the right size for the destination. For example, if Op1 is v4i1 then
7980 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
7981 // which when promoted is v8i16. That means each i32 element from Op1 needs
7982 // truncating to i16 and inserting in the result.
7983 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
7984 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
7985 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
7986 EVT NewVT = NewV.getValueType();
7987 EVT ConcatVT = ConVec.getValueType();
7988 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
7989 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
7990 DAG.getIntPtrConstant(i, dl));
7991 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
7992 DAG.getConstant(j, dl, MVT::i32));
7994 return ConVec;
7996 unsigned j = 0;
7997 ConVec = ExractInto(NewV1, ConVec, j);
7998 ConVec = ExractInto(NewV2, ConVec, j);
8000 // Now return the result of comparing the subvector with zero,
8001 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8002 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8003 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8006 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8007 const ARMSubtarget *ST) {
8008 EVT VT = Op->getValueType(0);
8009 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8010 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8012 // The only time a CONCAT_VECTORS operation can have legal types is when
8013 // two 64-bit vectors are concatenated to a 128-bit vector.
8014 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8015 "unexpected CONCAT_VECTORS");
8016 SDLoc dl(Op);
8017 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8018 SDValue Op0 = Op.getOperand(0);
8019 SDValue Op1 = Op.getOperand(1);
8020 if (!Op0.isUndef())
8021 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8022 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8023 DAG.getIntPtrConstant(0, dl));
8024 if (!Op1.isUndef())
8025 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8026 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8027 DAG.getIntPtrConstant(1, dl));
8028 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8031 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8032 const ARMSubtarget *ST) {
8033 SDValue V1 = Op.getOperand(0);
8034 SDValue V2 = Op.getOperand(1);
8035 SDLoc dl(Op);
8036 EVT VT = Op.getValueType();
8037 EVT Op1VT = V1.getValueType();
8038 unsigned NumElts = VT.getVectorNumElements();
8039 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8041 assert(VT.getScalarSizeInBits() == 1 &&
8042 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8043 assert(ST->hasMVEIntegerOps() &&
8044 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8046 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8048 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8049 // promoted to v8i16, etc.
8051 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8053 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8054 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8055 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8056 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8057 DAG.getIntPtrConstant(i, dl));
8058 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8059 DAG.getConstant(j, dl, MVT::i32));
8062 // Now return the result of comparing the subvector with zero,
8063 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8064 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8065 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8068 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8069 /// element has been zero/sign-extended, depending on the isSigned parameter,
8070 /// from an integer type half its size.
8071 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8072 bool isSigned) {
8073 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8074 EVT VT = N->getValueType(0);
8075 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8076 SDNode *BVN = N->getOperand(0).getNode();
8077 if (BVN->getValueType(0) != MVT::v4i32 ||
8078 BVN->getOpcode() != ISD::BUILD_VECTOR)
8079 return false;
8080 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8081 unsigned HiElt = 1 - LoElt;
8082 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8083 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8084 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8085 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8086 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8087 return false;
8088 if (isSigned) {
8089 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8090 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8091 return true;
8092 } else {
8093 if (Hi0->isNullValue() && Hi1->isNullValue())
8094 return true;
8096 return false;
8099 if (N->getOpcode() != ISD::BUILD_VECTOR)
8100 return false;
8102 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8103 SDNode *Elt = N->getOperand(i).getNode();
8104 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8105 unsigned EltSize = VT.getScalarSizeInBits();
8106 unsigned HalfSize = EltSize / 2;
8107 if (isSigned) {
8108 if (!isIntN(HalfSize, C->getSExtValue()))
8109 return false;
8110 } else {
8111 if (!isUIntN(HalfSize, C->getZExtValue()))
8112 return false;
8114 continue;
8116 return false;
8119 return true;
8122 /// isSignExtended - Check if a node is a vector value that is sign-extended
8123 /// or a constant BUILD_VECTOR with sign-extended elements.
8124 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8125 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8126 return true;
8127 if (isExtendedBUILD_VECTOR(N, DAG, true))
8128 return true;
8129 return false;
8132 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8133 /// or a constant BUILD_VECTOR with zero-extended elements.
8134 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8135 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8136 return true;
8137 if (isExtendedBUILD_VECTOR(N, DAG, false))
8138 return true;
8139 return false;
8142 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8143 if (OrigVT.getSizeInBits() >= 64)
8144 return OrigVT;
8146 assert(OrigVT.isSimple() && "Expecting a simple value type");
8148 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8149 switch (OrigSimpleTy) {
8150 default: llvm_unreachable("Unexpected Vector Type");
8151 case MVT::v2i8:
8152 case MVT::v2i16:
8153 return MVT::v2i32;
8154 case MVT::v4i8:
8155 return MVT::v4i16;
8159 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8160 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8161 /// We insert the required extension here to get the vector to fill a D register.
8162 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8163 const EVT &OrigTy,
8164 const EVT &ExtTy,
8165 unsigned ExtOpcode) {
8166 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8167 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8168 // 64-bits we need to insert a new extension so that it will be 64-bits.
8169 assert(ExtTy.is128BitVector() && "Unexpected extension size");
8170 if (OrigTy.getSizeInBits() >= 64)
8171 return N;
8173 // Must extend size to at least 64 bits to be used as an operand for VMULL.
8174 EVT NewVT = getExtensionTo64Bits(OrigTy);
8176 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8179 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8180 /// does not do any sign/zero extension. If the original vector is less
8181 /// than 64 bits, an appropriate extension will be added after the load to
8182 /// reach a total size of 64 bits. We have to add the extension separately
8183 /// because ARM does not have a sign/zero extending load for vectors.
8184 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8185 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8187 // The load already has the right type.
8188 if (ExtendedTy == LD->getMemoryVT())
8189 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8190 LD->getBasePtr(), LD->getPointerInfo(),
8191 LD->getAlignment(), LD->getMemOperand()->getFlags());
8193 // We need to create a zextload/sextload. We cannot just create a load
8194 // followed by a zext/zext node because LowerMUL is also run during normal
8195 // operation legalization where we can't create illegal types.
8196 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8197 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8198 LD->getMemoryVT(), LD->getAlignment(),
8199 LD->getMemOperand()->getFlags());
8202 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8203 /// extending load, or BUILD_VECTOR with extended elements, return the
8204 /// unextended value. The unextended vector should be 64 bits so that it can
8205 /// be used as an operand to a VMULL instruction. If the original vector size
8206 /// before extension is less than 64 bits we add a an extension to resize
8207 /// the vector to 64 bits.
8208 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8209 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8210 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8211 N->getOperand(0)->getValueType(0),
8212 N->getValueType(0),
8213 N->getOpcode());
8215 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8216 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8217 "Expected extending load");
8219 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8220 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8221 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8222 SDValue extLoad =
8223 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8224 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8226 return newLoad;
8229 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8230 // have been legalized as a BITCAST from v4i32.
8231 if (N->getOpcode() == ISD::BITCAST) {
8232 SDNode *BVN = N->getOperand(0).getNode();
8233 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8234 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8235 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8236 return DAG.getBuildVector(
8237 MVT::v2i32, SDLoc(N),
8238 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8240 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8241 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8242 EVT VT = N->getValueType(0);
8243 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8244 unsigned NumElts = VT.getVectorNumElements();
8245 MVT TruncVT = MVT::getIntegerVT(EltSize);
8246 SmallVector<SDValue, 8> Ops;
8247 SDLoc dl(N);
8248 for (unsigned i = 0; i != NumElts; ++i) {
8249 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8250 const APInt &CInt = C->getAPIntValue();
8251 // Element types smaller than 32 bits are not legal, so use i32 elements.
8252 // The values are implicitly truncated so sext vs. zext doesn't matter.
8253 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8255 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8258 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8259 unsigned Opcode = N->getOpcode();
8260 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8261 SDNode *N0 = N->getOperand(0).getNode();
8262 SDNode *N1 = N->getOperand(1).getNode();
8263 return N0->hasOneUse() && N1->hasOneUse() &&
8264 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8266 return false;
8269 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8270 unsigned Opcode = N->getOpcode();
8271 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8272 SDNode *N0 = N->getOperand(0).getNode();
8273 SDNode *N1 = N->getOperand(1).getNode();
8274 return N0->hasOneUse() && N1->hasOneUse() &&
8275 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8277 return false;
8280 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8281 // Multiplications are only custom-lowered for 128-bit vectors so that
8282 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8283 EVT VT = Op.getValueType();
8284 assert(VT.is128BitVector() && VT.isInteger() &&
8285 "unexpected type for custom-lowering ISD::MUL");
8286 SDNode *N0 = Op.getOperand(0).getNode();
8287 SDNode *N1 = Op.getOperand(1).getNode();
8288 unsigned NewOpc = 0;
8289 bool isMLA = false;
8290 bool isN0SExt = isSignExtended(N0, DAG);
8291 bool isN1SExt = isSignExtended(N1, DAG);
8292 if (isN0SExt && isN1SExt)
8293 NewOpc = ARMISD::VMULLs;
8294 else {
8295 bool isN0ZExt = isZeroExtended(N0, DAG);
8296 bool isN1ZExt = isZeroExtended(N1, DAG);
8297 if (isN0ZExt && isN1ZExt)
8298 NewOpc = ARMISD::VMULLu;
8299 else if (isN1SExt || isN1ZExt) {
8300 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8301 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8302 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8303 NewOpc = ARMISD::VMULLs;
8304 isMLA = true;
8305 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8306 NewOpc = ARMISD::VMULLu;
8307 isMLA = true;
8308 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8309 std::swap(N0, N1);
8310 NewOpc = ARMISD::VMULLu;
8311 isMLA = true;
8315 if (!NewOpc) {
8316 if (VT == MVT::v2i64)
8317 // Fall through to expand this. It is not legal.
8318 return SDValue();
8319 else
8320 // Other vector multiplications are legal.
8321 return Op;
8325 // Legalize to a VMULL instruction.
8326 SDLoc DL(Op);
8327 SDValue Op0;
8328 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8329 if (!isMLA) {
8330 Op0 = SkipExtensionForVMULL(N0, DAG);
8331 assert(Op0.getValueType().is64BitVector() &&
8332 Op1.getValueType().is64BitVector() &&
8333 "unexpected types for extended operands to VMULL");
8334 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8337 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8338 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8339 // vmull q0, d4, d6
8340 // vmlal q0, d5, d6
8341 // is faster than
8342 // vaddl q0, d4, d5
8343 // vmovl q1, d6
8344 // vmul q0, q0, q1
8345 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8346 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8347 EVT Op1VT = Op1.getValueType();
8348 return DAG.getNode(N0->getOpcode(), DL, VT,
8349 DAG.getNode(NewOpc, DL, VT,
8350 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8351 DAG.getNode(NewOpc, DL, VT,
8352 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8355 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8356 SelectionDAG &DAG) {
8357 // TODO: Should this propagate fast-math-flags?
8359 // Convert to float
8360 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8361 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8362 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8363 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8364 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8365 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8366 // Get reciprocal estimate.
8367 // float4 recip = vrecpeq_f32(yf);
8368 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8369 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8371 // Because char has a smaller range than uchar, we can actually get away
8372 // without any newton steps. This requires that we use a weird bias
8373 // of 0xb000, however (again, this has been exhaustively tested).
8374 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8375 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8376 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8377 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8378 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8379 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8380 // Convert back to short.
8381 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8382 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8383 return X;
8386 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8387 SelectionDAG &DAG) {
8388 // TODO: Should this propagate fast-math-flags?
8390 SDValue N2;
8391 // Convert to float.
8392 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8393 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8394 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8395 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8396 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8397 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8399 // Use reciprocal estimate and one refinement step.
8400 // float4 recip = vrecpeq_f32(yf);
8401 // recip *= vrecpsq_f32(yf, recip);
8402 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8403 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8404 N1);
8405 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8406 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8407 N1, N2);
8408 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8409 // Because short has a smaller range than ushort, we can actually get away
8410 // with only a single newton step. This requires that we use a weird bias
8411 // of 89, however (again, this has been exhaustively tested).
8412 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8413 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8414 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8415 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8416 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8417 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8418 // Convert back to integer and return.
8419 // return vmovn_s32(vcvt_s32_f32(result));
8420 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8421 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8422 return N0;
8425 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8426 const ARMSubtarget *ST) {
8427 EVT VT = Op.getValueType();
8428 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8429 "unexpected type for custom-lowering ISD::SDIV");
8431 SDLoc dl(Op);
8432 SDValue N0 = Op.getOperand(0);
8433 SDValue N1 = Op.getOperand(1);
8434 SDValue N2, N3;
8436 if (VT == MVT::v8i8) {
8437 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8438 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8440 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8441 DAG.getIntPtrConstant(4, dl));
8442 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8443 DAG.getIntPtrConstant(4, dl));
8444 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8445 DAG.getIntPtrConstant(0, dl));
8446 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8447 DAG.getIntPtrConstant(0, dl));
8449 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8450 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8452 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8453 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8455 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8456 return N0;
8458 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8461 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8462 const ARMSubtarget *ST) {
8463 // TODO: Should this propagate fast-math-flags?
8464 EVT VT = Op.getValueType();
8465 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8466 "unexpected type for custom-lowering ISD::UDIV");
8468 SDLoc dl(Op);
8469 SDValue N0 = Op.getOperand(0);
8470 SDValue N1 = Op.getOperand(1);
8471 SDValue N2, N3;
8473 if (VT == MVT::v8i8) {
8474 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8475 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8477 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8478 DAG.getIntPtrConstant(4, dl));
8479 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8480 DAG.getIntPtrConstant(4, dl));
8481 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8482 DAG.getIntPtrConstant(0, dl));
8483 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8484 DAG.getIntPtrConstant(0, dl));
8486 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8487 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8489 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8490 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8492 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8493 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8494 MVT::i32),
8495 N0);
8496 return N0;
8499 // v4i16 sdiv ... Convert to float.
8500 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8501 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8502 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8503 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8504 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8505 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8507 // Use reciprocal estimate and two refinement steps.
8508 // float4 recip = vrecpeq_f32(yf);
8509 // recip *= vrecpsq_f32(yf, recip);
8510 // recip *= vrecpsq_f32(yf, recip);
8511 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8512 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8513 BN1);
8514 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8515 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8516 BN1, N2);
8517 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8518 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8519 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8520 BN1, N2);
8521 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8522 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8523 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8524 // and that it will never cause us to return an answer too large).
8525 // float4 result = as_float4(as_int4(xf*recip) + 2);
8526 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8527 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8528 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8529 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8530 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8531 // Convert back to integer and return.
8532 // return vmovn_u32(vcvt_s32_f32(result));
8533 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8534 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8535 return N0;
8538 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8539 SDNode *N = Op.getNode();
8540 EVT VT = N->getValueType(0);
8541 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8543 SDValue Carry = Op.getOperand(2);
8545 SDLoc DL(Op);
8547 SDValue Result;
8548 if (Op.getOpcode() == ISD::ADDCARRY) {
8549 // This converts the boolean value carry into the carry flag.
8550 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8552 // Do the addition proper using the carry flag we wanted.
8553 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8554 Op.getOperand(1), Carry);
8556 // Now convert the carry flag into a boolean value.
8557 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8558 } else {
8559 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8560 // have to invert the carry first.
8561 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8562 DAG.getConstant(1, DL, MVT::i32), Carry);
8563 // This converts the boolean value carry into the carry flag.
8564 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8566 // Do the subtraction proper using the carry flag we wanted.
8567 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8568 Op.getOperand(1), Carry);
8570 // Now convert the carry flag into a boolean value.
8571 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8572 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8573 // by ISD::SUBCARRY, so compute 1 - C.
8574 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8575 DAG.getConstant(1, DL, MVT::i32), Carry);
8578 // Return both values.
8579 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8582 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8583 assert(Subtarget->isTargetDarwin());
8585 // For iOS, we want to call an alternative entry point: __sincos_stret,
8586 // return values are passed via sret.
8587 SDLoc dl(Op);
8588 SDValue Arg = Op.getOperand(0);
8589 EVT ArgVT = Arg.getValueType();
8590 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8591 auto PtrVT = getPointerTy(DAG.getDataLayout());
8593 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8594 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8596 // Pair of floats / doubles used to pass the result.
8597 Type *RetTy = StructType::get(ArgTy, ArgTy);
8598 auto &DL = DAG.getDataLayout();
8600 ArgListTy Args;
8601 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8602 SDValue SRet;
8603 if (ShouldUseSRet) {
8604 // Create stack object for sret.
8605 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8606 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8607 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8608 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8610 ArgListEntry Entry;
8611 Entry.Node = SRet;
8612 Entry.Ty = RetTy->getPointerTo();
8613 Entry.IsSExt = false;
8614 Entry.IsZExt = false;
8615 Entry.IsSRet = true;
8616 Args.push_back(Entry);
8617 RetTy = Type::getVoidTy(*DAG.getContext());
8620 ArgListEntry Entry;
8621 Entry.Node = Arg;
8622 Entry.Ty = ArgTy;
8623 Entry.IsSExt = false;
8624 Entry.IsZExt = false;
8625 Args.push_back(Entry);
8627 RTLIB::Libcall LC =
8628 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8629 const char *LibcallName = getLibcallName(LC);
8630 CallingConv::ID CC = getLibcallCallingConv(LC);
8631 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8633 TargetLowering::CallLoweringInfo CLI(DAG);
8634 CLI.setDebugLoc(dl)
8635 .setChain(DAG.getEntryNode())
8636 .setCallee(CC, RetTy, Callee, std::move(Args))
8637 .setDiscardResult(ShouldUseSRet);
8638 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8640 if (!ShouldUseSRet)
8641 return CallResult.first;
8643 SDValue LoadSin =
8644 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8646 // Address of cos field.
8647 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8648 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8649 SDValue LoadCos =
8650 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8652 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8653 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8654 LoadSin.getValue(0), LoadCos.getValue(0));
8657 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8658 bool Signed,
8659 SDValue &Chain) const {
8660 EVT VT = Op.getValueType();
8661 assert((VT == MVT::i32 || VT == MVT::i64) &&
8662 "unexpected type for custom lowering DIV");
8663 SDLoc dl(Op);
8665 const auto &DL = DAG.getDataLayout();
8666 const auto &TLI = DAG.getTargetLoweringInfo();
8668 const char *Name = nullptr;
8669 if (Signed)
8670 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8671 else
8672 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8674 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8676 ARMTargetLowering::ArgListTy Args;
8678 for (auto AI : {1, 0}) {
8679 ArgListEntry Arg;
8680 Arg.Node = Op.getOperand(AI);
8681 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8682 Args.push_back(Arg);
8685 CallLoweringInfo CLI(DAG);
8686 CLI.setDebugLoc(dl)
8687 .setChain(Chain)
8688 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8689 ES, std::move(Args));
8691 return LowerCallTo(CLI).first;
8694 // This is a code size optimisation: return the original SDIV node to
8695 // DAGCombiner when we don't want to expand SDIV into a sequence of
8696 // instructions, and an empty node otherwise which will cause the
8697 // SDIV to be expanded in DAGCombine.
8698 SDValue
8699 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8700 SelectionDAG &DAG,
8701 SmallVectorImpl<SDNode *> &Created) const {
8702 // TODO: Support SREM
8703 if (N->getOpcode() != ISD::SDIV)
8704 return SDValue();
8706 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8707 const bool MinSize = ST.hasMinSize();
8708 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8709 : ST.hasDivideInARMMode();
8711 // Don't touch vector types; rewriting this may lead to scalarizing
8712 // the int divs.
8713 if (N->getOperand(0).getValueType().isVector())
8714 return SDValue();
8716 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8717 // hwdiv support for this to be really profitable.
8718 if (!(MinSize && HasDivide))
8719 return SDValue();
8721 // ARM mode is a bit simpler than Thumb: we can handle large power
8722 // of 2 immediates with 1 mov instruction; no further checks required,
8723 // just return the sdiv node.
8724 if (!ST.isThumb())
8725 return SDValue(N, 0);
8727 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8728 // and thus lose the code size benefits of a MOVS that requires only 2.
8729 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8730 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8731 if (Divisor.sgt(128))
8732 return SDValue();
8734 return SDValue(N, 0);
8737 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8738 bool Signed) const {
8739 assert(Op.getValueType() == MVT::i32 &&
8740 "unexpected type for custom lowering DIV");
8741 SDLoc dl(Op);
8743 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8744 DAG.getEntryNode(), Op.getOperand(1));
8746 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8749 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8750 SDLoc DL(N);
8751 SDValue Op = N->getOperand(1);
8752 if (N->getValueType(0) == MVT::i32)
8753 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8754 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8755 DAG.getConstant(0, DL, MVT::i32));
8756 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8757 DAG.getConstant(1, DL, MVT::i32));
8758 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8759 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8762 void ARMTargetLowering::ExpandDIV_Windows(
8763 SDValue Op, SelectionDAG &DAG, bool Signed,
8764 SmallVectorImpl<SDValue> &Results) const {
8765 const auto &DL = DAG.getDataLayout();
8766 const auto &TLI = DAG.getTargetLoweringInfo();
8768 assert(Op.getValueType() == MVT::i64 &&
8769 "unexpected type for custom lowering DIV");
8770 SDLoc dl(Op);
8772 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8774 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8776 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8777 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8778 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8779 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8781 Results.push_back(Lower);
8782 Results.push_back(Upper);
8785 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8786 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8787 // Acquire/Release load/store is not legal for targets without a dmb or
8788 // equivalent available.
8789 return SDValue();
8791 // Monotonic load/store is legal for all targets.
8792 return Op;
8795 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8796 SmallVectorImpl<SDValue> &Results,
8797 SelectionDAG &DAG,
8798 const ARMSubtarget *Subtarget) {
8799 SDLoc DL(N);
8800 // Under Power Management extensions, the cycle-count is:
8801 // mrc p15, #0, <Rt>, c9, c13, #0
8802 SDValue Ops[] = { N->getOperand(0), // Chain
8803 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8804 DAG.getConstant(15, DL, MVT::i32),
8805 DAG.getConstant(0, DL, MVT::i32),
8806 DAG.getConstant(9, DL, MVT::i32),
8807 DAG.getConstant(13, DL, MVT::i32),
8808 DAG.getConstant(0, DL, MVT::i32)
8811 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8812 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8813 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8814 DAG.getConstant(0, DL, MVT::i32)));
8815 Results.push_back(Cycles32.getValue(1));
8818 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8819 SDLoc dl(V.getNode());
8820 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
8821 SDValue VHi = DAG.getAnyExtOrTrunc(
8822 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
8823 dl, MVT::i32);
8824 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8825 if (isBigEndian)
8826 std::swap (VLo, VHi);
8827 SDValue RegClass =
8828 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
8829 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
8830 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
8831 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
8832 return SDValue(
8833 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
8836 static void ReplaceCMP_SWAP_64Results(SDNode *N,
8837 SmallVectorImpl<SDValue> & Results,
8838 SelectionDAG &DAG) {
8839 assert(N->getValueType(0) == MVT::i64 &&
8840 "AtomicCmpSwap on types less than 64 should be legal");
8841 SDValue Ops[] = {N->getOperand(1),
8842 createGPRPairNode(DAG, N->getOperand(2)),
8843 createGPRPairNode(DAG, N->getOperand(3)),
8844 N->getOperand(0)};
8845 SDNode *CmpSwap = DAG.getMachineNode(
8846 ARM::CMP_SWAP_64, SDLoc(N),
8847 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
8849 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
8850 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8852 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8854 Results.push_back(
8855 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8856 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8857 Results.push_back(
8858 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8859 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8860 Results.push_back(SDValue(CmpSwap, 2));
8863 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8864 SelectionDAG &DAG) {
8865 const auto &TLI = DAG.getTargetLoweringInfo();
8867 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8868 "Custom lowering is MSVCRT specific!");
8870 SDLoc dl(Op);
8871 SDValue Val = Op.getOperand(0);
8872 MVT Ty = Val->getSimpleValueType(0);
8873 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8874 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8875 TLI.getPointerTy(DAG.getDataLayout()));
8877 TargetLowering::ArgListTy Args;
8878 TargetLowering::ArgListEntry Entry;
8880 Entry.Node = Val;
8881 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8882 Entry.IsZExt = true;
8883 Args.push_back(Entry);
8885 Entry.Node = Exponent;
8886 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8887 Entry.IsZExt = true;
8888 Args.push_back(Entry);
8890 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8892 // In the in-chain to the call is the entry node If we are emitting a
8893 // tailcall, the chain will be mutated if the node has a non-entry input
8894 // chain.
8895 SDValue InChain = DAG.getEntryNode();
8896 SDValue TCChain = InChain;
8898 const Function &F = DAG.getMachineFunction().getFunction();
8899 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8900 F.getReturnType() == LCRTy;
8901 if (IsTC)
8902 InChain = TCChain;
8904 TargetLowering::CallLoweringInfo CLI(DAG);
8905 CLI.setDebugLoc(dl)
8906 .setChain(InChain)
8907 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8908 .setTailCall(IsTC);
8909 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8911 // Return the chain (the DAG root) if it is a tail call
8912 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8915 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8916 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8917 switch (Op.getOpcode()) {
8918 default: llvm_unreachable("Don't know how to custom lower this!");
8919 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8920 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8921 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8922 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8923 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8924 case ISD::SELECT: return LowerSELECT(Op, DAG);
8925 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8926 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8927 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
8928 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
8929 case ISD::VASTART: return LowerVASTART(Op, DAG);
8930 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8931 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
8932 case ISD::SINT_TO_FP:
8933 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8934 case ISD::FP_TO_SINT:
8935 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
8936 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8937 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8938 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8939 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8940 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8941 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8942 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
8943 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8944 Subtarget);
8945 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8946 case ISD::SHL:
8947 case ISD::SRL:
8948 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
8949 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
8950 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
8951 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
8952 case ISD::SRL_PARTS:
8953 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
8954 case ISD::CTTZ:
8955 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8956 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8957 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
8958 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
8959 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
8960 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8961 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
8962 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
8963 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8964 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
8965 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
8966 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8967 case ISD::MUL: return LowerMUL(Op, DAG);
8968 case ISD::SDIV:
8969 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8970 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8971 return LowerSDIV(Op, DAG, Subtarget);
8972 case ISD::UDIV:
8973 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8974 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8975 return LowerUDIV(Op, DAG, Subtarget);
8976 case ISD::ADDCARRY:
8977 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
8978 case ISD::SADDO:
8979 case ISD::SSUBO:
8980 return LowerSignedALUO(Op, DAG);
8981 case ISD::UADDO:
8982 case ISD::USUBO:
8983 return LowerUnsignedALUO(Op, DAG);
8984 case ISD::ATOMIC_LOAD:
8985 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
8986 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
8987 case ISD::SDIVREM:
8988 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
8989 case ISD::DYNAMIC_STACKALLOC:
8990 if (Subtarget->isTargetWindows())
8991 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8992 llvm_unreachable("Don't know how to custom lower this!");
8993 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8994 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8995 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8996 case ARMISD::WIN__DBZCHK: return SDValue();
9000 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9001 SelectionDAG &DAG) {
9002 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9003 unsigned Opc = 0;
9004 if (IntNo == Intrinsic::arm_smlald)
9005 Opc = ARMISD::SMLALD;
9006 else if (IntNo == Intrinsic::arm_smlaldx)
9007 Opc = ARMISD::SMLALDX;
9008 else if (IntNo == Intrinsic::arm_smlsld)
9009 Opc = ARMISD::SMLSLD;
9010 else if (IntNo == Intrinsic::arm_smlsldx)
9011 Opc = ARMISD::SMLSLDX;
9012 else
9013 return;
9015 SDLoc dl(N);
9016 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9017 N->getOperand(3),
9018 DAG.getConstant(0, dl, MVT::i32));
9019 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9020 N->getOperand(3),
9021 DAG.getConstant(1, dl, MVT::i32));
9023 SDValue LongMul = DAG.getNode(Opc, dl,
9024 DAG.getVTList(MVT::i32, MVT::i32),
9025 N->getOperand(1), N->getOperand(2),
9026 Lo, Hi);
9027 Results.push_back(LongMul.getValue(0));
9028 Results.push_back(LongMul.getValue(1));
9031 /// ReplaceNodeResults - Replace the results of node with an illegal result
9032 /// type with new values built out of custom code.
9033 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9034 SmallVectorImpl<SDValue> &Results,
9035 SelectionDAG &DAG) const {
9036 SDValue Res;
9037 switch (N->getOpcode()) {
9038 default:
9039 llvm_unreachable("Don't know how to custom expand this!");
9040 case ISD::READ_REGISTER:
9041 ExpandREAD_REGISTER(N, Results, DAG);
9042 break;
9043 case ISD::BITCAST:
9044 Res = ExpandBITCAST(N, DAG, Subtarget);
9045 break;
9046 case ISD::SRL:
9047 case ISD::SRA:
9048 case ISD::SHL:
9049 Res = Expand64BitShift(N, DAG, Subtarget);
9050 break;
9051 case ISD::SREM:
9052 case ISD::UREM:
9053 Res = LowerREM(N, DAG);
9054 break;
9055 case ISD::SDIVREM:
9056 case ISD::UDIVREM:
9057 Res = LowerDivRem(SDValue(N, 0), DAG);
9058 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9059 Results.push_back(Res.getValue(0));
9060 Results.push_back(Res.getValue(1));
9061 return;
9062 case ISD::READCYCLECOUNTER:
9063 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9064 return;
9065 case ISD::UDIV:
9066 case ISD::SDIV:
9067 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9068 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9069 Results);
9070 case ISD::ATOMIC_CMP_SWAP:
9071 ReplaceCMP_SWAP_64Results(N, Results, DAG);
9072 return;
9073 case ISD::INTRINSIC_WO_CHAIN:
9074 return ReplaceLongIntrinsic(N, Results, DAG);
9075 case ISD::ABS:
9076 lowerABS(N, Results, DAG);
9077 return ;
9080 if (Res.getNode())
9081 Results.push_back(Res);
9084 //===----------------------------------------------------------------------===//
9085 // ARM Scheduler Hooks
9086 //===----------------------------------------------------------------------===//
9088 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9089 /// registers the function context.
9090 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9091 MachineBasicBlock *MBB,
9092 MachineBasicBlock *DispatchBB,
9093 int FI) const {
9094 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9095 "ROPI/RWPI not currently supported with SjLj");
9096 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9097 DebugLoc dl = MI.getDebugLoc();
9098 MachineFunction *MF = MBB->getParent();
9099 MachineRegisterInfo *MRI = &MF->getRegInfo();
9100 MachineConstantPool *MCP = MF->getConstantPool();
9101 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9102 const Function &F = MF->getFunction();
9104 bool isThumb = Subtarget->isThumb();
9105 bool isThumb2 = Subtarget->isThumb2();
9107 unsigned PCLabelId = AFI->createPICLabelUId();
9108 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9109 ARMConstantPoolValue *CPV =
9110 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9111 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9113 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9114 : &ARM::GPRRegClass;
9116 // Grab constant pool and fixed stack memory operands.
9117 MachineMemOperand *CPMMO =
9118 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9119 MachineMemOperand::MOLoad, 4, 4);
9121 MachineMemOperand *FIMMOSt =
9122 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9123 MachineMemOperand::MOStore, 4, 4);
9125 // Load the address of the dispatch MBB into the jump buffer.
9126 if (isThumb2) {
9127 // Incoming value: jbuf
9128 // ldr.n r5, LCPI1_1
9129 // orr r5, r5, #1
9130 // add r5, pc
9131 // str r5, [$jbuf, #+4] ; &jbuf[1]
9132 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9133 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9134 .addConstantPoolIndex(CPI)
9135 .addMemOperand(CPMMO)
9136 .add(predOps(ARMCC::AL));
9137 // Set the low bit because of thumb mode.
9138 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9139 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9140 .addReg(NewVReg1, RegState::Kill)
9141 .addImm(0x01)
9142 .add(predOps(ARMCC::AL))
9143 .add(condCodeOp());
9144 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9145 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9146 .addReg(NewVReg2, RegState::Kill)
9147 .addImm(PCLabelId);
9148 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9149 .addReg(NewVReg3, RegState::Kill)
9150 .addFrameIndex(FI)
9151 .addImm(36) // &jbuf[1] :: pc
9152 .addMemOperand(FIMMOSt)
9153 .add(predOps(ARMCC::AL));
9154 } else if (isThumb) {
9155 // Incoming value: jbuf
9156 // ldr.n r1, LCPI1_4
9157 // add r1, pc
9158 // mov r2, #1
9159 // orrs r1, r2
9160 // add r2, $jbuf, #+4 ; &jbuf[1]
9161 // str r1, [r2]
9162 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9163 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9164 .addConstantPoolIndex(CPI)
9165 .addMemOperand(CPMMO)
9166 .add(predOps(ARMCC::AL));
9167 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9168 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9169 .addReg(NewVReg1, RegState::Kill)
9170 .addImm(PCLabelId);
9171 // Set the low bit because of thumb mode.
9172 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9173 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9174 .addReg(ARM::CPSR, RegState::Define)
9175 .addImm(1)
9176 .add(predOps(ARMCC::AL));
9177 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9178 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9179 .addReg(ARM::CPSR, RegState::Define)
9180 .addReg(NewVReg2, RegState::Kill)
9181 .addReg(NewVReg3, RegState::Kill)
9182 .add(predOps(ARMCC::AL));
9183 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9184 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9185 .addFrameIndex(FI)
9186 .addImm(36); // &jbuf[1] :: pc
9187 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9188 .addReg(NewVReg4, RegState::Kill)
9189 .addReg(NewVReg5, RegState::Kill)
9190 .addImm(0)
9191 .addMemOperand(FIMMOSt)
9192 .add(predOps(ARMCC::AL));
9193 } else {
9194 // Incoming value: jbuf
9195 // ldr r1, LCPI1_1
9196 // add r1, pc, r1
9197 // str r1, [$jbuf, #+4] ; &jbuf[1]
9198 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9199 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9200 .addConstantPoolIndex(CPI)
9201 .addImm(0)
9202 .addMemOperand(CPMMO)
9203 .add(predOps(ARMCC::AL));
9204 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9205 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9206 .addReg(NewVReg1, RegState::Kill)
9207 .addImm(PCLabelId)
9208 .add(predOps(ARMCC::AL));
9209 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9210 .addReg(NewVReg2, RegState::Kill)
9211 .addFrameIndex(FI)
9212 .addImm(36) // &jbuf[1] :: pc
9213 .addMemOperand(FIMMOSt)
9214 .add(predOps(ARMCC::AL));
9218 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9219 MachineBasicBlock *MBB) const {
9220 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9221 DebugLoc dl = MI.getDebugLoc();
9222 MachineFunction *MF = MBB->getParent();
9223 MachineRegisterInfo *MRI = &MF->getRegInfo();
9224 MachineFrameInfo &MFI = MF->getFrameInfo();
9225 int FI = MFI.getFunctionContextIndex();
9227 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9228 : &ARM::GPRnopcRegClass;
9230 // Get a mapping of the call site numbers to all of the landing pads they're
9231 // associated with.
9232 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9233 unsigned MaxCSNum = 0;
9234 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9235 ++BB) {
9236 if (!BB->isEHPad()) continue;
9238 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9239 // pad.
9240 for (MachineBasicBlock::iterator
9241 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9242 if (!II->isEHLabel()) continue;
9244 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9245 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9247 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9248 for (SmallVectorImpl<unsigned>::iterator
9249 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9250 CSI != CSE; ++CSI) {
9251 CallSiteNumToLPad[*CSI].push_back(&*BB);
9252 MaxCSNum = std::max(MaxCSNum, *CSI);
9254 break;
9258 // Get an ordered list of the machine basic blocks for the jump table.
9259 std::vector<MachineBasicBlock*> LPadList;
9260 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9261 LPadList.reserve(CallSiteNumToLPad.size());
9262 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9263 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9264 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9265 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9266 LPadList.push_back(*II);
9267 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9271 assert(!LPadList.empty() &&
9272 "No landing pad destinations for the dispatch jump table!");
9274 // Create the jump table and associated information.
9275 MachineJumpTableInfo *JTI =
9276 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9277 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9279 // Create the MBBs for the dispatch code.
9281 // Shove the dispatch's address into the return slot in the function context.
9282 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9283 DispatchBB->setIsEHPad();
9285 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9286 unsigned trap_opcode;
9287 if (Subtarget->isThumb())
9288 trap_opcode = ARM::tTRAP;
9289 else
9290 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9292 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9293 DispatchBB->addSuccessor(TrapBB);
9295 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9296 DispatchBB->addSuccessor(DispContBB);
9298 // Insert and MBBs.
9299 MF->insert(MF->end(), DispatchBB);
9300 MF->insert(MF->end(), DispContBB);
9301 MF->insert(MF->end(), TrapBB);
9303 // Insert code into the entry block that creates and registers the function
9304 // context.
9305 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9307 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9308 MachinePointerInfo::getFixedStack(*MF, FI),
9309 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9311 MachineInstrBuilder MIB;
9312 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9314 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9315 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9317 // Add a register mask with no preserved registers. This results in all
9318 // registers being marked as clobbered. This can't work if the dispatch block
9319 // is in a Thumb1 function and is linked with ARM code which uses the FP
9320 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9321 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9323 bool IsPositionIndependent = isPositionIndependent();
9324 unsigned NumLPads = LPadList.size();
9325 if (Subtarget->isThumb2()) {
9326 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9327 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9328 .addFrameIndex(FI)
9329 .addImm(4)
9330 .addMemOperand(FIMMOLd)
9331 .add(predOps(ARMCC::AL));
9333 if (NumLPads < 256) {
9334 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9335 .addReg(NewVReg1)
9336 .addImm(LPadList.size())
9337 .add(predOps(ARMCC::AL));
9338 } else {
9339 Register VReg1 = MRI->createVirtualRegister(TRC);
9340 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9341 .addImm(NumLPads & 0xFFFF)
9342 .add(predOps(ARMCC::AL));
9344 unsigned VReg2 = VReg1;
9345 if ((NumLPads & 0xFFFF0000) != 0) {
9346 VReg2 = MRI->createVirtualRegister(TRC);
9347 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9348 .addReg(VReg1)
9349 .addImm(NumLPads >> 16)
9350 .add(predOps(ARMCC::AL));
9353 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9354 .addReg(NewVReg1)
9355 .addReg(VReg2)
9356 .add(predOps(ARMCC::AL));
9359 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9360 .addMBB(TrapBB)
9361 .addImm(ARMCC::HI)
9362 .addReg(ARM::CPSR);
9364 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9365 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9366 .addJumpTableIndex(MJTI)
9367 .add(predOps(ARMCC::AL));
9369 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9370 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9371 .addReg(NewVReg3, RegState::Kill)
9372 .addReg(NewVReg1)
9373 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9374 .add(predOps(ARMCC::AL))
9375 .add(condCodeOp());
9377 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9378 .addReg(NewVReg4, RegState::Kill)
9379 .addReg(NewVReg1)
9380 .addJumpTableIndex(MJTI);
9381 } else if (Subtarget->isThumb()) {
9382 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9383 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9384 .addFrameIndex(FI)
9385 .addImm(1)
9386 .addMemOperand(FIMMOLd)
9387 .add(predOps(ARMCC::AL));
9389 if (NumLPads < 256) {
9390 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9391 .addReg(NewVReg1)
9392 .addImm(NumLPads)
9393 .add(predOps(ARMCC::AL));
9394 } else {
9395 MachineConstantPool *ConstantPool = MF->getConstantPool();
9396 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9397 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9399 // MachineConstantPool wants an explicit alignment.
9400 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9401 if (Align == 0)
9402 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9403 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9405 Register VReg1 = MRI->createVirtualRegister(TRC);
9406 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9407 .addReg(VReg1, RegState::Define)
9408 .addConstantPoolIndex(Idx)
9409 .add(predOps(ARMCC::AL));
9410 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9411 .addReg(NewVReg1)
9412 .addReg(VReg1)
9413 .add(predOps(ARMCC::AL));
9416 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9417 .addMBB(TrapBB)
9418 .addImm(ARMCC::HI)
9419 .addReg(ARM::CPSR);
9421 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9422 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9423 .addReg(ARM::CPSR, RegState::Define)
9424 .addReg(NewVReg1)
9425 .addImm(2)
9426 .add(predOps(ARMCC::AL));
9428 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9429 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9430 .addJumpTableIndex(MJTI)
9431 .add(predOps(ARMCC::AL));
9433 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9434 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9435 .addReg(ARM::CPSR, RegState::Define)
9436 .addReg(NewVReg2, RegState::Kill)
9437 .addReg(NewVReg3)
9438 .add(predOps(ARMCC::AL));
9440 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9441 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9443 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9444 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9445 .addReg(NewVReg4, RegState::Kill)
9446 .addImm(0)
9447 .addMemOperand(JTMMOLd)
9448 .add(predOps(ARMCC::AL));
9450 unsigned NewVReg6 = NewVReg5;
9451 if (IsPositionIndependent) {
9452 NewVReg6 = MRI->createVirtualRegister(TRC);
9453 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9454 .addReg(ARM::CPSR, RegState::Define)
9455 .addReg(NewVReg5, RegState::Kill)
9456 .addReg(NewVReg3)
9457 .add(predOps(ARMCC::AL));
9460 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9461 .addReg(NewVReg6, RegState::Kill)
9462 .addJumpTableIndex(MJTI);
9463 } else {
9464 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9465 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9466 .addFrameIndex(FI)
9467 .addImm(4)
9468 .addMemOperand(FIMMOLd)
9469 .add(predOps(ARMCC::AL));
9471 if (NumLPads < 256) {
9472 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9473 .addReg(NewVReg1)
9474 .addImm(NumLPads)
9475 .add(predOps(ARMCC::AL));
9476 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9477 Register VReg1 = MRI->createVirtualRegister(TRC);
9478 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9479 .addImm(NumLPads & 0xFFFF)
9480 .add(predOps(ARMCC::AL));
9482 unsigned VReg2 = VReg1;
9483 if ((NumLPads & 0xFFFF0000) != 0) {
9484 VReg2 = MRI->createVirtualRegister(TRC);
9485 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9486 .addReg(VReg1)
9487 .addImm(NumLPads >> 16)
9488 .add(predOps(ARMCC::AL));
9491 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9492 .addReg(NewVReg1)
9493 .addReg(VReg2)
9494 .add(predOps(ARMCC::AL));
9495 } else {
9496 MachineConstantPool *ConstantPool = MF->getConstantPool();
9497 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9498 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9500 // MachineConstantPool wants an explicit alignment.
9501 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9502 if (Align == 0)
9503 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9504 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9506 Register VReg1 = MRI->createVirtualRegister(TRC);
9507 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9508 .addReg(VReg1, RegState::Define)
9509 .addConstantPoolIndex(Idx)
9510 .addImm(0)
9511 .add(predOps(ARMCC::AL));
9512 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9513 .addReg(NewVReg1)
9514 .addReg(VReg1, RegState::Kill)
9515 .add(predOps(ARMCC::AL));
9518 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9519 .addMBB(TrapBB)
9520 .addImm(ARMCC::HI)
9521 .addReg(ARM::CPSR);
9523 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9524 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9525 .addReg(NewVReg1)
9526 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9527 .add(predOps(ARMCC::AL))
9528 .add(condCodeOp());
9529 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9530 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9531 .addJumpTableIndex(MJTI)
9532 .add(predOps(ARMCC::AL));
9534 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9535 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9536 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9537 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9538 .addReg(NewVReg3, RegState::Kill)
9539 .addReg(NewVReg4)
9540 .addImm(0)
9541 .addMemOperand(JTMMOLd)
9542 .add(predOps(ARMCC::AL));
9544 if (IsPositionIndependent) {
9545 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9546 .addReg(NewVReg5, RegState::Kill)
9547 .addReg(NewVReg4)
9548 .addJumpTableIndex(MJTI);
9549 } else {
9550 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9551 .addReg(NewVReg5, RegState::Kill)
9552 .addJumpTableIndex(MJTI);
9556 // Add the jump table entries as successors to the MBB.
9557 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9558 for (std::vector<MachineBasicBlock*>::iterator
9559 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9560 MachineBasicBlock *CurMBB = *I;
9561 if (SeenMBBs.insert(CurMBB).second)
9562 DispContBB->addSuccessor(CurMBB);
9565 // N.B. the order the invoke BBs are processed in doesn't matter here.
9566 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9567 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9568 for (MachineBasicBlock *BB : InvokeBBs) {
9570 // Remove the landing pad successor from the invoke block and replace it
9571 // with the new dispatch block.
9572 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9573 BB->succ_end());
9574 while (!Successors.empty()) {
9575 MachineBasicBlock *SMBB = Successors.pop_back_val();
9576 if (SMBB->isEHPad()) {
9577 BB->removeSuccessor(SMBB);
9578 MBBLPads.push_back(SMBB);
9582 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9583 BB->normalizeSuccProbs();
9585 // Find the invoke call and mark all of the callee-saved registers as
9586 // 'implicit defined' so that they're spilled. This prevents code from
9587 // moving instructions to before the EH block, where they will never be
9588 // executed.
9589 for (MachineBasicBlock::reverse_iterator
9590 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9591 if (!II->isCall()) continue;
9593 DenseMap<unsigned, bool> DefRegs;
9594 for (MachineInstr::mop_iterator
9595 OI = II->operands_begin(), OE = II->operands_end();
9596 OI != OE; ++OI) {
9597 if (!OI->isReg()) continue;
9598 DefRegs[OI->getReg()] = true;
9601 MachineInstrBuilder MIB(*MF, &*II);
9603 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9604 unsigned Reg = SavedRegs[i];
9605 if (Subtarget->isThumb2() &&
9606 !ARM::tGPRRegClass.contains(Reg) &&
9607 !ARM::hGPRRegClass.contains(Reg))
9608 continue;
9609 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9610 continue;
9611 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9612 continue;
9613 if (!DefRegs[Reg])
9614 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9617 break;
9621 // Mark all former landing pads as non-landing pads. The dispatch is the only
9622 // landing pad now.
9623 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9624 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9625 (*I)->setIsEHPad(false);
9627 // The instruction is gone now.
9628 MI.eraseFromParent();
9631 static
9632 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9633 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9634 E = MBB->succ_end(); I != E; ++I)
9635 if (*I != Succ)
9636 return *I;
9637 llvm_unreachable("Expecting a BB with two successors!");
9640 /// Return the load opcode for a given load size. If load size >= 8,
9641 /// neon opcode will be returned.
9642 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9643 if (LdSize >= 8)
9644 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9645 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9646 if (IsThumb1)
9647 return LdSize == 4 ? ARM::tLDRi
9648 : LdSize == 2 ? ARM::tLDRHi
9649 : LdSize == 1 ? ARM::tLDRBi : 0;
9650 if (IsThumb2)
9651 return LdSize == 4 ? ARM::t2LDR_POST
9652 : LdSize == 2 ? ARM::t2LDRH_POST
9653 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9654 return LdSize == 4 ? ARM::LDR_POST_IMM
9655 : LdSize == 2 ? ARM::LDRH_POST
9656 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9659 /// Return the store opcode for a given store size. If store size >= 8,
9660 /// neon opcode will be returned.
9661 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9662 if (StSize >= 8)
9663 return StSize == 16 ? ARM::VST1q32wb_fixed
9664 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9665 if (IsThumb1)
9666 return StSize == 4 ? ARM::tSTRi
9667 : StSize == 2 ? ARM::tSTRHi
9668 : StSize == 1 ? ARM::tSTRBi : 0;
9669 if (IsThumb2)
9670 return StSize == 4 ? ARM::t2STR_POST
9671 : StSize == 2 ? ARM::t2STRH_POST
9672 : StSize == 1 ? ARM::t2STRB_POST : 0;
9673 return StSize == 4 ? ARM::STR_POST_IMM
9674 : StSize == 2 ? ARM::STRH_POST
9675 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9678 /// Emit a post-increment load operation with given size. The instructions
9679 /// will be added to BB at Pos.
9680 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9681 const TargetInstrInfo *TII, const DebugLoc &dl,
9682 unsigned LdSize, unsigned Data, unsigned AddrIn,
9683 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9684 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9685 assert(LdOpc != 0 && "Should have a load opcode");
9686 if (LdSize >= 8) {
9687 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9688 .addReg(AddrOut, RegState::Define)
9689 .addReg(AddrIn)
9690 .addImm(0)
9691 .add(predOps(ARMCC::AL));
9692 } else if (IsThumb1) {
9693 // load + update AddrIn
9694 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9695 .addReg(AddrIn)
9696 .addImm(0)
9697 .add(predOps(ARMCC::AL));
9698 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9699 .add(t1CondCodeOp())
9700 .addReg(AddrIn)
9701 .addImm(LdSize)
9702 .add(predOps(ARMCC::AL));
9703 } else if (IsThumb2) {
9704 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9705 .addReg(AddrOut, RegState::Define)
9706 .addReg(AddrIn)
9707 .addImm(LdSize)
9708 .add(predOps(ARMCC::AL));
9709 } else { // arm
9710 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9711 .addReg(AddrOut, RegState::Define)
9712 .addReg(AddrIn)
9713 .addReg(0)
9714 .addImm(LdSize)
9715 .add(predOps(ARMCC::AL));
9719 /// Emit a post-increment store operation with given size. The instructions
9720 /// will be added to BB at Pos.
9721 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9722 const TargetInstrInfo *TII, const DebugLoc &dl,
9723 unsigned StSize, unsigned Data, unsigned AddrIn,
9724 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9725 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9726 assert(StOpc != 0 && "Should have a store opcode");
9727 if (StSize >= 8) {
9728 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9729 .addReg(AddrIn)
9730 .addImm(0)
9731 .addReg(Data)
9732 .add(predOps(ARMCC::AL));
9733 } else if (IsThumb1) {
9734 // store + update AddrIn
9735 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9736 .addReg(Data)
9737 .addReg(AddrIn)
9738 .addImm(0)
9739 .add(predOps(ARMCC::AL));
9740 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9741 .add(t1CondCodeOp())
9742 .addReg(AddrIn)
9743 .addImm(StSize)
9744 .add(predOps(ARMCC::AL));
9745 } else if (IsThumb2) {
9746 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9747 .addReg(Data)
9748 .addReg(AddrIn)
9749 .addImm(StSize)
9750 .add(predOps(ARMCC::AL));
9751 } else { // arm
9752 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9753 .addReg(Data)
9754 .addReg(AddrIn)
9755 .addReg(0)
9756 .addImm(StSize)
9757 .add(predOps(ARMCC::AL));
9761 MachineBasicBlock *
9762 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9763 MachineBasicBlock *BB) const {
9764 // This pseudo instruction has 3 operands: dst, src, size
9765 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9766 // Otherwise, we will generate unrolled scalar copies.
9767 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9768 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9769 MachineFunction::iterator It = ++BB->getIterator();
9771 Register dest = MI.getOperand(0).getReg();
9772 Register src = MI.getOperand(1).getReg();
9773 unsigned SizeVal = MI.getOperand(2).getImm();
9774 unsigned Align = MI.getOperand(3).getImm();
9775 DebugLoc dl = MI.getDebugLoc();
9777 MachineFunction *MF = BB->getParent();
9778 MachineRegisterInfo &MRI = MF->getRegInfo();
9779 unsigned UnitSize = 0;
9780 const TargetRegisterClass *TRC = nullptr;
9781 const TargetRegisterClass *VecTRC = nullptr;
9783 bool IsThumb1 = Subtarget->isThumb1Only();
9784 bool IsThumb2 = Subtarget->isThumb2();
9785 bool IsThumb = Subtarget->isThumb();
9787 if (Align & 1) {
9788 UnitSize = 1;
9789 } else if (Align & 2) {
9790 UnitSize = 2;
9791 } else {
9792 // Check whether we can use NEON instructions.
9793 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9794 Subtarget->hasNEON()) {
9795 if ((Align % 16 == 0) && SizeVal >= 16)
9796 UnitSize = 16;
9797 else if ((Align % 8 == 0) && SizeVal >= 8)
9798 UnitSize = 8;
9800 // Can't use NEON instructions.
9801 if (UnitSize == 0)
9802 UnitSize = 4;
9805 // Select the correct opcode and register class for unit size load/store
9806 bool IsNeon = UnitSize >= 8;
9807 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
9808 if (IsNeon)
9809 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
9810 : UnitSize == 8 ? &ARM::DPRRegClass
9811 : nullptr;
9813 unsigned BytesLeft = SizeVal % UnitSize;
9814 unsigned LoopSize = SizeVal - BytesLeft;
9816 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
9817 // Use LDR and STR to copy.
9818 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
9819 // [destOut] = STR_POST(scratch, destIn, UnitSize)
9820 unsigned srcIn = src;
9821 unsigned destIn = dest;
9822 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
9823 Register srcOut = MRI.createVirtualRegister(TRC);
9824 Register destOut = MRI.createVirtualRegister(TRC);
9825 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9826 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
9827 IsThumb1, IsThumb2);
9828 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
9829 IsThumb1, IsThumb2);
9830 srcIn = srcOut;
9831 destIn = destOut;
9834 // Handle the leftover bytes with LDRB and STRB.
9835 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
9836 // [destOut] = STRB_POST(scratch, destIn, 1)
9837 for (unsigned i = 0; i < BytesLeft; i++) {
9838 Register srcOut = MRI.createVirtualRegister(TRC);
9839 Register destOut = MRI.createVirtualRegister(TRC);
9840 Register scratch = MRI.createVirtualRegister(TRC);
9841 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
9842 IsThumb1, IsThumb2);
9843 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
9844 IsThumb1, IsThumb2);
9845 srcIn = srcOut;
9846 destIn = destOut;
9848 MI.eraseFromParent(); // The instruction is gone now.
9849 return BB;
9852 // Expand the pseudo op to a loop.
9853 // thisMBB:
9854 // ...
9855 // movw varEnd, # --> with thumb2
9856 // movt varEnd, #
9857 // ldrcp varEnd, idx --> without thumb2
9858 // fallthrough --> loopMBB
9859 // loopMBB:
9860 // PHI varPhi, varEnd, varLoop
9861 // PHI srcPhi, src, srcLoop
9862 // PHI destPhi, dst, destLoop
9863 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9864 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9865 // subs varLoop, varPhi, #UnitSize
9866 // bne loopMBB
9867 // fallthrough --> exitMBB
9868 // exitMBB:
9869 // epilogue to handle left-over bytes
9870 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9871 // [destOut] = STRB_POST(scratch, destLoop, 1)
9872 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9873 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9874 MF->insert(It, loopMBB);
9875 MF->insert(It, exitMBB);
9877 // Transfer the remainder of BB and its successor edges to exitMBB.
9878 exitMBB->splice(exitMBB->begin(), BB,
9879 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9880 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9882 // Load an immediate to varEnd.
9883 Register varEnd = MRI.createVirtualRegister(TRC);
9884 if (Subtarget->useMovt()) {
9885 unsigned Vtmp = varEnd;
9886 if ((LoopSize & 0xFFFF0000) != 0)
9887 Vtmp = MRI.createVirtualRegister(TRC);
9888 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9889 .addImm(LoopSize & 0xFFFF)
9890 .add(predOps(ARMCC::AL));
9892 if ((LoopSize & 0xFFFF0000) != 0)
9893 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9894 .addReg(Vtmp)
9895 .addImm(LoopSize >> 16)
9896 .add(predOps(ARMCC::AL));
9897 } else {
9898 MachineConstantPool *ConstantPool = MF->getConstantPool();
9899 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9900 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9902 // MachineConstantPool wants an explicit alignment.
9903 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9904 if (Align == 0)
9905 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9906 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9907 MachineMemOperand *CPMMO =
9908 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9909 MachineMemOperand::MOLoad, 4, 4);
9911 if (IsThumb)
9912 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9913 .addReg(varEnd, RegState::Define)
9914 .addConstantPoolIndex(Idx)
9915 .add(predOps(ARMCC::AL))
9916 .addMemOperand(CPMMO);
9917 else
9918 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9919 .addReg(varEnd, RegState::Define)
9920 .addConstantPoolIndex(Idx)
9921 .addImm(0)
9922 .add(predOps(ARMCC::AL))
9923 .addMemOperand(CPMMO);
9925 BB->addSuccessor(loopMBB);
9927 // Generate the loop body:
9928 // varPhi = PHI(varLoop, varEnd)
9929 // srcPhi = PHI(srcLoop, src)
9930 // destPhi = PHI(destLoop, dst)
9931 MachineBasicBlock *entryBB = BB;
9932 BB = loopMBB;
9933 Register varLoop = MRI.createVirtualRegister(TRC);
9934 Register varPhi = MRI.createVirtualRegister(TRC);
9935 Register srcLoop = MRI.createVirtualRegister(TRC);
9936 Register srcPhi = MRI.createVirtualRegister(TRC);
9937 Register destLoop = MRI.createVirtualRegister(TRC);
9938 Register destPhi = MRI.createVirtualRegister(TRC);
9940 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9941 .addReg(varLoop).addMBB(loopMBB)
9942 .addReg(varEnd).addMBB(entryBB);
9943 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9944 .addReg(srcLoop).addMBB(loopMBB)
9945 .addReg(src).addMBB(entryBB);
9946 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9947 .addReg(destLoop).addMBB(loopMBB)
9948 .addReg(dest).addMBB(entryBB);
9950 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9951 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9952 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9953 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9954 IsThumb1, IsThumb2);
9955 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9956 IsThumb1, IsThumb2);
9958 // Decrement loop variable by UnitSize.
9959 if (IsThumb1) {
9960 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9961 .add(t1CondCodeOp())
9962 .addReg(varPhi)
9963 .addImm(UnitSize)
9964 .add(predOps(ARMCC::AL));
9965 } else {
9966 MachineInstrBuilder MIB =
9967 BuildMI(*BB, BB->end(), dl,
9968 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9969 MIB.addReg(varPhi)
9970 .addImm(UnitSize)
9971 .add(predOps(ARMCC::AL))
9972 .add(condCodeOp());
9973 MIB->getOperand(5).setReg(ARM::CPSR);
9974 MIB->getOperand(5).setIsDef(true);
9976 BuildMI(*BB, BB->end(), dl,
9977 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9978 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9980 // loopMBB can loop back to loopMBB or fall through to exitMBB.
9981 BB->addSuccessor(loopMBB);
9982 BB->addSuccessor(exitMBB);
9984 // Add epilogue to handle BytesLeft.
9985 BB = exitMBB;
9986 auto StartOfExit = exitMBB->begin();
9988 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9989 // [destOut] = STRB_POST(scratch, destLoop, 1)
9990 unsigned srcIn = srcLoop;
9991 unsigned destIn = destLoop;
9992 for (unsigned i = 0; i < BytesLeft; i++) {
9993 Register srcOut = MRI.createVirtualRegister(TRC);
9994 Register destOut = MRI.createVirtualRegister(TRC);
9995 Register scratch = MRI.createVirtualRegister(TRC);
9996 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9997 IsThumb1, IsThumb2);
9998 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9999 IsThumb1, IsThumb2);
10000 srcIn = srcOut;
10001 destIn = destOut;
10004 MI.eraseFromParent(); // The instruction is gone now.
10005 return BB;
10008 MachineBasicBlock *
10009 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10010 MachineBasicBlock *MBB) const {
10011 const TargetMachine &TM = getTargetMachine();
10012 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10013 DebugLoc DL = MI.getDebugLoc();
10015 assert(Subtarget->isTargetWindows() &&
10016 "__chkstk is only supported on Windows");
10017 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10019 // __chkstk takes the number of words to allocate on the stack in R4, and
10020 // returns the stack adjustment in number of bytes in R4. This will not
10021 // clober any other registers (other than the obvious lr).
10023 // Although, technically, IP should be considered a register which may be
10024 // clobbered, the call itself will not touch it. Windows on ARM is a pure
10025 // thumb-2 environment, so there is no interworking required. As a result, we
10026 // do not expect a veneer to be emitted by the linker, clobbering IP.
10028 // Each module receives its own copy of __chkstk, so no import thunk is
10029 // required, again, ensuring that IP is not clobbered.
10031 // Finally, although some linkers may theoretically provide a trampoline for
10032 // out of range calls (which is quite common due to a 32M range limitation of
10033 // branches for Thumb), we can generate the long-call version via
10034 // -mcmodel=large, alleviating the need for the trampoline which may clobber
10035 // IP.
10037 switch (TM.getCodeModel()) {
10038 case CodeModel::Tiny:
10039 llvm_unreachable("Tiny code model not available on ARM.");
10040 case CodeModel::Small:
10041 case CodeModel::Medium:
10042 case CodeModel::Kernel:
10043 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10044 .add(predOps(ARMCC::AL))
10045 .addExternalSymbol("__chkstk")
10046 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10047 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10048 .addReg(ARM::R12,
10049 RegState::Implicit | RegState::Define | RegState::Dead)
10050 .addReg(ARM::CPSR,
10051 RegState::Implicit | RegState::Define | RegState::Dead);
10052 break;
10053 case CodeModel::Large: {
10054 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10055 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10057 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10058 .addExternalSymbol("__chkstk");
10059 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10060 .add(predOps(ARMCC::AL))
10061 .addReg(Reg, RegState::Kill)
10062 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10063 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10064 .addReg(ARM::R12,
10065 RegState::Implicit | RegState::Define | RegState::Dead)
10066 .addReg(ARM::CPSR,
10067 RegState::Implicit | RegState::Define | RegState::Dead);
10068 break;
10072 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10073 .addReg(ARM::SP, RegState::Kill)
10074 .addReg(ARM::R4, RegState::Kill)
10075 .setMIFlags(MachineInstr::FrameSetup)
10076 .add(predOps(ARMCC::AL))
10077 .add(condCodeOp());
10079 MI.eraseFromParent();
10080 return MBB;
10083 MachineBasicBlock *
10084 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10085 MachineBasicBlock *MBB) const {
10086 DebugLoc DL = MI.getDebugLoc();
10087 MachineFunction *MF = MBB->getParent();
10088 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10090 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10091 MF->insert(++MBB->getIterator(), ContBB);
10092 ContBB->splice(ContBB->begin(), MBB,
10093 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10094 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10095 MBB->addSuccessor(ContBB);
10097 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10098 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10099 MF->push_back(TrapBB);
10100 MBB->addSuccessor(TrapBB);
10102 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10103 .addReg(MI.getOperand(0).getReg())
10104 .addImm(0)
10105 .add(predOps(ARMCC::AL));
10106 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10107 .addMBB(TrapBB)
10108 .addImm(ARMCC::EQ)
10109 .addReg(ARM::CPSR);
10111 MI.eraseFromParent();
10112 return ContBB;
10115 // The CPSR operand of SelectItr might be missing a kill marker
10116 // because there were multiple uses of CPSR, and ISel didn't know
10117 // which to mark. Figure out whether SelectItr should have had a
10118 // kill marker, and set it if it should. Returns the correct kill
10119 // marker value.
10120 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10121 MachineBasicBlock* BB,
10122 const TargetRegisterInfo* TRI) {
10123 // Scan forward through BB for a use/def of CPSR.
10124 MachineBasicBlock::iterator miI(std::next(SelectItr));
10125 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10126 const MachineInstr& mi = *miI;
10127 if (mi.readsRegister(ARM::CPSR))
10128 return false;
10129 if (mi.definesRegister(ARM::CPSR))
10130 break; // Should have kill-flag - update below.
10133 // If we hit the end of the block, check whether CPSR is live into a
10134 // successor.
10135 if (miI == BB->end()) {
10136 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10137 sEnd = BB->succ_end();
10138 sItr != sEnd; ++sItr) {
10139 MachineBasicBlock* succ = *sItr;
10140 if (succ->isLiveIn(ARM::CPSR))
10141 return false;
10145 // We found a def, or hit the end of the basic block and CPSR wasn't live
10146 // out. SelectMI should have a kill flag on CPSR.
10147 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10148 return true;
10151 MachineBasicBlock *
10152 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10153 MachineBasicBlock *BB) const {
10154 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10155 DebugLoc dl = MI.getDebugLoc();
10156 bool isThumb2 = Subtarget->isThumb2();
10157 switch (MI.getOpcode()) {
10158 default: {
10159 MI.print(errs());
10160 llvm_unreachable("Unexpected instr type to insert");
10163 // Thumb1 post-indexed loads are really just single-register LDMs.
10164 case ARM::tLDR_postidx: {
10165 MachineOperand Def(MI.getOperand(1));
10166 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10167 .add(Def) // Rn_wb
10168 .add(MI.getOperand(2)) // Rn
10169 .add(MI.getOperand(3)) // PredImm
10170 .add(MI.getOperand(4)) // PredReg
10171 .add(MI.getOperand(0)) // Rt
10172 .cloneMemRefs(MI);
10173 MI.eraseFromParent();
10174 return BB;
10177 // The Thumb2 pre-indexed stores have the same MI operands, they just
10178 // define them differently in the .td files from the isel patterns, so
10179 // they need pseudos.
10180 case ARM::t2STR_preidx:
10181 MI.setDesc(TII->get(ARM::t2STR_PRE));
10182 return BB;
10183 case ARM::t2STRB_preidx:
10184 MI.setDesc(TII->get(ARM::t2STRB_PRE));
10185 return BB;
10186 case ARM::t2STRH_preidx:
10187 MI.setDesc(TII->get(ARM::t2STRH_PRE));
10188 return BB;
10190 case ARM::STRi_preidx:
10191 case ARM::STRBi_preidx: {
10192 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10193 : ARM::STRB_PRE_IMM;
10194 // Decode the offset.
10195 unsigned Offset = MI.getOperand(4).getImm();
10196 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10197 Offset = ARM_AM::getAM2Offset(Offset);
10198 if (isSub)
10199 Offset = -Offset;
10201 MachineMemOperand *MMO = *MI.memoperands_begin();
10202 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10203 .add(MI.getOperand(0)) // Rn_wb
10204 .add(MI.getOperand(1)) // Rt
10205 .add(MI.getOperand(2)) // Rn
10206 .addImm(Offset) // offset (skip GPR==zero_reg)
10207 .add(MI.getOperand(5)) // pred
10208 .add(MI.getOperand(6))
10209 .addMemOperand(MMO);
10210 MI.eraseFromParent();
10211 return BB;
10213 case ARM::STRr_preidx:
10214 case ARM::STRBr_preidx:
10215 case ARM::STRH_preidx: {
10216 unsigned NewOpc;
10217 switch (MI.getOpcode()) {
10218 default: llvm_unreachable("unexpected opcode!");
10219 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10220 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10221 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10223 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10224 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10225 MIB.add(MI.getOperand(i));
10226 MI.eraseFromParent();
10227 return BB;
10230 case ARM::tMOVCCr_pseudo: {
10231 // To "insert" a SELECT_CC instruction, we actually have to insert the
10232 // diamond control-flow pattern. The incoming instruction knows the
10233 // destination vreg to set, the condition code register to branch on, the
10234 // true/false values to select between, and a branch opcode to use.
10235 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10236 MachineFunction::iterator It = ++BB->getIterator();
10238 // thisMBB:
10239 // ...
10240 // TrueVal = ...
10241 // cmpTY ccX, r1, r2
10242 // bCC copy1MBB
10243 // fallthrough --> copy0MBB
10244 MachineBasicBlock *thisMBB = BB;
10245 MachineFunction *F = BB->getParent();
10246 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10247 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10248 F->insert(It, copy0MBB);
10249 F->insert(It, sinkMBB);
10251 // Check whether CPSR is live past the tMOVCCr_pseudo.
10252 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10253 if (!MI.killsRegister(ARM::CPSR) &&
10254 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10255 copy0MBB->addLiveIn(ARM::CPSR);
10256 sinkMBB->addLiveIn(ARM::CPSR);
10259 // Transfer the remainder of BB and its successor edges to sinkMBB.
10260 sinkMBB->splice(sinkMBB->begin(), BB,
10261 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10262 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10264 BB->addSuccessor(copy0MBB);
10265 BB->addSuccessor(sinkMBB);
10267 BuildMI(BB, dl, TII->get(ARM::tBcc))
10268 .addMBB(sinkMBB)
10269 .addImm(MI.getOperand(3).getImm())
10270 .addReg(MI.getOperand(4).getReg());
10272 // copy0MBB:
10273 // %FalseValue = ...
10274 // # fallthrough to sinkMBB
10275 BB = copy0MBB;
10277 // Update machine-CFG edges
10278 BB->addSuccessor(sinkMBB);
10280 // sinkMBB:
10281 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10282 // ...
10283 BB = sinkMBB;
10284 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10285 .addReg(MI.getOperand(1).getReg())
10286 .addMBB(copy0MBB)
10287 .addReg(MI.getOperand(2).getReg())
10288 .addMBB(thisMBB);
10290 MI.eraseFromParent(); // The pseudo instruction is gone now.
10291 return BB;
10294 case ARM::BCCi64:
10295 case ARM::BCCZi64: {
10296 // If there is an unconditional branch to the other successor, remove it.
10297 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10299 // Compare both parts that make up the double comparison separately for
10300 // equality.
10301 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10303 Register LHS1 = MI.getOperand(1).getReg();
10304 Register LHS2 = MI.getOperand(2).getReg();
10305 if (RHSisZero) {
10306 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10307 .addReg(LHS1)
10308 .addImm(0)
10309 .add(predOps(ARMCC::AL));
10310 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10311 .addReg(LHS2).addImm(0)
10312 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10313 } else {
10314 Register RHS1 = MI.getOperand(3).getReg();
10315 Register RHS2 = MI.getOperand(4).getReg();
10316 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10317 .addReg(LHS1)
10318 .addReg(RHS1)
10319 .add(predOps(ARMCC::AL));
10320 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10321 .addReg(LHS2).addReg(RHS2)
10322 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10325 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10326 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10327 if (MI.getOperand(0).getImm() == ARMCC::NE)
10328 std::swap(destMBB, exitMBB);
10330 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10331 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10332 if (isThumb2)
10333 BuildMI(BB, dl, TII->get(ARM::t2B))
10334 .addMBB(exitMBB)
10335 .add(predOps(ARMCC::AL));
10336 else
10337 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10339 MI.eraseFromParent(); // The pseudo instruction is gone now.
10340 return BB;
10343 case ARM::Int_eh_sjlj_setjmp:
10344 case ARM::Int_eh_sjlj_setjmp_nofp:
10345 case ARM::tInt_eh_sjlj_setjmp:
10346 case ARM::t2Int_eh_sjlj_setjmp:
10347 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10348 return BB;
10350 case ARM::Int_eh_sjlj_setup_dispatch:
10351 EmitSjLjDispatchBlock(MI, BB);
10352 return BB;
10354 case ARM::ABS:
10355 case ARM::t2ABS: {
10356 // To insert an ABS instruction, we have to insert the
10357 // diamond control-flow pattern. The incoming instruction knows the
10358 // source vreg to test against 0, the destination vreg to set,
10359 // the condition code register to branch on, the
10360 // true/false values to select between, and a branch opcode to use.
10361 // It transforms
10362 // V1 = ABS V0
10363 // into
10364 // V2 = MOVS V0
10365 // BCC (branch to SinkBB if V0 >= 0)
10366 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10367 // SinkBB: V1 = PHI(V2, V3)
10368 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10369 MachineFunction::iterator BBI = ++BB->getIterator();
10370 MachineFunction *Fn = BB->getParent();
10371 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10372 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10373 Fn->insert(BBI, RSBBB);
10374 Fn->insert(BBI, SinkBB);
10376 Register ABSSrcReg = MI.getOperand(1).getReg();
10377 Register ABSDstReg = MI.getOperand(0).getReg();
10378 bool ABSSrcKIll = MI.getOperand(1).isKill();
10379 bool isThumb2 = Subtarget->isThumb2();
10380 MachineRegisterInfo &MRI = Fn->getRegInfo();
10381 // In Thumb mode S must not be specified if source register is the SP or
10382 // PC and if destination register is the SP, so restrict register class
10383 Register NewRsbDstReg = MRI.createVirtualRegister(
10384 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10386 // Transfer the remainder of BB and its successor edges to sinkMBB.
10387 SinkBB->splice(SinkBB->begin(), BB,
10388 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10389 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10391 BB->addSuccessor(RSBBB);
10392 BB->addSuccessor(SinkBB);
10394 // fall through to SinkMBB
10395 RSBBB->addSuccessor(SinkBB);
10397 // insert a cmp at the end of BB
10398 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10399 .addReg(ABSSrcReg)
10400 .addImm(0)
10401 .add(predOps(ARMCC::AL));
10403 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10404 BuildMI(BB, dl,
10405 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10406 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10408 // insert rsbri in RSBBB
10409 // Note: BCC and rsbri will be converted into predicated rsbmi
10410 // by if-conversion pass
10411 BuildMI(*RSBBB, RSBBB->begin(), dl,
10412 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10413 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10414 .addImm(0)
10415 .add(predOps(ARMCC::AL))
10416 .add(condCodeOp());
10418 // insert PHI in SinkBB,
10419 // reuse ABSDstReg to not change uses of ABS instruction
10420 BuildMI(*SinkBB, SinkBB->begin(), dl,
10421 TII->get(ARM::PHI), ABSDstReg)
10422 .addReg(NewRsbDstReg).addMBB(RSBBB)
10423 .addReg(ABSSrcReg).addMBB(BB);
10425 // remove ABS instruction
10426 MI.eraseFromParent();
10428 // return last added BB
10429 return SinkBB;
10431 case ARM::COPY_STRUCT_BYVAL_I32:
10432 ++NumLoopByVals;
10433 return EmitStructByval(MI, BB);
10434 case ARM::WIN__CHKSTK:
10435 return EmitLowered__chkstk(MI, BB);
10436 case ARM::WIN__DBZCHK:
10437 return EmitLowered__dbzchk(MI, BB);
10441 /// Attaches vregs to MEMCPY that it will use as scratch registers
10442 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10443 /// instead of as a custom inserter because we need the use list from the SDNode.
10444 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10445 MachineInstr &MI, const SDNode *Node) {
10446 bool isThumb1 = Subtarget->isThumb1Only();
10448 DebugLoc DL = MI.getDebugLoc();
10449 MachineFunction *MF = MI.getParent()->getParent();
10450 MachineRegisterInfo &MRI = MF->getRegInfo();
10451 MachineInstrBuilder MIB(*MF, MI);
10453 // If the new dst/src is unused mark it as dead.
10454 if (!Node->hasAnyUseOfValue(0)) {
10455 MI.getOperand(0).setIsDead(true);
10457 if (!Node->hasAnyUseOfValue(1)) {
10458 MI.getOperand(1).setIsDead(true);
10461 // The MEMCPY both defines and kills the scratch registers.
10462 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10463 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10464 : &ARM::GPRRegClass);
10465 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10469 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10470 SDNode *Node) const {
10471 if (MI.getOpcode() == ARM::MEMCPY) {
10472 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10473 return;
10476 const MCInstrDesc *MCID = &MI.getDesc();
10477 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10478 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10479 // operand is still set to noreg. If needed, set the optional operand's
10480 // register to CPSR, and remove the redundant implicit def.
10482 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10484 // Rename pseudo opcodes.
10485 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10486 unsigned ccOutIdx;
10487 if (NewOpc) {
10488 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10489 MCID = &TII->get(NewOpc);
10491 assert(MCID->getNumOperands() ==
10492 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10493 && "converted opcode should be the same except for cc_out"
10494 " (and, on Thumb1, pred)");
10496 MI.setDesc(*MCID);
10498 // Add the optional cc_out operand
10499 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10501 // On Thumb1, move all input operands to the end, then add the predicate
10502 if (Subtarget->isThumb1Only()) {
10503 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10504 MI.addOperand(MI.getOperand(1));
10505 MI.RemoveOperand(1);
10508 // Restore the ties
10509 for (unsigned i = MI.getNumOperands(); i--;) {
10510 const MachineOperand& op = MI.getOperand(i);
10511 if (op.isReg() && op.isUse()) {
10512 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10513 if (DefIdx != -1)
10514 MI.tieOperands(DefIdx, i);
10518 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10519 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10520 ccOutIdx = 1;
10521 } else
10522 ccOutIdx = MCID->getNumOperands() - 1;
10523 } else
10524 ccOutIdx = MCID->getNumOperands() - 1;
10526 // Any ARM instruction that sets the 's' bit should specify an optional
10527 // "cc_out" operand in the last operand position.
10528 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10529 assert(!NewOpc && "Optional cc_out operand required");
10530 return;
10532 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10533 // since we already have an optional CPSR def.
10534 bool definesCPSR = false;
10535 bool deadCPSR = false;
10536 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10537 ++i) {
10538 const MachineOperand &MO = MI.getOperand(i);
10539 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10540 definesCPSR = true;
10541 if (MO.isDead())
10542 deadCPSR = true;
10543 MI.RemoveOperand(i);
10544 break;
10547 if (!definesCPSR) {
10548 assert(!NewOpc && "Optional cc_out operand required");
10549 return;
10551 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10552 if (deadCPSR) {
10553 assert(!MI.getOperand(ccOutIdx).getReg() &&
10554 "expect uninitialized optional cc_out operand");
10555 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10556 if (!Subtarget->isThumb1Only())
10557 return;
10560 // If this instruction was defined with an optional CPSR def and its dag node
10561 // had a live implicit CPSR def, then activate the optional CPSR def.
10562 MachineOperand &MO = MI.getOperand(ccOutIdx);
10563 MO.setReg(ARM::CPSR);
10564 MO.setIsDef(true);
10567 //===----------------------------------------------------------------------===//
10568 // ARM Optimization Hooks
10569 //===----------------------------------------------------------------------===//
10571 // Helper function that checks if N is a null or all ones constant.
10572 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10573 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10576 // Return true if N is conditionally 0 or all ones.
10577 // Detects these expressions where cc is an i1 value:
10579 // (select cc 0, y) [AllOnes=0]
10580 // (select cc y, 0) [AllOnes=0]
10581 // (zext cc) [AllOnes=0]
10582 // (sext cc) [AllOnes=0/1]
10583 // (select cc -1, y) [AllOnes=1]
10584 // (select cc y, -1) [AllOnes=1]
10586 // Invert is set when N is the null/all ones constant when CC is false.
10587 // OtherOp is set to the alternative value of N.
10588 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10589 SDValue &CC, bool &Invert,
10590 SDValue &OtherOp,
10591 SelectionDAG &DAG) {
10592 switch (N->getOpcode()) {
10593 default: return false;
10594 case ISD::SELECT: {
10595 CC = N->getOperand(0);
10596 SDValue N1 = N->getOperand(1);
10597 SDValue N2 = N->getOperand(2);
10598 if (isZeroOrAllOnes(N1, AllOnes)) {
10599 Invert = false;
10600 OtherOp = N2;
10601 return true;
10603 if (isZeroOrAllOnes(N2, AllOnes)) {
10604 Invert = true;
10605 OtherOp = N1;
10606 return true;
10608 return false;
10610 case ISD::ZERO_EXTEND:
10611 // (zext cc) can never be the all ones value.
10612 if (AllOnes)
10613 return false;
10614 LLVM_FALLTHROUGH;
10615 case ISD::SIGN_EXTEND: {
10616 SDLoc dl(N);
10617 EVT VT = N->getValueType(0);
10618 CC = N->getOperand(0);
10619 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10620 return false;
10621 Invert = !AllOnes;
10622 if (AllOnes)
10623 // When looking for an AllOnes constant, N is an sext, and the 'other'
10624 // value is 0.
10625 OtherOp = DAG.getConstant(0, dl, VT);
10626 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10627 // When looking for a 0 constant, N can be zext or sext.
10628 OtherOp = DAG.getConstant(1, dl, VT);
10629 else
10630 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10631 VT);
10632 return true;
10637 // Combine a constant select operand into its use:
10639 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10640 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10641 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10642 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10643 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10645 // The transform is rejected if the select doesn't have a constant operand that
10646 // is null, or all ones when AllOnes is set.
10648 // Also recognize sext/zext from i1:
10650 // (add (zext cc), x) -> (select cc (add x, 1), x)
10651 // (add (sext cc), x) -> (select cc (add x, -1), x)
10653 // These transformations eventually create predicated instructions.
10655 // @param N The node to transform.
10656 // @param Slct The N operand that is a select.
10657 // @param OtherOp The other N operand (x above).
10658 // @param DCI Context.
10659 // @param AllOnes Require the select constant to be all ones instead of null.
10660 // @returns The new node, or SDValue() on failure.
10661 static
10662 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10663 TargetLowering::DAGCombinerInfo &DCI,
10664 bool AllOnes = false) {
10665 SelectionDAG &DAG = DCI.DAG;
10666 EVT VT = N->getValueType(0);
10667 SDValue NonConstantVal;
10668 SDValue CCOp;
10669 bool SwapSelectOps;
10670 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10671 NonConstantVal, DAG))
10672 return SDValue();
10674 // Slct is now know to be the desired identity constant when CC is true.
10675 SDValue TrueVal = OtherOp;
10676 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10677 OtherOp, NonConstantVal);
10678 // Unless SwapSelectOps says CC should be false.
10679 if (SwapSelectOps)
10680 std::swap(TrueVal, FalseVal);
10682 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10683 CCOp, TrueVal, FalseVal);
10686 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10687 static
10688 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10689 TargetLowering::DAGCombinerInfo &DCI) {
10690 SDValue N0 = N->getOperand(0);
10691 SDValue N1 = N->getOperand(1);
10692 if (N0.getNode()->hasOneUse())
10693 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10694 return Result;
10695 if (N1.getNode()->hasOneUse())
10696 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10697 return Result;
10698 return SDValue();
10701 static bool IsVUZPShuffleNode(SDNode *N) {
10702 // VUZP shuffle node.
10703 if (N->getOpcode() == ARMISD::VUZP)
10704 return true;
10706 // "VUZP" on i32 is an alias for VTRN.
10707 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10708 return true;
10710 return false;
10713 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10714 TargetLowering::DAGCombinerInfo &DCI,
10715 const ARMSubtarget *Subtarget) {
10716 // Look for ADD(VUZP.0, VUZP.1).
10717 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10718 N0 == N1)
10719 return SDValue();
10721 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10722 if (!N->getValueType(0).is64BitVector())
10723 return SDValue();
10725 // Generate vpadd.
10726 SelectionDAG &DAG = DCI.DAG;
10727 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10728 SDLoc dl(N);
10729 SDNode *Unzip = N0.getNode();
10730 EVT VT = N->getValueType(0);
10732 SmallVector<SDValue, 8> Ops;
10733 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10734 TLI.getPointerTy(DAG.getDataLayout())));
10735 Ops.push_back(Unzip->getOperand(0));
10736 Ops.push_back(Unzip->getOperand(1));
10738 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10741 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10742 TargetLowering::DAGCombinerInfo &DCI,
10743 const ARMSubtarget *Subtarget) {
10744 // Check for two extended operands.
10745 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10746 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10747 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10748 N1.getOpcode() == ISD::ZERO_EXTEND))
10749 return SDValue();
10751 SDValue N00 = N0.getOperand(0);
10752 SDValue N10 = N1.getOperand(0);
10754 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10755 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10756 N00 == N10)
10757 return SDValue();
10759 // We only recognize Q register paddl here; this can't be reached until
10760 // after type legalization.
10761 if (!N00.getValueType().is64BitVector() ||
10762 !N0.getValueType().is128BitVector())
10763 return SDValue();
10765 // Generate vpaddl.
10766 SelectionDAG &DAG = DCI.DAG;
10767 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10768 SDLoc dl(N);
10769 EVT VT = N->getValueType(0);
10771 SmallVector<SDValue, 8> Ops;
10772 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10773 unsigned Opcode;
10774 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10775 Opcode = Intrinsic::arm_neon_vpaddls;
10776 else
10777 Opcode = Intrinsic::arm_neon_vpaddlu;
10778 Ops.push_back(DAG.getConstant(Opcode, dl,
10779 TLI.getPointerTy(DAG.getDataLayout())));
10780 EVT ElemTy = N00.getValueType().getVectorElementType();
10781 unsigned NumElts = VT.getVectorNumElements();
10782 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10783 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10784 N00.getOperand(0), N00.getOperand(1));
10785 Ops.push_back(Concat);
10787 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10790 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10791 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10792 // much easier to match.
10793 static SDValue
10794 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10795 TargetLowering::DAGCombinerInfo &DCI,
10796 const ARMSubtarget *Subtarget) {
10797 // Only perform optimization if after legalize, and if NEON is available. We
10798 // also expected both operands to be BUILD_VECTORs.
10799 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10800 || N0.getOpcode() != ISD::BUILD_VECTOR
10801 || N1.getOpcode() != ISD::BUILD_VECTOR)
10802 return SDValue();
10804 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10805 EVT VT = N->getValueType(0);
10806 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10807 return SDValue();
10809 // Check that the vector operands are of the right form.
10810 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
10811 // operands, where N is the size of the formed vector.
10812 // Each EXTRACT_VECTOR should have the same input vector and odd or even
10813 // index such that we have a pair wise add pattern.
10815 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
10816 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10817 return SDValue();
10818 SDValue Vec = N0->getOperand(0)->getOperand(0);
10819 SDNode *V = Vec.getNode();
10820 unsigned nextIndex = 0;
10822 // For each operands to the ADD which are BUILD_VECTORs,
10823 // check to see if each of their operands are an EXTRACT_VECTOR with
10824 // the same vector and appropriate index.
10825 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
10826 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
10827 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10829 SDValue ExtVec0 = N0->getOperand(i);
10830 SDValue ExtVec1 = N1->getOperand(i);
10832 // First operand is the vector, verify its the same.
10833 if (V != ExtVec0->getOperand(0).getNode() ||
10834 V != ExtVec1->getOperand(0).getNode())
10835 return SDValue();
10837 // Second is the constant, verify its correct.
10838 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
10839 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
10841 // For the constant, we want to see all the even or all the odd.
10842 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
10843 || C1->getZExtValue() != nextIndex+1)
10844 return SDValue();
10846 // Increment index.
10847 nextIndex+=2;
10848 } else
10849 return SDValue();
10852 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
10853 // we're using the entire input vector, otherwise there's a size/legality
10854 // mismatch somewhere.
10855 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10856 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10857 return SDValue();
10859 // Create VPADDL node.
10860 SelectionDAG &DAG = DCI.DAG;
10861 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10863 SDLoc dl(N);
10865 // Build operand list.
10866 SmallVector<SDValue, 8> Ops;
10867 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10868 TLI.getPointerTy(DAG.getDataLayout())));
10870 // Input is the vector.
10871 Ops.push_back(Vec);
10873 // Get widened type and narrowed type.
10874 MVT widenType;
10875 unsigned numElem = VT.getVectorNumElements();
10877 EVT inputLaneType = Vec.getValueType().getVectorElementType();
10878 switch (inputLaneType.getSimpleVT().SimpleTy) {
10879 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10880 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10881 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10882 default:
10883 llvm_unreachable("Invalid vector element type for padd optimization.");
10886 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
10887 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
10888 return DAG.getNode(ExtOp, dl, VT, tmp);
10891 static SDValue findMUL_LOHI(SDValue V) {
10892 if (V->getOpcode() == ISD::UMUL_LOHI ||
10893 V->getOpcode() == ISD::SMUL_LOHI)
10894 return V;
10895 return SDValue();
10898 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
10899 TargetLowering::DAGCombinerInfo &DCI,
10900 const ARMSubtarget *Subtarget) {
10901 if (Subtarget->isThumb()) {
10902 if (!Subtarget->hasDSP())
10903 return SDValue();
10904 } else if (!Subtarget->hasV5TEOps())
10905 return SDValue();
10907 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10908 // accumulates the product into a 64-bit value. The 16-bit values will
10909 // be sign extended somehow or SRA'd into 32-bit values
10910 // (addc (adde (mul 16bit, 16bit), lo), hi)
10911 SDValue Mul = AddcNode->getOperand(0);
10912 SDValue Lo = AddcNode->getOperand(1);
10913 if (Mul.getOpcode() != ISD::MUL) {
10914 Lo = AddcNode->getOperand(0);
10915 Mul = AddcNode->getOperand(1);
10916 if (Mul.getOpcode() != ISD::MUL)
10917 return SDValue();
10920 SDValue SRA = AddeNode->getOperand(0);
10921 SDValue Hi = AddeNode->getOperand(1);
10922 if (SRA.getOpcode() != ISD::SRA) {
10923 SRA = AddeNode->getOperand(1);
10924 Hi = AddeNode->getOperand(0);
10925 if (SRA.getOpcode() != ISD::SRA)
10926 return SDValue();
10928 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10929 if (Const->getZExtValue() != 31)
10930 return SDValue();
10931 } else
10932 return SDValue();
10934 if (SRA.getOperand(0) != Mul)
10935 return SDValue();
10937 SelectionDAG &DAG = DCI.DAG;
10938 SDLoc dl(AddcNode);
10939 unsigned Opcode = 0;
10940 SDValue Op0;
10941 SDValue Op1;
10943 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10944 Opcode = ARMISD::SMLALBB;
10945 Op0 = Mul.getOperand(0);
10946 Op1 = Mul.getOperand(1);
10947 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10948 Opcode = ARMISD::SMLALBT;
10949 Op0 = Mul.getOperand(0);
10950 Op1 = Mul.getOperand(1).getOperand(0);
10951 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10952 Opcode = ARMISD::SMLALTB;
10953 Op0 = Mul.getOperand(0).getOperand(0);
10954 Op1 = Mul.getOperand(1);
10955 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10956 Opcode = ARMISD::SMLALTT;
10957 Op0 = Mul->getOperand(0).getOperand(0);
10958 Op1 = Mul->getOperand(1).getOperand(0);
10961 if (!Op0 || !Op1)
10962 return SDValue();
10964 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10965 Op0, Op1, Lo, Hi);
10966 // Replace the ADDs' nodes uses by the MLA node's values.
10967 SDValue HiMLALResult(SMLAL.getNode(), 1);
10968 SDValue LoMLALResult(SMLAL.getNode(), 0);
10970 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10971 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10973 // Return original node to notify the driver to stop replacing.
10974 SDValue resNode(AddcNode, 0);
10975 return resNode;
10978 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10979 TargetLowering::DAGCombinerInfo &DCI,
10980 const ARMSubtarget *Subtarget) {
10981 // Look for multiply add opportunities.
10982 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10983 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10984 // a glue link from the first add to the second add.
10985 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10986 // a S/UMLAL instruction.
10987 // UMUL_LOHI
10988 // / :lo \ :hi
10989 // V \ [no multiline comment]
10990 // loAdd -> ADDC |
10991 // \ :carry /
10992 // V V
10993 // ADDE <- hiAdd
10995 // In the special case where only the higher part of a signed result is used
10996 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10997 // a constant with the exact value of 0x80000000, we recognize we are dealing
10998 // with a "rounded multiply and add" (or subtract) and transform it into
10999 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11001 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11002 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11003 "Expect an ADDE or SUBE");
11005 assert(AddeSubeNode->getNumOperands() == 3 &&
11006 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11007 "ADDE node has the wrong inputs");
11009 // Check that we are chained to the right ADDC or SUBC node.
11010 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11011 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11012 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11013 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11014 AddcSubcNode->getOpcode() != ARMISD::SUBC))
11015 return SDValue();
11017 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11018 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11020 // Check if the two operands are from the same mul_lohi node.
11021 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11022 return SDValue();
11024 assert(AddcSubcNode->getNumValues() == 2 &&
11025 AddcSubcNode->getValueType(0) == MVT::i32 &&
11026 "Expect ADDC with two result values. First: i32");
11028 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11029 // maybe a SMLAL which multiplies two 16-bit values.
11030 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11031 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11032 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11033 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11034 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11035 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11037 // Check for the triangle shape.
11038 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11039 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11041 // Make sure that the ADDE/SUBE operands are not coming from the same node.
11042 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11043 return SDValue();
11045 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11046 bool IsLeftOperandMUL = false;
11047 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11048 if (MULOp == SDValue())
11049 MULOp = findMUL_LOHI(AddeSubeOp1);
11050 else
11051 IsLeftOperandMUL = true;
11052 if (MULOp == SDValue())
11053 return SDValue();
11055 // Figure out the right opcode.
11056 unsigned Opc = MULOp->getOpcode();
11057 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11059 // Figure out the high and low input values to the MLAL node.
11060 SDValue *HiAddSub = nullptr;
11061 SDValue *LoMul = nullptr;
11062 SDValue *LowAddSub = nullptr;
11064 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11065 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11066 return SDValue();
11068 if (IsLeftOperandMUL)
11069 HiAddSub = &AddeSubeOp1;
11070 else
11071 HiAddSub = &AddeSubeOp0;
11073 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11074 // whose low result is fed to the ADDC/SUBC we are checking.
11076 if (AddcSubcOp0 == MULOp.getValue(0)) {
11077 LoMul = &AddcSubcOp0;
11078 LowAddSub = &AddcSubcOp1;
11080 if (AddcSubcOp1 == MULOp.getValue(0)) {
11081 LoMul = &AddcSubcOp1;
11082 LowAddSub = &AddcSubcOp0;
11085 if (!LoMul)
11086 return SDValue();
11088 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11089 // the replacement below will create a cycle.
11090 if (AddcSubcNode == HiAddSub->getNode() ||
11091 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11092 return SDValue();
11094 // Create the merged node.
11095 SelectionDAG &DAG = DCI.DAG;
11097 // Start building operand list.
11098 SmallVector<SDValue, 8> Ops;
11099 Ops.push_back(LoMul->getOperand(0));
11100 Ops.push_back(LoMul->getOperand(1));
11102 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
11103 // the case, we must be doing signed multiplication and only use the higher
11104 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11105 // addition or subtraction with the value of 0x800000.
11106 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11107 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11108 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11109 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11110 0x80000000) {
11111 Ops.push_back(*HiAddSub);
11112 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11113 FinalOpc = ARMISD::SMMLSR;
11114 } else {
11115 FinalOpc = ARMISD::SMMLAR;
11117 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11118 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11120 return SDValue(AddeSubeNode, 0);
11121 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11122 // SMMLS is generated during instruction selection and the rest of this
11123 // function can not handle the case where AddcSubcNode is a SUBC.
11124 return SDValue();
11126 // Finish building the operand list for {U/S}MLAL
11127 Ops.push_back(*LowAddSub);
11128 Ops.push_back(*HiAddSub);
11130 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11131 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11133 // Replace the ADDs' nodes uses by the MLA node's values.
11134 SDValue HiMLALResult(MLALNode.getNode(), 1);
11135 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11137 SDValue LoMLALResult(MLALNode.getNode(), 0);
11138 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11140 // Return original node to notify the driver to stop replacing.
11141 return SDValue(AddeSubeNode, 0);
11144 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11145 TargetLowering::DAGCombinerInfo &DCI,
11146 const ARMSubtarget *Subtarget) {
11147 // UMAAL is similar to UMLAL except that it adds two unsigned values.
11148 // While trying to combine for the other MLAL nodes, first search for the
11149 // chance to use UMAAL. Check if Addc uses a node which has already
11150 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11151 // as the addend, and it's handled in PerformUMLALCombine.
11153 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11154 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11156 // Check that we have a glued ADDC node.
11157 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11158 if (AddcNode->getOpcode() != ARMISD::ADDC)
11159 return SDValue();
11161 // Find the converted UMAAL or quit if it doesn't exist.
11162 SDNode *UmlalNode = nullptr;
11163 SDValue AddHi;
11164 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11165 UmlalNode = AddcNode->getOperand(0).getNode();
11166 AddHi = AddcNode->getOperand(1);
11167 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11168 UmlalNode = AddcNode->getOperand(1).getNode();
11169 AddHi = AddcNode->getOperand(0);
11170 } else {
11171 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11174 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11175 // the ADDC as well as Zero.
11176 if (!isNullConstant(UmlalNode->getOperand(3)))
11177 return SDValue();
11179 if ((isNullConstant(AddeNode->getOperand(0)) &&
11180 AddeNode->getOperand(1).getNode() == UmlalNode) ||
11181 (AddeNode->getOperand(0).getNode() == UmlalNode &&
11182 isNullConstant(AddeNode->getOperand(1)))) {
11183 SelectionDAG &DAG = DCI.DAG;
11184 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11185 UmlalNode->getOperand(2), AddHi };
11186 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11187 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11189 // Replace the ADDs' nodes uses by the UMAAL node's values.
11190 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11191 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11193 // Return original node to notify the driver to stop replacing.
11194 return SDValue(AddeNode, 0);
11196 return SDValue();
11199 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11200 const ARMSubtarget *Subtarget) {
11201 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11202 return SDValue();
11204 // Check that we have a pair of ADDC and ADDE as operands.
11205 // Both addends of the ADDE must be zero.
11206 SDNode* AddcNode = N->getOperand(2).getNode();
11207 SDNode* AddeNode = N->getOperand(3).getNode();
11208 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11209 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11210 isNullConstant(AddeNode->getOperand(0)) &&
11211 isNullConstant(AddeNode->getOperand(1)) &&
11212 (AddeNode->getOperand(2).getNode() == AddcNode))
11213 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11214 DAG.getVTList(MVT::i32, MVT::i32),
11215 {N->getOperand(0), N->getOperand(1),
11216 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11217 else
11218 return SDValue();
11221 static SDValue PerformAddcSubcCombine(SDNode *N,
11222 TargetLowering::DAGCombinerInfo &DCI,
11223 const ARMSubtarget *Subtarget) {
11224 SelectionDAG &DAG(DCI.DAG);
11226 if (N->getOpcode() == ARMISD::SUBC) {
11227 // (SUBC (ADDE 0, 0, C), 1) -> C
11228 SDValue LHS = N->getOperand(0);
11229 SDValue RHS = N->getOperand(1);
11230 if (LHS->getOpcode() == ARMISD::ADDE &&
11231 isNullConstant(LHS->getOperand(0)) &&
11232 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11233 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11237 if (Subtarget->isThumb1Only()) {
11238 SDValue RHS = N->getOperand(1);
11239 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11240 int32_t imm = C->getSExtValue();
11241 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11242 SDLoc DL(N);
11243 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11244 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11245 : ARMISD::ADDC;
11246 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11251 return SDValue();
11254 static SDValue PerformAddeSubeCombine(SDNode *N,
11255 TargetLowering::DAGCombinerInfo &DCI,
11256 const ARMSubtarget *Subtarget) {
11257 if (Subtarget->isThumb1Only()) {
11258 SelectionDAG &DAG = DCI.DAG;
11259 SDValue RHS = N->getOperand(1);
11260 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11261 int64_t imm = C->getSExtValue();
11262 if (imm < 0) {
11263 SDLoc DL(N);
11265 // The with-carry-in form matches bitwise not instead of the negation.
11266 // Effectively, the inverse interpretation of the carry flag already
11267 // accounts for part of the negation.
11268 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11270 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11271 : ARMISD::ADDE;
11272 return DAG.getNode(Opcode, DL, N->getVTList(),
11273 N->getOperand(0), RHS, N->getOperand(2));
11276 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11277 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11279 return SDValue();
11282 static SDValue PerformABSCombine(SDNode *N,
11283 TargetLowering::DAGCombinerInfo &DCI,
11284 const ARMSubtarget *Subtarget) {
11285 SDValue res;
11286 SelectionDAG &DAG = DCI.DAG;
11287 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11289 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11290 return SDValue();
11292 if (!TLI.expandABS(N, res, DAG))
11293 return SDValue();
11295 return res;
11298 /// PerformADDECombine - Target-specific dag combine transform from
11299 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11300 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11301 static SDValue PerformADDECombine(SDNode *N,
11302 TargetLowering::DAGCombinerInfo &DCI,
11303 const ARMSubtarget *Subtarget) {
11304 // Only ARM and Thumb2 support UMLAL/SMLAL.
11305 if (Subtarget->isThumb1Only())
11306 return PerformAddeSubeCombine(N, DCI, Subtarget);
11308 // Only perform the checks after legalize when the pattern is available.
11309 if (DCI.isBeforeLegalize()) return SDValue();
11311 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11314 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11315 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11316 /// called with the default operands, and if that fails, with commuted
11317 /// operands.
11318 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11319 TargetLowering::DAGCombinerInfo &DCI,
11320 const ARMSubtarget *Subtarget){
11321 // Attempt to create vpadd for this add.
11322 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11323 return Result;
11325 // Attempt to create vpaddl for this add.
11326 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11327 return Result;
11328 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11329 Subtarget))
11330 return Result;
11332 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11333 if (N0.getNode()->hasOneUse())
11334 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11335 return Result;
11336 return SDValue();
11339 bool
11340 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11341 CombineLevel Level) const {
11342 if (Level == BeforeLegalizeTypes)
11343 return true;
11345 if (N->getOpcode() != ISD::SHL)
11346 return true;
11348 if (Subtarget->isThumb1Only()) {
11349 // Avoid making expensive immediates by commuting shifts. (This logic
11350 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11351 // for free.)
11352 if (N->getOpcode() != ISD::SHL)
11353 return true;
11354 SDValue N1 = N->getOperand(0);
11355 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11356 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11357 return true;
11358 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11359 if (Const->getAPIntValue().ult(256))
11360 return false;
11361 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11362 Const->getAPIntValue().sgt(-256))
11363 return false;
11365 return true;
11368 // Turn off commute-with-shift transform after legalization, so it doesn't
11369 // conflict with PerformSHLSimplify. (We could try to detect when
11370 // PerformSHLSimplify would trigger more precisely, but it isn't
11371 // really necessary.)
11372 return false;
11375 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11376 const SDNode *N, CombineLevel Level) const {
11377 if (!Subtarget->isThumb1Only())
11378 return true;
11380 if (Level == BeforeLegalizeTypes)
11381 return true;
11383 return false;
11386 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11387 if (!Subtarget->hasNEON()) {
11388 if (Subtarget->isThumb1Only())
11389 return VT.getScalarSizeInBits() <= 32;
11390 return true;
11392 return VT.isScalarInteger();
11395 static SDValue PerformSHLSimplify(SDNode *N,
11396 TargetLowering::DAGCombinerInfo &DCI,
11397 const ARMSubtarget *ST) {
11398 // Allow the generic combiner to identify potential bswaps.
11399 if (DCI.isBeforeLegalize())
11400 return SDValue();
11402 // DAG combiner will fold:
11403 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11404 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11405 // Other code patterns that can be also be modified have the following form:
11406 // b + ((a << 1) | 510)
11407 // b + ((a << 1) & 510)
11408 // b + ((a << 1) ^ 510)
11409 // b + ((a << 1) + 510)
11411 // Many instructions can perform the shift for free, but it requires both
11412 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11413 // instruction will needed. So, unfold back to the original pattern if:
11414 // - if c1 and c2 are small enough that they don't require mov imms.
11415 // - the user(s) of the node can perform an shl
11417 // No shifted operands for 16-bit instructions.
11418 if (ST->isThumb() && ST->isThumb1Only())
11419 return SDValue();
11421 // Check that all the users could perform the shl themselves.
11422 for (auto U : N->uses()) {
11423 switch(U->getOpcode()) {
11424 default:
11425 return SDValue();
11426 case ISD::SUB:
11427 case ISD::ADD:
11428 case ISD::AND:
11429 case ISD::OR:
11430 case ISD::XOR:
11431 case ISD::SETCC:
11432 case ARMISD::CMP:
11433 // Check that the user isn't already using a constant because there
11434 // aren't any instructions that support an immediate operand and a
11435 // shifted operand.
11436 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11437 isa<ConstantSDNode>(U->getOperand(1)))
11438 return SDValue();
11440 // Check that it's not already using a shift.
11441 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11442 U->getOperand(1).getOpcode() == ISD::SHL)
11443 return SDValue();
11444 break;
11448 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11449 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11450 return SDValue();
11452 if (N->getOperand(0).getOpcode() != ISD::SHL)
11453 return SDValue();
11455 SDValue SHL = N->getOperand(0);
11457 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11458 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11459 if (!C1ShlC2 || !C2)
11460 return SDValue();
11462 APInt C2Int = C2->getAPIntValue();
11463 APInt C1Int = C1ShlC2->getAPIntValue();
11465 // Check that performing a lshr will not lose any information.
11466 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11467 C2Int.getBitWidth() - C2->getZExtValue());
11468 if ((C1Int & Mask) != C1Int)
11469 return SDValue();
11471 // Shift the first constant.
11472 C1Int.lshrInPlace(C2Int);
11474 // The immediates are encoded as an 8-bit value that can be rotated.
11475 auto LargeImm = [](const APInt &Imm) {
11476 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11477 return Imm.getBitWidth() - Zeros > 8;
11480 if (LargeImm(C1Int) || LargeImm(C2Int))
11481 return SDValue();
11483 SelectionDAG &DAG = DCI.DAG;
11484 SDLoc dl(N);
11485 SDValue X = SHL.getOperand(0);
11486 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11487 DAG.getConstant(C1Int, dl, MVT::i32));
11488 // Shift left to compensate for the lshr of C1Int.
11489 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11491 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11492 SHL.dump(); N->dump());
11493 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11494 return Res;
11498 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11500 static SDValue PerformADDCombine(SDNode *N,
11501 TargetLowering::DAGCombinerInfo &DCI,
11502 const ARMSubtarget *Subtarget) {
11503 SDValue N0 = N->getOperand(0);
11504 SDValue N1 = N->getOperand(1);
11506 // Only works one way, because it needs an immediate operand.
11507 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11508 return Result;
11510 // First try with the default operand order.
11511 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11512 return Result;
11514 // If that didn't work, try again with the operands commuted.
11515 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11518 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11520 static SDValue PerformSUBCombine(SDNode *N,
11521 TargetLowering::DAGCombinerInfo &DCI) {
11522 SDValue N0 = N->getOperand(0);
11523 SDValue N1 = N->getOperand(1);
11525 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11526 if (N1.getNode()->hasOneUse())
11527 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11528 return Result;
11530 return SDValue();
11533 /// PerformVMULCombine
11534 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11535 /// special multiplier accumulator forwarding.
11536 /// vmul d3, d0, d2
11537 /// vmla d3, d1, d2
11538 /// is faster than
11539 /// vadd d3, d0, d1
11540 /// vmul d3, d3, d2
11541 // However, for (A + B) * (A + B),
11542 // vadd d2, d0, d1
11543 // vmul d3, d0, d2
11544 // vmla d3, d1, d2
11545 // is slower than
11546 // vadd d2, d0, d1
11547 // vmul d3, d2, d2
11548 static SDValue PerformVMULCombine(SDNode *N,
11549 TargetLowering::DAGCombinerInfo &DCI,
11550 const ARMSubtarget *Subtarget) {
11551 if (!Subtarget->hasVMLxForwarding())
11552 return SDValue();
11554 SelectionDAG &DAG = DCI.DAG;
11555 SDValue N0 = N->getOperand(0);
11556 SDValue N1 = N->getOperand(1);
11557 unsigned Opcode = N0.getOpcode();
11558 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11559 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11560 Opcode = N1.getOpcode();
11561 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11562 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11563 return SDValue();
11564 std::swap(N0, N1);
11567 if (N0 == N1)
11568 return SDValue();
11570 EVT VT = N->getValueType(0);
11571 SDLoc DL(N);
11572 SDValue N00 = N0->getOperand(0);
11573 SDValue N01 = N0->getOperand(1);
11574 return DAG.getNode(Opcode, DL, VT,
11575 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11576 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11579 static SDValue PerformMULCombine(SDNode *N,
11580 TargetLowering::DAGCombinerInfo &DCI,
11581 const ARMSubtarget *Subtarget) {
11582 SelectionDAG &DAG = DCI.DAG;
11584 if (Subtarget->isThumb1Only())
11585 return SDValue();
11587 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11588 return SDValue();
11590 EVT VT = N->getValueType(0);
11591 if (VT.is64BitVector() || VT.is128BitVector())
11592 return PerformVMULCombine(N, DCI, Subtarget);
11593 if (VT != MVT::i32)
11594 return SDValue();
11596 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11597 if (!C)
11598 return SDValue();
11600 int64_t MulAmt = C->getSExtValue();
11601 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11603 ShiftAmt = ShiftAmt & (32 - 1);
11604 SDValue V = N->getOperand(0);
11605 SDLoc DL(N);
11607 SDValue Res;
11608 MulAmt >>= ShiftAmt;
11610 if (MulAmt >= 0) {
11611 if (isPowerOf2_32(MulAmt - 1)) {
11612 // (mul x, 2^N + 1) => (add (shl x, N), x)
11613 Res = DAG.getNode(ISD::ADD, DL, VT,
11615 DAG.getNode(ISD::SHL, DL, VT,
11617 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11618 MVT::i32)));
11619 } else if (isPowerOf2_32(MulAmt + 1)) {
11620 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11621 Res = DAG.getNode(ISD::SUB, DL, VT,
11622 DAG.getNode(ISD::SHL, DL, VT,
11624 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11625 MVT::i32)),
11627 } else
11628 return SDValue();
11629 } else {
11630 uint64_t MulAmtAbs = -MulAmt;
11631 if (isPowerOf2_32(MulAmtAbs + 1)) {
11632 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11633 Res = DAG.getNode(ISD::SUB, DL, VT,
11635 DAG.getNode(ISD::SHL, DL, VT,
11637 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11638 MVT::i32)));
11639 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11640 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11641 Res = DAG.getNode(ISD::ADD, DL, VT,
11643 DAG.getNode(ISD::SHL, DL, VT,
11645 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11646 MVT::i32)));
11647 Res = DAG.getNode(ISD::SUB, DL, VT,
11648 DAG.getConstant(0, DL, MVT::i32), Res);
11649 } else
11650 return SDValue();
11653 if (ShiftAmt != 0)
11654 Res = DAG.getNode(ISD::SHL, DL, VT,
11655 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11657 // Do not add new nodes to DAG combiner worklist.
11658 DCI.CombineTo(N, Res, false);
11659 return SDValue();
11662 static SDValue CombineANDShift(SDNode *N,
11663 TargetLowering::DAGCombinerInfo &DCI,
11664 const ARMSubtarget *Subtarget) {
11665 // Allow DAGCombine to pattern-match before we touch the canonical form.
11666 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11667 return SDValue();
11669 if (N->getValueType(0) != MVT::i32)
11670 return SDValue();
11672 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11673 if (!N1C)
11674 return SDValue();
11676 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11677 // Don't transform uxtb/uxth.
11678 if (C1 == 255 || C1 == 65535)
11679 return SDValue();
11681 SDNode *N0 = N->getOperand(0).getNode();
11682 if (!N0->hasOneUse())
11683 return SDValue();
11685 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11686 return SDValue();
11688 bool LeftShift = N0->getOpcode() == ISD::SHL;
11690 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11691 if (!N01C)
11692 return SDValue();
11694 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11695 if (!C2 || C2 >= 32)
11696 return SDValue();
11698 // Clear irrelevant bits in the mask.
11699 if (LeftShift)
11700 C1 &= (-1U << C2);
11701 else
11702 C1 &= (-1U >> C2);
11704 SelectionDAG &DAG = DCI.DAG;
11705 SDLoc DL(N);
11707 // We have a pattern of the form "(and (shl x, c2) c1)" or
11708 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11709 // transform to a pair of shifts, to save materializing c1.
11711 // First pattern: right shift, then mask off leading bits.
11712 // FIXME: Use demanded bits?
11713 if (!LeftShift && isMask_32(C1)) {
11714 uint32_t C3 = countLeadingZeros(C1);
11715 if (C2 < C3) {
11716 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11717 DAG.getConstant(C3 - C2, DL, MVT::i32));
11718 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11719 DAG.getConstant(C3, DL, MVT::i32));
11723 // First pattern, reversed: left shift, then mask off trailing bits.
11724 if (LeftShift && isMask_32(~C1)) {
11725 uint32_t C3 = countTrailingZeros(C1);
11726 if (C2 < C3) {
11727 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11728 DAG.getConstant(C3 - C2, DL, MVT::i32));
11729 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11730 DAG.getConstant(C3, DL, MVT::i32));
11734 // Second pattern: left shift, then mask off leading bits.
11735 // FIXME: Use demanded bits?
11736 if (LeftShift && isShiftedMask_32(C1)) {
11737 uint32_t Trailing = countTrailingZeros(C1);
11738 uint32_t C3 = countLeadingZeros(C1);
11739 if (Trailing == C2 && C2 + C3 < 32) {
11740 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11741 DAG.getConstant(C2 + C3, DL, MVT::i32));
11742 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11743 DAG.getConstant(C3, DL, MVT::i32));
11747 // Second pattern, reversed: right shift, then mask off trailing bits.
11748 // FIXME: Handle other patterns of known/demanded bits.
11749 if (!LeftShift && isShiftedMask_32(C1)) {
11750 uint32_t Leading = countLeadingZeros(C1);
11751 uint32_t C3 = countTrailingZeros(C1);
11752 if (Leading == C2 && C2 + C3 < 32) {
11753 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11754 DAG.getConstant(C2 + C3, DL, MVT::i32));
11755 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11756 DAG.getConstant(C3, DL, MVT::i32));
11760 // FIXME: Transform "(and (shl x, c2) c1)" ->
11761 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11762 // c1.
11763 return SDValue();
11766 static SDValue PerformANDCombine(SDNode *N,
11767 TargetLowering::DAGCombinerInfo &DCI,
11768 const ARMSubtarget *Subtarget) {
11769 // Attempt to use immediate-form VBIC
11770 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11771 SDLoc dl(N);
11772 EVT VT = N->getValueType(0);
11773 SelectionDAG &DAG = DCI.DAG;
11775 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11776 return SDValue();
11778 APInt SplatBits, SplatUndef;
11779 unsigned SplatBitSize;
11780 bool HasAnyUndefs;
11781 if (BVN && Subtarget->hasNEON() &&
11782 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11783 if (SplatBitSize <= 64) {
11784 EVT VbicVT;
11785 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11786 SplatUndef.getZExtValue(), SplatBitSize,
11787 DAG, dl, VbicVT, VT.is128BitVector(),
11788 OtherModImm);
11789 if (Val.getNode()) {
11790 SDValue Input =
11791 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11792 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11793 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11798 if (!Subtarget->isThumb1Only()) {
11799 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11800 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11801 return Result;
11803 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11804 return Result;
11807 if (Subtarget->isThumb1Only())
11808 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
11809 return Result;
11811 return SDValue();
11814 // Try combining OR nodes to SMULWB, SMULWT.
11815 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
11816 TargetLowering::DAGCombinerInfo &DCI,
11817 const ARMSubtarget *Subtarget) {
11818 if (!Subtarget->hasV6Ops() ||
11819 (Subtarget->isThumb() &&
11820 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
11821 return SDValue();
11823 SDValue SRL = OR->getOperand(0);
11824 SDValue SHL = OR->getOperand(1);
11826 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
11827 SRL = OR->getOperand(1);
11828 SHL = OR->getOperand(0);
11830 if (!isSRL16(SRL) || !isSHL16(SHL))
11831 return SDValue();
11833 // The first operands to the shifts need to be the two results from the
11834 // same smul_lohi node.
11835 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
11836 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
11837 return SDValue();
11839 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
11840 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
11841 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
11842 return SDValue();
11844 // Now we have:
11845 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
11846 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
11847 // For SMUWB the 16-bit value will signed extended somehow.
11848 // For SMULWT only the SRA is required.
11849 // Check both sides of SMUL_LOHI
11850 SDValue OpS16 = SMULLOHI->getOperand(0);
11851 SDValue OpS32 = SMULLOHI->getOperand(1);
11853 SelectionDAG &DAG = DCI.DAG;
11854 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
11855 OpS16 = OpS32;
11856 OpS32 = SMULLOHI->getOperand(0);
11859 SDLoc dl(OR);
11860 unsigned Opcode = 0;
11861 if (isS16(OpS16, DAG))
11862 Opcode = ARMISD::SMULWB;
11863 else if (isSRA16(OpS16)) {
11864 Opcode = ARMISD::SMULWT;
11865 OpS16 = OpS16->getOperand(0);
11867 else
11868 return SDValue();
11870 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11871 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11872 return SDValue(OR, 0);
11875 static SDValue PerformORCombineToBFI(SDNode *N,
11876 TargetLowering::DAGCombinerInfo &DCI,
11877 const ARMSubtarget *Subtarget) {
11878 // BFI is only available on V6T2+
11879 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11880 return SDValue();
11882 EVT VT = N->getValueType(0);
11883 SDValue N0 = N->getOperand(0);
11884 SDValue N1 = N->getOperand(1);
11885 SelectionDAG &DAG = DCI.DAG;
11886 SDLoc DL(N);
11887 // 1) or (and A, mask), val => ARMbfi A, val, mask
11888 // iff (val & mask) == val
11890 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11891 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
11892 // && mask == ~mask2
11893 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
11894 // && ~mask == mask2
11895 // (i.e., copy a bitfield value into another bitfield of the same width)
11897 if (VT != MVT::i32)
11898 return SDValue();
11900 SDValue N00 = N0.getOperand(0);
11902 // The value and the mask need to be constants so we can verify this is
11903 // actually a bitfield set. If the mask is 0xffff, we can do better
11904 // via a movt instruction, so don't use BFI in that case.
11905 SDValue MaskOp = N0.getOperand(1);
11906 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
11907 if (!MaskC)
11908 return SDValue();
11909 unsigned Mask = MaskC->getZExtValue();
11910 if (Mask == 0xffff)
11911 return SDValue();
11912 SDValue Res;
11913 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
11914 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11915 if (N1C) {
11916 unsigned Val = N1C->getZExtValue();
11917 if ((Val & ~Mask) != Val)
11918 return SDValue();
11920 if (ARM::isBitFieldInvertedMask(Mask)) {
11921 Val >>= countTrailingZeros(~Mask);
11923 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
11924 DAG.getConstant(Val, DL, MVT::i32),
11925 DAG.getConstant(Mask, DL, MVT::i32));
11927 DCI.CombineTo(N, Res, false);
11928 // Return value from the original node to inform the combiner than N is
11929 // now dead.
11930 return SDValue(N, 0);
11932 } else if (N1.getOpcode() == ISD::AND) {
11933 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11934 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11935 if (!N11C)
11936 return SDValue();
11937 unsigned Mask2 = N11C->getZExtValue();
11939 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
11940 // as is to match.
11941 if (ARM::isBitFieldInvertedMask(Mask) &&
11942 (Mask == ~Mask2)) {
11943 // The pack halfword instruction works better for masks that fit it,
11944 // so use that when it's available.
11945 if (Subtarget->hasDSP() &&
11946 (Mask == 0xffff || Mask == 0xffff0000))
11947 return SDValue();
11948 // 2a
11949 unsigned amt = countTrailingZeros(Mask2);
11950 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
11951 DAG.getConstant(amt, DL, MVT::i32));
11952 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
11953 DAG.getConstant(Mask, DL, MVT::i32));
11954 DCI.CombineTo(N, Res, false);
11955 // Return value from the original node to inform the combiner than N is
11956 // now dead.
11957 return SDValue(N, 0);
11958 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
11959 (~Mask == Mask2)) {
11960 // The pack halfword instruction works better for masks that fit it,
11961 // so use that when it's available.
11962 if (Subtarget->hasDSP() &&
11963 (Mask2 == 0xffff || Mask2 == 0xffff0000))
11964 return SDValue();
11965 // 2b
11966 unsigned lsb = countTrailingZeros(Mask);
11967 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
11968 DAG.getConstant(lsb, DL, MVT::i32));
11969 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
11970 DAG.getConstant(Mask2, DL, MVT::i32));
11971 DCI.CombineTo(N, Res, false);
11972 // Return value from the original node to inform the combiner than N is
11973 // now dead.
11974 return SDValue(N, 0);
11978 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
11979 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
11980 ARM::isBitFieldInvertedMask(~Mask)) {
11981 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
11982 // where lsb(mask) == #shamt and masked bits of B are known zero.
11983 SDValue ShAmt = N00.getOperand(1);
11984 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
11985 unsigned LSB = countTrailingZeros(Mask);
11986 if (ShAmtC != LSB)
11987 return SDValue();
11989 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11990 DAG.getConstant(~Mask, DL, MVT::i32));
11992 DCI.CombineTo(N, Res, false);
11993 // Return value from the original node to inform the combiner than N is
11994 // now dead.
11995 return SDValue(N, 0);
11998 return SDValue();
12001 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12002 switch (CC) {
12003 case ARMCC::EQ:
12004 case ARMCC::NE:
12005 case ARMCC::LE:
12006 case ARMCC::GT:
12007 case ARMCC::GE:
12008 case ARMCC::LT:
12009 return true;
12010 case ARMCC::HS:
12011 case ARMCC::HI:
12012 return !IsFloat;
12013 default:
12014 return false;
12018 static SDValue PerformORCombine_i1(SDNode *N,
12019 TargetLowering::DAGCombinerInfo &DCI,
12020 const ARMSubtarget *Subtarget) {
12021 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12022 // together with predicates
12023 EVT VT = N->getValueType(0);
12024 SDValue N0 = N->getOperand(0);
12025 SDValue N1 = N->getOperand(1);
12027 ARMCC::CondCodes CondCode0 = ARMCC::AL;
12028 ARMCC::CondCodes CondCode1 = ARMCC::AL;
12029 if (N0->getOpcode() == ARMISD::VCMP)
12030 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
12031 ->getZExtValue();
12032 else if (N0->getOpcode() == ARMISD::VCMPZ)
12033 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
12034 ->getZExtValue();
12035 if (N1->getOpcode() == ARMISD::VCMP)
12036 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
12037 ->getZExtValue();
12038 else if (N1->getOpcode() == ARMISD::VCMPZ)
12039 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
12040 ->getZExtValue();
12042 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
12043 return SDValue();
12045 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
12046 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
12048 if (!isValidMVECond(Opposite0,
12049 N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
12050 !isValidMVECond(Opposite1,
12051 N1->getOperand(0)->getValueType(0).isFloatingPoint()))
12052 return SDValue();
12054 SmallVector<SDValue, 4> Ops0;
12055 Ops0.push_back(N0->getOperand(0));
12056 if (N0->getOpcode() == ARMISD::VCMP)
12057 Ops0.push_back(N0->getOperand(1));
12058 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12059 SmallVector<SDValue, 4> Ops1;
12060 Ops1.push_back(N1->getOperand(0));
12061 if (N1->getOpcode() == ARMISD::VCMP)
12062 Ops1.push_back(N1->getOperand(1));
12063 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12065 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12066 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12067 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12068 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12069 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12072 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12073 static SDValue PerformORCombine(SDNode *N,
12074 TargetLowering::DAGCombinerInfo &DCI,
12075 const ARMSubtarget *Subtarget) {
12076 // Attempt to use immediate-form VORR
12077 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12078 SDLoc dl(N);
12079 EVT VT = N->getValueType(0);
12080 SelectionDAG &DAG = DCI.DAG;
12082 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12083 return SDValue();
12085 APInt SplatBits, SplatUndef;
12086 unsigned SplatBitSize;
12087 bool HasAnyUndefs;
12088 if (BVN && Subtarget->hasNEON() &&
12089 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12090 if (SplatBitSize <= 64) {
12091 EVT VorrVT;
12092 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
12093 SplatUndef.getZExtValue(), SplatBitSize,
12094 DAG, dl, VorrVT, VT.is128BitVector(),
12095 OtherModImm);
12096 if (Val.getNode()) {
12097 SDValue Input =
12098 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12099 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12100 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12105 if (!Subtarget->isThumb1Only()) {
12106 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12107 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12108 return Result;
12109 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12110 return Result;
12113 SDValue N0 = N->getOperand(0);
12114 SDValue N1 = N->getOperand(1);
12116 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12117 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12118 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12120 // The code below optimizes (or (and X, Y), Z).
12121 // The AND operand needs to have a single user to make these optimizations
12122 // profitable.
12123 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12124 return SDValue();
12126 APInt SplatUndef;
12127 unsigned SplatBitSize;
12128 bool HasAnyUndefs;
12130 APInt SplatBits0, SplatBits1;
12131 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12132 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12133 // Ensure that the second operand of both ands are constants
12134 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12135 HasAnyUndefs) && !HasAnyUndefs) {
12136 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12137 HasAnyUndefs) && !HasAnyUndefs) {
12138 // Ensure that the bit width of the constants are the same and that
12139 // the splat arguments are logical inverses as per the pattern we
12140 // are trying to simplify.
12141 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12142 SplatBits0 == ~SplatBits1) {
12143 // Canonicalize the vector type to make instruction selection
12144 // simpler.
12145 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12146 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12147 N0->getOperand(1),
12148 N0->getOperand(0),
12149 N1->getOperand(0));
12150 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12156 if (Subtarget->hasMVEIntegerOps() &&
12157 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12158 return PerformORCombine_i1(N, DCI, Subtarget);
12160 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12161 // reasonable.
12162 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12163 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12164 return Res;
12167 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12168 return Result;
12170 return SDValue();
12173 static SDValue PerformXORCombine(SDNode *N,
12174 TargetLowering::DAGCombinerInfo &DCI,
12175 const ARMSubtarget *Subtarget) {
12176 EVT VT = N->getValueType(0);
12177 SelectionDAG &DAG = DCI.DAG;
12179 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12180 return SDValue();
12182 if (!Subtarget->isThumb1Only()) {
12183 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12184 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12185 return Result;
12187 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12188 return Result;
12191 return SDValue();
12194 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12195 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12196 // their position in "to" (Rd).
12197 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12198 assert(N->getOpcode() == ARMISD::BFI);
12200 SDValue From = N->getOperand(1);
12201 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12202 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12204 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12205 // #C in the base of the SHR.
12206 if (From->getOpcode() == ISD::SRL &&
12207 isa<ConstantSDNode>(From->getOperand(1))) {
12208 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12209 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12210 FromMask <<= Shift.getLimitedValue(31);
12211 From = From->getOperand(0);
12214 return From;
12217 // If A and B contain one contiguous set of bits, does A | B == A . B?
12219 // Neither A nor B must be zero.
12220 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12221 unsigned LastActiveBitInA = A.countTrailingZeros();
12222 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12223 return LastActiveBitInA - 1 == FirstActiveBitInB;
12226 static SDValue FindBFIToCombineWith(SDNode *N) {
12227 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12228 // if one exists.
12229 APInt ToMask, FromMask;
12230 SDValue From = ParseBFI(N, ToMask, FromMask);
12231 SDValue To = N->getOperand(0);
12233 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12234 // aren't compatible, but not if they set the same bit in their destination as
12235 // we do (or that of any BFI we're going to combine with).
12236 SDValue V = To;
12237 APInt CombinedToMask = ToMask;
12238 while (V.getOpcode() == ARMISD::BFI) {
12239 APInt NewToMask, NewFromMask;
12240 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12241 if (NewFrom != From) {
12242 // This BFI has a different base. Keep going.
12243 CombinedToMask |= NewToMask;
12244 V = V.getOperand(0);
12245 continue;
12248 // Do the written bits conflict with any we've seen so far?
12249 if ((NewToMask & CombinedToMask).getBoolValue())
12250 // Conflicting bits - bail out because going further is unsafe.
12251 return SDValue();
12253 // Are the new bits contiguous when combined with the old bits?
12254 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12255 BitsProperlyConcatenate(FromMask, NewFromMask))
12256 return V;
12257 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12258 BitsProperlyConcatenate(NewFromMask, FromMask))
12259 return V;
12261 // We've seen a write to some bits, so track it.
12262 CombinedToMask |= NewToMask;
12263 // Keep going...
12264 V = V.getOperand(0);
12267 return SDValue();
12270 static SDValue PerformBFICombine(SDNode *N,
12271 TargetLowering::DAGCombinerInfo &DCI) {
12272 SDValue N1 = N->getOperand(1);
12273 if (N1.getOpcode() == ISD::AND) {
12274 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12275 // the bits being cleared by the AND are not demanded by the BFI.
12276 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12277 if (!N11C)
12278 return SDValue();
12279 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12280 unsigned LSB = countTrailingZeros(~InvMask);
12281 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12282 assert(Width <
12283 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12284 "undefined behavior");
12285 unsigned Mask = (1u << Width) - 1;
12286 unsigned Mask2 = N11C->getZExtValue();
12287 if ((Mask & (~Mask2)) == 0)
12288 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12289 N->getOperand(0), N1.getOperand(0),
12290 N->getOperand(2));
12291 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12292 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12293 // Keep track of any consecutive bits set that all come from the same base
12294 // value. We can combine these together into a single BFI.
12295 SDValue CombineBFI = FindBFIToCombineWith(N);
12296 if (CombineBFI == SDValue())
12297 return SDValue();
12299 // We've found a BFI.
12300 APInt ToMask1, FromMask1;
12301 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12303 APInt ToMask2, FromMask2;
12304 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12305 assert(From1 == From2);
12306 (void)From2;
12308 // First, unlink CombineBFI.
12309 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12310 // Then create a new BFI, combining the two together.
12311 APInt NewFromMask = FromMask1 | FromMask2;
12312 APInt NewToMask = ToMask1 | ToMask2;
12314 EVT VT = N->getValueType(0);
12315 SDLoc dl(N);
12317 if (NewFromMask[0] == 0)
12318 From1 = DCI.DAG.getNode(
12319 ISD::SRL, dl, VT, From1,
12320 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12321 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12322 DCI.DAG.getConstant(~NewToMask, dl, VT));
12324 return SDValue();
12327 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12328 /// ARMISD::VMOVRRD.
12329 static SDValue PerformVMOVRRDCombine(SDNode *N,
12330 TargetLowering::DAGCombinerInfo &DCI,
12331 const ARMSubtarget *Subtarget) {
12332 // vmovrrd(vmovdrr x, y) -> x,y
12333 SDValue InDouble = N->getOperand(0);
12334 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12335 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12337 // vmovrrd(load f64) -> (load i32), (load i32)
12338 SDNode *InNode = InDouble.getNode();
12339 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12340 InNode->getValueType(0) == MVT::f64 &&
12341 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12342 !cast<LoadSDNode>(InNode)->isVolatile()) {
12343 // TODO: Should this be done for non-FrameIndex operands?
12344 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12346 SelectionDAG &DAG = DCI.DAG;
12347 SDLoc DL(LD);
12348 SDValue BasePtr = LD->getBasePtr();
12349 SDValue NewLD1 =
12350 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12351 LD->getAlignment(), LD->getMemOperand()->getFlags());
12353 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12354 DAG.getConstant(4, DL, MVT::i32));
12356 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12357 LD->getPointerInfo().getWithOffset(4),
12358 std::min(4U, LD->getAlignment()),
12359 LD->getMemOperand()->getFlags());
12361 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12362 if (DCI.DAG.getDataLayout().isBigEndian())
12363 std::swap (NewLD1, NewLD2);
12364 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12365 return Result;
12368 return SDValue();
12371 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12372 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12373 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12374 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12375 SDValue Op0 = N->getOperand(0);
12376 SDValue Op1 = N->getOperand(1);
12377 if (Op0.getOpcode() == ISD::BITCAST)
12378 Op0 = Op0.getOperand(0);
12379 if (Op1.getOpcode() == ISD::BITCAST)
12380 Op1 = Op1.getOperand(0);
12381 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12382 Op0.getNode() == Op1.getNode() &&
12383 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12384 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12385 N->getValueType(0), Op0.getOperand(0));
12386 return SDValue();
12389 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12390 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12391 /// i64 vector to have f64 elements, since the value can then be loaded
12392 /// directly into a VFP register.
12393 static bool hasNormalLoadOperand(SDNode *N) {
12394 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12395 for (unsigned i = 0; i < NumElts; ++i) {
12396 SDNode *Elt = N->getOperand(i).getNode();
12397 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12398 return true;
12400 return false;
12403 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12404 /// ISD::BUILD_VECTOR.
12405 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12406 TargetLowering::DAGCombinerInfo &DCI,
12407 const ARMSubtarget *Subtarget) {
12408 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12409 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12410 // into a pair of GPRs, which is fine when the value is used as a scalar,
12411 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12412 SelectionDAG &DAG = DCI.DAG;
12413 if (N->getNumOperands() == 2)
12414 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12415 return RV;
12417 // Load i64 elements as f64 values so that type legalization does not split
12418 // them up into i32 values.
12419 EVT VT = N->getValueType(0);
12420 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12421 return SDValue();
12422 SDLoc dl(N);
12423 SmallVector<SDValue, 8> Ops;
12424 unsigned NumElts = VT.getVectorNumElements();
12425 for (unsigned i = 0; i < NumElts; ++i) {
12426 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12427 Ops.push_back(V);
12428 // Make the DAGCombiner fold the bitcast.
12429 DCI.AddToWorklist(V.getNode());
12431 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12432 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12433 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12436 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12437 static SDValue
12438 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12439 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12440 // At that time, we may have inserted bitcasts from integer to float.
12441 // If these bitcasts have survived DAGCombine, change the lowering of this
12442 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12443 // force to use floating point types.
12445 // Make sure we can change the type of the vector.
12446 // This is possible iff:
12447 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12448 // 1.1. Vector is used only once.
12449 // 1.2. Use is a bit convert to an integer type.
12450 // 2. The size of its operands are 32-bits (64-bits are not legal).
12451 EVT VT = N->getValueType(0);
12452 EVT EltVT = VT.getVectorElementType();
12454 // Check 1.1. and 2.
12455 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12456 return SDValue();
12458 // By construction, the input type must be float.
12459 assert(EltVT == MVT::f32 && "Unexpected type!");
12461 // Check 1.2.
12462 SDNode *Use = *N->use_begin();
12463 if (Use->getOpcode() != ISD::BITCAST ||
12464 Use->getValueType(0).isFloatingPoint())
12465 return SDValue();
12467 // Check profitability.
12468 // Model is, if more than half of the relevant operands are bitcast from
12469 // i32, turn the build_vector into a sequence of insert_vector_elt.
12470 // Relevant operands are everything that is not statically
12471 // (i.e., at compile time) bitcasted.
12472 unsigned NumOfBitCastedElts = 0;
12473 unsigned NumElts = VT.getVectorNumElements();
12474 unsigned NumOfRelevantElts = NumElts;
12475 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12476 SDValue Elt = N->getOperand(Idx);
12477 if (Elt->getOpcode() == ISD::BITCAST) {
12478 // Assume only bit cast to i32 will go away.
12479 if (Elt->getOperand(0).getValueType() == MVT::i32)
12480 ++NumOfBitCastedElts;
12481 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12482 // Constants are statically casted, thus do not count them as
12483 // relevant operands.
12484 --NumOfRelevantElts;
12487 // Check if more than half of the elements require a non-free bitcast.
12488 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12489 return SDValue();
12491 SelectionDAG &DAG = DCI.DAG;
12492 // Create the new vector type.
12493 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12494 // Check if the type is legal.
12495 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12496 if (!TLI.isTypeLegal(VecVT))
12497 return SDValue();
12499 // Combine:
12500 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12501 // => BITCAST INSERT_VECTOR_ELT
12502 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12503 // (BITCAST EN), N.
12504 SDValue Vec = DAG.getUNDEF(VecVT);
12505 SDLoc dl(N);
12506 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12507 SDValue V = N->getOperand(Idx);
12508 if (V.isUndef())
12509 continue;
12510 if (V.getOpcode() == ISD::BITCAST &&
12511 V->getOperand(0).getValueType() == MVT::i32)
12512 // Fold obvious case.
12513 V = V.getOperand(0);
12514 else {
12515 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12516 // Make the DAGCombiner fold the bitcasts.
12517 DCI.AddToWorklist(V.getNode());
12519 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12520 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12522 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12523 // Make the DAGCombiner fold the bitcasts.
12524 DCI.AddToWorklist(Vec.getNode());
12525 return Vec;
12528 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12529 /// ISD::INSERT_VECTOR_ELT.
12530 static SDValue PerformInsertEltCombine(SDNode *N,
12531 TargetLowering::DAGCombinerInfo &DCI) {
12532 // Bitcast an i64 load inserted into a vector to f64.
12533 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12534 EVT VT = N->getValueType(0);
12535 SDNode *Elt = N->getOperand(1).getNode();
12536 if (VT.getVectorElementType() != MVT::i64 ||
12537 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12538 return SDValue();
12540 SelectionDAG &DAG = DCI.DAG;
12541 SDLoc dl(N);
12542 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12543 VT.getVectorNumElements());
12544 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12545 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12546 // Make the DAGCombiner fold the bitcasts.
12547 DCI.AddToWorklist(Vec.getNode());
12548 DCI.AddToWorklist(V.getNode());
12549 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12550 Vec, V, N->getOperand(2));
12551 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12554 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12555 /// ISD::VECTOR_SHUFFLE.
12556 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12557 // The LLVM shufflevector instruction does not require the shuffle mask
12558 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12559 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12560 // operands do not match the mask length, they are extended by concatenating
12561 // them with undef vectors. That is probably the right thing for other
12562 // targets, but for NEON it is better to concatenate two double-register
12563 // size vector operands into a single quad-register size vector. Do that
12564 // transformation here:
12565 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12566 // shuffle(concat(v1, v2), undef)
12567 SDValue Op0 = N->getOperand(0);
12568 SDValue Op1 = N->getOperand(1);
12569 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12570 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12571 Op0.getNumOperands() != 2 ||
12572 Op1.getNumOperands() != 2)
12573 return SDValue();
12574 SDValue Concat0Op1 = Op0.getOperand(1);
12575 SDValue Concat1Op1 = Op1.getOperand(1);
12576 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12577 return SDValue();
12578 // Skip the transformation if any of the types are illegal.
12579 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12580 EVT VT = N->getValueType(0);
12581 if (!TLI.isTypeLegal(VT) ||
12582 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12583 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12584 return SDValue();
12586 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12587 Op0.getOperand(0), Op1.getOperand(0));
12588 // Translate the shuffle mask.
12589 SmallVector<int, 16> NewMask;
12590 unsigned NumElts = VT.getVectorNumElements();
12591 unsigned HalfElts = NumElts/2;
12592 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12593 for (unsigned n = 0; n < NumElts; ++n) {
12594 int MaskElt = SVN->getMaskElt(n);
12595 int NewElt = -1;
12596 if (MaskElt < (int)HalfElts)
12597 NewElt = MaskElt;
12598 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12599 NewElt = HalfElts + MaskElt - NumElts;
12600 NewMask.push_back(NewElt);
12602 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12603 DAG.getUNDEF(VT), NewMask);
12606 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12607 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12608 /// base address updates.
12609 /// For generic load/stores, the memory type is assumed to be a vector.
12610 /// The caller is assumed to have checked legality.
12611 static SDValue CombineBaseUpdate(SDNode *N,
12612 TargetLowering::DAGCombinerInfo &DCI) {
12613 SelectionDAG &DAG = DCI.DAG;
12614 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12615 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12616 const bool isStore = N->getOpcode() == ISD::STORE;
12617 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12618 SDValue Addr = N->getOperand(AddrOpIdx);
12619 MemSDNode *MemN = cast<MemSDNode>(N);
12620 SDLoc dl(N);
12622 // Search for a use of the address operand that is an increment.
12623 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12624 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12625 SDNode *User = *UI;
12626 if (User->getOpcode() != ISD::ADD ||
12627 UI.getUse().getResNo() != Addr.getResNo())
12628 continue;
12630 // Check that the add is independent of the load/store. Otherwise, folding
12631 // it would create a cycle. We can avoid searching through Addr as it's a
12632 // predecessor to both.
12633 SmallPtrSet<const SDNode *, 32> Visited;
12634 SmallVector<const SDNode *, 16> Worklist;
12635 Visited.insert(Addr.getNode());
12636 Worklist.push_back(N);
12637 Worklist.push_back(User);
12638 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12639 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12640 continue;
12642 // Find the new opcode for the updating load/store.
12643 bool isLoadOp = true;
12644 bool isLaneOp = false;
12645 unsigned NewOpc = 0;
12646 unsigned NumVecs = 0;
12647 if (isIntrinsic) {
12648 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12649 switch (IntNo) {
12650 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12651 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12652 NumVecs = 1; break;
12653 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12654 NumVecs = 2; break;
12655 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12656 NumVecs = 3; break;
12657 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12658 NumVecs = 4; break;
12659 case Intrinsic::arm_neon_vld2dup:
12660 case Intrinsic::arm_neon_vld3dup:
12661 case Intrinsic::arm_neon_vld4dup:
12662 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12663 // combining base updates for such intrinsics.
12664 continue;
12665 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12666 NumVecs = 2; isLaneOp = true; break;
12667 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12668 NumVecs = 3; isLaneOp = true; break;
12669 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12670 NumVecs = 4; isLaneOp = true; break;
12671 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12672 NumVecs = 1; isLoadOp = false; break;
12673 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12674 NumVecs = 2; isLoadOp = false; break;
12675 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12676 NumVecs = 3; isLoadOp = false; break;
12677 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12678 NumVecs = 4; isLoadOp = false; break;
12679 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12680 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12681 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12682 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12683 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12684 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12686 } else {
12687 isLaneOp = true;
12688 switch (N->getOpcode()) {
12689 default: llvm_unreachable("unexpected opcode for Neon base update");
12690 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12691 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12692 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12693 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12694 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12695 NumVecs = 1; isLaneOp = false; break;
12696 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12697 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12701 // Find the size of memory referenced by the load/store.
12702 EVT VecTy;
12703 if (isLoadOp) {
12704 VecTy = N->getValueType(0);
12705 } else if (isIntrinsic) {
12706 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12707 } else {
12708 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12709 VecTy = N->getOperand(1).getValueType();
12712 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12713 if (isLaneOp)
12714 NumBytes /= VecTy.getVectorNumElements();
12716 // If the increment is a constant, it must match the memory ref size.
12717 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12718 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12719 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12720 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12721 // separate instructions that make it harder to use a non-constant update.
12722 continue;
12725 // OK, we found an ADD we can fold into the base update.
12726 // Now, create a _UPD node, taking care of not breaking alignment.
12728 EVT AlignedVecTy = VecTy;
12729 unsigned Alignment = MemN->getAlignment();
12731 // If this is a less-than-standard-aligned load/store, change the type to
12732 // match the standard alignment.
12733 // The alignment is overlooked when selecting _UPD variants; and it's
12734 // easier to introduce bitcasts here than fix that.
12735 // There are 3 ways to get to this base-update combine:
12736 // - intrinsics: they are assumed to be properly aligned (to the standard
12737 // alignment of the memory type), so we don't need to do anything.
12738 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12739 // intrinsics, so, likewise, there's nothing to do.
12740 // - generic load/store instructions: the alignment is specified as an
12741 // explicit operand, rather than implicitly as the standard alignment
12742 // of the memory type (like the intrisics). We need to change the
12743 // memory type to match the explicit alignment. That way, we don't
12744 // generate non-standard-aligned ARMISD::VLDx nodes.
12745 if (isa<LSBaseSDNode>(N)) {
12746 if (Alignment == 0)
12747 Alignment = 1;
12748 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12749 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12750 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12751 assert(!isLaneOp && "Unexpected generic load/store lane.");
12752 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12753 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12755 // Don't set an explicit alignment on regular load/stores that we want
12756 // to transform to VLD/VST 1_UPD nodes.
12757 // This matches the behavior of regular load/stores, which only get an
12758 // explicit alignment if the MMO alignment is larger than the standard
12759 // alignment of the memory type.
12760 // Intrinsics, however, always get an explicit alignment, set to the
12761 // alignment of the MMO.
12762 Alignment = 1;
12765 // Create the new updating load/store node.
12766 // First, create an SDVTList for the new updating node's results.
12767 EVT Tys[6];
12768 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12769 unsigned n;
12770 for (n = 0; n < NumResultVecs; ++n)
12771 Tys[n] = AlignedVecTy;
12772 Tys[n++] = MVT::i32;
12773 Tys[n] = MVT::Other;
12774 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12776 // Then, gather the new node's operands.
12777 SmallVector<SDValue, 8> Ops;
12778 Ops.push_back(N->getOperand(0)); // incoming chain
12779 Ops.push_back(N->getOperand(AddrOpIdx));
12780 Ops.push_back(Inc);
12782 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12783 // Try to match the intrinsic's signature
12784 Ops.push_back(StN->getValue());
12785 } else {
12786 // Loads (and of course intrinsics) match the intrinsics' signature,
12787 // so just add all but the alignment operand.
12788 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12789 Ops.push_back(N->getOperand(i));
12792 // For all node types, the alignment operand is always the last one.
12793 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
12795 // If this is a non-standard-aligned STORE, the penultimate operand is the
12796 // stored value. Bitcast it to the aligned type.
12797 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
12798 SDValue &StVal = Ops[Ops.size()-2];
12799 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
12802 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
12803 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
12804 MemN->getMemOperand());
12806 // Update the uses.
12807 SmallVector<SDValue, 5> NewResults;
12808 for (unsigned i = 0; i < NumResultVecs; ++i)
12809 NewResults.push_back(SDValue(UpdN.getNode(), i));
12811 // If this is an non-standard-aligned LOAD, the first result is the loaded
12812 // value. Bitcast it to the expected result type.
12813 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
12814 SDValue &LdVal = NewResults[0];
12815 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
12818 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
12819 DCI.CombineTo(N, NewResults);
12820 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12822 break;
12824 return SDValue();
12827 static SDValue PerformVLDCombine(SDNode *N,
12828 TargetLowering::DAGCombinerInfo &DCI) {
12829 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12830 return SDValue();
12832 return CombineBaseUpdate(N, DCI);
12835 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
12836 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
12837 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
12838 /// return true.
12839 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12840 SelectionDAG &DAG = DCI.DAG;
12841 EVT VT = N->getValueType(0);
12842 // vldN-dup instructions only support 64-bit vectors for N > 1.
12843 if (!VT.is64BitVector())
12844 return false;
12846 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
12847 SDNode *VLD = N->getOperand(0).getNode();
12848 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
12849 return false;
12850 unsigned NumVecs = 0;
12851 unsigned NewOpc = 0;
12852 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
12853 if (IntNo == Intrinsic::arm_neon_vld2lane) {
12854 NumVecs = 2;
12855 NewOpc = ARMISD::VLD2DUP;
12856 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
12857 NumVecs = 3;
12858 NewOpc = ARMISD::VLD3DUP;
12859 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
12860 NumVecs = 4;
12861 NewOpc = ARMISD::VLD4DUP;
12862 } else {
12863 return false;
12866 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
12867 // numbers match the load.
12868 unsigned VLDLaneNo =
12869 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
12870 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12871 UI != UE; ++UI) {
12872 // Ignore uses of the chain result.
12873 if (UI.getUse().getResNo() == NumVecs)
12874 continue;
12875 SDNode *User = *UI;
12876 if (User->getOpcode() != ARMISD::VDUPLANE ||
12877 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
12878 return false;
12881 // Create the vldN-dup node.
12882 EVT Tys[5];
12883 unsigned n;
12884 for (n = 0; n < NumVecs; ++n)
12885 Tys[n] = VT;
12886 Tys[n] = MVT::Other;
12887 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
12888 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
12889 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
12890 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
12891 Ops, VLDMemInt->getMemoryVT(),
12892 VLDMemInt->getMemOperand());
12894 // Update the uses.
12895 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12896 UI != UE; ++UI) {
12897 unsigned ResNo = UI.getUse().getResNo();
12898 // Ignore uses of the chain result.
12899 if (ResNo == NumVecs)
12900 continue;
12901 SDNode *User = *UI;
12902 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
12905 // Now the vldN-lane intrinsic is dead except for its chain result.
12906 // Update uses of the chain.
12907 std::vector<SDValue> VLDDupResults;
12908 for (unsigned n = 0; n < NumVecs; ++n)
12909 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
12910 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
12911 DCI.CombineTo(VLD, VLDDupResults);
12913 return true;
12916 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
12917 /// ARMISD::VDUPLANE.
12918 static SDValue PerformVDUPLANECombine(SDNode *N,
12919 TargetLowering::DAGCombinerInfo &DCI) {
12920 SDValue Op = N->getOperand(0);
12922 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
12923 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
12924 if (CombineVLDDUP(N, DCI))
12925 return SDValue(N, 0);
12927 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
12928 // redundant. Ignore bit_converts for now; element sizes are checked below.
12929 while (Op.getOpcode() == ISD::BITCAST)
12930 Op = Op.getOperand(0);
12931 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
12932 return SDValue();
12934 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
12935 unsigned EltSize = Op.getScalarValueSizeInBits();
12936 // The canonical VMOV for a zero vector uses a 32-bit element size.
12937 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12938 unsigned EltBits;
12939 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
12940 EltSize = 8;
12941 EVT VT = N->getValueType(0);
12942 if (EltSize > VT.getScalarSizeInBits())
12943 return SDValue();
12945 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
12948 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
12949 static SDValue PerformVDUPCombine(SDNode *N,
12950 TargetLowering::DAGCombinerInfo &DCI,
12951 const ARMSubtarget *Subtarget) {
12952 SelectionDAG &DAG = DCI.DAG;
12953 SDValue Op = N->getOperand(0);
12955 if (!Subtarget->hasNEON())
12956 return SDValue();
12958 // Match VDUP(LOAD) -> VLD1DUP.
12959 // We match this pattern here rather than waiting for isel because the
12960 // transform is only legal for unindexed loads.
12961 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
12962 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
12963 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
12964 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
12965 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
12966 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
12967 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
12968 Ops, LD->getMemoryVT(),
12969 LD->getMemOperand());
12970 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
12971 return VLDDup;
12974 return SDValue();
12977 static SDValue PerformLOADCombine(SDNode *N,
12978 TargetLowering::DAGCombinerInfo &DCI) {
12979 EVT VT = N->getValueType(0);
12981 // If this is a legal vector load, try to combine it into a VLD1_UPD.
12982 if (ISD::isNormalLoad(N) && VT.isVector() &&
12983 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12984 return CombineBaseUpdate(N, DCI);
12986 return SDValue();
12989 /// PerformSTORECombine - Target-specific dag combine xforms for
12990 /// ISD::STORE.
12991 static SDValue PerformSTORECombine(SDNode *N,
12992 TargetLowering::DAGCombinerInfo &DCI) {
12993 StoreSDNode *St = cast<StoreSDNode>(N);
12994 if (St->isVolatile())
12995 return SDValue();
12997 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
12998 // pack all of the elements in one place. Next, store to memory in fewer
12999 // chunks.
13000 SDValue StVal = St->getValue();
13001 EVT VT = StVal.getValueType();
13002 if (St->isTruncatingStore() && VT.isVector()) {
13003 SelectionDAG &DAG = DCI.DAG;
13004 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13005 EVT StVT = St->getMemoryVT();
13006 unsigned NumElems = VT.getVectorNumElements();
13007 assert(StVT != VT && "Cannot truncate to the same type");
13008 unsigned FromEltSz = VT.getScalarSizeInBits();
13009 unsigned ToEltSz = StVT.getScalarSizeInBits();
13011 // From, To sizes and ElemCount must be pow of two
13012 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
13014 // We are going to use the original vector elt for storing.
13015 // Accumulated smaller vector elements must be a multiple of the store size.
13016 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
13018 unsigned SizeRatio = FromEltSz / ToEltSz;
13019 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13021 // Create a type on which we perform the shuffle.
13022 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13023 NumElems*SizeRatio);
13024 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13026 SDLoc DL(St);
13027 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13028 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13029 for (unsigned i = 0; i < NumElems; ++i)
13030 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
13031 ? (i + 1) * SizeRatio - 1
13032 : i * SizeRatio;
13034 // Can't shuffle using an illegal type.
13035 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13037 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
13038 DAG.getUNDEF(WideVec.getValueType()),
13039 ShuffleVec);
13040 // At this point all of the data is stored at the bottom of the
13041 // register. We now need to save it to mem.
13043 // Find the largest store unit
13044 MVT StoreType = MVT::i8;
13045 for (MVT Tp : MVT::integer_valuetypes()) {
13046 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13047 StoreType = Tp;
13049 // Didn't find a legal store type.
13050 if (!TLI.isTypeLegal(StoreType))
13051 return SDValue();
13053 // Bitcast the original vector into a vector of store-size units
13054 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13055 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13056 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13057 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13058 SmallVector<SDValue, 8> Chains;
13059 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13060 TLI.getPointerTy(DAG.getDataLayout()));
13061 SDValue BasePtr = St->getBasePtr();
13063 // Perform one or more big stores into memory.
13064 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
13065 for (unsigned I = 0; I < E; I++) {
13066 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
13067 StoreType, ShuffWide,
13068 DAG.getIntPtrConstant(I, DL));
13069 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
13070 St->getPointerInfo(), St->getAlignment(),
13071 St->getMemOperand()->getFlags());
13072 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
13073 Increment);
13074 Chains.push_back(Ch);
13076 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13079 if (!ISD::isNormalStore(St))
13080 return SDValue();
13082 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
13083 // ARM stores of arguments in the same cache line.
13084 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
13085 StVal.getNode()->hasOneUse()) {
13086 SelectionDAG &DAG = DCI.DAG;
13087 bool isBigEndian = DAG.getDataLayout().isBigEndian();
13088 SDLoc DL(St);
13089 SDValue BasePtr = St->getBasePtr();
13090 SDValue NewST1 = DAG.getStore(
13091 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
13092 BasePtr, St->getPointerInfo(), St->getAlignment(),
13093 St->getMemOperand()->getFlags());
13095 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13096 DAG.getConstant(4, DL, MVT::i32));
13097 return DAG.getStore(NewST1.getValue(0), DL,
13098 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
13099 OffsetPtr, St->getPointerInfo(),
13100 std::min(4U, St->getAlignment() / 2),
13101 St->getMemOperand()->getFlags());
13104 if (StVal.getValueType() == MVT::i64 &&
13105 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13107 // Bitcast an i64 store extracted from a vector to f64.
13108 // Otherwise, the i64 value will be legalized to a pair of i32 values.
13109 SelectionDAG &DAG = DCI.DAG;
13110 SDLoc dl(StVal);
13111 SDValue IntVec = StVal.getOperand(0);
13112 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13113 IntVec.getValueType().getVectorNumElements());
13114 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
13115 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13116 Vec, StVal.getOperand(1));
13117 dl = SDLoc(N);
13118 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
13119 // Make the DAGCombiner fold the bitcasts.
13120 DCI.AddToWorklist(Vec.getNode());
13121 DCI.AddToWorklist(ExtElt.getNode());
13122 DCI.AddToWorklist(V.getNode());
13123 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
13124 St->getPointerInfo(), St->getAlignment(),
13125 St->getMemOperand()->getFlags(), St->getAAInfo());
13128 // If this is a legal vector store, try to combine it into a VST1_UPD.
13129 if (ISD::isNormalStore(N) && VT.isVector() &&
13130 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13131 return CombineBaseUpdate(N, DCI);
13133 return SDValue();
13136 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
13137 /// can replace combinations of VMUL and VCVT (floating-point to integer)
13138 /// when the VMUL has a constant operand that is a power of 2.
13140 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13141 /// vmul.f32 d16, d17, d16
13142 /// vcvt.s32.f32 d16, d16
13143 /// becomes:
13144 /// vcvt.s32.f32 d16, d16, #3
13145 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
13146 const ARMSubtarget *Subtarget) {
13147 if (!Subtarget->hasNEON())
13148 return SDValue();
13150 SDValue Op = N->getOperand(0);
13151 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13152 Op.getOpcode() != ISD::FMUL)
13153 return SDValue();
13155 SDValue ConstVec = Op->getOperand(1);
13156 if (!isa<BuildVectorSDNode>(ConstVec))
13157 return SDValue();
13159 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13160 uint32_t FloatBits = FloatTy.getSizeInBits();
13161 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13162 uint32_t IntBits = IntTy.getSizeInBits();
13163 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13164 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13165 // These instructions only exist converting from f32 to i32. We can handle
13166 // smaller integers by generating an extra truncate, but larger ones would
13167 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13168 // these intructions only support v2i32/v4i32 types.
13169 return SDValue();
13172 BitVector UndefElements;
13173 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13174 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13175 if (C == -1 || C == 0 || C > 32)
13176 return SDValue();
13178 SDLoc dl(N);
13179 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
13180 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
13181 Intrinsic::arm_neon_vcvtfp2fxu;
13182 SDValue FixConv = DAG.getNode(
13183 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13184 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
13185 DAG.getConstant(C, dl, MVT::i32));
13187 if (IntBits < FloatBits)
13188 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
13190 return FixConv;
13193 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13194 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13195 /// when the VDIV has a constant operand that is a power of 2.
13197 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13198 /// vcvt.f32.s32 d16, d16
13199 /// vdiv.f32 d16, d17, d16
13200 /// becomes:
13201 /// vcvt.f32.s32 d16, d16, #3
13202 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13203 const ARMSubtarget *Subtarget) {
13204 if (!Subtarget->hasNEON())
13205 return SDValue();
13207 SDValue Op = N->getOperand(0);
13208 unsigned OpOpcode = Op.getNode()->getOpcode();
13209 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13210 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13211 return SDValue();
13213 SDValue ConstVec = N->getOperand(1);
13214 if (!isa<BuildVectorSDNode>(ConstVec))
13215 return SDValue();
13217 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13218 uint32_t FloatBits = FloatTy.getSizeInBits();
13219 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13220 uint32_t IntBits = IntTy.getSizeInBits();
13221 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13222 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13223 // These instructions only exist converting from i32 to f32. We can handle
13224 // smaller integers by generating an extra extend, but larger ones would
13225 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13226 // these intructions only support v2i32/v4i32 types.
13227 return SDValue();
13230 BitVector UndefElements;
13231 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13232 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13233 if (C == -1 || C == 0 || C > 32)
13234 return SDValue();
13236 SDLoc dl(N);
13237 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13238 SDValue ConvInput = Op.getOperand(0);
13239 if (IntBits < FloatBits)
13240 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13241 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13242 ConvInput);
13244 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13245 Intrinsic::arm_neon_vcvtfxu2fp;
13246 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13247 Op.getValueType(),
13248 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13249 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13252 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13253 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13254 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13255 switch (IntNo) {
13256 default:
13257 // Don't do anything for most intrinsics.
13258 break;
13260 // Vector shifts: check for immediate versions and lower them.
13261 // Note: This is done during DAG combining instead of DAG legalizing because
13262 // the build_vectors for 64-bit vector element shift counts are generally
13263 // not legal, and it is hard to see their values after they get legalized to
13264 // loads from a constant pool.
13265 case Intrinsic::arm_neon_vshifts:
13266 case Intrinsic::arm_neon_vshiftu:
13267 case Intrinsic::arm_neon_vrshifts:
13268 case Intrinsic::arm_neon_vrshiftu:
13269 case Intrinsic::arm_neon_vrshiftn:
13270 case Intrinsic::arm_neon_vqshifts:
13271 case Intrinsic::arm_neon_vqshiftu:
13272 case Intrinsic::arm_neon_vqshiftsu:
13273 case Intrinsic::arm_neon_vqshiftns:
13274 case Intrinsic::arm_neon_vqshiftnu:
13275 case Intrinsic::arm_neon_vqshiftnsu:
13276 case Intrinsic::arm_neon_vqrshiftns:
13277 case Intrinsic::arm_neon_vqrshiftnu:
13278 case Intrinsic::arm_neon_vqrshiftnsu: {
13279 EVT VT = N->getOperand(1).getValueType();
13280 int64_t Cnt;
13281 unsigned VShiftOpc = 0;
13283 switch (IntNo) {
13284 case Intrinsic::arm_neon_vshifts:
13285 case Intrinsic::arm_neon_vshiftu:
13286 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13287 VShiftOpc = ARMISD::VSHLIMM;
13288 break;
13290 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13291 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13292 : ARMISD::VSHRuIMM);
13293 break;
13295 return SDValue();
13297 case Intrinsic::arm_neon_vrshifts:
13298 case Intrinsic::arm_neon_vrshiftu:
13299 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13300 break;
13301 return SDValue();
13303 case Intrinsic::arm_neon_vqshifts:
13304 case Intrinsic::arm_neon_vqshiftu:
13305 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13306 break;
13307 return SDValue();
13309 case Intrinsic::arm_neon_vqshiftsu:
13310 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13311 break;
13312 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13314 case Intrinsic::arm_neon_vrshiftn:
13315 case Intrinsic::arm_neon_vqshiftns:
13316 case Intrinsic::arm_neon_vqshiftnu:
13317 case Intrinsic::arm_neon_vqshiftnsu:
13318 case Intrinsic::arm_neon_vqrshiftns:
13319 case Intrinsic::arm_neon_vqrshiftnu:
13320 case Intrinsic::arm_neon_vqrshiftnsu:
13321 // Narrowing shifts require an immediate right shift.
13322 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13323 break;
13324 llvm_unreachable("invalid shift count for narrowing vector shift "
13325 "intrinsic");
13327 default:
13328 llvm_unreachable("unhandled vector shift");
13331 switch (IntNo) {
13332 case Intrinsic::arm_neon_vshifts:
13333 case Intrinsic::arm_neon_vshiftu:
13334 // Opcode already set above.
13335 break;
13336 case Intrinsic::arm_neon_vrshifts:
13337 VShiftOpc = ARMISD::VRSHRsIMM;
13338 break;
13339 case Intrinsic::arm_neon_vrshiftu:
13340 VShiftOpc = ARMISD::VRSHRuIMM;
13341 break;
13342 case Intrinsic::arm_neon_vrshiftn:
13343 VShiftOpc = ARMISD::VRSHRNIMM;
13344 break;
13345 case Intrinsic::arm_neon_vqshifts:
13346 VShiftOpc = ARMISD::VQSHLsIMM;
13347 break;
13348 case Intrinsic::arm_neon_vqshiftu:
13349 VShiftOpc = ARMISD::VQSHLuIMM;
13350 break;
13351 case Intrinsic::arm_neon_vqshiftsu:
13352 VShiftOpc = ARMISD::VQSHLsuIMM;
13353 break;
13354 case Intrinsic::arm_neon_vqshiftns:
13355 VShiftOpc = ARMISD::VQSHRNsIMM;
13356 break;
13357 case Intrinsic::arm_neon_vqshiftnu:
13358 VShiftOpc = ARMISD::VQSHRNuIMM;
13359 break;
13360 case Intrinsic::arm_neon_vqshiftnsu:
13361 VShiftOpc = ARMISD::VQSHRNsuIMM;
13362 break;
13363 case Intrinsic::arm_neon_vqrshiftns:
13364 VShiftOpc = ARMISD::VQRSHRNsIMM;
13365 break;
13366 case Intrinsic::arm_neon_vqrshiftnu:
13367 VShiftOpc = ARMISD::VQRSHRNuIMM;
13368 break;
13369 case Intrinsic::arm_neon_vqrshiftnsu:
13370 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13371 break;
13374 SDLoc dl(N);
13375 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13376 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13379 case Intrinsic::arm_neon_vshiftins: {
13380 EVT VT = N->getOperand(1).getValueType();
13381 int64_t Cnt;
13382 unsigned VShiftOpc = 0;
13384 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13385 VShiftOpc = ARMISD::VSLIIMM;
13386 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13387 VShiftOpc = ARMISD::VSRIIMM;
13388 else {
13389 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13392 SDLoc dl(N);
13393 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13394 N->getOperand(1), N->getOperand(2),
13395 DAG.getConstant(Cnt, dl, MVT::i32));
13398 case Intrinsic::arm_neon_vqrshifts:
13399 case Intrinsic::arm_neon_vqrshiftu:
13400 // No immediate versions of these to check for.
13401 break;
13404 return SDValue();
13407 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13408 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13409 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13410 /// vector element shift counts are generally not legal, and it is hard to see
13411 /// their values after they get legalized to loads from a constant pool.
13412 static SDValue PerformShiftCombine(SDNode *N,
13413 TargetLowering::DAGCombinerInfo &DCI,
13414 const ARMSubtarget *ST) {
13415 SelectionDAG &DAG = DCI.DAG;
13416 EVT VT = N->getValueType(0);
13417 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13418 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13419 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13420 SDValue N1 = N->getOperand(1);
13421 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13422 SDValue N0 = N->getOperand(0);
13423 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13424 DAG.MaskedValueIsZero(N0.getOperand(0),
13425 APInt::getHighBitsSet(32, 16)))
13426 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13430 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13431 N->getOperand(0)->getOpcode() == ISD::AND &&
13432 N->getOperand(0)->hasOneUse()) {
13433 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13434 return SDValue();
13435 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13436 // usually show up because instcombine prefers to canonicalize it to
13437 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13438 // out of GEP lowering in some cases.
13439 SDValue N0 = N->getOperand(0);
13440 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13441 if (!ShiftAmtNode)
13442 return SDValue();
13443 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13444 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13445 if (!AndMaskNode)
13446 return SDValue();
13447 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13448 // Don't transform uxtb/uxth.
13449 if (AndMask == 255 || AndMask == 65535)
13450 return SDValue();
13451 if (isMask_32(AndMask)) {
13452 uint32_t MaskedBits = countLeadingZeros(AndMask);
13453 if (MaskedBits > ShiftAmt) {
13454 SDLoc DL(N);
13455 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13456 DAG.getConstant(MaskedBits, DL, MVT::i32));
13457 return DAG.getNode(
13458 ISD::SRL, DL, MVT::i32, SHL,
13459 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13464 // Nothing to be done for scalar shifts.
13465 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13466 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13467 return SDValue();
13468 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13469 return SDValue();
13471 int64_t Cnt;
13473 switch (N->getOpcode()) {
13474 default: llvm_unreachable("unexpected shift opcode");
13476 case ISD::SHL:
13477 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13478 SDLoc dl(N);
13479 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13480 DAG.getConstant(Cnt, dl, MVT::i32));
13482 break;
13484 case ISD::SRA:
13485 case ISD::SRL:
13486 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13487 unsigned VShiftOpc =
13488 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13489 SDLoc dl(N);
13490 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13491 DAG.getConstant(Cnt, dl, MVT::i32));
13494 return SDValue();
13497 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13498 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13499 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13500 const ARMSubtarget *ST) {
13501 SDValue N0 = N->getOperand(0);
13503 // Check for sign- and zero-extensions of vector extract operations of 8-
13504 // and 16-bit vector elements. NEON supports these directly. They are
13505 // handled during DAG combining because type legalization will promote them
13506 // to 32-bit types and it is messy to recognize the operations after that.
13507 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13508 SDValue Vec = N0.getOperand(0);
13509 SDValue Lane = N0.getOperand(1);
13510 EVT VT = N->getValueType(0);
13511 EVT EltVT = N0.getValueType();
13512 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13514 if (VT == MVT::i32 &&
13515 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13516 TLI.isTypeLegal(Vec.getValueType()) &&
13517 isa<ConstantSDNode>(Lane)) {
13519 unsigned Opc = 0;
13520 switch (N->getOpcode()) {
13521 default: llvm_unreachable("unexpected opcode");
13522 case ISD::SIGN_EXTEND:
13523 Opc = ARMISD::VGETLANEs;
13524 break;
13525 case ISD::ZERO_EXTEND:
13526 case ISD::ANY_EXTEND:
13527 Opc = ARMISD::VGETLANEu;
13528 break;
13530 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13534 return SDValue();
13537 static const APInt *isPowerOf2Constant(SDValue V) {
13538 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13539 if (!C)
13540 return nullptr;
13541 const APInt *CV = &C->getAPIntValue();
13542 return CV->isPowerOf2() ? CV : nullptr;
13545 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13546 // If we have a CMOV, OR and AND combination such as:
13547 // if (x & CN)
13548 // y |= CM;
13550 // And:
13551 // * CN is a single bit;
13552 // * All bits covered by CM are known zero in y
13554 // Then we can convert this into a sequence of BFI instructions. This will
13555 // always be a win if CM is a single bit, will always be no worse than the
13556 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13557 // three bits (due to the extra IT instruction).
13559 SDValue Op0 = CMOV->getOperand(0);
13560 SDValue Op1 = CMOV->getOperand(1);
13561 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13562 auto CC = CCNode->getAPIntValue().getLimitedValue();
13563 SDValue CmpZ = CMOV->getOperand(4);
13565 // The compare must be against zero.
13566 if (!isNullConstant(CmpZ->getOperand(1)))
13567 return SDValue();
13569 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13570 SDValue And = CmpZ->getOperand(0);
13571 if (And->getOpcode() != ISD::AND)
13572 return SDValue();
13573 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13574 if (!AndC)
13575 return SDValue();
13576 SDValue X = And->getOperand(0);
13578 if (CC == ARMCC::EQ) {
13579 // We're performing an "equal to zero" compare. Swap the operands so we
13580 // canonicalize on a "not equal to zero" compare.
13581 std::swap(Op0, Op1);
13582 } else {
13583 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13586 if (Op1->getOpcode() != ISD::OR)
13587 return SDValue();
13589 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13590 if (!OrC)
13591 return SDValue();
13592 SDValue Y = Op1->getOperand(0);
13594 if (Op0 != Y)
13595 return SDValue();
13597 // Now, is it profitable to continue?
13598 APInt OrCI = OrC->getAPIntValue();
13599 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13600 if (OrCI.countPopulation() > Heuristic)
13601 return SDValue();
13603 // Lastly, can we determine that the bits defined by OrCI
13604 // are zero in Y?
13605 KnownBits Known = DAG.computeKnownBits(Y);
13606 if ((OrCI & Known.Zero) != OrCI)
13607 return SDValue();
13609 // OK, we can do the combine.
13610 SDValue V = Y;
13611 SDLoc dl(X);
13612 EVT VT = X.getValueType();
13613 unsigned BitInX = AndC->logBase2();
13615 if (BitInX != 0) {
13616 // We must shift X first.
13617 X = DAG.getNode(ISD::SRL, dl, VT, X,
13618 DAG.getConstant(BitInX, dl, VT));
13621 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13622 BitInY < NumActiveBits; ++BitInY) {
13623 if (OrCI[BitInY] == 0)
13624 continue;
13625 APInt Mask(VT.getSizeInBits(), 0);
13626 Mask.setBit(BitInY);
13627 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13628 // Confusingly, the operand is an *inverted* mask.
13629 DAG.getConstant(~Mask, dl, VT));
13632 return V;
13635 // Given N, the value controlling the conditional branch, search for the loop
13636 // intrinsic, returning it, along with how the value is used. We need to handle
13637 // patterns such as the following:
13638 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13639 // (brcond (setcc (loop.decrement), 0, eq), exit)
13640 // (brcond (setcc (loop.decrement), 0, ne), header)
13641 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13642 bool &Negate) {
13643 switch (N->getOpcode()) {
13644 default:
13645 break;
13646 case ISD::XOR: {
13647 if (!isa<ConstantSDNode>(N.getOperand(1)))
13648 return SDValue();
13649 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13650 return SDValue();
13651 Negate = !Negate;
13652 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
13654 case ISD::SETCC: {
13655 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
13656 if (!Const)
13657 return SDValue();
13658 if (Const->isNullValue())
13659 Imm = 0;
13660 else if (Const->isOne())
13661 Imm = 1;
13662 else
13663 return SDValue();
13664 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
13665 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
13667 case ISD::INTRINSIC_W_CHAIN: {
13668 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
13669 if (IntOp != Intrinsic::test_set_loop_iterations &&
13670 IntOp != Intrinsic::loop_decrement_reg)
13671 return SDValue();
13672 return N;
13675 return SDValue();
13678 static SDValue PerformHWLoopCombine(SDNode *N,
13679 TargetLowering::DAGCombinerInfo &DCI,
13680 const ARMSubtarget *ST) {
13682 // The hwloop intrinsics that we're interested are used for control-flow,
13683 // either for entering or exiting the loop:
13684 // - test.set.loop.iterations will test whether its operand is zero. If it
13685 // is zero, the proceeding branch should not enter the loop.
13686 // - loop.decrement.reg also tests whether its operand is zero. If it is
13687 // zero, the proceeding branch should not branch back to the beginning of
13688 // the loop.
13689 // So here, we need to check that how the brcond is using the result of each
13690 // of the intrinsics to ensure that we're branching to the right place at the
13691 // right time.
13693 ISD::CondCode CC;
13694 SDValue Cond;
13695 int Imm = 1;
13696 bool Negate = false;
13697 SDValue Chain = N->getOperand(0);
13698 SDValue Dest;
13700 if (N->getOpcode() == ISD::BRCOND) {
13701 CC = ISD::SETEQ;
13702 Cond = N->getOperand(1);
13703 Dest = N->getOperand(2);
13704 } else {
13705 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
13706 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13707 Cond = N->getOperand(2);
13708 Dest = N->getOperand(4);
13709 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
13710 if (!Const->isOne() && !Const->isNullValue())
13711 return SDValue();
13712 Imm = Const->getZExtValue();
13713 } else
13714 return SDValue();
13717 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
13718 if (!Int)
13719 return SDValue();
13721 if (Negate)
13722 CC = ISD::getSetCCInverse(CC, true);
13724 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
13725 return (CC == ISD::SETEQ && Imm == 0) ||
13726 (CC == ISD::SETNE && Imm == 1) ||
13727 (CC == ISD::SETLT && Imm == 1) ||
13728 (CC == ISD::SETULT && Imm == 1);
13731 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
13732 return (CC == ISD::SETEQ && Imm == 1) ||
13733 (CC == ISD::SETNE && Imm == 0) ||
13734 (CC == ISD::SETGT && Imm == 0) ||
13735 (CC == ISD::SETUGT && Imm == 0) ||
13736 (CC == ISD::SETGE && Imm == 1) ||
13737 (CC == ISD::SETUGE && Imm == 1);
13740 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
13741 "unsupported condition");
13743 SDLoc dl(Int);
13744 SelectionDAG &DAG = DCI.DAG;
13745 SDValue Elements = Int.getOperand(2);
13746 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
13747 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
13748 && "expected single br user");
13749 SDNode *Br = *N->use_begin();
13750 SDValue OtherTarget = Br->getOperand(1);
13752 // Update the unconditional branch to branch to the given Dest.
13753 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
13754 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
13755 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
13756 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
13759 if (IntOp == Intrinsic::test_set_loop_iterations) {
13760 SDValue Res;
13761 // We expect this 'instruction' to branch when the counter is zero.
13762 if (IsTrueIfZero(CC, Imm)) {
13763 SDValue Ops[] = { Chain, Elements, Dest };
13764 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13765 } else {
13766 // The logic is the reverse of what we need for WLS, so find the other
13767 // basic block target: the target of the proceeding br.
13768 UpdateUncondBr(Br, Dest, DAG);
13770 SDValue Ops[] = { Chain, Elements, OtherTarget };
13771 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13773 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
13774 return Res;
13775 } else {
13776 SDValue Size = DAG.getTargetConstant(
13777 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
13778 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
13779 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
13780 DAG.getVTList(MVT::i32, MVT::Other), Args);
13781 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
13783 // We expect this instruction to branch when the count is not zero.
13784 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
13786 // Update the unconditional branch to target the loop preheader if we've
13787 // found the condition has been reversed.
13788 if (Target == OtherTarget)
13789 UpdateUncondBr(Br, Dest, DAG);
13791 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13792 SDValue(LoopDec.getNode(), 1), Chain);
13794 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
13795 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
13797 return SDValue();
13800 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
13801 SDValue
13802 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
13803 SDValue Cmp = N->getOperand(4);
13804 if (Cmp.getOpcode() != ARMISD::CMPZ)
13805 // Only looking at NE cases.
13806 return SDValue();
13808 EVT VT = N->getValueType(0);
13809 SDLoc dl(N);
13810 SDValue LHS = Cmp.getOperand(0);
13811 SDValue RHS = Cmp.getOperand(1);
13812 SDValue Chain = N->getOperand(0);
13813 SDValue BB = N->getOperand(1);
13814 SDValue ARMcc = N->getOperand(2);
13815 ARMCC::CondCodes CC =
13816 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13818 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
13819 // -> (brcond Chain BB CC CPSR Cmp)
13820 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
13821 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
13822 LHS->getOperand(0)->hasOneUse()) {
13823 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
13824 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
13825 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13826 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13827 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
13828 (LHS01C && LHS01C->getZExtValue() == 1) &&
13829 (LHS1C && LHS1C->getZExtValue() == 1) &&
13830 (RHSC && RHSC->getZExtValue() == 0)) {
13831 return DAG.getNode(
13832 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
13833 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
13837 return SDValue();
13840 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
13841 SDValue
13842 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
13843 SDValue Cmp = N->getOperand(4);
13844 if (Cmp.getOpcode() != ARMISD::CMPZ)
13845 // Only looking at EQ and NE cases.
13846 return SDValue();
13848 EVT VT = N->getValueType(0);
13849 SDLoc dl(N);
13850 SDValue LHS = Cmp.getOperand(0);
13851 SDValue RHS = Cmp.getOperand(1);
13852 SDValue FalseVal = N->getOperand(0);
13853 SDValue TrueVal = N->getOperand(1);
13854 SDValue ARMcc = N->getOperand(2);
13855 ARMCC::CondCodes CC =
13856 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13858 // BFI is only available on V6T2+.
13859 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
13860 SDValue R = PerformCMOVToBFICombine(N, DAG);
13861 if (R)
13862 return R;
13865 // Simplify
13866 // mov r1, r0
13867 // cmp r1, x
13868 // mov r0, y
13869 // moveq r0, x
13870 // to
13871 // cmp r0, x
13872 // movne r0, y
13874 // mov r1, r0
13875 // cmp r1, x
13876 // mov r0, x
13877 // movne r0, y
13878 // to
13879 // cmp r0, x
13880 // movne r0, y
13881 /// FIXME: Turn this into a target neutral optimization?
13882 SDValue Res;
13883 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
13884 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
13885 N->getOperand(3), Cmp);
13886 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
13887 SDValue ARMcc;
13888 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
13889 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
13890 N->getOperand(3), NewCmp);
13893 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
13894 // -> (cmov F T CC CPSR Cmp)
13895 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
13896 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
13897 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13898 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13899 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
13900 (LHS1C && LHS1C->getZExtValue() == 1) &&
13901 (RHSC && RHSC->getZExtValue() == 0)) {
13902 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
13903 LHS->getOperand(2), LHS->getOperand(3),
13904 LHS->getOperand(4));
13908 if (!VT.isInteger())
13909 return SDValue();
13911 // Materialize a boolean comparison for integers so we can avoid branching.
13912 if (isNullConstant(FalseVal)) {
13913 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
13914 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
13915 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
13916 // right 5 bits will make that 32 be 1, otherwise it will be 0.
13917 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
13918 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13919 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
13920 DAG.getConstant(5, dl, MVT::i32));
13921 } else {
13922 // CMOV 0, 1, ==, (CMPZ x, y) ->
13923 // (ADDCARRY (SUB x, y), t:0, t:1)
13924 // where t = (SUBCARRY 0, (SUB x, y), 0)
13926 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
13927 // x != y. In other words, a carry C == 1 when x == y, C == 0
13928 // otherwise.
13929 // The final ADDCARRY computes
13930 // x - y + (0 - (x - y)) + C == C
13931 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13932 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13933 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
13934 // ISD::SUBCARRY returns a borrow but we want the carry here
13935 // actually.
13936 SDValue Carry =
13937 DAG.getNode(ISD::SUB, dl, MVT::i32,
13938 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
13939 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
13941 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
13942 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
13943 // This seems pointless but will allow us to combine it further below.
13944 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13945 SDValue Sub =
13946 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13947 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13948 Sub.getValue(1), SDValue());
13949 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
13950 N->getOperand(3), CPSRGlue.getValue(1));
13951 FalseVal = Sub;
13953 } else if (isNullConstant(TrueVal)) {
13954 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
13955 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
13956 // This seems pointless but will allow us to combine it further below
13957 // Note that we change == for != as this is the dual for the case above.
13958 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13959 SDValue Sub =
13960 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13961 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13962 Sub.getValue(1), SDValue());
13963 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
13964 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
13965 N->getOperand(3), CPSRGlue.getValue(1));
13966 FalseVal = Sub;
13970 // On Thumb1, the DAG above may be further combined if z is a power of 2
13971 // (z == 2 ^ K).
13972 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
13973 // t1 = (USUBO (SUB x, y), 1)
13974 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
13975 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13977 // This also handles the special case of comparing against zero; it's
13978 // essentially, the same pattern, except there's no SUBS:
13979 // CMOV x, z, !=, (CMPZ x, 0) ->
13980 // t1 = (USUBO x, 1)
13981 // t2 = (SUBCARRY x, t1:0, t1:1)
13982 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13983 const APInt *TrueConst;
13984 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
13985 ((FalseVal.getOpcode() == ARMISD::SUBS &&
13986 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
13987 (FalseVal == LHS && isNullConstant(RHS))) &&
13988 (TrueConst = isPowerOf2Constant(TrueVal))) {
13989 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13990 unsigned ShiftAmount = TrueConst->logBase2();
13991 if (ShiftAmount)
13992 TrueVal = DAG.getConstant(1, dl, VT);
13993 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
13994 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
13996 if (ShiftAmount)
13997 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
13998 DAG.getConstant(ShiftAmount, dl, MVT::i32));
14001 if (Res.getNode()) {
14002 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
14003 // Capture demanded bits information that would be otherwise lost.
14004 if (Known.Zero == 0xfffffffe)
14005 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14006 DAG.getValueType(MVT::i1));
14007 else if (Known.Zero == 0xffffff00)
14008 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14009 DAG.getValueType(MVT::i8));
14010 else if (Known.Zero == 0xffff0000)
14011 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14012 DAG.getValueType(MVT::i16));
14015 return Res;
14018 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
14019 DAGCombinerInfo &DCI) const {
14020 switch (N->getOpcode()) {
14021 default: break;
14022 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
14023 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
14024 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
14025 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
14026 case ISD::SUB: return PerformSUBCombine(N, DCI);
14027 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
14028 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
14029 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
14030 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
14031 case ISD::BRCOND:
14032 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
14033 case ARMISD::ADDC:
14034 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
14035 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
14036 case ARMISD::BFI: return PerformBFICombine(N, DCI);
14037 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
14038 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
14039 case ISD::STORE: return PerformSTORECombine(N, DCI);
14040 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
14041 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
14042 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
14043 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
14044 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
14045 case ISD::FP_TO_SINT:
14046 case ISD::FP_TO_UINT:
14047 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
14048 case ISD::FDIV:
14049 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
14050 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
14051 case ISD::SHL:
14052 case ISD::SRA:
14053 case ISD::SRL:
14054 return PerformShiftCombine(N, DCI, Subtarget);
14055 case ISD::SIGN_EXTEND:
14056 case ISD::ZERO_EXTEND:
14057 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
14058 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
14059 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
14060 case ISD::LOAD: return PerformLOADCombine(N, DCI);
14061 case ARMISD::VLD1DUP:
14062 case ARMISD::VLD2DUP:
14063 case ARMISD::VLD3DUP:
14064 case ARMISD::VLD4DUP:
14065 return PerformVLDCombine(N, DCI);
14066 case ARMISD::BUILD_VECTOR:
14067 return PerformARMBUILD_VECTORCombine(N, DCI);
14068 case ARMISD::SMULWB: {
14069 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14070 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14071 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14072 return SDValue();
14073 break;
14075 case ARMISD::SMULWT: {
14076 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14077 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14078 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14079 return SDValue();
14080 break;
14082 case ARMISD::SMLALBB: {
14083 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14084 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14085 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14086 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14087 return SDValue();
14088 break;
14090 case ARMISD::SMLALBT: {
14091 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
14092 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14093 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
14094 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14095 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
14096 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
14097 return SDValue();
14098 break;
14100 case ARMISD::SMLALTB: {
14101 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
14102 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14103 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
14104 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14105 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
14106 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
14107 return SDValue();
14108 break;
14110 case ARMISD::SMLALTT: {
14111 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14112 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14113 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14114 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14115 return SDValue();
14116 break;
14118 case ISD::INTRINSIC_VOID:
14119 case ISD::INTRINSIC_W_CHAIN:
14120 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14121 case Intrinsic::arm_neon_vld1:
14122 case Intrinsic::arm_neon_vld1x2:
14123 case Intrinsic::arm_neon_vld1x3:
14124 case Intrinsic::arm_neon_vld1x4:
14125 case Intrinsic::arm_neon_vld2:
14126 case Intrinsic::arm_neon_vld3:
14127 case Intrinsic::arm_neon_vld4:
14128 case Intrinsic::arm_neon_vld2lane:
14129 case Intrinsic::arm_neon_vld3lane:
14130 case Intrinsic::arm_neon_vld4lane:
14131 case Intrinsic::arm_neon_vld2dup:
14132 case Intrinsic::arm_neon_vld3dup:
14133 case Intrinsic::arm_neon_vld4dup:
14134 case Intrinsic::arm_neon_vst1:
14135 case Intrinsic::arm_neon_vst1x2:
14136 case Intrinsic::arm_neon_vst1x3:
14137 case Intrinsic::arm_neon_vst1x4:
14138 case Intrinsic::arm_neon_vst2:
14139 case Intrinsic::arm_neon_vst3:
14140 case Intrinsic::arm_neon_vst4:
14141 case Intrinsic::arm_neon_vst2lane:
14142 case Intrinsic::arm_neon_vst3lane:
14143 case Intrinsic::arm_neon_vst4lane:
14144 return PerformVLDCombine(N, DCI);
14145 default: break;
14147 break;
14149 return SDValue();
14152 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
14153 EVT VT) const {
14154 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
14157 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
14158 unsigned Alignment,
14159 MachineMemOperand::Flags,
14160 bool *Fast) const {
14161 // Depends what it gets converted into if the type is weird.
14162 if (!VT.isSimple())
14163 return false;
14165 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
14166 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
14167 auto Ty = VT.getSimpleVT().SimpleTy;
14169 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
14170 // Unaligned access can use (for example) LRDB, LRDH, LDR
14171 if (AllowsUnaligned) {
14172 if (Fast)
14173 *Fast = Subtarget->hasV7Ops();
14174 return true;
14178 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
14179 // For any little-endian targets with neon, we can support unaligned ld/st
14180 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
14181 // A big-endian target may also explicitly support unaligned accesses
14182 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
14183 if (Fast)
14184 *Fast = true;
14185 return true;
14189 if (!Subtarget->hasMVEIntegerOps())
14190 return false;
14192 // These are for predicates
14193 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14194 if (Fast)
14195 *Fast = true;
14196 return true;
14199 // These are for truncated stores/narrowing loads. They are fine so long as
14200 // the alignment is at least the size of the item being loaded
14201 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
14202 Alignment >= VT.getScalarSizeInBits() / 8) {
14203 if (Fast)
14204 *Fast = true;
14205 return true;
14208 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
14209 // VSTRW.U32 all store the vector register in exactly the same format, and
14210 // differ only in the range of their immediate offset field and the required
14211 // alignment. So there is always a store that can be used, regardless of
14212 // actual type.
14214 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
14215 // VREV64.8) pair and get the same effect. This will likely be better than
14216 // aligning the vector through the stack.
14217 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
14218 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
14219 Ty == MVT::v2f64) {
14220 if (Fast)
14221 *Fast = true;
14222 return true;
14225 return false;
14228 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14229 unsigned AlignCheck) {
14230 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14231 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14234 EVT ARMTargetLowering::getOptimalMemOpType(
14235 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14236 bool ZeroMemset, bool MemcpyStrSrc,
14237 const AttributeList &FuncAttributes) const {
14238 // See if we can use NEON instructions for this...
14239 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14240 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14241 bool Fast;
14242 if (Size >= 16 &&
14243 (memOpAlign(SrcAlign, DstAlign, 16) ||
14244 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14245 MachineMemOperand::MONone, &Fast) &&
14246 Fast))) {
14247 return MVT::v2f64;
14248 } else if (Size >= 8 &&
14249 (memOpAlign(SrcAlign, DstAlign, 8) ||
14250 (allowsMisalignedMemoryAccesses(
14251 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14252 Fast))) {
14253 return MVT::f64;
14257 // Let the target-independent logic figure it out.
14258 return MVT::Other;
14261 // 64-bit integers are split into their high and low parts and held in two
14262 // different registers, so the trunc is free since the low register can just
14263 // be used.
14264 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14265 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14266 return false;
14267 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14268 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14269 return (SrcBits == 64 && DestBits == 32);
14272 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14273 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14274 !DstVT.isInteger())
14275 return false;
14276 unsigned SrcBits = SrcVT.getSizeInBits();
14277 unsigned DestBits = DstVT.getSizeInBits();
14278 return (SrcBits == 64 && DestBits == 32);
14281 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14282 if (Val.getOpcode() != ISD::LOAD)
14283 return false;
14285 EVT VT1 = Val.getValueType();
14286 if (!VT1.isSimple() || !VT1.isInteger() ||
14287 !VT2.isSimple() || !VT2.isInteger())
14288 return false;
14290 switch (VT1.getSimpleVT().SimpleTy) {
14291 default: break;
14292 case MVT::i1:
14293 case MVT::i8:
14294 case MVT::i16:
14295 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14296 return true;
14299 return false;
14302 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14303 if (!VT.isSimple())
14304 return false;
14306 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14307 // negate values directly (fneg is free). So, we don't want to let the DAG
14308 // combiner rewrite fneg into xors and some other instructions. For f16 and
14309 // FullFP16 argument passing, some bitcast nodes may be introduced,
14310 // triggering this DAG combine rewrite, so we are avoiding that with this.
14311 switch (VT.getSimpleVT().SimpleTy) {
14312 default: break;
14313 case MVT::f16:
14314 return Subtarget->hasFullFP16();
14317 return false;
14320 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14321 /// of the vector elements.
14322 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14323 auto areExtDoubled = [](Instruction *Ext) {
14324 return Ext->getType()->getScalarSizeInBits() ==
14325 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14328 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14329 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14330 !areExtDoubled(cast<Instruction>(Ext1)) ||
14331 !areExtDoubled(cast<Instruction>(Ext2)))
14332 return false;
14334 return true;
14337 /// Check if sinking \p I's operands to I's basic block is profitable, because
14338 /// the operands can be folded into a target instruction, e.g.
14339 /// sext/zext can be folded into vsubl.
14340 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14341 SmallVectorImpl<Use *> &Ops) const {
14342 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy())
14343 return false;
14345 switch (I->getOpcode()) {
14346 case Instruction::Sub:
14347 case Instruction::Add: {
14348 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14349 return false;
14350 Ops.push_back(&I->getOperandUse(0));
14351 Ops.push_back(&I->getOperandUse(1));
14352 return true;
14354 default:
14355 return false;
14357 return false;
14360 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14361 EVT VT = ExtVal.getValueType();
14363 if (!isTypeLegal(VT))
14364 return false;
14366 // Don't create a loadext if we can fold the extension into a wide/long
14367 // instruction.
14368 // If there's more than one user instruction, the loadext is desirable no
14369 // matter what. There can be two uses by the same instruction.
14370 if (ExtVal->use_empty() ||
14371 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14372 return true;
14374 SDNode *U = *ExtVal->use_begin();
14375 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14376 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14377 return false;
14379 return true;
14382 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14383 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14384 return false;
14386 if (!isTypeLegal(EVT::getEVT(Ty1)))
14387 return false;
14389 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14391 // Assuming the caller doesn't have a zeroext or signext return parameter,
14392 // truncation all the way down to i1 is valid.
14393 return true;
14396 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14397 const AddrMode &AM, Type *Ty,
14398 unsigned AS) const {
14399 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14400 if (Subtarget->hasFPAO())
14401 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14402 return 0;
14404 return -1;
14407 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14408 if (V < 0)
14409 return false;
14411 unsigned Scale = 1;
14412 switch (VT.getSimpleVT().SimpleTy) {
14413 case MVT::i1:
14414 case MVT::i8:
14415 // Scale == 1;
14416 break;
14417 case MVT::i16:
14418 // Scale == 2;
14419 Scale = 2;
14420 break;
14421 default:
14422 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14423 // Scale == 4;
14424 Scale = 4;
14425 break;
14428 if ((V & (Scale - 1)) != 0)
14429 return false;
14430 return isUInt<5>(V / Scale);
14433 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14434 const ARMSubtarget *Subtarget) {
14435 if (!VT.isInteger() && !VT.isFloatingPoint())
14436 return false;
14437 if (VT.isVector() && Subtarget->hasNEON())
14438 return false;
14439 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14440 !Subtarget->hasMVEFloatOps())
14441 return false;
14443 bool IsNeg = false;
14444 if (V < 0) {
14445 IsNeg = true;
14446 V = -V;
14449 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14451 // MVE: size * imm7
14452 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14453 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14454 case MVT::i32:
14455 case MVT::f32:
14456 return isShiftedUInt<7,2>(V);
14457 case MVT::i16:
14458 case MVT::f16:
14459 return isShiftedUInt<7,1>(V);
14460 case MVT::i8:
14461 return isUInt<7>(V);
14462 default:
14463 return false;
14467 // half VLDR: 2 * imm8
14468 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14469 return isShiftedUInt<8, 1>(V);
14470 // VLDR and LDRD: 4 * imm8
14471 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14472 return isShiftedUInt<8, 2>(V);
14474 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14475 // + imm12 or - imm8
14476 if (IsNeg)
14477 return isUInt<8>(V);
14478 return isUInt<12>(V);
14481 return false;
14484 /// isLegalAddressImmediate - Return true if the integer value can be used
14485 /// as the offset of the target addressing mode for load / store of the
14486 /// given type.
14487 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14488 const ARMSubtarget *Subtarget) {
14489 if (V == 0)
14490 return true;
14492 if (!VT.isSimple())
14493 return false;
14495 if (Subtarget->isThumb1Only())
14496 return isLegalT1AddressImmediate(V, VT);
14497 else if (Subtarget->isThumb2())
14498 return isLegalT2AddressImmediate(V, VT, Subtarget);
14500 // ARM mode.
14501 if (V < 0)
14502 V = - V;
14503 switch (VT.getSimpleVT().SimpleTy) {
14504 default: return false;
14505 case MVT::i1:
14506 case MVT::i8:
14507 case MVT::i32:
14508 // +- imm12
14509 return isUInt<12>(V);
14510 case MVT::i16:
14511 // +- imm8
14512 return isUInt<8>(V);
14513 case MVT::f32:
14514 case MVT::f64:
14515 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14516 return false;
14517 return isShiftedUInt<8, 2>(V);
14521 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14522 EVT VT) const {
14523 int Scale = AM.Scale;
14524 if (Scale < 0)
14525 return false;
14527 switch (VT.getSimpleVT().SimpleTy) {
14528 default: return false;
14529 case MVT::i1:
14530 case MVT::i8:
14531 case MVT::i16:
14532 case MVT::i32:
14533 if (Scale == 1)
14534 return true;
14535 // r + r << imm
14536 Scale = Scale & ~1;
14537 return Scale == 2 || Scale == 4 || Scale == 8;
14538 case MVT::i64:
14539 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14540 // version in Thumb mode.
14541 // r + r
14542 if (Scale == 1)
14543 return true;
14544 // r * 2 (this can be lowered to r + r).
14545 if (!AM.HasBaseReg && Scale == 2)
14546 return true;
14547 return false;
14548 case MVT::isVoid:
14549 // Note, we allow "void" uses (basically, uses that aren't loads or
14550 // stores), because arm allows folding a scale into many arithmetic
14551 // operations. This should be made more precise and revisited later.
14553 // Allow r << imm, but the imm has to be a multiple of two.
14554 if (Scale & 1) return false;
14555 return isPowerOf2_32(Scale);
14559 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14560 EVT VT) const {
14561 const int Scale = AM.Scale;
14563 // Negative scales are not supported in Thumb1.
14564 if (Scale < 0)
14565 return false;
14567 // Thumb1 addressing modes do not support register scaling excepting the
14568 // following cases:
14569 // 1. Scale == 1 means no scaling.
14570 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14571 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14574 /// isLegalAddressingMode - Return true if the addressing mode represented
14575 /// by AM is legal for this target, for a load/store of the specified type.
14576 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14577 const AddrMode &AM, Type *Ty,
14578 unsigned AS, Instruction *I) const {
14579 EVT VT = getValueType(DL, Ty, true);
14580 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14581 return false;
14583 // Can never fold addr of global into load/store.
14584 if (AM.BaseGV)
14585 return false;
14587 switch (AM.Scale) {
14588 case 0: // no scale reg, must be "r+i" or "r", or "i".
14589 break;
14590 default:
14591 // ARM doesn't support any R+R*scale+imm addr modes.
14592 if (AM.BaseOffs)
14593 return false;
14595 if (!VT.isSimple())
14596 return false;
14598 if (Subtarget->isThumb1Only())
14599 return isLegalT1ScaledAddressingMode(AM, VT);
14601 if (Subtarget->isThumb2())
14602 return isLegalT2ScaledAddressingMode(AM, VT);
14604 int Scale = AM.Scale;
14605 switch (VT.getSimpleVT().SimpleTy) {
14606 default: return false;
14607 case MVT::i1:
14608 case MVT::i8:
14609 case MVT::i32:
14610 if (Scale < 0) Scale = -Scale;
14611 if (Scale == 1)
14612 return true;
14613 // r + r << imm
14614 return isPowerOf2_32(Scale & ~1);
14615 case MVT::i16:
14616 case MVT::i64:
14617 // r +/- r
14618 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
14619 return true;
14620 // r * 2 (this can be lowered to r + r).
14621 if (!AM.HasBaseReg && Scale == 2)
14622 return true;
14623 return false;
14625 case MVT::isVoid:
14626 // Note, we allow "void" uses (basically, uses that aren't loads or
14627 // stores), because arm allows folding a scale into many arithmetic
14628 // operations. This should be made more precise and revisited later.
14630 // Allow r << imm, but the imm has to be a multiple of two.
14631 if (Scale & 1) return false;
14632 return isPowerOf2_32(Scale);
14635 return true;
14638 /// isLegalICmpImmediate - Return true if the specified immediate is legal
14639 /// icmp immediate, that is the target has icmp instructions which can compare
14640 /// a register against the immediate without having to materialize the
14641 /// immediate into a register.
14642 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14643 // Thumb2 and ARM modes can use cmn for negative immediates.
14644 if (!Subtarget->isThumb())
14645 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
14646 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
14647 if (Subtarget->isThumb2())
14648 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
14649 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
14650 // Thumb1 doesn't have cmn, and only 8-bit immediates.
14651 return Imm >= 0 && Imm <= 255;
14654 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
14655 /// *or sub* immediate, that is the target has add or sub instructions which can
14656 /// add a register with the immediate without having to materialize the
14657 /// immediate into a register.
14658 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14659 // Same encoding for add/sub, just flip the sign.
14660 int64_t AbsImm = std::abs(Imm);
14661 if (!Subtarget->isThumb())
14662 return ARM_AM::getSOImmVal(AbsImm) != -1;
14663 if (Subtarget->isThumb2())
14664 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
14665 // Thumb1 only has 8-bit unsigned immediate.
14666 return AbsImm >= 0 && AbsImm <= 255;
14669 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
14670 bool isSEXTLoad, SDValue &Base,
14671 SDValue &Offset, bool &isInc,
14672 SelectionDAG &DAG) {
14673 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14674 return false;
14676 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
14677 // AddressingMode 3
14678 Base = Ptr->getOperand(0);
14679 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14680 int RHSC = (int)RHS->getZExtValue();
14681 if (RHSC < 0 && RHSC > -256) {
14682 assert(Ptr->getOpcode() == ISD::ADD);
14683 isInc = false;
14684 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14685 return true;
14688 isInc = (Ptr->getOpcode() == ISD::ADD);
14689 Offset = Ptr->getOperand(1);
14690 return true;
14691 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
14692 // AddressingMode 2
14693 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14694 int RHSC = (int)RHS->getZExtValue();
14695 if (RHSC < 0 && RHSC > -0x1000) {
14696 assert(Ptr->getOpcode() == ISD::ADD);
14697 isInc = false;
14698 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14699 Base = Ptr->getOperand(0);
14700 return true;
14704 if (Ptr->getOpcode() == ISD::ADD) {
14705 isInc = true;
14706 ARM_AM::ShiftOpc ShOpcVal=
14707 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
14708 if (ShOpcVal != ARM_AM::no_shift) {
14709 Base = Ptr->getOperand(1);
14710 Offset = Ptr->getOperand(0);
14711 } else {
14712 Base = Ptr->getOperand(0);
14713 Offset = Ptr->getOperand(1);
14715 return true;
14718 isInc = (Ptr->getOpcode() == ISD::ADD);
14719 Base = Ptr->getOperand(0);
14720 Offset = Ptr->getOperand(1);
14721 return true;
14724 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
14725 return false;
14728 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
14729 bool isSEXTLoad, SDValue &Base,
14730 SDValue &Offset, bool &isInc,
14731 SelectionDAG &DAG) {
14732 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14733 return false;
14735 Base = Ptr->getOperand(0);
14736 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14737 int RHSC = (int)RHS->getZExtValue();
14738 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
14739 assert(Ptr->getOpcode() == ISD::ADD);
14740 isInc = false;
14741 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14742 return true;
14743 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
14744 isInc = Ptr->getOpcode() == ISD::ADD;
14745 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14746 return true;
14750 return false;
14753 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
14754 bool isSEXTLoad, bool isLE, SDValue &Base,
14755 SDValue &Offset, bool &isInc,
14756 SelectionDAG &DAG) {
14757 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14758 return false;
14759 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
14760 return false;
14762 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
14763 int RHSC = (int)RHS->getZExtValue();
14765 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
14766 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
14767 assert(Ptr->getOpcode() == ISD::ADD);
14768 isInc = false;
14769 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14770 return true;
14771 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
14772 isInc = Ptr->getOpcode() == ISD::ADD;
14773 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14774 return true;
14776 return false;
14779 // Try to find a matching instruction based on s/zext, Alignment, Offset and
14780 // (in BE) type.
14781 Base = Ptr->getOperand(0);
14782 if (VT == MVT::v4i16) {
14783 if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
14784 return true;
14785 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
14786 if (IsInRange(RHSC, 0x80, 1))
14787 return true;
14788 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) &&
14789 IsInRange(RHSC, 0x80, 4))
14790 return true;
14791 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) &&
14792 IsInRange(RHSC, 0x80, 2))
14793 return true;
14794 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
14795 return true;
14796 return false;
14799 /// getPreIndexedAddressParts - returns true by value, base pointer and
14800 /// offset pointer and addressing mode by reference if the node's address
14801 /// can be legally represented as pre-indexed load / store address.
14802 bool
14803 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14804 SDValue &Offset,
14805 ISD::MemIndexedMode &AM,
14806 SelectionDAG &DAG) const {
14807 if (Subtarget->isThumb1Only())
14808 return false;
14810 EVT VT;
14811 SDValue Ptr;
14812 unsigned Align;
14813 bool isSEXTLoad = false;
14814 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14815 Ptr = LD->getBasePtr();
14816 VT = LD->getMemoryVT();
14817 Align = LD->getAlignment();
14818 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14819 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14820 Ptr = ST->getBasePtr();
14821 VT = ST->getMemoryVT();
14822 Align = ST->getAlignment();
14823 } else
14824 return false;
14826 bool isInc;
14827 bool isLegal = false;
14828 if (VT.isVector())
14829 isLegal = Subtarget->hasMVEIntegerOps() &&
14830 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
14831 Subtarget->isLittle(), Base, Offset,
14832 isInc, DAG);
14833 else {
14834 if (Subtarget->isThumb2())
14835 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14836 Offset, isInc, DAG);
14837 else
14838 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14839 Offset, isInc, DAG);
14841 if (!isLegal)
14842 return false;
14844 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
14845 return true;
14848 /// getPostIndexedAddressParts - returns true by value, base pointer and
14849 /// offset pointer and addressing mode by reference if this node can be
14850 /// combined with a load / store to form a post-indexed load / store.
14851 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
14852 SDValue &Base,
14853 SDValue &Offset,
14854 ISD::MemIndexedMode &AM,
14855 SelectionDAG &DAG) const {
14856 EVT VT;
14857 SDValue Ptr;
14858 unsigned Align;
14859 bool isSEXTLoad = false, isNonExt;
14860 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14861 VT = LD->getMemoryVT();
14862 Ptr = LD->getBasePtr();
14863 Align = LD->getAlignment();
14864 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14865 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
14866 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14867 VT = ST->getMemoryVT();
14868 Ptr = ST->getBasePtr();
14869 Align = ST->getAlignment();
14870 isNonExt = !ST->isTruncatingStore();
14871 } else
14872 return false;
14874 if (Subtarget->isThumb1Only()) {
14875 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
14876 // must be non-extending/truncating, i32, with an offset of 4.
14877 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
14878 if (Op->getOpcode() != ISD::ADD || !isNonExt)
14879 return false;
14880 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14881 if (!RHS || RHS->getZExtValue() != 4)
14882 return false;
14884 Offset = Op->getOperand(1);
14885 Base = Op->getOperand(0);
14886 AM = ISD::POST_INC;
14887 return true;
14890 bool isInc;
14891 bool isLegal = false;
14892 if (VT.isVector())
14893 isLegal = Subtarget->hasMVEIntegerOps() &&
14894 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad,
14895 Subtarget->isLittle(), Base, Offset,
14896 isInc, DAG);
14897 else {
14898 if (Subtarget->isThumb2())
14899 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14900 isInc, DAG);
14901 else
14902 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14903 isInc, DAG);
14905 if (!isLegal)
14906 return false;
14908 if (Ptr != Base) {
14909 // Swap base ptr and offset to catch more post-index load / store when
14910 // it's legal. In Thumb2 mode, offset must be an immediate.
14911 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
14912 !Subtarget->isThumb2())
14913 std::swap(Base, Offset);
14915 // Post-indexed load / store update the base pointer.
14916 if (Ptr != Base)
14917 return false;
14920 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
14921 return true;
14924 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14925 KnownBits &Known,
14926 const APInt &DemandedElts,
14927 const SelectionDAG &DAG,
14928 unsigned Depth) const {
14929 unsigned BitWidth = Known.getBitWidth();
14930 Known.resetAll();
14931 switch (Op.getOpcode()) {
14932 default: break;
14933 case ARMISD::ADDC:
14934 case ARMISD::ADDE:
14935 case ARMISD::SUBC:
14936 case ARMISD::SUBE:
14937 // Special cases when we convert a carry to a boolean.
14938 if (Op.getResNo() == 0) {
14939 SDValue LHS = Op.getOperand(0);
14940 SDValue RHS = Op.getOperand(1);
14941 // (ADDE 0, 0, C) will give us a single bit.
14942 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
14943 isNullConstant(RHS)) {
14944 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14945 return;
14948 break;
14949 case ARMISD::CMOV: {
14950 // Bits are known zero/one if known on the LHS and RHS.
14951 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
14952 if (Known.isUnknown())
14953 return;
14955 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
14956 Known.Zero &= KnownRHS.Zero;
14957 Known.One &= KnownRHS.One;
14958 return;
14960 case ISD::INTRINSIC_W_CHAIN: {
14961 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
14962 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14963 switch (IntID) {
14964 default: return;
14965 case Intrinsic::arm_ldaex:
14966 case Intrinsic::arm_ldrex: {
14967 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
14968 unsigned MemBits = VT.getScalarSizeInBits();
14969 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
14970 return;
14974 case ARMISD::BFI: {
14975 // Conservatively, we can recurse down the first operand
14976 // and just mask out all affected bits.
14977 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
14979 // The operand to BFI is already a mask suitable for removing the bits it
14980 // sets.
14981 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
14982 const APInt &Mask = CI->getAPIntValue();
14983 Known.Zero &= Mask;
14984 Known.One &= Mask;
14985 return;
14987 case ARMISD::VGETLANEs:
14988 case ARMISD::VGETLANEu: {
14989 const SDValue &SrcSV = Op.getOperand(0);
14990 EVT VecVT = SrcSV.getValueType();
14991 assert(VecVT.isVector() && "VGETLANE expected a vector type");
14992 const unsigned NumSrcElts = VecVT.getVectorNumElements();
14993 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
14994 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
14995 "VGETLANE index out of bounds");
14996 unsigned Idx = Pos->getZExtValue();
14997 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
14998 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
15000 EVT VT = Op.getValueType();
15001 const unsigned DstSz = VT.getScalarSizeInBits();
15002 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
15003 (void)SrcSz;
15004 assert(SrcSz == Known.getBitWidth());
15005 assert(DstSz > SrcSz);
15006 if (Op.getOpcode() == ARMISD::VGETLANEs)
15007 Known = Known.sext(DstSz);
15008 else {
15009 Known = Known.zext(DstSz, true /* extended bits are known zero */);
15011 assert(DstSz == Known.getBitWidth());
15012 break;
15017 bool
15018 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
15019 const APInt &DemandedAPInt,
15020 TargetLoweringOpt &TLO) const {
15021 // Delay optimization, so we don't have to deal with illegal types, or block
15022 // optimizations.
15023 if (!TLO.LegalOps)
15024 return false;
15026 // Only optimize AND for now.
15027 if (Op.getOpcode() != ISD::AND)
15028 return false;
15030 EVT VT = Op.getValueType();
15032 // Ignore vectors.
15033 if (VT.isVector())
15034 return false;
15036 assert(VT == MVT::i32 && "Unexpected integer type");
15038 // Make sure the RHS really is a constant.
15039 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15040 if (!C)
15041 return false;
15043 unsigned Mask = C->getZExtValue();
15045 unsigned Demanded = DemandedAPInt.getZExtValue();
15046 unsigned ShrunkMask = Mask & Demanded;
15047 unsigned ExpandedMask = Mask | ~Demanded;
15049 // If the mask is all zeros, let the target-independent code replace the
15050 // result with zero.
15051 if (ShrunkMask == 0)
15052 return false;
15054 // If the mask is all ones, erase the AND. (Currently, the target-independent
15055 // code won't do this, so we have to do it explicitly to avoid an infinite
15056 // loop in obscure cases.)
15057 if (ExpandedMask == ~0U)
15058 return TLO.CombineTo(Op, Op.getOperand(0));
15060 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
15061 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
15063 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
15064 if (NewMask == Mask)
15065 return true;
15066 SDLoc DL(Op);
15067 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
15068 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
15069 return TLO.CombineTo(Op, NewOp);
15072 // Prefer uxtb mask.
15073 if (IsLegalMask(0xFF))
15074 return UseMask(0xFF);
15076 // Prefer uxth mask.
15077 if (IsLegalMask(0xFFFF))
15078 return UseMask(0xFFFF);
15080 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
15081 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15082 if (ShrunkMask < 256)
15083 return UseMask(ShrunkMask);
15085 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
15086 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15087 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
15088 return UseMask(ExpandedMask);
15090 // Potential improvements:
15092 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
15093 // We could try to prefer Thumb1 immediates which can be lowered to a
15094 // two-instruction sequence.
15095 // We could try to recognize more legal ARM/Thumb2 immediates here.
15097 return false;
15101 //===----------------------------------------------------------------------===//
15102 // ARM Inline Assembly Support
15103 //===----------------------------------------------------------------------===//
15105 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
15106 // Looking for "rev" which is V6+.
15107 if (!Subtarget->hasV6Ops())
15108 return false;
15110 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15111 std::string AsmStr = IA->getAsmString();
15112 SmallVector<StringRef, 4> AsmPieces;
15113 SplitString(AsmStr, AsmPieces, ";\n");
15115 switch (AsmPieces.size()) {
15116 default: return false;
15117 case 1:
15118 AsmStr = AsmPieces[0];
15119 AsmPieces.clear();
15120 SplitString(AsmStr, AsmPieces, " \t,");
15122 // rev $0, $1
15123 if (AsmPieces.size() == 3 &&
15124 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
15125 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
15126 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15127 if (Ty && Ty->getBitWidth() == 32)
15128 return IntrinsicLowering::LowerToByteSwap(CI);
15130 break;
15133 return false;
15136 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
15137 // At this point, we have to lower this constraint to something else, so we
15138 // lower it to an "r" or "w". However, by doing this we will force the result
15139 // to be in register, while the X constraint is much more permissive.
15141 // Although we are correct (we are free to emit anything, without
15142 // constraints), we might break use cases that would expect us to be more
15143 // efficient and emit something else.
15144 if (!Subtarget->hasVFP2Base())
15145 return "r";
15146 if (ConstraintVT.isFloatingPoint())
15147 return "w";
15148 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
15149 (ConstraintVT.getSizeInBits() == 64 ||
15150 ConstraintVT.getSizeInBits() == 128))
15151 return "w";
15153 return "r";
15156 /// getConstraintType - Given a constraint letter, return the type of
15157 /// constraint it is for this target.
15158 ARMTargetLowering::ConstraintType
15159 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
15160 unsigned S = Constraint.size();
15161 if (S == 1) {
15162 switch (Constraint[0]) {
15163 default: break;
15164 case 'l': return C_RegisterClass;
15165 case 'w': return C_RegisterClass;
15166 case 'h': return C_RegisterClass;
15167 case 'x': return C_RegisterClass;
15168 case 't': return C_RegisterClass;
15169 case 'j': return C_Immediate; // Constant for movw.
15170 // An address with a single base register. Due to the way we
15171 // currently handle addresses it is the same as an 'r' memory constraint.
15172 case 'Q': return C_Memory;
15174 } else if (S == 2) {
15175 switch (Constraint[0]) {
15176 default: break;
15177 case 'T': return C_RegisterClass;
15178 // All 'U+' constraints are addresses.
15179 case 'U': return C_Memory;
15182 return TargetLowering::getConstraintType(Constraint);
15185 /// Examine constraint type and operand type and determine a weight value.
15186 /// This object must already have been set up with the operand type
15187 /// and the current alternative constraint selected.
15188 TargetLowering::ConstraintWeight
15189 ARMTargetLowering::getSingleConstraintMatchWeight(
15190 AsmOperandInfo &info, const char *constraint) const {
15191 ConstraintWeight weight = CW_Invalid;
15192 Value *CallOperandVal = info.CallOperandVal;
15193 // If we don't have a value, we can't do a match,
15194 // but allow it at the lowest weight.
15195 if (!CallOperandVal)
15196 return CW_Default;
15197 Type *type = CallOperandVal->getType();
15198 // Look at the constraint type.
15199 switch (*constraint) {
15200 default:
15201 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15202 break;
15203 case 'l':
15204 if (type->isIntegerTy()) {
15205 if (Subtarget->isThumb())
15206 weight = CW_SpecificReg;
15207 else
15208 weight = CW_Register;
15210 break;
15211 case 'w':
15212 if (type->isFloatingPointTy())
15213 weight = CW_Register;
15214 break;
15216 return weight;
15219 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
15221 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
15222 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
15223 switch (Constraint.size()) {
15224 case 1:
15225 // GCC ARM Constraint Letters
15226 switch (Constraint[0]) {
15227 case 'l': // Low regs or general regs.
15228 if (Subtarget->isThumb())
15229 return RCPair(0U, &ARM::tGPRRegClass);
15230 return RCPair(0U, &ARM::GPRRegClass);
15231 case 'h': // High regs or no regs.
15232 if (Subtarget->isThumb())
15233 return RCPair(0U, &ARM::hGPRRegClass);
15234 break;
15235 case 'r':
15236 if (Subtarget->isThumb1Only())
15237 return RCPair(0U, &ARM::tGPRRegClass);
15238 return RCPair(0U, &ARM::GPRRegClass);
15239 case 'w':
15240 if (VT == MVT::Other)
15241 break;
15242 if (VT == MVT::f32)
15243 return RCPair(0U, &ARM::SPRRegClass);
15244 if (VT.getSizeInBits() == 64)
15245 return RCPair(0U, &ARM::DPRRegClass);
15246 if (VT.getSizeInBits() == 128)
15247 return RCPair(0U, &ARM::QPRRegClass);
15248 break;
15249 case 'x':
15250 if (VT == MVT::Other)
15251 break;
15252 if (VT == MVT::f32)
15253 return RCPair(0U, &ARM::SPR_8RegClass);
15254 if (VT.getSizeInBits() == 64)
15255 return RCPair(0U, &ARM::DPR_8RegClass);
15256 if (VT.getSizeInBits() == 128)
15257 return RCPair(0U, &ARM::QPR_8RegClass);
15258 break;
15259 case 't':
15260 if (VT == MVT::Other)
15261 break;
15262 if (VT == MVT::f32 || VT == MVT::i32)
15263 return RCPair(0U, &ARM::SPRRegClass);
15264 if (VT.getSizeInBits() == 64)
15265 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15266 if (VT.getSizeInBits() == 128)
15267 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15268 break;
15270 break;
15272 case 2:
15273 if (Constraint[0] == 'T') {
15274 switch (Constraint[1]) {
15275 default:
15276 break;
15277 case 'e':
15278 return RCPair(0U, &ARM::tGPREvenRegClass);
15279 case 'o':
15280 return RCPair(0U, &ARM::tGPROddRegClass);
15283 break;
15285 default:
15286 break;
15289 if (StringRef("{cc}").equals_lower(Constraint))
15290 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15292 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15295 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15296 /// vector. If it is invalid, don't add anything to Ops.
15297 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15298 std::string &Constraint,
15299 std::vector<SDValue>&Ops,
15300 SelectionDAG &DAG) const {
15301 SDValue Result;
15303 // Currently only support length 1 constraints.
15304 if (Constraint.length() != 1) return;
15306 char ConstraintLetter = Constraint[0];
15307 switch (ConstraintLetter) {
15308 default: break;
15309 case 'j':
15310 case 'I': case 'J': case 'K': case 'L':
15311 case 'M': case 'N': case 'O':
15312 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15313 if (!C)
15314 return;
15316 int64_t CVal64 = C->getSExtValue();
15317 int CVal = (int) CVal64;
15318 // None of these constraints allow values larger than 32 bits. Check
15319 // that the value fits in an int.
15320 if (CVal != CVal64)
15321 return;
15323 switch (ConstraintLetter) {
15324 case 'j':
15325 // Constant suitable for movw, must be between 0 and
15326 // 65535.
15327 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
15328 if (CVal >= 0 && CVal <= 65535)
15329 break;
15330 return;
15331 case 'I':
15332 if (Subtarget->isThumb1Only()) {
15333 // This must be a constant between 0 and 255, for ADD
15334 // immediates.
15335 if (CVal >= 0 && CVal <= 255)
15336 break;
15337 } else if (Subtarget->isThumb2()) {
15338 // A constant that can be used as an immediate value in a
15339 // data-processing instruction.
15340 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15341 break;
15342 } else {
15343 // A constant that can be used as an immediate value in a
15344 // data-processing instruction.
15345 if (ARM_AM::getSOImmVal(CVal) != -1)
15346 break;
15348 return;
15350 case 'J':
15351 if (Subtarget->isThumb1Only()) {
15352 // This must be a constant between -255 and -1, for negated ADD
15353 // immediates. This can be used in GCC with an "n" modifier that
15354 // prints the negated value, for use with SUB instructions. It is
15355 // not useful otherwise but is implemented for compatibility.
15356 if (CVal >= -255 && CVal <= -1)
15357 break;
15358 } else {
15359 // This must be a constant between -4095 and 4095. It is not clear
15360 // what this constraint is intended for. Implemented for
15361 // compatibility with GCC.
15362 if (CVal >= -4095 && CVal <= 4095)
15363 break;
15365 return;
15367 case 'K':
15368 if (Subtarget->isThumb1Only()) {
15369 // A 32-bit value where only one byte has a nonzero value. Exclude
15370 // zero to match GCC. This constraint is used by GCC internally for
15371 // constants that can be loaded with a move/shift combination.
15372 // It is not useful otherwise but is implemented for compatibility.
15373 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15374 break;
15375 } else if (Subtarget->isThumb2()) {
15376 // A constant whose bitwise inverse can be used as an immediate
15377 // value in a data-processing instruction. This can be used in GCC
15378 // with a "B" modifier that prints the inverted value, for use with
15379 // BIC and MVN instructions. It is not useful otherwise but is
15380 // implemented for compatibility.
15381 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15382 break;
15383 } else {
15384 // A constant whose bitwise inverse can be used as an immediate
15385 // value in a data-processing instruction. This can be used in GCC
15386 // with a "B" modifier that prints the inverted value, for use with
15387 // BIC and MVN instructions. It is not useful otherwise but is
15388 // implemented for compatibility.
15389 if (ARM_AM::getSOImmVal(~CVal) != -1)
15390 break;
15392 return;
15394 case 'L':
15395 if (Subtarget->isThumb1Only()) {
15396 // This must be a constant between -7 and 7,
15397 // for 3-operand ADD/SUB immediate instructions.
15398 if (CVal >= -7 && CVal < 7)
15399 break;
15400 } else if (Subtarget->isThumb2()) {
15401 // A constant whose negation can be used as an immediate value in a
15402 // data-processing instruction. This can be used in GCC with an "n"
15403 // modifier that prints the negated value, for use with SUB
15404 // instructions. It is not useful otherwise but is implemented for
15405 // compatibility.
15406 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15407 break;
15408 } else {
15409 // A constant whose negation can be used as an immediate value in a
15410 // data-processing instruction. This can be used in GCC with an "n"
15411 // modifier that prints the negated value, for use with SUB
15412 // instructions. It is not useful otherwise but is implemented for
15413 // compatibility.
15414 if (ARM_AM::getSOImmVal(-CVal) != -1)
15415 break;
15417 return;
15419 case 'M':
15420 if (Subtarget->isThumb1Only()) {
15421 // This must be a multiple of 4 between 0 and 1020, for
15422 // ADD sp + immediate.
15423 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15424 break;
15425 } else {
15426 // A power of two or a constant between 0 and 32. This is used in
15427 // GCC for the shift amount on shifted register operands, but it is
15428 // useful in general for any shift amounts.
15429 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15430 break;
15432 return;
15434 case 'N':
15435 if (Subtarget->isThumb1Only()) {
15436 // This must be a constant between 0 and 31, for shift amounts.
15437 if (CVal >= 0 && CVal <= 31)
15438 break;
15440 return;
15442 case 'O':
15443 if (Subtarget->isThumb1Only()) {
15444 // This must be a multiple of 4 between -508 and 508, for
15445 // ADD/SUB sp = sp + immediate.
15446 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15447 break;
15449 return;
15451 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15452 break;
15455 if (Result.getNode()) {
15456 Ops.push_back(Result);
15457 return;
15459 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15462 static RTLIB::Libcall getDivRemLibcall(
15463 const SDNode *N, MVT::SimpleValueType SVT) {
15464 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15465 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15466 "Unhandled Opcode in getDivRemLibcall");
15467 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15468 N->getOpcode() == ISD::SREM;
15469 RTLIB::Libcall LC;
15470 switch (SVT) {
15471 default: llvm_unreachable("Unexpected request for libcall!");
15472 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15473 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15474 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15475 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15477 return LC;
15480 static TargetLowering::ArgListTy getDivRemArgList(
15481 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15482 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15483 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15484 "Unhandled Opcode in getDivRemArgList");
15485 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15486 N->getOpcode() == ISD::SREM;
15487 TargetLowering::ArgListTy Args;
15488 TargetLowering::ArgListEntry Entry;
15489 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15490 EVT ArgVT = N->getOperand(i).getValueType();
15491 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15492 Entry.Node = N->getOperand(i);
15493 Entry.Ty = ArgTy;
15494 Entry.IsSExt = isSigned;
15495 Entry.IsZExt = !isSigned;
15496 Args.push_back(Entry);
15498 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15499 std::swap(Args[0], Args[1]);
15500 return Args;
15503 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15504 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15505 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15506 Subtarget->isTargetWindows()) &&
15507 "Register-based DivRem lowering only");
15508 unsigned Opcode = Op->getOpcode();
15509 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15510 "Invalid opcode for Div/Rem lowering");
15511 bool isSigned = (Opcode == ISD::SDIVREM);
15512 EVT VT = Op->getValueType(0);
15513 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15514 SDLoc dl(Op);
15516 // If the target has hardware divide, use divide + multiply + subtract:
15517 // div = a / b
15518 // rem = a - b * div
15519 // return {div, rem}
15520 // This should be lowered into UDIV/SDIV + MLS later on.
15521 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15522 : Subtarget->hasDivideInARMMode();
15523 if (hasDivide && Op->getValueType(0).isSimple() &&
15524 Op->getSimpleValueType(0) == MVT::i32) {
15525 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15526 const SDValue Dividend = Op->getOperand(0);
15527 const SDValue Divisor = Op->getOperand(1);
15528 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15529 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15530 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15532 SDValue Values[2] = {Div, Rem};
15533 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15536 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15537 VT.getSimpleVT().SimpleTy);
15538 SDValue InChain = DAG.getEntryNode();
15540 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15541 DAG.getContext(),
15542 Subtarget);
15544 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15545 getPointerTy(DAG.getDataLayout()));
15547 Type *RetTy = StructType::get(Ty, Ty);
15549 if (Subtarget->isTargetWindows())
15550 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15552 TargetLowering::CallLoweringInfo CLI(DAG);
15553 CLI.setDebugLoc(dl).setChain(InChain)
15554 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15555 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15557 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15558 return CallInfo.first;
15561 // Lowers REM using divmod helpers
15562 // see RTABI section 4.2/4.3
15563 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15564 // Build return types (div and rem)
15565 std::vector<Type*> RetTyParams;
15566 Type *RetTyElement;
15568 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15569 default: llvm_unreachable("Unexpected request for libcall!");
15570 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15571 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15572 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15573 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15576 RetTyParams.push_back(RetTyElement);
15577 RetTyParams.push_back(RetTyElement);
15578 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15579 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15581 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15582 SimpleTy);
15583 SDValue InChain = DAG.getEntryNode();
15584 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15585 Subtarget);
15586 bool isSigned = N->getOpcode() == ISD::SREM;
15587 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15588 getPointerTy(DAG.getDataLayout()));
15590 if (Subtarget->isTargetWindows())
15591 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15593 // Lower call
15594 CallLoweringInfo CLI(DAG);
15595 CLI.setChain(InChain)
15596 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
15597 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
15598 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
15600 // Return second (rem) result operand (first contains div)
15601 SDNode *ResNode = CallResult.first.getNode();
15602 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
15603 return ResNode->getOperand(1);
15606 SDValue
15607 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
15608 assert(Subtarget->isTargetWindows() && "unsupported target platform");
15609 SDLoc DL(Op);
15611 // Get the inputs.
15612 SDValue Chain = Op.getOperand(0);
15613 SDValue Size = Op.getOperand(1);
15615 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
15616 "no-stack-arg-probe")) {
15617 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15618 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15619 Chain = SP.getValue(1);
15620 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
15621 if (Align)
15622 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
15623 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
15624 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
15625 SDValue Ops[2] = { SP, Chain };
15626 return DAG.getMergeValues(Ops, DL);
15629 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
15630 DAG.getConstant(2, DL, MVT::i32));
15632 SDValue Flag;
15633 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
15634 Flag = Chain.getValue(1);
15636 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15637 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
15639 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15640 Chain = NewSP.getValue(1);
15642 SDValue Ops[2] = { NewSP, Chain };
15643 return DAG.getMergeValues(Ops, DL);
15646 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
15647 SDValue SrcVal = Op.getOperand(0);
15648 const unsigned DstSz = Op.getValueType().getSizeInBits();
15649 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
15650 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
15651 "Unexpected type for custom-lowering FP_EXTEND");
15653 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15654 "With both FP DP and 16, any FP conversion is legal!");
15656 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
15657 "With FP16, 16 to 32 conversion is legal!");
15659 // Either we are converting from 16 -> 64, without FP16 and/or
15660 // FP.double-precision or without Armv8-fp. So we must do it in two
15661 // steps.
15662 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
15663 // without FP16. So we must do a function call.
15664 SDLoc Loc(Op);
15665 RTLIB::Libcall LC;
15666 MakeLibCallOptions CallOptions;
15667 if (SrcSz == 16) {
15668 // Instruction from 16 -> 32
15669 if (Subtarget->hasFP16())
15670 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
15671 // Lib call from 16 -> 32
15672 else {
15673 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
15674 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15675 "Unexpected type for custom-lowering FP_EXTEND");
15676 SrcVal =
15677 makeLibCall(DAG, LC, MVT::f32, SrcVal, CallOptions, Loc).first;
15681 if (DstSz != 64)
15682 return SrcVal;
15683 // For sure now SrcVal is 32 bits
15684 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
15685 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
15687 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
15688 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15689 "Unexpected type for custom-lowering FP_EXTEND");
15690 return makeLibCall(DAG, LC, MVT::f64, SrcVal, CallOptions, Loc).first;
15693 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
15694 SDValue SrcVal = Op.getOperand(0);
15695 EVT SrcVT = SrcVal.getValueType();
15696 EVT DstVT = Op.getValueType();
15697 const unsigned DstSz = Op.getValueType().getSizeInBits();
15698 const unsigned SrcSz = SrcVT.getSizeInBits();
15699 (void)DstSz;
15700 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
15701 "Unexpected type for custom-lowering FP_ROUND");
15703 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15704 "With both FP DP and 16, any FP conversion is legal!");
15706 SDLoc Loc(Op);
15708 // Instruction from 32 -> 16 if hasFP16 is valid
15709 if (SrcSz == 32 && Subtarget->hasFP16())
15710 return Op;
15712 // Lib call from 32 -> 16 / 64 -> [32, 16]
15713 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
15714 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15715 "Unexpected type for custom-lowering FP_ROUND");
15716 MakeLibCallOptions CallOptions;
15717 return makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, Loc).first;
15720 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
15721 SelectionDAG &DAG) const {
15722 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
15723 MVT HalfT = MVT::i32;
15724 SDLoc dl(N);
15725 SDValue Hi, Lo, Tmp;
15727 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
15728 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
15729 return ;
15731 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
15732 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
15734 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15735 DAG.getConstant(0, dl, HalfT));
15736 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15737 DAG.getConstant(1, dl, HalfT));
15739 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
15740 DAG.getConstant(OpTypeBits - 1, dl,
15741 getShiftAmountTy(HalfT, DAG.getDataLayout())));
15742 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
15743 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
15744 SDValue(Lo.getNode(), 1));
15745 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
15746 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
15748 Results.push_back(Lo);
15749 Results.push_back(Hi);
15752 bool
15753 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15754 // The ARM target isn't yet aware of offsets.
15755 return false;
15758 bool ARM::isBitFieldInvertedMask(unsigned v) {
15759 if (v == 0xffffffff)
15760 return false;
15762 // there can be 1's on either or both "outsides", all the "inside"
15763 // bits must be 0's
15764 return isShiftedMask_32(~v);
15767 /// isFPImmLegal - Returns true if the target can instruction select the
15768 /// specified FP immediate natively. If false, the legalizer will
15769 /// materialize the FP immediate as a load from a constant pool.
15770 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15771 bool ForCodeSize) const {
15772 if (!Subtarget->hasVFP3Base())
15773 return false;
15774 if (VT == MVT::f16 && Subtarget->hasFullFP16())
15775 return ARM_AM::getFP16Imm(Imm) != -1;
15776 if (VT == MVT::f32)
15777 return ARM_AM::getFP32Imm(Imm) != -1;
15778 if (VT == MVT::f64 && Subtarget->hasFP64())
15779 return ARM_AM::getFP64Imm(Imm) != -1;
15780 return false;
15783 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
15784 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
15785 /// specified in the intrinsic calls.
15786 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15787 const CallInst &I,
15788 MachineFunction &MF,
15789 unsigned Intrinsic) const {
15790 switch (Intrinsic) {
15791 case Intrinsic::arm_neon_vld1:
15792 case Intrinsic::arm_neon_vld2:
15793 case Intrinsic::arm_neon_vld3:
15794 case Intrinsic::arm_neon_vld4:
15795 case Intrinsic::arm_neon_vld2lane:
15796 case Intrinsic::arm_neon_vld3lane:
15797 case Intrinsic::arm_neon_vld4lane:
15798 case Intrinsic::arm_neon_vld2dup:
15799 case Intrinsic::arm_neon_vld3dup:
15800 case Intrinsic::arm_neon_vld4dup: {
15801 Info.opc = ISD::INTRINSIC_W_CHAIN;
15802 // Conservatively set memVT to the entire set of vectors loaded.
15803 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15804 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15805 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15806 Info.ptrVal = I.getArgOperand(0);
15807 Info.offset = 0;
15808 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15809 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15810 // volatile loads with NEON intrinsics not supported
15811 Info.flags = MachineMemOperand::MOLoad;
15812 return true;
15814 case Intrinsic::arm_neon_vld1x2:
15815 case Intrinsic::arm_neon_vld1x3:
15816 case Intrinsic::arm_neon_vld1x4: {
15817 Info.opc = ISD::INTRINSIC_W_CHAIN;
15818 // Conservatively set memVT to the entire set of vectors loaded.
15819 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15820 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15821 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15822 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
15823 Info.offset = 0;
15824 Info.align.reset();
15825 // volatile loads with NEON intrinsics not supported
15826 Info.flags = MachineMemOperand::MOLoad;
15827 return true;
15829 case Intrinsic::arm_neon_vst1:
15830 case Intrinsic::arm_neon_vst2:
15831 case Intrinsic::arm_neon_vst3:
15832 case Intrinsic::arm_neon_vst4:
15833 case Intrinsic::arm_neon_vst2lane:
15834 case Intrinsic::arm_neon_vst3lane:
15835 case Intrinsic::arm_neon_vst4lane: {
15836 Info.opc = ISD::INTRINSIC_VOID;
15837 // Conservatively set memVT to the entire set of vectors stored.
15838 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15839 unsigned NumElts = 0;
15840 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15841 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15842 if (!ArgTy->isVectorTy())
15843 break;
15844 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15846 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15847 Info.ptrVal = I.getArgOperand(0);
15848 Info.offset = 0;
15849 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15850 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15851 // volatile stores with NEON intrinsics not supported
15852 Info.flags = MachineMemOperand::MOStore;
15853 return true;
15855 case Intrinsic::arm_neon_vst1x2:
15856 case Intrinsic::arm_neon_vst1x3:
15857 case Intrinsic::arm_neon_vst1x4: {
15858 Info.opc = ISD::INTRINSIC_VOID;
15859 // Conservatively set memVT to the entire set of vectors stored.
15860 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15861 unsigned NumElts = 0;
15862 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15863 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15864 if (!ArgTy->isVectorTy())
15865 break;
15866 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15868 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15869 Info.ptrVal = I.getArgOperand(0);
15870 Info.offset = 0;
15871 Info.align.reset();
15872 // volatile stores with NEON intrinsics not supported
15873 Info.flags = MachineMemOperand::MOStore;
15874 return true;
15876 case Intrinsic::arm_ldaex:
15877 case Intrinsic::arm_ldrex: {
15878 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15879 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
15880 Info.opc = ISD::INTRINSIC_W_CHAIN;
15881 Info.memVT = MVT::getVT(PtrTy->getElementType());
15882 Info.ptrVal = I.getArgOperand(0);
15883 Info.offset = 0;
15884 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
15885 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15886 return true;
15888 case Intrinsic::arm_stlex:
15889 case Intrinsic::arm_strex: {
15890 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15891 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
15892 Info.opc = ISD::INTRINSIC_W_CHAIN;
15893 Info.memVT = MVT::getVT(PtrTy->getElementType());
15894 Info.ptrVal = I.getArgOperand(1);
15895 Info.offset = 0;
15896 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
15897 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15898 return true;
15900 case Intrinsic::arm_stlexd:
15901 case Intrinsic::arm_strexd:
15902 Info.opc = ISD::INTRINSIC_W_CHAIN;
15903 Info.memVT = MVT::i64;
15904 Info.ptrVal = I.getArgOperand(2);
15905 Info.offset = 0;
15906 Info.align = Align(8);
15907 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15908 return true;
15910 case Intrinsic::arm_ldaexd:
15911 case Intrinsic::arm_ldrexd:
15912 Info.opc = ISD::INTRINSIC_W_CHAIN;
15913 Info.memVT = MVT::i64;
15914 Info.ptrVal = I.getArgOperand(0);
15915 Info.offset = 0;
15916 Info.align = Align(8);
15917 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15918 return true;
15920 default:
15921 break;
15924 return false;
15927 /// Returns true if it is beneficial to convert a load of a constant
15928 /// to just the constant itself.
15929 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15930 Type *Ty) const {
15931 assert(Ty->isIntegerTy());
15933 unsigned Bits = Ty->getPrimitiveSizeInBits();
15934 if (Bits == 0 || Bits > 32)
15935 return false;
15936 return true;
15939 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
15940 unsigned Index) const {
15941 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
15942 return false;
15944 return (Index == 0 || Index == ResVT.getVectorNumElements());
15947 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
15948 ARM_MB::MemBOpt Domain) const {
15949 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15951 // First, if the target has no DMB, see what fallback we can use.
15952 if (!Subtarget->hasDataBarrier()) {
15953 // Some ARMv6 cpus can support data barriers with an mcr instruction.
15954 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
15955 // here.
15956 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
15957 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
15958 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
15959 Builder.getInt32(0), Builder.getInt32(7),
15960 Builder.getInt32(10), Builder.getInt32(5)};
15961 return Builder.CreateCall(MCR, args);
15962 } else {
15963 // Instead of using barriers, atomic accesses on these subtargets use
15964 // libcalls.
15965 llvm_unreachable("makeDMB on a target so old that it has no barriers");
15967 } else {
15968 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
15969 // Only a full system barrier exists in the M-class architectures.
15970 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
15971 Constant *CDomain = Builder.getInt32(Domain);
15972 return Builder.CreateCall(DMB, CDomain);
15976 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
15977 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
15978 Instruction *Inst,
15979 AtomicOrdering Ord) const {
15980 switch (Ord) {
15981 case AtomicOrdering::NotAtomic:
15982 case AtomicOrdering::Unordered:
15983 llvm_unreachable("Invalid fence: unordered/non-atomic");
15984 case AtomicOrdering::Monotonic:
15985 case AtomicOrdering::Acquire:
15986 return nullptr; // Nothing to do
15987 case AtomicOrdering::SequentiallyConsistent:
15988 if (!Inst->hasAtomicStore())
15989 return nullptr; // Nothing to do
15990 LLVM_FALLTHROUGH;
15991 case AtomicOrdering::Release:
15992 case AtomicOrdering::AcquireRelease:
15993 if (Subtarget->preferISHSTBarriers())
15994 return makeDMB(Builder, ARM_MB::ISHST);
15995 // FIXME: add a comment with a link to documentation justifying this.
15996 else
15997 return makeDMB(Builder, ARM_MB::ISH);
15999 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
16002 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
16003 Instruction *Inst,
16004 AtomicOrdering Ord) const {
16005 switch (Ord) {
16006 case AtomicOrdering::NotAtomic:
16007 case AtomicOrdering::Unordered:
16008 llvm_unreachable("Invalid fence: unordered/not-atomic");
16009 case AtomicOrdering::Monotonic:
16010 case AtomicOrdering::Release:
16011 return nullptr; // Nothing to do
16012 case AtomicOrdering::Acquire:
16013 case AtomicOrdering::AcquireRelease:
16014 case AtomicOrdering::SequentiallyConsistent:
16015 return makeDMB(Builder, ARM_MB::ISH);
16017 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
16020 // Loads and stores less than 64-bits are already atomic; ones above that
16021 // are doomed anyway, so defer to the default libcall and blame the OS when
16022 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16023 // anything for those.
16024 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16025 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
16026 return (Size == 64) && !Subtarget->isMClass();
16029 // Loads and stores less than 64-bits are already atomic; ones above that
16030 // are doomed anyway, so defer to the default libcall and blame the OS when
16031 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16032 // anything for those.
16033 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
16034 // guarantee, see DDI0406C ARM architecture reference manual,
16035 // sections A8.8.72-74 LDRD)
16036 TargetLowering::AtomicExpansionKind
16037 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16038 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
16039 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
16040 : AtomicExpansionKind::None;
16043 // For the real atomic operations, we have ldrex/strex up to 32 bits,
16044 // and up to 64 bits on the non-M profiles
16045 TargetLowering::AtomicExpansionKind
16046 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16047 if (AI->isFloatingPointOperation())
16048 return AtomicExpansionKind::CmpXChg;
16050 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
16051 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16052 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
16053 ? AtomicExpansionKind::LLSC
16054 : AtomicExpansionKind::None;
16057 TargetLowering::AtomicExpansionKind
16058 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
16059 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16060 // implement cmpxchg without spilling. If the address being exchanged is also
16061 // on the stack and close enough to the spill slot, this can lead to a
16062 // situation where the monitor always gets cleared and the atomic operation
16063 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16064 bool HasAtomicCmpXchg =
16065 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16066 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
16067 return AtomicExpansionKind::LLSC;
16068 return AtomicExpansionKind::None;
16071 bool ARMTargetLowering::shouldInsertFencesForAtomic(
16072 const Instruction *I) const {
16073 return InsertFencesForAtomic;
16076 // This has so far only been implemented for MachO.
16077 bool ARMTargetLowering::useLoadStackGuardNode() const {
16078 return Subtarget->isTargetMachO();
16081 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
16082 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16083 return TargetLowering::insertSSPDeclarations(M);
16085 // MSVC CRT has a global variable holding security cookie.
16086 M.getOrInsertGlobal("__security_cookie",
16087 Type::getInt8PtrTy(M.getContext()));
16089 // MSVC CRT has a function to validate security cookie.
16090 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16091 "__security_check_cookie", Type::getVoidTy(M.getContext()),
16092 Type::getInt8PtrTy(M.getContext()));
16093 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
16094 F->addAttribute(1, Attribute::AttrKind::InReg);
16097 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
16098 // MSVC CRT has a global variable holding security cookie.
16099 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16100 return M.getGlobalVariable("__security_cookie");
16101 return TargetLowering::getSDagStackGuard(M);
16104 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
16105 // MSVC CRT has a function to validate security cookie.
16106 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16107 return M.getFunction("__security_check_cookie");
16108 return TargetLowering::getSSPStackGuardCheck(M);
16111 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
16112 unsigned &Cost) const {
16113 // If we do not have NEON, vector types are not natively supported.
16114 if (!Subtarget->hasNEON())
16115 return false;
16117 // Floating point values and vector values map to the same register file.
16118 // Therefore, although we could do a store extract of a vector type, this is
16119 // better to leave at float as we have more freedom in the addressing mode for
16120 // those.
16121 if (VectorTy->isFPOrFPVectorTy())
16122 return false;
16124 // If the index is unknown at compile time, this is very expensive to lower
16125 // and it is not possible to combine the store with the extract.
16126 if (!isa<ConstantInt>(Idx))
16127 return false;
16129 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
16130 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
16131 // We can do a store + vector extract on any vector that fits perfectly in a D
16132 // or Q register.
16133 if (BitWidth == 64 || BitWidth == 128) {
16134 Cost = 0;
16135 return true;
16137 return false;
16140 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
16141 return Subtarget->hasV6T2Ops();
16144 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
16145 return Subtarget->hasV6T2Ops();
16148 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
16149 return !Subtarget->hasMinSize();
16152 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16153 AtomicOrdering Ord) const {
16154 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16155 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16156 bool IsAcquire = isAcquireOrStronger(Ord);
16158 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
16159 // intrinsic must return {i32, i32} and we have to recombine them into a
16160 // single i64 here.
16161 if (ValTy->getPrimitiveSizeInBits() == 64) {
16162 Intrinsic::ID Int =
16163 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
16164 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
16166 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16167 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
16169 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16170 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16171 if (!Subtarget->isLittle())
16172 std::swap (Lo, Hi);
16173 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16174 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16175 return Builder.CreateOr(
16176 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
16179 Type *Tys[] = { Addr->getType() };
16180 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
16181 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
16183 return Builder.CreateTruncOrBitCast(
16184 Builder.CreateCall(Ldrex, Addr),
16185 cast<PointerType>(Addr->getType())->getElementType());
16188 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16189 IRBuilder<> &Builder) const {
16190 if (!Subtarget->hasV7Ops())
16191 return;
16192 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16193 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
16196 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
16197 Value *Addr,
16198 AtomicOrdering Ord) const {
16199 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16200 bool IsRelease = isReleaseOrStronger(Ord);
16202 // Since the intrinsics must have legal type, the i64 intrinsics take two
16203 // parameters: "i32, i32". We must marshal Val into the appropriate form
16204 // before the call.
16205 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
16206 Intrinsic::ID Int =
16207 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
16208 Function *Strex = Intrinsic::getDeclaration(M, Int);
16209 Type *Int32Ty = Type::getInt32Ty(M->getContext());
16211 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
16212 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
16213 if (!Subtarget->isLittle())
16214 std::swap(Lo, Hi);
16215 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16216 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
16219 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
16220 Type *Tys[] = { Addr->getType() };
16221 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
16223 return Builder.CreateCall(
16224 Strex, {Builder.CreateZExtOrBitCast(
16225 Val, Strex->getFunctionType()->getParamType(0)),
16226 Addr});
16230 bool ARMTargetLowering::alignLoopsWithOptSize() const {
16231 return Subtarget->isMClass();
16234 /// A helper function for determining the number of interleaved accesses we
16235 /// will generate when lowering accesses of the given type.
16236 unsigned
16237 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
16238 const DataLayout &DL) const {
16239 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
16242 bool ARMTargetLowering::isLegalInterleavedAccessType(
16243 VectorType *VecTy, const DataLayout &DL) const {
16245 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16246 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16248 // Ensure the vector doesn't have f16 elements. Even though we could do an
16249 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16250 // f32.
16251 if (VecTy->getElementType()->isHalfTy())
16252 return false;
16254 // Ensure the number of vector elements is greater than 1.
16255 if (VecTy->getNumElements() < 2)
16256 return false;
16258 // Ensure the element type is legal.
16259 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16260 return false;
16262 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16263 // 128 will be split into multiple interleaved accesses.
16264 return VecSize == 64 || VecSize % 128 == 0;
16267 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
16268 if (Subtarget->hasNEON())
16269 return 4;
16270 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
16273 /// Lower an interleaved load into a vldN intrinsic.
16275 /// E.g. Lower an interleaved load (Factor = 2):
16276 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16277 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16278 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16280 /// Into:
16281 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16282 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16283 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16284 bool ARMTargetLowering::lowerInterleavedLoad(
16285 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16286 ArrayRef<unsigned> Indices, unsigned Factor) const {
16287 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16288 "Invalid interleave factor");
16289 assert(!Shuffles.empty() && "Empty shufflevector input");
16290 assert(Shuffles.size() == Indices.size() &&
16291 "Unmatched number of shufflevectors and indices");
16293 VectorType *VecTy = Shuffles[0]->getType();
16294 Type *EltTy = VecTy->getVectorElementType();
16296 const DataLayout &DL = LI->getModule()->getDataLayout();
16298 // Skip if we do not have NEON and skip illegal vector types. We can
16299 // "legalize" wide vector types into multiple interleaved accesses as long as
16300 // the vector types are divisible by 128.
16301 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16302 return false;
16304 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16306 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16307 // load integer vectors first and then convert to pointer vectors.
16308 if (EltTy->isPointerTy())
16309 VecTy =
16310 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16312 IRBuilder<> Builder(LI);
16314 // The base address of the load.
16315 Value *BaseAddr = LI->getPointerOperand();
16317 if (NumLoads > 1) {
16318 // If we're going to generate more than one load, reset the sub-vector type
16319 // to something legal.
16320 VecTy = VectorType::get(VecTy->getVectorElementType(),
16321 VecTy->getVectorNumElements() / NumLoads);
16323 // We will compute the pointer operand of each load from the original base
16324 // address using GEPs. Cast the base address to a pointer to the scalar
16325 // element type.
16326 BaseAddr = Builder.CreateBitCast(
16327 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16328 LI->getPointerAddressSpace()));
16331 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16333 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16334 Type *Tys[] = {VecTy, Int8Ptr};
16335 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16336 Intrinsic::arm_neon_vld3,
16337 Intrinsic::arm_neon_vld4};
16338 Function *VldnFunc =
16339 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16341 // Holds sub-vectors extracted from the load intrinsic return values. The
16342 // sub-vectors are associated with the shufflevector instructions they will
16343 // replace.
16344 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16346 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16347 // If we're generating more than one load, compute the base address of
16348 // subsequent loads as an offset from the previous.
16349 if (LoadCount > 0)
16350 BaseAddr =
16351 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16352 VecTy->getVectorNumElements() * Factor);
16354 SmallVector<Value *, 2> Ops;
16355 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16356 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16358 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16360 // Replace uses of each shufflevector with the corresponding vector loaded
16361 // by ldN.
16362 for (unsigned i = 0; i < Shuffles.size(); i++) {
16363 ShuffleVectorInst *SV = Shuffles[i];
16364 unsigned Index = Indices[i];
16366 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16368 // Convert the integer vector to pointer vector if the element is pointer.
16369 if (EltTy->isPointerTy())
16370 SubVec = Builder.CreateIntToPtr(
16371 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16372 VecTy->getVectorNumElements()));
16374 SubVecs[SV].push_back(SubVec);
16378 // Replace uses of the shufflevector instructions with the sub-vectors
16379 // returned by the load intrinsic. If a shufflevector instruction is
16380 // associated with more than one sub-vector, those sub-vectors will be
16381 // concatenated into a single wide vector.
16382 for (ShuffleVectorInst *SVI : Shuffles) {
16383 auto &SubVec = SubVecs[SVI];
16384 auto *WideVec =
16385 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16386 SVI->replaceAllUsesWith(WideVec);
16389 return true;
16392 /// Lower an interleaved store into a vstN intrinsic.
16394 /// E.g. Lower an interleaved store (Factor = 3):
16395 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16396 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16397 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16399 /// Into:
16400 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16401 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16402 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16403 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16405 /// Note that the new shufflevectors will be removed and we'll only generate one
16406 /// vst3 instruction in CodeGen.
16408 /// Example for a more general valid mask (Factor 3). Lower:
16409 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16410 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16411 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16413 /// Into:
16414 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16415 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16416 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16417 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16418 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16419 ShuffleVectorInst *SVI,
16420 unsigned Factor) const {
16421 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16422 "Invalid interleave factor");
16424 VectorType *VecTy = SVI->getType();
16425 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16426 "Invalid interleaved store");
16428 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16429 Type *EltTy = VecTy->getVectorElementType();
16430 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16432 const DataLayout &DL = SI->getModule()->getDataLayout();
16434 // Skip if we do not have NEON and skip illegal vector types. We can
16435 // "legalize" wide vector types into multiple interleaved accesses as long as
16436 // the vector types are divisible by 128.
16437 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16438 return false;
16440 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16442 Value *Op0 = SVI->getOperand(0);
16443 Value *Op1 = SVI->getOperand(1);
16444 IRBuilder<> Builder(SI);
16446 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16447 // vectors to integer vectors.
16448 if (EltTy->isPointerTy()) {
16449 Type *IntTy = DL.getIntPtrType(EltTy);
16451 // Convert to the corresponding integer vector.
16452 Type *IntVecTy =
16453 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16454 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16455 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16457 SubVecTy = VectorType::get(IntTy, LaneLen);
16460 // The base address of the store.
16461 Value *BaseAddr = SI->getPointerOperand();
16463 if (NumStores > 1) {
16464 // If we're going to generate more than one store, reset the lane length
16465 // and sub-vector type to something legal.
16466 LaneLen /= NumStores;
16467 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16469 // We will compute the pointer operand of each store from the original base
16470 // address using GEPs. Cast the base address to a pointer to the scalar
16471 // element type.
16472 BaseAddr = Builder.CreateBitCast(
16473 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16474 SI->getPointerAddressSpace()));
16477 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16479 auto Mask = SVI->getShuffleMask();
16481 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16482 Type *Tys[] = {Int8Ptr, SubVecTy};
16483 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16484 Intrinsic::arm_neon_vst3,
16485 Intrinsic::arm_neon_vst4};
16487 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16488 // If we generating more than one store, we compute the base address of
16489 // subsequent stores as an offset from the previous.
16490 if (StoreCount > 0)
16491 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16492 BaseAddr, LaneLen * Factor);
16494 SmallVector<Value *, 6> Ops;
16495 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16497 Function *VstNFunc =
16498 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16500 // Split the shufflevector operands into sub vectors for the new vstN call.
16501 for (unsigned i = 0; i < Factor; i++) {
16502 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16503 if (Mask[IdxI] >= 0) {
16504 Ops.push_back(Builder.CreateShuffleVector(
16505 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16506 } else {
16507 unsigned StartMask = 0;
16508 for (unsigned j = 1; j < LaneLen; j++) {
16509 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16510 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16511 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16512 break;
16515 // Note: If all elements in a chunk are undefs, StartMask=0!
16516 // Note: Filling undef gaps with random elements is ok, since
16517 // those elements were being written anyway (with undefs).
16518 // In the case of all undefs we're defaulting to using elems from 0
16519 // Note: StartMask cannot be negative, it's checked in
16520 // isReInterleaveMask
16521 Ops.push_back(Builder.CreateShuffleVector(
16522 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16526 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16527 Builder.CreateCall(VstNFunc, Ops);
16529 return true;
16532 enum HABaseType {
16533 HA_UNKNOWN = 0,
16534 HA_FLOAT,
16535 HA_DOUBLE,
16536 HA_VECT64,
16537 HA_VECT128
16540 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16541 uint64_t &Members) {
16542 if (auto *ST = dyn_cast<StructType>(Ty)) {
16543 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16544 uint64_t SubMembers = 0;
16545 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16546 return false;
16547 Members += SubMembers;
16549 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16550 uint64_t SubMembers = 0;
16551 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16552 return false;
16553 Members += SubMembers * AT->getNumElements();
16554 } else if (Ty->isFloatTy()) {
16555 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16556 return false;
16557 Members = 1;
16558 Base = HA_FLOAT;
16559 } else if (Ty->isDoubleTy()) {
16560 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16561 return false;
16562 Members = 1;
16563 Base = HA_DOUBLE;
16564 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16565 Members = 1;
16566 switch (Base) {
16567 case HA_FLOAT:
16568 case HA_DOUBLE:
16569 return false;
16570 case HA_VECT64:
16571 return VT->getBitWidth() == 64;
16572 case HA_VECT128:
16573 return VT->getBitWidth() == 128;
16574 case HA_UNKNOWN:
16575 switch (VT->getBitWidth()) {
16576 case 64:
16577 Base = HA_VECT64;
16578 return true;
16579 case 128:
16580 Base = HA_VECT128;
16581 return true;
16582 default:
16583 return false;
16588 return (Members > 0 && Members <= 4);
16591 /// Return the correct alignment for the current calling convention.
16592 unsigned
16593 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16594 DataLayout DL) const {
16595 if (!ArgTy->isVectorTy())
16596 return DL.getABITypeAlignment(ArgTy);
16598 // Avoid over-aligning vector parameters. It would require realigning the
16599 // stack and waste space for no real benefit.
16600 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
16603 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
16604 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
16605 /// passing according to AAPCS rules.
16606 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
16607 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
16608 if (getEffectiveCallingConv(CallConv, isVarArg) !=
16609 CallingConv::ARM_AAPCS_VFP)
16610 return false;
16612 HABaseType Base = HA_UNKNOWN;
16613 uint64_t Members = 0;
16614 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
16615 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
16617 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
16618 return IsHA || IsIntArray;
16621 unsigned ARMTargetLowering::getExceptionPointerRegister(
16622 const Constant *PersonalityFn) const {
16623 // Platforms which do not use SjLj EH may return values in these registers
16624 // via the personality function.
16625 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
16628 unsigned ARMTargetLowering::getExceptionSelectorRegister(
16629 const Constant *PersonalityFn) const {
16630 // Platforms which do not use SjLj EH may return values in these registers
16631 // via the personality function.
16632 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
16635 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
16636 // Update IsSplitCSR in ARMFunctionInfo.
16637 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
16638 AFI->setIsSplitCSR(true);
16641 void ARMTargetLowering::insertCopiesSplitCSR(
16642 MachineBasicBlock *Entry,
16643 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
16644 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
16645 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
16646 if (!IStart)
16647 return;
16649 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
16650 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
16651 MachineBasicBlock::iterator MBBI = Entry->begin();
16652 for (const MCPhysReg *I = IStart; *I; ++I) {
16653 const TargetRegisterClass *RC = nullptr;
16654 if (ARM::GPRRegClass.contains(*I))
16655 RC = &ARM::GPRRegClass;
16656 else if (ARM::DPRRegClass.contains(*I))
16657 RC = &ARM::DPRRegClass;
16658 else
16659 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
16661 Register NewVR = MRI->createVirtualRegister(RC);
16662 // Create copy from CSR to a virtual register.
16663 // FIXME: this currently does not emit CFI pseudo-instructions, it works
16664 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
16665 // nounwind. If we want to generalize this later, we may need to emit
16666 // CFI pseudo-instructions.
16667 assert(Entry->getParent()->getFunction().hasFnAttribute(
16668 Attribute::NoUnwind) &&
16669 "Function should be nounwind in insertCopiesSplitCSR!");
16670 Entry->addLiveIn(*I);
16671 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
16672 .addReg(*I);
16674 // Insert the copy-back instructions right before the terminator.
16675 for (auto *Exit : Exits)
16676 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
16677 TII->get(TargetOpcode::COPY), *I)
16678 .addReg(NewVR);
16682 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
16683 MF.getFrameInfo().computeMaxCallFrameSize(MF);
16684 TargetLoweringBase::finalizeLowering(MF);