LLVM 24.0.0git
TargetLowering.cpp
Go to the documentation of this file.
1//===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
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 implements the TargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/STLExtras.h"
27#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/MC/MCAsmInfo.h"
32#include "llvm/MC/MCExpr.h"
38#include <cctype>
39#include <deque>
40#include <list>
41using namespace llvm;
42using namespace llvm::SDPatternMatch;
43
44/// NOTE: The TargetMachine owns TLOF.
48
49// Define the virtual destructor out-of-line for build efficiency.
51
52const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
53 return nullptr;
54}
55
59
60/// Check whether a given call node is in tail position within its function. If
61/// so, it sets Chain to the input chain of the tail call.
63 SDValue &Chain) const {
65
66 // First, check if tail calls have been disabled in this function.
67 if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
68 return false;
69
70 // Conservatively require the attributes of the call to match those of
71 // the return. Ignore following attributes because they don't affect the
72 // call sequence.
73 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
74 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
75 Attribute::DereferenceableOrNull, Attribute::NoAlias,
76 Attribute::NonNull, Attribute::NoUndef,
77 Attribute::Range, Attribute::NoFPClass})
78 CallerAttrs.removeAttribute(Attr);
79
80 if (CallerAttrs.hasAttributes())
81 return false;
82
83 // It's not safe to eliminate the sign / zero extension of the return value.
84 if (CallerAttrs.contains(Attribute::ZExt) ||
85 CallerAttrs.contains(Attribute::SExt))
86 return false;
87
88 // Check if the only use is a function return node.
89 return isUsedByReturnOnly(Node, Chain);
90}
91
93 const uint32_t *CallerPreservedMask,
94 const SmallVectorImpl<CCValAssign> &ArgLocs,
95 const SmallVectorImpl<SDValue> &OutVals) const {
96 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
97 const CCValAssign &ArgLoc = ArgLocs[I];
98 if (!ArgLoc.isRegLoc())
99 continue;
100 MCRegister Reg = ArgLoc.getLocReg();
101 // Only look at callee saved registers.
102 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
103 continue;
104 // Check that we pass the value used for the caller.
105 // (We look for a CopyFromReg reading a virtual register that is used
106 // for the function live-in value of register Reg)
107 SDValue Value = OutVals[I];
108 if (Value->getOpcode() == ISD::AssertZext)
109 Value = Value.getOperand(0);
110 if (Value->getOpcode() != ISD::CopyFromReg)
111 return false;
112 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
113 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
114 return false;
115 }
116 return true;
117}
118
119static bool paramHasAttr(const CallBase &Call, unsigned ArgIdx,
120 Attribute::AttrKind Kind) {
121 return Call.paramHasAttr(ArgIdx, Kind);
122}
123
124static bool paramHasAttr(const AttributeList &Attrs, unsigned ArgIdx,
125 Attribute::AttrKind Kind) {
126 return Attrs.hasParamAttr(ArgIdx, Kind);
127}
128
129static MaybeAlign getParamStackAlign(const CallBase &Call, unsigned ArgIdx) {
130 return Call.getParamStackAlign(ArgIdx);
131}
132
134 unsigned ArgIdx) {
135 return Attrs.getParamStackAlignment(ArgIdx);
136}
137
138static MaybeAlign getParamAlign(const CallBase &Call, unsigned ArgIdx) {
139 return Call.getParamAlign(ArgIdx);
140}
141
142static MaybeAlign getParamAlign(const AttributeList &Attrs, unsigned ArgIdx) {
143 return Attrs.getParamAlignment(ArgIdx);
144}
145
146/// Set CallLoweringInfo attribute flags based on a call instruction
147/// and called function attributes.
148template <typename SourceT>
150 const SourceT &Src, unsigned ArgIdx) {
151 Entry.IsSExt = paramHasAttr(Src, ArgIdx, Attribute::SExt);
152 Entry.IsZExt = paramHasAttr(Src, ArgIdx, Attribute::ZExt);
153 Entry.IsNoExt = paramHasAttr(Src, ArgIdx, Attribute::NoExt);
154 Entry.IsInReg = paramHasAttr(Src, ArgIdx, Attribute::InReg);
155 Entry.IsSRet = paramHasAttr(Src, ArgIdx, Attribute::StructRet);
156 Entry.IsNest = paramHasAttr(Src, ArgIdx, Attribute::Nest);
157 Entry.IsByVal = paramHasAttr(Src, ArgIdx, Attribute::ByVal);
158 Entry.IsPreallocated = paramHasAttr(Src, ArgIdx, Attribute::Preallocated);
159 Entry.IsInAlloca = paramHasAttr(Src, ArgIdx, Attribute::InAlloca);
160 Entry.IsReturned = paramHasAttr(Src, ArgIdx, Attribute::Returned);
161 Entry.IsSwiftSelf = paramHasAttr(Src, ArgIdx, Attribute::SwiftSelf);
162 Entry.IsSwiftAsync = paramHasAttr(Src, ArgIdx, Attribute::SwiftAsync);
163 Entry.IsSwiftError = paramHasAttr(Src, ArgIdx, Attribute::SwiftError);
164 Entry.Alignment = getParamStackAlign(Src, ArgIdx);
165 Entry.IndirectType = nullptr;
166 assert(Entry.IsByVal + Entry.IsPreallocated + Entry.IsInAlloca +
167 Entry.IsSRet <=
168 1 &&
169 "multiple ABI attributes?");
170 if (Entry.IsByVal) {
171 Entry.IndirectType = Src.getParamByValType(ArgIdx);
172 if (!Entry.Alignment)
173 Entry.Alignment = getParamAlign(Src, ArgIdx);
174 }
175 if (Entry.IsPreallocated)
176 Entry.IndirectType = Src.getParamPreallocatedType(ArgIdx);
177 if (Entry.IsInAlloca)
178 Entry.IndirectType = Src.getParamInAllocaType(ArgIdx);
179 if (Entry.IsSRet)
180 Entry.IndirectType = Src.getParamStructRetType(ArgIdx);
181}
182
184 unsigned ArgIdx) {
185 setArgListEntryAttributes(*this, *Call, ArgIdx);
186}
187
189 unsigned ArgIdx) {
190 setArgListEntryAttributes(*this, Attrs, ArgIdx);
191}
192
194 Attribute::AttrKind Attr) {
195 if (Attr != Attribute::None) {
196 if (Attr == Attribute::SExt)
197 IsSExt = true;
198 else if (Attr == Attribute::ZExt)
199 IsZExt = true;
200 else if (Attr == Attribute::NoExt)
201 IsNoExt = true;
202 else
203 llvm_unreachable("Unexpected extension attribute!");
204 }
205}
206
209 const AttributeList &FuncAttrs,
211 // TODO: This assumes each parameter maps to exactly one operand node, which
212 // does not hold when an argument requires type splitting.
213 assert(Ops.size() == FuncTy->getNumParams() &&
214 "argument count does not match the function type");
215 ArgListTy Args;
216 Args.reserve(Ops.size());
217 for (unsigned I = 0, E = FuncTy->getNumParams(); I != E; ++I) {
218 ArgListEntry Entry(Ops[I], FuncTy->getParamType(I));
219 Entry.setAttributes(FuncAttrs, I);
220 Args.push_back(Entry);
221 }
222 return Args;
223}
224
225std::pair<SDValue, SDValue> TargetLowering::makeLibCall(
226 SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, ArrayRef<SDValue> Ops,
227 MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain) const {
228 return makeLibCall(DAG, DAG.getLibcalls().getLibcallImpl(LC), RetVT, Ops,
229 CallOptions, dl, Chain);
230}
231
232/// Generate a libcall taking the given operands as arguments and returning a
233/// result of type RetVT.
234std::pair<SDValue, SDValue>
235TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl,
237 MakeLibCallOptions CallOptions, const SDLoc &dl,
238 SDValue InChain) const {
239 if (LibcallImpl == RTLIB::Unsupported)
240 reportFatalInternalError("unsupported library call operation");
241
242 if (!InChain)
243 InChain = DAG.getEntryNode();
244
246 Args.reserve(Ops.size());
247
248 ArrayRef<Type *> OpsTypeOverrides = CallOptions.OpsTypeOverrides;
249 for (unsigned i = 0; i < Ops.size(); ++i) {
250 SDValue NewOp = Ops[i];
251 Type *Ty = i < OpsTypeOverrides.size() && OpsTypeOverrides[i]
252 ? OpsTypeOverrides[i]
253 : NewOp.getValueType().getTypeForEVT(*DAG.getContext());
254 TargetLowering::ArgListEntry Entry(NewOp, Ty);
255 if (CallOptions.IsSoften)
256 Entry.OrigTy =
257 CallOptions.OpsVTBeforeSoften[i].getTypeForEVT(*DAG.getContext());
258
259 Entry.IsSExt =
260 shouldSignExtendTypeInLibCall(Entry.Ty, CallOptions.IsSigned);
261 Entry.IsZExt = !Entry.IsSExt;
262
263 if (CallOptions.IsSoften &&
265 Entry.IsSExt = Entry.IsZExt = false;
266 }
267 Args.push_back(Entry);
268 }
269
270 SDValue Callee =
271 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
272
273 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
274 Type *OrigRetTy = RetTy;
276 bool signExtend = shouldSignExtendTypeInLibCall(RetTy, CallOptions.IsSigned);
277 bool zeroExtend = !signExtend;
278
279 if (CallOptions.IsSoften) {
280 OrigRetTy = CallOptions.RetVTBeforeSoften.getTypeForEVT(*DAG.getContext());
282 signExtend = zeroExtend = false;
283 }
284
285 CLI.setDebugLoc(dl)
286 .setChain(InChain)
288 RetTy, OrigRetTy, Callee, std::move(Args))
289 .setNoReturn(CallOptions.DoesNotReturn)
292 .setSExtResult(signExtend)
293 .setZExtResult(zeroExtend);
294 return LowerCallTo(CLI);
295}
296
298 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
299 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
300 const AttributeList &FuncAttributes, EVT *LargestVT) const {
301 EVT VT = getOptimalMemOpType(Context, Op, FuncAttributes);
302
303 if (VT == MVT::Other) {
304 // Use the largest integer type whose alignment constraints are satisfied.
305 VT = MVT::LAST_INTEGER_VALUETYPE;
306 if (Op.isFixedDstAlign()) {
307 bool LoadsFromSrc = Op.isMemcpyOrMemmove() && !Op.isMemcpyStrSrc();
308 while (VT != MVT::i8) {
309 unsigned VTSize = VT.getSizeInBits() / 8;
310 bool DstOk =
311 Op.getDstAlign() >= VTSize ||
312 allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign());
313 bool SrcOk =
314 !LoadsFromSrc || Op.getSrcAlign() >= VTSize ||
315 allowsMisalignedMemoryAccesses(VT, SrcAS, Op.getSrcAlign());
316 if (DstOk && SrcOk)
317 break;
319 }
320 }
321 assert(VT.isInteger());
322
323 // Find the largest legal integer type.
324 MVT LVT = MVT::LAST_INTEGER_VALUETYPE;
325 while (!isTypeLegal(LVT))
326 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
327 assert(LVT.isInteger());
328
329 // If the type we've chosen is larger than the largest legal integer type
330 // then use the largest legal type.
331 if (VT.bitsGT(LVT))
332 VT = LVT;
333 }
334
335 unsigned NumMemOps = 0;
336 uint64_t Size = Op.size();
337 while (Size) {
338 unsigned VTSize = VT.getSizeInBits() / 8;
339 while (VTSize > Size) {
340 // For now, only use non-vector load / store's for the left-over pieces.
341 EVT NewVT = VT;
342 unsigned NewVTSize;
343
344 bool Found = false;
345 if (VT.isVector() || VT.isFloatingPoint()) {
346 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
349 Found = true;
350 else if (NewVT == MVT::i64 &&
352 isSafeMemOpType(MVT::f64)) {
353 // i64 is usually not legal on 32-bit targets, but f64 may be.
354 NewVT = MVT::f64;
355 Found = true;
356 }
357 }
358
359 if (!Found) {
360 do {
361 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
362 if (NewVT == MVT::i8)
363 break;
364 } while (!isSafeMemOpType(NewVT.getSimpleVT()));
365 }
366 NewVTSize = NewVT.getSizeInBits() / 8;
367
368 // If the new VT cannot cover all of the remaining bits, then consider
369 // issuing a (or a pair of) unaligned and overlapping load / store.
370 unsigned Fast;
371 if (NumMemOps && !Op.isVolatile() && NewVTSize < Size &&
373 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
375 Fast)
376 VTSize = Size;
377 else {
378 VT = NewVT;
379 VTSize = NewVTSize;
380 }
381 }
382
383 if (++NumMemOps > Limit)
384 return false;
385
386 MemOps.push_back(VT);
387 Size -= VTSize;
388 }
389
390 return true;
391}
392
393/// Soften the operands of a comparison. This code is shared among BR_CC,
394/// SELECT_CC, and SETCC handlers.
396 SDValue &NewLHS, SDValue &NewRHS,
397 ISD::CondCode &CCCode,
398 const SDLoc &dl, const SDValue OldLHS,
399 const SDValue OldRHS) const {
400 SDValue Chain;
401 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
402 OldRHS, Chain);
403}
404
405/// Select the libcall and the condition code to test its result against 0 for
406/// an ordered floating-point compare. \p BoolLC is the boolean helper (result
407/// is 0/1). \p TriStateLC is the per-predicate three-way helper and \p
408/// GenericLC the generic single-symbol three-way helper (both return -1/0/1,
409/// tested against 0 with \p TriStateCC). The boolean form is preferred, then
410/// the per-predicate three-way, then the generic three-way.
411static std::pair<RTLIB::Libcall, ISD::CondCode>
412selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC,
413 RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC,
414 ISD::CondCode TriStateCC) {
415 if (Libcalls.getLibcallImpl(BoolLC) != RTLIB::Unsupported)
416 return {BoolLC, ISD::SETNE};
417 if (Libcalls.getLibcallImpl(TriStateLC) != RTLIB::Unsupported)
418 return {TriStateLC, TriStateCC};
419 return {GenericLC, TriStateCC};
420}
421
423 SDValue &NewLHS, SDValue &NewRHS,
424 ISD::CondCode &CCCode,
425 const SDLoc &dl, const SDValue OldLHS,
426 const SDValue OldRHS,
427 SDValue &Chain,
428 bool IsSignaling) const {
429 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
430 // not supporting it. We can update this code when libgcc provides such
431 // functions.
432
433 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
434 && "Unsupported setcc type!");
435
436 // Expand into one or more soft-fp libcall(s).
437 ISD::CondCode OrigCCCode = CCCode;
438 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
440 bool ShouldInvertCC = false;
441
442 // Expand a compare libcall family name (e.g. OEQ, FCMP3_PRED_OEQ) to the
443 // RTLIB::Libcall for VT.
444#define FP_CMP_LIBCALL(BASE) \
445 RTLIB::getFPLibCall(VT, RTLIB::BASE##_F32, RTLIB::BASE##_F64, \
446 RTLIB::UNKNOWN_LIBCALL, RTLIB::BASE##_F128, \
447 RTLIB::BASE##_PPCF128)
448
449 switch (CCCode) {
450 case ISD::SETEQ:
451 case ISD::SETOEQ:
452 std::tie(LC1, CC1) = selectFPCmpLibcall(
453 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
454 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
455 break;
456 case ISD::SETNE:
457 case ISD::SETUNE:
458 std::tie(LC1, CC1) = selectFPCmpLibcall(
459 DAG.getLibcalls(), FP_CMP_LIBCALL(UNE), FP_CMP_LIBCALL(FCMP3_PRED_UNE),
460 FP_CMP_LIBCALL(FCMP3), ISD::SETNE);
461 // Some ABIs (e.g. AEABI) provide neither a not-equal nor a three-way
462 // compare; obtain not-equal (UNE = !OEQ) by inverting ordered-equal.
463 if (DAG.getLibcalls().getLibcallImpl(LC1) == RTLIB::Unsupported) {
464 std::tie(LC1, CC1) = selectFPCmpLibcall(
465 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ),
466 FP_CMP_LIBCALL(FCMP3_PRED_OEQ), FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
467 ShouldInvertCC = true;
468 }
469 break;
470 case ISD::SETGE:
471 case ISD::SETOGE:
472 std::tie(LC1, CC1) = selectFPCmpLibcall(
473 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE), FP_CMP_LIBCALL(FCMP3_PRED_OGE),
474 FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
475 break;
476 case ISD::SETLT:
477 case ISD::SETOLT:
478 std::tie(LC1, CC1) = selectFPCmpLibcall(
479 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT), FP_CMP_LIBCALL(FCMP3_PRED_OLT),
480 FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
481 break;
482 case ISD::SETLE:
483 case ISD::SETOLE:
484 std::tie(LC1, CC1) = selectFPCmpLibcall(
485 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE), FP_CMP_LIBCALL(FCMP3_PRED_OLE),
486 FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
487 break;
488 case ISD::SETGT:
489 case ISD::SETOGT:
490 std::tie(LC1, CC1) = selectFPCmpLibcall(
491 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT), FP_CMP_LIBCALL(FCMP3_PRED_OGT),
492 FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
493 break;
494 case ISD::SETO:
495 ShouldInvertCC = true;
496 [[fallthrough]];
497 case ISD::SETUO:
498 // Unordered is a boolean everywhere (__unordXf2 returns 0/1).
499 LC1 = FP_CMP_LIBCALL(UO);
500 CC1 = ISD::SETNE;
501 break;
502 case ISD::SETONE:
503 // SETONE = O && UNE
504 ShouldInvertCC = true;
505 [[fallthrough]];
506 case ISD::SETUEQ:
507 LC1 = FP_CMP_LIBCALL(UO);
508 CC1 = ISD::SETNE;
509 std::tie(LC2, CC2) = selectFPCmpLibcall(
510 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
511 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
512 break;
513 default:
514 // Invert CC for unordered comparisons, handled by the ordered inverse.
515 ShouldInvertCC = true;
516 switch (CCCode) {
517 case ISD::SETULT:
518 std::tie(LC1, CC1) = selectFPCmpLibcall(
519 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE),
520 FP_CMP_LIBCALL(FCMP3_PRED_OGE), FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
521 break;
522 case ISD::SETULE:
523 std::tie(LC1, CC1) = selectFPCmpLibcall(
524 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT),
525 FP_CMP_LIBCALL(FCMP3_PRED_OGT), FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
526 break;
527 case ISD::SETUGT:
528 std::tie(LC1, CC1) = selectFPCmpLibcall(
529 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE),
530 FP_CMP_LIBCALL(FCMP3_PRED_OLE), FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
531 break;
532 case ISD::SETUGE:
533 std::tie(LC1, CC1) = selectFPCmpLibcall(
534 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT),
535 FP_CMP_LIBCALL(FCMP3_PRED_OLT), FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
536 break;
537 default:
538 llvm_unreachable("Do not know how to soften this setcc!");
539 }
540 }
541
542#undef FP_CMP_LIBCALL
543
544 // Use the target specific return value for comparison lib calls.
546 SDValue Ops[2] = {NewLHS, NewRHS};
548 EVT OpsVT[2] = { OldLHS.getValueType(),
549 OldRHS.getValueType() };
550 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT);
551
552 auto ReportNoLibcall = [&]() {
553 DAG.getContext()->emitError(
554 Twine("no libcall available to soften floating-point ") +
555 ISD::getCondCodeName(OrigCCCode) + " compare with type " +
556 VT.getEVTString());
557 NewLHS = DAG.getPOISON(RetVT);
558 NewRHS = DAG.getConstant(0, dl, RetVT);
559 CCCode = ISD::SETNE;
560 };
561
562 // Check availability before makeLibCall, which fatally errors otherwise.
563 RTLIB::LibcallImpl LC1Impl = DAG.getLibcalls().getLibcallImpl(LC1);
564 if (LC1Impl == RTLIB::Unsupported) {
565 ReportNoLibcall();
566 return;
567 }
568
569 auto Call = makeLibCall(DAG, LC1Impl, RetVT, Ops, CallOptions, dl, Chain);
570 NewLHS = Call.first;
571 NewRHS = DAG.getConstant(0, dl, RetVT);
572
573 CCCode = CC1;
574 if (ShouldInvertCC) {
575 assert(RetVT.isInteger());
576 CCCode = getSetCCInverse(CCCode, RetVT);
577 }
578
579 if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
580 // Update Chain.
581 Chain = Call.second;
582 } else {
583 RTLIB::LibcallImpl LC2Impl = DAG.getLibcalls().getLibcallImpl(LC2);
584 if (LC2Impl == RTLIB::Unsupported) {
585 ReportNoLibcall();
586 return;
587 }
588
589 assert(CCCode == (ShouldInvertCC ? ISD::SETEQ : ISD::SETNE) &&
590 "unordered call should be simple boolean");
591
592 EVT SetCCVT =
593 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
595 NewLHS = DAG.getNode(ISD::AssertZext, dl, RetVT, Call.first,
596 DAG.getValueType(MVT::i1));
597 }
598
599 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
600 auto Call2 = makeLibCall(DAG, LC2Impl, RetVT, Ops, CallOptions, dl, Chain);
601 CCCode = CC2;
602 if (ShouldInvertCC)
603 CCCode = getSetCCInverse(CCCode, RetVT);
604 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
605 if (Chain)
606 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
607 Call2.second);
608 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
609 Tmp.getValueType(), Tmp, NewLHS);
610 NewRHS = SDValue();
611 }
612}
613
614/// Return the entry encoding for a jump table in the current function. The
615/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
617 // In non-pic modes, just use the address of a block.
620
621 // Otherwise, use a label difference.
623}
624
629
630/// This returns the relocation base for the given PIC jumptable, the same as
631/// getPICJumpTableRelocBase, but as an MCExpr.
632const MCExpr *
634 unsigned JTI,MCContext &Ctx) const{
635 // The normal PIC reloc base is the label at the start of the jump table.
636 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
637}
638
640 SDValue Addr, int JTI,
641 SelectionDAG &DAG) const {
642 SDValue Chain = Value;
643 // Jump table debug info is only needed if CodeView is enabled.
645 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl);
646 }
647 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr);
648}
649
650bool
652 const TargetMachine &TM = getTargetMachine();
653 const GlobalValue *GV = GA->getGlobal();
654
655 // If the address is not even local to this DSO we will have to load it from
656 // a got and then add the offset.
657 if (!TM.shouldAssumeDSOLocal(GV))
658 return false;
659
660 // If the code is position independent we will have to add a base register.
662 return false;
663
664 // Otherwise we can do it.
665 return true;
666}
667
668//===----------------------------------------------------------------------===//
669// Optimization Methods
670//===----------------------------------------------------------------------===//
671
672/// If the specified instruction has a constant integer operand and there are
673/// bits set in that constant that are not demanded, then clear those bits and
674/// return true.
676 const APInt &DemandedBits,
677 const APInt &DemandedElts,
678 TargetLoweringOpt &TLO) const {
679 SDLoc DL(Op);
680 unsigned Opcode = Op.getOpcode();
681
682 // Early-out if we've ended up calling an undemanded node, leave this to
683 // constant folding.
684 if (DemandedBits.isZero() || DemandedElts.isZero())
685 return false;
686
687 // Do target-specific constant optimization.
688 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
689 return TLO.New.getNode();
690
691 // FIXME: ISD::SELECT, ISD::SELECT_CC
692 switch (Opcode) {
693 default:
694 break;
695 case ISD::XOR:
696 case ISD::AND:
697 case ISD::OR: {
698 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
699 if (!Op1C || Op1C->isOpaque())
700 return false;
701
702 // If this is a 'not' op, don't touch it because that's a canonical form.
703 const APInt &C = Op1C->getAPIntValue();
704 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
705 return false;
706
707 if (!C.isSubsetOf(DemandedBits)) {
708 EVT VT = Op.getValueType();
709 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
710 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC,
711 Op->getFlags());
712 return TLO.CombineTo(Op, NewOp);
713 }
714
715 break;
716 }
717 }
718
719 return false;
720}
721
723 const APInt &DemandedBits,
724 TargetLoweringOpt &TLO) const {
725 EVT VT = Op.getValueType();
726 APInt DemandedElts = VT.isVector()
728 : APInt(1, 1);
729 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
730}
731
732/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
733/// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
734/// but it could be generalized for targets with other types of implicit
735/// widening casts.
737 const APInt &DemandedBits,
738 TargetLoweringOpt &TLO) const {
739 assert(Op.getNumOperands() == 2 &&
740 "ShrinkDemandedOp only supports binary operators!");
741 assert(Op.getNode()->getNumValues() == 1 &&
742 "ShrinkDemandedOp only supports nodes with one result!");
743
744 EVT VT = Op.getValueType();
745 SelectionDAG &DAG = TLO.DAG;
746 SDLoc dl(Op);
747
748 // Early return, as this function cannot handle vector types.
749 if (VT.isVector())
750 return false;
751
752 assert(Op.getOperand(0).getValueType().getScalarSizeInBits() == BitWidth &&
753 Op.getOperand(1).getValueType().getScalarSizeInBits() == BitWidth &&
754 "ShrinkDemandedOp only supports operands that have the same size!");
755
756 // Don't do this if the node has another user, which may require the
757 // full value.
758 if (!Op.getNode()->hasOneUse())
759 return false;
760
761 // Search for the smallest integer type with free casts to and from
762 // Op's type. For expedience, just check power-of-2 integer types.
763 unsigned DemandedSize = DemandedBits.getActiveBits();
764 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
765 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
766 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
767 if (isTruncateFree(Op, SmallVT) && isZExtFree(SmallVT, VT)) {
768 // We found a type with free casts.
769
770 // If the operation has the 'disjoint' flag, then the
771 // operands on the new node are also disjoint.
772 SDNodeFlags Flags(Op->getFlags().hasDisjoint() ? SDNodeFlags::Disjoint
774 unsigned Opcode = Op.getOpcode();
775 if (Opcode == ISD::PTRADD) {
776 // It isn't a ptradd anymore if it doesn't operate on the entire
777 // pointer.
778 Opcode = ISD::ADD;
779 }
780 SDValue X = DAG.getNode(
781 Opcode, dl, SmallVT,
782 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
783 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)), Flags);
784 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
785 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X);
786 return TLO.CombineTo(Op, Z);
787 }
788 }
789 return false;
790}
791
793 DAGCombinerInfo &DCI) const {
794 SelectionDAG &DAG = DCI.DAG;
795 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
796 !DCI.isBeforeLegalizeOps());
798
799 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
800 if (Simplified) {
801 DCI.AddToWorklist(Op.getNode());
803 }
804 return Simplified;
805}
806
808 const APInt &DemandedElts,
809 DAGCombinerInfo &DCI) const {
810 SelectionDAG &DAG = DCI.DAG;
811 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
812 !DCI.isBeforeLegalizeOps());
814
815 bool Simplified =
816 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
817 if (Simplified) {
818 DCI.AddToWorklist(Op.getNode());
820 }
821 return Simplified;
822}
823
827 unsigned Depth,
828 bool AssumeSingleUse) const {
829 EVT VT = Op.getValueType();
830
831 // Since the number of lanes in a scalable vector is unknown at compile time,
832 // we track one bit which is implicitly broadcast to all lanes. This means
833 // that all lanes in a scalable vector are considered demanded.
834 APInt DemandedElts = VT.isFixedLengthVector()
836 : APInt(1, 1);
837 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
838 AssumeSingleUse);
839}
840
841// TODO: Under what circumstances can we create nodes? Constant folding?
843 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
844 SelectionDAG &DAG, unsigned Depth) const {
845 EVT VT = Op.getValueType();
846
847 // Limit search depth.
849 return SDValue();
850
851 // Ignore UNDEFs.
852 if (Op.isUndef())
853 return SDValue();
854
855 // Not demanding any bits/elts from Op.
856 if (DemandedBits == 0 || DemandedElts == 0)
857 return DAG.getUNDEF(VT);
858
859 bool IsLE = DAG.getDataLayout().isLittleEndian();
860 unsigned NumElts = DemandedElts.getBitWidth();
861 unsigned BitWidth = DemandedBits.getBitWidth();
862 KnownBits LHSKnown, RHSKnown;
863 switch (Op.getOpcode()) {
864 case ISD::Constant: {
865 const APInt &Value = Op->getAsAPIntVal();
866 if (!Value.isZero() && (Value & DemandedBits).isZero())
867 return DAG.getConstant(0, SDLoc(Op), VT);
868 break;
869 }
870 case ISD::BITCAST: {
871 if (VT.isScalableVector())
872 return SDValue();
873
874 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
875 EVT SrcVT = Src.getValueType();
876 EVT DstVT = Op.getValueType();
877 if (SrcVT == DstVT)
878 return Src;
879
880 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
881 unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
882 if (NumSrcEltBits == NumDstEltBits)
884 Src, DemandedBits, DemandedElts, DAG, Depth + 1))
885 return DAG.getBitcast(DstVT, V);
886
887 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
888 unsigned Scale = NumDstEltBits / NumSrcEltBits;
889 unsigned NumSrcElts = SrcVT.getVectorNumElements();
890 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
891 for (unsigned i = 0; i != Scale; ++i) {
892 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
893 unsigned BitOffset = EltOffset * NumSrcEltBits;
894 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
895 }
896 // Recursive calls below may turn not demanded elements into poison, so we
897 // need to demand all smaller source elements that maps to a demanded
898 // destination element.
899 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
900
902 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
903 return DAG.getBitcast(DstVT, V);
904 }
905
906 // TODO - bigendian once we have test coverage.
907 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
908 unsigned Scale = NumSrcEltBits / NumDstEltBits;
909 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
910 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
911 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
912 for (unsigned i = 0; i != NumElts; ++i)
913 if (DemandedElts[i]) {
914 unsigned Offset = (i % Scale) * NumDstEltBits;
915 DemandedSrcBits.insertBits(DemandedBits, Offset);
916 DemandedSrcElts.setBit(i / Scale);
917 }
918
920 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
921 return DAG.getBitcast(DstVT, V);
922 }
923
924 break;
925 }
927 if (!VT.isScalableVector() && !DemandedElts[0])
928 return DAG.getPOISON(VT);
929 break;
930 }
931 case ISD::AND: {
932 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
933 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
934
935 // If all of the demanded bits are known 1 on one side, return the other.
936 // These bits cannot contribute to the result of the 'and' in this
937 // context.
938 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
939 return Op.getOperand(0);
940 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
941 return Op.getOperand(1);
942 break;
943 }
944 case ISD::OR: {
945 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
946 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
947
948 // If all of the demanded bits are known zero on one side, return the
949 // other. These bits cannot contribute to the result of the 'or' in this
950 // context.
951 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
952 return Op.getOperand(0);
953 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
954 return Op.getOperand(1);
955 break;
956 }
957 case ISD::XOR: {
958 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
959 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
960
961 // If all of the demanded bits are known zero on one side, return the
962 // other.
963 if (DemandedBits.isSubsetOf(RHSKnown.Zero))
964 return Op.getOperand(0);
965 if (DemandedBits.isSubsetOf(LHSKnown.Zero))
966 return Op.getOperand(1);
967 break;
968 }
969 case ISD::ADD:
970 case ISD::MUL:
971 case ISD::SMIN:
972 case ISD::SMAX:
973 case ISD::UMIN:
974 case ISD::UMAX: {
975 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(1),
976 DemandedElts, 1, Depth + 1))
977 return Op.getOperand(0);
978
979 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(0),
980 DemandedElts, 0, Depth + 1))
981 return Op.getOperand(1);
982 break;
983 }
984 case ISD::SHL: {
985 // If we are only demanding sign bits then we can use the shift source
986 // directly.
987 if (std::optional<unsigned> MaxSA =
988 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
989 SDValue Op0 = Op.getOperand(0);
990 unsigned ShAmt = *MaxSA;
991 unsigned NumSignBits =
992 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
993 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
994 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
995 return Op0;
996 }
997 break;
998 }
999 case ISD::SRL: {
1000 // If we are only demanding sign bits then we can use the shift source
1001 // directly.
1002 if (std::optional<unsigned> MaxSA =
1003 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
1004 SDValue Op0 = Op.getOperand(0);
1005 unsigned ShAmt = *MaxSA;
1006 // Must already be signbits in DemandedBits bounds, and can't demand any
1007 // shifted in zeroes.
1008 if (DemandedBits.countl_zero() >= ShAmt) {
1009 unsigned NumSignBits =
1010 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1011 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
1012 return Op0;
1013 }
1014 }
1015 break;
1016 }
1017 case ISD::SETCC: {
1018 SDValue Op0 = Op.getOperand(0);
1019 SDValue Op1 = Op.getOperand(1);
1020 ISD::CondCode CC = Op.getOperandCondCode(2);
1021 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1022 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1023 // -1, we may be able to bypass the setcc.
1024 if (DemandedBits.isSignMask() &&
1028 // If we're testing X < 0, then this compare isn't needed - just use X!
1029 // FIXME: We're limiting to integer types here, but this should also work
1030 // if we don't care about FP signed-zero. The use of SETLT with FP means
1031 // that we don't care about NaNs.
1032 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1034 return Op0;
1035 }
1036 break;
1037 }
1039 // If none of the extended bits are demanded, eliminate the sextinreg.
1040 SDValue Op0 = Op.getOperand(0);
1041 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1042 unsigned ExBits = ExVT.getScalarSizeInBits();
1043 if (DemandedBits.getActiveBits() <= ExBits &&
1045 return Op0;
1046 // If the input is already sign extended, just drop the extension.
1047 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1048 if (NumSignBits >= (BitWidth - ExBits + 1))
1049 return Op0;
1050 break;
1051 }
1055 if (VT.isScalableVector())
1056 return SDValue();
1057
1058 // If we only want the lowest element and none of extended bits, then we can
1059 // return the bitcasted source vector.
1060 SDValue Src = Op.getOperand(0);
1061 EVT SrcVT = Src.getValueType();
1062 EVT DstVT = Op.getValueType();
1063 if (IsLE && DemandedElts == 1 &&
1064 DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
1065 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
1066 return DAG.getBitcast(DstVT, Src);
1067 }
1068 break;
1069 }
1071 if (VT.isScalableVector())
1072 return SDValue();
1073
1074 // If we don't demand the inserted element, return the base vector.
1075 SDValue Vec = Op.getOperand(0);
1076 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1077 EVT VecVT = Vec.getValueType();
1078 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
1079 !DemandedElts[CIdx->getZExtValue()])
1080 return Vec;
1081 break;
1082 }
1083 case ISD::INSERT_SUBVECTOR: {
1084 if (VT.isScalableVector())
1085 return SDValue();
1086
1087 SDValue Vec = Op.getOperand(0);
1088 SDValue Sub = Op.getOperand(1);
1089 uint64_t Idx = Op.getConstantOperandVal(2);
1090 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1091 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1092 // If we don't demand the inserted subvector, return the base vector.
1093 if (DemandedSubElts == 0)
1094 return Vec;
1095 break;
1096 }
1097 case ISD::VECTOR_SHUFFLE: {
1098 assert(!VT.isScalableVector());
1099 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1100
1101 // If all the demanded elts are from one operand and are inline,
1102 // then we can use the operand directly.
1103 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
1104 for (unsigned i = 0; i != NumElts; ++i) {
1105 int M = ShuffleMask[i];
1106 if (M < 0 || !DemandedElts[i])
1107 continue;
1108 AllUndef = false;
1109 IdentityLHS &= (M == (int)i);
1110 IdentityRHS &= ((M - NumElts) == i);
1111 }
1112
1113 if (AllUndef)
1114 return DAG.getUNDEF(Op.getValueType());
1115 if (IdentityLHS)
1116 return Op.getOperand(0);
1117 if (IdentityRHS)
1118 return Op.getOperand(1);
1119 break;
1120 }
1121 default:
1122 // TODO: Probably okay to remove after audit; here to reduce change size
1123 // in initial enablement patch for scalable vectors
1124 if (VT.isScalableVector())
1125 return SDValue();
1126
1127 if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
1129 Op, DemandedBits, DemandedElts, DAG, Depth))
1130 return V;
1131 break;
1132 }
1133 return SDValue();
1134}
1135
1138 unsigned Depth) const {
1139 EVT VT = Op.getValueType();
1140 // Since the number of lanes in a scalable vector is unknown at compile time,
1141 // we track one bit which is implicitly broadcast to all lanes. This means
1142 // that all lanes in a scalable vector are considered demanded.
1143 APInt DemandedElts = VT.isFixedLengthVector()
1145 : APInt(1, 1);
1146 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1147 Depth);
1148}
1149
1151 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
1152 unsigned Depth) const {
1153 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
1154 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1155 Depth);
1156}
1157
1158// Find the smallest power-2 type that is at least 8 bits and can hold a value
1159// of type VT that has KnownBits known sign/zero bits. Returns std::nullopt if
1160// that is wider than VT.
1161static std::optional<EVT> getNarrowAVGType(EVT VT, unsigned KnownBits,
1162 LLVMContext &Ctx) {
1163 unsigned MinWidth =
1164 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1165 EVT NVT = EVT::getIntegerVT(Ctx, llvm::bit_ceil(MinWidth));
1167 return std::nullopt;
1168 if (VT.isVector())
1169 NVT = EVT::getVectorVT(Ctx, NVT, VT.getVectorElementCount());
1170 return NVT;
1171}
1172
1173// Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
1174// or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
1177 const TargetLowering &TLI,
1178 const APInt &DemandedBits,
1179 const APInt &DemandedElts, unsigned Depth) {
1180 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1181 "SRL or SRA node is required here!");
1182 // Is the right shift using an immediate value of 1?
1183 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1184 if (!N1C || !N1C->isOne())
1185 return SDValue();
1186
1187 // We are looking for an avgfloor
1188 // add(ext, ext)
1189 // or one of these as a avgceil
1190 // add(add(ext, ext), 1)
1191 // add(add(ext, 1), ext)
1192 // add(ext, add(ext, 1))
1193 SDValue Add = Op.getOperand(0);
1194 if (Add.getOpcode() != ISD::ADD)
1195 return SDValue();
1196
1197 SDValue ExtOpA = Add.getOperand(0);
1198 SDValue ExtOpB = Add.getOperand(1);
1199 SDValue Add2;
1200 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) {
1201 ConstantSDNode *ConstOp;
1202 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
1203 ConstOp->isOne()) {
1204 ExtOpA = Op1;
1205 ExtOpB = Op3;
1206 Add2 = A;
1207 return true;
1208 }
1209 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
1210 ConstOp->isOne()) {
1211 ExtOpA = Op1;
1212 ExtOpB = Op2;
1213 Add2 = A;
1214 return true;
1215 }
1216 return false;
1217 };
1218 bool IsCeil =
1219 (ExtOpA.getOpcode() == ISD::ADD &&
1220 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) ||
1221 (ExtOpB.getOpcode() == ISD::ADD &&
1222 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB));
1223
1224 // If the shift is signed (sra):
1225 // - Needs >= 2 sign bit for both operands.
1226 // - Needs >= 2 zero bits.
1227 // If the shift is unsigned (srl):
1228 // - Needs >= 1 zero bit for both operands.
1229 // - Needs 1 demanded bit zero and >= 2 sign bits.
1230 SelectionDAG &DAG = TLO.DAG;
1231 unsigned ShiftOpc = Op.getOpcode();
1232 bool IsSigned = false;
1233 unsigned KnownBits;
1234 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
1235 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
1236 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
1237 unsigned NumZeroA =
1238 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
1239 unsigned NumZeroB =
1240 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
1241 unsigned NumZero = std::min(NumZeroA, NumZeroB);
1242
1243 switch (ShiftOpc) {
1244 default:
1245 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
1246 case ISD::SRA: {
1247 if (NumZero >= 2 && NumSigned < NumZero) {
1248 IsSigned = false;
1249 KnownBits = NumZero;
1250 break;
1251 }
1252 if (NumSigned >= 1) {
1253 IsSigned = true;
1254 KnownBits = NumSigned;
1255 break;
1256 }
1257 return SDValue();
1258 }
1259 case ISD::SRL: {
1260 if (NumZero >= 1 && NumSigned < NumZero) {
1261 IsSigned = false;
1262 KnownBits = NumZero;
1263 break;
1264 }
1265 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1266 IsSigned = true;
1267 KnownBits = NumSigned;
1268 break;
1269 }
1270 return SDValue();
1271 }
1272 }
1273
1274 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1275 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1276
1277 // Find the smallest power-2 type that is legal for this vector size and
1278 // operation, given the original type size and the number of known sign/zero
1279 // bits.
1280 EVT VT = Op.getValueType();
1281 std::optional<EVT> NarrowVT =
1283 if (!NarrowVT)
1284 return SDValue();
1285 EVT NVT = *NarrowVT;
1286 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) {
1287 // If we could not transform, and (both) adds are nuw/nsw, we can use the
1288 // larger type size to do the transform.
1289 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT))
1290 return SDValue();
1291 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0),
1292 Add.getOperand(1)) &&
1293 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0),
1294 Add2.getOperand(1))))
1295 NVT = VT;
1296 else
1297 return SDValue();
1298 }
1299
1300 // Don't create a AVGFLOOR node with a scalar constant unless its legal as
1301 // this is likely to stop other folds (reassociation, value tracking etc.)
1302 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) &&
1303 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB)))
1304 return SDValue();
1305
1306 SDLoc DL(Op);
1307 SDValue ResultAVG =
1308 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT),
1309 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT));
1310 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT);
1311}
1312
1313// Attempt to form ext(avgsubfloor(A, B)) from shr(sub(ext(A), ext(B)), 1).
1316 const TargetLowering &TLI,
1317 const APInt &DemandedBits,
1318 const APInt &DemandedElts, unsigned Depth) {
1319 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1320 "SRL or SRA node is required here!");
1321 // Is the right shift using an immediate value of 1?
1322 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1323 if (!N1C || !N1C->isOne())
1324 return SDValue();
1325
1326 SDValue Sub = Op.getOperand(0);
1327 if (Sub.getOpcode() != ISD::SUB)
1328 return SDValue();
1329
1330 // The result of the avgsub is sign extended to match the sra. For srl, the
1331 // top bit of the result is always zero so it must not be demanded.
1332 if (Op.getOpcode() == ISD::SRL && !DemandedBits.isSignBitClear())
1333 return SDValue();
1334
1335 SDValue A = Sub.getOperand(0);
1336 SDValue B = Sub.getOperand(1);
1337
1338 // If both operands have at least 2 sign bits or at least 1 leading zero, the
1339 // subtract can't overflow and the operands are extended from a narrower type.
1340 SelectionDAG &DAG = TLO.DAG;
1341 bool IsSigned;
1342 unsigned KnownBits;
1343 unsigned NumSigned =
1344 std::min(DAG.ComputeNumSignBits(A, DemandedElts, Depth),
1345 DAG.ComputeNumSignBits(B, DemandedElts, Depth)) -
1346 1;
1347 unsigned NumZero = std::min(
1348 DAG.computeKnownBits(A, DemandedElts, Depth).countMinLeadingZeros(),
1349 DAG.computeKnownBits(B, DemandedElts, Depth).countMinLeadingZeros());
1350 if (NumZero >= 1 && NumSigned < NumZero) {
1351 IsSigned = false;
1352 KnownBits = NumZero;
1353 } else if (NumSigned >= 1) {
1354 IsSigned = true;
1355 KnownBits = NumSigned;
1356 } else {
1357 return SDValue();
1358 }
1359
1360 unsigned AVGOpc = IsSigned ? ISD::AVGSUBFLOORS : ISD::AVGSUBFLOORU;
1361
1362 // Return true if the AVG node is legal or custom on the type VT will be
1363 // legalized to, provided that legalization doesn't change the scalar size.
1364 // That means vectors that are widened or split are accepted, but integers
1365 // that are promoted or expanded are not.
1366 LLVMContext &Ctx = *DAG.getContext();
1367 auto IsLegalAfterTypeLegalization = [&](EVT VT) {
1368 EVT LegalVT = TLI.getLegalTypeToTransformTo(Ctx, VT);
1369 return LegalVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
1370 TLI.isOperationLegal(AVGOpc, LegalVT);
1371 };
1372
1373 // Use the narrow type if the node is legal or custom there. Otherwise fall
1374 // back to the original type, which is still correct since the subtract can't
1375 // overflow. Don't form the node if the target can't do it on either type, as
1376 // expanding it may be worse than the original subtract and shift.
1377 // FIXME: Enable for illegal types/operations like combineShiftToAVG.
1378 EVT VT = Op.getValueType();
1379 std::optional<EVT> NarrowVT = getNarrowAVGType(VT, KnownBits, Ctx);
1380 EVT NVT = VT;
1381 if (NarrowVT && IsLegalAfterTypeLegalization(*NarrowVT))
1382 NVT = *NarrowVT;
1383 else if (!IsLegalAfterTypeLegalization(VT))
1384 return SDValue();
1385
1386 // Don't create an AVGSUBFLOOR node with a scalar constant unless it's legal
1387 // as this is likely to stop other folds (reassociation, value tracking etc.)
1388 if (!TLI.isOperationLegal(AVGOpc, NVT) &&
1390 return SDValue();
1391
1392 // The difference of two unsigned values can be negative, so the result is
1393 // always sign extended.
1394 SDLoc DL(Op);
1395 SDValue ResultAVG =
1396 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, A, DL, NVT),
1397 DAG.getExtOrTrunc(IsSigned, B, DL, NVT));
1398 return DAG.getExtOrTrunc(/*IsSigned=*/true, ResultAVG, DL, VT);
1399}
1400
1401/// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1402/// result of Op are ever used downstream. If we can use this information to
1403/// simplify Op, create a new simplified DAG node and return true, returning the
1404/// original and new nodes in Old and New. Otherwise, analyze the expression and
1405/// return a mask of Known bits for the expression (used to simplify the
1406/// caller). The Known bits may only be accurate for those bits in the
1407/// OriginalDemandedBits and OriginalDemandedElts.
1409 SDValue Op, const APInt &OriginalDemandedBits,
1410 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1411 unsigned Depth, bool AssumeSingleUse) const {
1412 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1413 assert(Op.getScalarValueSizeInBits() == BitWidth &&
1414 "Mask size mismatches value type size!");
1415
1416 // Don't know anything.
1418
1419 EVT VT = Op.getValueType();
1420 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1421 unsigned NumElts = OriginalDemandedElts.getBitWidth();
1422 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1423 "Unexpected vector size");
1424
1425 APInt DemandedBits = OriginalDemandedBits;
1426 APInt DemandedElts = OriginalDemandedElts;
1427 SDLoc dl(Op);
1428
1429 // Undef operand.
1430 if (Op.isUndef())
1431 return false;
1432
1433 // We can't simplify target constants.
1434 if (Op.getOpcode() == ISD::TargetConstant)
1435 return false;
1436
1437 if (Op.getOpcode() == ISD::Constant) {
1438 // We know all of the bits for a constant!
1439 Known = KnownBits::makeConstant(Op->getAsAPIntVal());
1440 return false;
1441 }
1442
1443 if (Op.getOpcode() == ISD::ConstantFP) {
1444 // We know all of the bits for a floating point constant!
1446 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1447 return false;
1448 }
1449
1450 // Other users may use these bits.
1451 bool HasMultiUse = false;
1452 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1454 // Limit search depth.
1455 return false;
1456 }
1457 // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1459 DemandedElts = APInt::getAllOnes(NumElts);
1460 HasMultiUse = true;
1461 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1462 // Not demanding any bits/elts from Op.
1463 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1464 } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1465 // Limit search depth.
1466 return false;
1467 }
1468
1469 // Before folding to the LHS, recheck bits excluded from its earlier demand
1470 // using the full result demand. Mask identifies these excluded bits.
1471 // KnownMask selects the Zero/One member of the recomputed LHS known bits
1472 // that must cover Mask & DemandedBits.
1473 auto TryFoldToLHS = [&](const APInt &Mask,
1474 const APInt KnownBits::*KnownMask) {
1475 SDValue LHS = Op.getOperand(0);
1476 APInt MaskedBits = Mask & DemandedBits;
1477 if (MaskedBits.isZero())
1478 return TLO.CombineTo(Op, LHS);
1479
1480 KnownBits LHSKnown;
1481 if (SimplifyDemandedBits(LHS, DemandedBits, DemandedElts, LHSKnown, TLO,
1482 Depth + 1))
1483 return true;
1484
1485 return MaskedBits.isSubsetOf(LHSKnown.*KnownMask) && TLO.CombineTo(Op, LHS);
1486 };
1487
1488 // Try reducing the RHS demand using LHS known bits.
1489 // KnownMask selects the LHS Zero/One bits that make RHS bits irrelevant.
1490 auto TryReduceRHSDemand = [&](const KnownBits &LHSKnown,
1491 const APInt KnownBits::*KnownMask) {
1492 SDValue RHS = Op.getOperand(1);
1493 if (!RHS.hasOneUse() || isConstOrConstSplat(RHS, DemandedElts))
1494 return false;
1495
1496 // Reuse LHS facts if the RHS did not reduce its earlier demand. Otherwise,
1497 // query independent facts to avoid using bits outside that demand.
1498 SDValue LHS = Op.getOperand(0);
1499 // Keep only the selected mask, then compute DemandedBits & ~Mask in place.
1500 // This avoids copying the unused KnownBits mask and extra APInt
1501 // temporaries, which can allocate memory for masks wider than one word.
1502 APInt RHSDemandedBits =
1503 DemandedBits.intersects(Known.*KnownMask)
1504 ? TLO.DAG.computeKnownBits(LHS, DemandedElts, Depth + 1).*KnownMask
1505 : LHSKnown.*KnownMask;
1506 RHSDemandedBits.flipAllBits();
1507 RHSDemandedBits &= DemandedBits;
1508 if (RHSDemandedBits == DemandedBits)
1509 return false;
1510
1511 // A failed retry must not replace Known with reduced-demand facts.
1512 KnownBits RetryKnown;
1513 return SimplifyDemandedBits(RHS, RHSDemandedBits, DemandedElts, RetryKnown,
1514 TLO, Depth + 1);
1515 };
1516
1517 KnownBits Known2;
1518 switch (Op.getOpcode()) {
1519 case ISD::SCALAR_TO_VECTOR: {
1520 if (VT.isScalableVector())
1521 return false;
1522 if (!DemandedElts[0])
1523 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
1524
1525 KnownBits SrcKnown;
1526 SDValue Src = Op.getOperand(0);
1527 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1528 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1529 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1530 return true;
1531
1532 // Upper elements are poison, so only get the knownbits if we just demand
1533 // the bottom element.
1534 if (DemandedElts == 1)
1535 Known = SrcKnown.anyextOrTrunc(BitWidth);
1536 break;
1537 }
1538 case ISD::BUILD_VECTOR:
1539 // Collect the known bits that are shared by every demanded element.
1540 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1541 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1542 return false; // Don't fall through, will infinitely loop.
1543 case ISD::SPLAT_VECTOR: {
1544 SDValue Scl = Op.getOperand(0);
1545 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1546 KnownBits KnownScl;
1547 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1548 return true;
1549
1550 // Implicitly truncate the bits to match the official semantics of
1551 // SPLAT_VECTOR.
1552 Known = KnownScl.trunc(BitWidth);
1553 break;
1554 }
1555 case ISD::FREEZE: {
1556 SDValue N0 = Op.getOperand(0);
1558 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
1559 return TLO.CombineTo(Op, N0);
1560 break;
1561 }
1562 case ISD::LOAD: {
1563 auto *LD = cast<LoadSDNode>(Op);
1564 if (getTargetConstantFromLoad(LD)) {
1565 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1566 return false; // Don't fall through, will infinitely loop.
1567 }
1568 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1569 // If this is a ZEXTLoad and we are looking at the loaded value.
1570 EVT MemVT = LD->getMemoryVT();
1571 unsigned MemBits = MemVT.getScalarSizeInBits();
1572 Known.Zero.setBitsFrom(MemBits);
1573 return false; // Don't fall through, will infinitely loop.
1574 }
1575 break;
1576 }
1578 if (VT.isScalableVector())
1579 return false;
1580 SDValue Vec = Op.getOperand(0);
1581 SDValue Scl = Op.getOperand(1);
1582 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1583 EVT VecVT = Vec.getValueType();
1584
1585 // If index isn't constant, assume we need all vector elements AND the
1586 // inserted element.
1587 APInt DemandedVecElts(DemandedElts);
1588 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1589 unsigned Idx = CIdx->getZExtValue();
1590 DemandedVecElts.clearBit(Idx);
1591
1592 // Inserted element is not required.
1593 if (!DemandedElts[Idx])
1594 return TLO.CombineTo(Op, Vec);
1595 }
1596
1597 KnownBits KnownScl;
1598 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1599 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1600 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1601 return true;
1602
1603 Known = KnownScl.anyextOrTrunc(BitWidth);
1604
1605 KnownBits KnownVec;
1606 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1607 Depth + 1))
1608 return true;
1609
1610 if (!!DemandedVecElts)
1611 Known = Known.intersectWith(KnownVec);
1612
1613 return false;
1614 }
1615 case ISD::INSERT_SUBVECTOR: {
1616 if (VT.isScalableVector())
1617 return false;
1618 // Demand any elements from the subvector and the remainder from the src its
1619 // inserted into.
1620 SDValue Src = Op.getOperand(0);
1621 SDValue Sub = Op.getOperand(1);
1622 uint64_t Idx = Op.getConstantOperandVal(2);
1623 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1624 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1625 APInt DemandedSrcElts = DemandedElts;
1626 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
1627
1628 KnownBits KnownSub, KnownSrc;
1629 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1630 Depth + 1))
1631 return true;
1632 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1633 Depth + 1))
1634 return true;
1635
1636 Known.setAllConflict();
1637 if (!!DemandedSubElts)
1638 Known = Known.intersectWith(KnownSub);
1639 if (!!DemandedSrcElts)
1640 Known = Known.intersectWith(KnownSrc);
1641
1642 // Attempt to avoid multi-use src if we don't need anything from it.
1643 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1644 !DemandedSrcElts.isAllOnes()) {
1646 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1648 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1649 if (NewSub || NewSrc) {
1650 NewSub = NewSub ? NewSub : Sub;
1651 NewSrc = NewSrc ? NewSrc : Src;
1652 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1653 Op.getOperand(2));
1654 return TLO.CombineTo(Op, NewOp);
1655 }
1656 }
1657 break;
1658 }
1660 if (VT.isScalableVector())
1661 return false;
1662 // Offset the demanded elts by the subvector index.
1663 SDValue Src = Op.getOperand(0);
1664 if (Src.getValueType().isScalableVector())
1665 break;
1666 uint64_t Idx = Op.getConstantOperandVal(1);
1667 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1668 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1669
1670 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1671 Depth + 1))
1672 return true;
1673
1674 // Attempt to avoid multi-use src if we don't need anything from it.
1675 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1677 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1678 if (DemandedSrc) {
1679 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1680 Op.getOperand(1));
1681 return TLO.CombineTo(Op, NewOp);
1682 }
1683 }
1684 break;
1685 }
1686 case ISD::CONCAT_VECTORS: {
1687 if (VT.isScalableVector())
1688 return false;
1689 Known.setAllConflict();
1690 EVT SubVT = Op.getOperand(0).getValueType();
1691 unsigned NumSubVecs = Op.getNumOperands();
1692 unsigned NumSubElts = SubVT.getVectorNumElements();
1693 for (unsigned i = 0; i != NumSubVecs; ++i) {
1694 APInt DemandedSubElts =
1695 DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1696 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1697 Known2, TLO, Depth + 1))
1698 return true;
1699 // Known bits are shared by every demanded subvector element.
1700 if (!!DemandedSubElts)
1701 Known = Known.intersectWith(Known2);
1702 }
1703 break;
1704 }
1705 case ISD::VECTOR_SHUFFLE: {
1706 assert(!VT.isScalableVector());
1707 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1708
1709 // Collect demanded elements from shuffle operands..
1710 APInt DemandedLHS, DemandedRHS;
1711 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1712 DemandedRHS))
1713 break;
1714
1715 if (!!DemandedLHS || !!DemandedRHS) {
1716 SDValue Op0 = Op.getOperand(0);
1717 SDValue Op1 = Op.getOperand(1);
1718
1719 Known.setAllConflict();
1720 if (!!DemandedLHS) {
1721 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1722 Depth + 1))
1723 return true;
1724 Known = Known.intersectWith(Known2);
1725 }
1726 if (!!DemandedRHS) {
1727 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1728 Depth + 1))
1729 return true;
1730 Known = Known.intersectWith(Known2);
1731 }
1732
1733 // Attempt to avoid multi-use ops if we don't need anything from them.
1735 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1737 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1738 if (DemandedOp0 || DemandedOp1) {
1739 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1740 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1741 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1742 return TLO.CombineTo(Op, NewOp);
1743 }
1744 }
1745 break;
1746 }
1747 case ISD::AND: {
1748 SDValue Op0 = Op.getOperand(0);
1749 SDValue Op1 = Op.getOperand(1);
1750
1751 // If the RHS is a constant, check to see if the LHS would be zero without
1752 // using the bits from the RHS. Below, we use knowledge about the RHS to
1753 // simplify the LHS, here we're using information from the LHS to simplify
1754 // the RHS.
1755 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) {
1756 // Do not increment Depth here; that can cause an infinite loop.
1757 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1758 // If the LHS already has zeros where RHSC does, this 'and' is dead.
1759 if ((LHSKnown.Zero & DemandedBits) ==
1760 (~RHSC->getAPIntValue() & DemandedBits))
1761 return TLO.CombineTo(Op, Op0);
1762
1763 // If any of the set bits in the RHS are known zero on the LHS, shrink
1764 // the constant.
1765 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1766 DemandedElts, TLO))
1767 return true;
1768
1769 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1770 // constant, but if this 'and' is only clearing bits that were just set by
1771 // the xor, then this 'and' can be eliminated by shrinking the mask of
1772 // the xor. For example, for a 32-bit X:
1773 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1774 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1775 LHSKnown.One == ~RHSC->getAPIntValue()) {
1776 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1777 return TLO.CombineTo(Op, Xor);
1778 }
1779 }
1780
1781 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2 (or zero).
1782 SDValue X, Y;
1783 if (sd_match(Op,
1784 m_And(m_Value(Y),
1786 m_Sub(m_Value(X), m_Deferred(Y)))))) &&
1787 TLO.DAG.isKnownToBeAPowerOfTwo(Y, DemandedElts, /*OrZero=*/true)) {
1788 return TLO.CombineTo(
1789 Op, TLO.DAG.getNode(ISD::AND, dl, VT, TLO.DAG.getNOT(dl, X, VT), Y));
1790 }
1791
1792 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1793 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1794 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1795 (Op0.getOperand(0).isUndef() ||
1797 Op0->hasOneUse()) {
1798 unsigned NumSubElts =
1800 unsigned SubIdx = Op0.getConstantOperandVal(2);
1801 APInt DemandedSub =
1802 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1803 KnownBits KnownSubMask =
1804 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1805 if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1806 SDValue NewAnd =
1807 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1808 SDValue NewInsert =
1809 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1810 Op0.getOperand(1), Op0.getOperand(2));
1811 return TLO.CombineTo(Op, NewInsert);
1812 }
1813 }
1814
1815 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1816 Depth + 1))
1817 return true;
1818 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1819 Known2, TLO, Depth + 1))
1820 return true;
1821
1822 // If all of the demanded bits are known one on one side, return the other.
1823 // These bits cannot contribute to the result of the 'and'.
1824 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) {
1825 if (TryFoldToLHS(Known.Zero, &KnownBits::Zero))
1826 return true;
1827 }
1828 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1829 return TLO.CombineTo(Op, Op1);
1830 // If all of the demanded bits in the inputs are known zeros, return zero.
1831 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1832 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1833 // If the RHS is a constant, see if we can simplify it.
1834 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1835 TLO))
1836 return true;
1837 // If the operation can be done in a smaller type, do so.
1839 return true;
1840
1841 // Attempt to avoid multi-use ops if we don't need anything from them.
1842 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1844 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1846 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1847 if (DemandedOp0 || DemandedOp1) {
1848 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1849 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1850 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1851 return TLO.CombineTo(Op, NewOp);
1852 }
1853 }
1854
1855 if (TryReduceRHSDemand(Known2, &KnownBits::Zero))
1856 return true;
1857
1858 Known &= Known2;
1859 break;
1860 }
1861 case ISD::OR: {
1862 SDValue Op0 = Op.getOperand(0);
1863 SDValue Op1 = Op.getOperand(1);
1864 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1865 Depth + 1)) {
1866 Op->dropFlags(SDNodeFlags::Disjoint);
1867 return true;
1868 }
1869
1870 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1871 Known2, TLO, Depth + 1)) {
1872 Op->dropFlags(SDNodeFlags::Disjoint);
1873 return true;
1874 }
1875
1876 // If all of the demanded bits are known zero on one side, return the other.
1877 // These bits cannot contribute to the result of the 'or'.
1878 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) {
1879 if (TryFoldToLHS(Known.One, &KnownBits::One)) {
1880 Op->dropFlags(SDNodeFlags::Disjoint);
1881 return true;
1882 }
1883 }
1884 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1885 return TLO.CombineTo(Op, Op1);
1886 // If the RHS is a constant, see if we can simplify it.
1887 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1888 return true;
1889 // If the operation can be done in a smaller type, do so.
1891 return true;
1892
1893 // Attempt to avoid multi-use ops if we don't need anything from them.
1894 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1896 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1898 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1899 if (DemandedOp0 || DemandedOp1) {
1900 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1901 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1902 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1903 return TLO.CombineTo(Op, NewOp);
1904 }
1905 }
1906
1907 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1908 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1909 SDValue X, Y, C1, C2;
1912 m_Value(C2)))))) {
1913 if (SDValue C12 =
1914 TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, {C1, C2})) {
1915 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1916 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1917 return TLO.CombineTo(Op,
1918 TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1919 }
1920 }
1921
1922 if (TryReduceRHSDemand(Known2, &KnownBits::One)) {
1923 Op->dropFlags(SDNodeFlags::Disjoint);
1924 return true;
1925 }
1926
1927 Known |= Known2;
1928 break;
1929 }
1930 case ISD::XOR: {
1931 SDValue Op0 = Op.getOperand(0);
1932 SDValue Op1 = Op.getOperand(1);
1933
1934 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1935 Depth + 1))
1936 return true;
1937 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1938 Depth + 1))
1939 return true;
1940
1941 // If all of the demanded bits are known zero on one side, return the other.
1942 // These bits cannot contribute to the result of the 'xor'.
1943 if (DemandedBits.isSubsetOf(Known.Zero))
1944 return TLO.CombineTo(Op, Op0);
1945 if (DemandedBits.isSubsetOf(Known2.Zero))
1946 return TLO.CombineTo(Op, Op1);
1947 // If the operation can be done in a smaller type, do so.
1949 return true;
1950
1951 // If all of the unknown bits are known to be zero on one side or the other
1952 // turn this into an *inclusive* or.
1953 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1954 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1955 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1956
1957 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1958 if (C) {
1959 // If one side is a constant, and all of the set bits in the constant are
1960 // also known set on the other side, turn this into an AND, as we know
1961 // the bits will be cleared.
1962 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1963 // NB: it is okay if more bits are known than are requested
1964 if (C->getAPIntValue() == Known2.One) {
1965 SDValue ANDC =
1966 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1967 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1968 }
1969
1970 // If the RHS is a constant, see if we can change it. Don't alter a -1
1971 // constant because that's a 'not' op, and that is better for combining
1972 // and codegen.
1973 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1974 // We're flipping all demanded bits. Flip the undemanded bits too.
1975 SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1976 return TLO.CombineTo(Op, New);
1977 }
1978
1979 unsigned Op0Opcode = Op0.getOpcode();
1980 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1981 if (ConstantSDNode *ShiftC =
1982 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1983 // Don't crash on an oversized shift. We can not guarantee that a
1984 // bogus shift has been simplified to undef.
1985 if (ShiftC->getAPIntValue().ult(BitWidth)) {
1986 uint64_t ShiftAmt = ShiftC->getZExtValue();
1988 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1989 : Ones.lshr(ShiftAmt);
1990 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1992 // If the xor constant is a demanded mask, do a 'not' before the
1993 // shift:
1994 // xor (X << ShiftC), XorC --> (not X) << ShiftC
1995 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1996 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1997 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1998 Op0.getOperand(1)));
1999 }
2000 }
2001 }
2002 }
2003 }
2004
2005 // If we can't turn this into a 'not', try to shrink the constant.
2006 if (!C || !C->isAllOnes())
2007 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
2008 return true;
2009
2010 // Attempt to avoid multi-use ops if we don't need anything from them.
2011 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
2013 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
2015 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
2016 if (DemandedOp0 || DemandedOp1) {
2017 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2018 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2019 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
2020 return TLO.CombineTo(Op, NewOp);
2021 }
2022 }
2023
2024 Known ^= Known2;
2025 break;
2026 }
2027 case ISD::SELECT:
2028 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
2029 Known, TLO, Depth + 1))
2030 return true;
2031 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
2032 Known2, TLO, Depth + 1))
2033 return true;
2034
2035 // If the operands are constants, see if we can simplify them.
2036 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
2037 return true;
2038
2039 // Only known if known in both the LHS and RHS.
2040 Known = Known.intersectWith(Known2);
2041 break;
2042 case ISD::VSELECT:
2043 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
2044 Known, TLO, Depth + 1))
2045 return true;
2046 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
2047 Known2, TLO, Depth + 1))
2048 return true;
2049
2050 // Only known if known in both the LHS and RHS.
2051 Known = Known.intersectWith(Known2);
2052 break;
2053 case ISD::SELECT_CC:
2054 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts,
2055 Known, TLO, Depth + 1))
2056 return true;
2057 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
2058 Known2, TLO, Depth + 1))
2059 return true;
2060
2061 // If the operands are constants, see if we can simplify them.
2062 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
2063 return true;
2064
2065 // Only known if known in both the LHS and RHS.
2066 Known = Known.intersectWith(Known2);
2067 break;
2068 case ISD::SETCC: {
2069 SDValue Op0 = Op.getOperand(0);
2070 SDValue Op1 = Op.getOperand(1);
2071 ISD::CondCode CC = Op.getOperandCondCode(2);
2072 // If we're testing X < 0, X >= 0, X <= -1 or X > -1
2073 // (X is of integer type) then we only need the sign mask of the previous
2074 // result
2075 if (Op1.getValueType().isInteger() &&
2076 (((CC == ISD::SETLT || CC == ISD::SETGE) && isNullOrNullSplat(Op1)) ||
2077 ((CC == ISD::SETLE || CC == ISD::SETGT) &&
2078 isAllOnesOrAllOnesSplat(Op1)))) {
2079 KnownBits KnownOp0;
2082 DemandedElts, KnownOp0, TLO, Depth + 1))
2083 return true;
2084 // If (1) we only need the sign-bit, (2) the setcc operands are the same
2085 // width as the setcc result, and (3) the result of a setcc conforms to 0
2086 // or -1, we may be able to bypass the setcc.
2087 if (DemandedBits.isSignMask() &&
2091 // If we remove a >= 0 or > -1 (for integers), we need to introduce a
2092 // NOT Operation
2093 if (CC == ISD::SETGE || CC == ISD::SETGT) {
2094 SDLoc DL(Op);
2095 EVT VT = Op0.getValueType();
2096 SDValue NotOp0 = TLO.DAG.getNOT(DL, Op0, VT);
2097 return TLO.CombineTo(Op, NotOp0);
2098 }
2099 return TLO.CombineTo(Op, Op0);
2100 }
2101 }
2102 if (getBooleanContents(Op0.getValueType()) ==
2104 BitWidth > 1)
2105 Known.Zero.setBitsFrom(1);
2106 break;
2107 }
2108 case ISD::SHL: {
2109 SDValue Op0 = Op.getOperand(0);
2110 SDValue Op1 = Op.getOperand(1);
2111 EVT ShiftVT = Op1.getValueType();
2112
2113 if (std::optional<unsigned> KnownSA =
2114 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2115 unsigned ShAmt = *KnownSA;
2116 if (ShAmt == 0)
2117 return TLO.CombineTo(Op, Op0);
2118
2119 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
2120 // single shift. We can do this if the bottom bits (which are shifted
2121 // out) are never demanded.
2122 // TODO - support non-uniform vector amounts.
2123 if (Op0.getOpcode() == ISD::SRL) {
2124 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
2125 if (std::optional<unsigned> InnerSA =
2126 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2127 unsigned C1 = *InnerSA;
2128 unsigned Opc = ISD::SHL;
2129 int Diff = ShAmt - C1;
2130 if (Diff < 0) {
2131 Diff = -Diff;
2132 Opc = ISD::SRL;
2133 }
2134 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2135 return TLO.CombineTo(
2136 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2137 }
2138 }
2139 }
2140
2141 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
2142 // are not demanded. This will likely allow the anyext to be folded away.
2143 // TODO - support non-uniform vector amounts.
2144 if (Op0.getOpcode() == ISD::ANY_EXTEND) {
2145 SDValue InnerOp = Op0.getOperand(0);
2146 EVT InnerVT = InnerOp.getValueType();
2147 unsigned InnerBits = InnerVT.getScalarSizeInBits();
2148 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
2149 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
2150 SDValue NarrowShl = TLO.DAG.getNode(
2151 ISD::SHL, dl, InnerVT, InnerOp,
2152 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
2153 return TLO.CombineTo(
2154 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2155 }
2156
2157 // Repeat the SHL optimization above in cases where an extension
2158 // intervenes: (shl (anyext (shr x, c1)), c2) to
2159 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
2160 // aren't demanded (as above) and that the shifted upper c1 bits of
2161 // x aren't demanded.
2162 // TODO - support non-uniform vector amounts.
2163 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
2164 InnerOp.hasOneUse()) {
2165 if (std::optional<unsigned> SA2 = TLO.DAG.getValidShiftAmount(
2166 InnerOp, DemandedElts, Depth + 2)) {
2167 unsigned InnerShAmt = *SA2;
2168 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
2169 DemandedBits.getActiveBits() <=
2170 (InnerBits - InnerShAmt + ShAmt) &&
2171 DemandedBits.countr_zero() >= ShAmt) {
2172 SDValue NewSA =
2173 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
2174 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
2175 InnerOp.getOperand(0));
2176 return TLO.CombineTo(
2177 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
2178 }
2179 }
2180 }
2181 }
2182
2183 APInt InDemandedMask = DemandedBits.lshr(ShAmt);
2184 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2185 Depth + 1)) {
2186 // Disable the nsw and nuw flags. We can no longer guarantee that we
2187 // won't wrap after simplification.
2188 Op->dropFlags(SDNodeFlags::NoWrap);
2189 return true;
2190 }
2191 Known <<= ShAmt;
2192 // low bits known zero.
2193 Known.Zero.setLowBits(ShAmt);
2194
2195 // Attempt to avoid multi-use ops if we don't need anything from them.
2196 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2198 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2199 if (DemandedOp0) {
2200 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
2201 return TLO.CombineTo(Op, NewOp);
2202 }
2203 }
2204
2205 // TODO: Can we merge this fold with the one below?
2206 // Try shrinking the operation as long as the shift amount will still be
2207 // in range.
2208 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() &&
2209 Op.getNode()->hasOneUse()) {
2210 // Search for the smallest integer type with free casts to and from
2211 // Op's type. For expedience, just check power-of-2 integer types.
2212 unsigned DemandedSize = DemandedBits.getActiveBits();
2213 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
2214 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
2215 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits);
2216 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) &&
2217 isTypeDesirableForOp(ISD::SHL, SmallVT) &&
2218 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) &&
2219 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) {
2220 assert(DemandedSize <= SmallVTBits &&
2221 "Narrowed below demanded bits?");
2222 // We found a type with free casts.
2223 SDValue NarrowShl = TLO.DAG.getNode(
2224 ISD::SHL, dl, SmallVT,
2225 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
2226 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl));
2227 return TLO.CombineTo(
2228 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2229 }
2230 }
2231 }
2232
2233 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2234 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
2235 // Only do this if we demand the upper half so the knownbits are correct.
2236 unsigned HalfWidth = BitWidth / 2;
2237 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
2238 DemandedBits.countLeadingOnes() >= HalfWidth) {
2239 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
2240 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2241 isTypeDesirableForOp(ISD::SHL, HalfVT) &&
2242 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2243 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
2244 // If we're demanding the upper bits at all, we must ensure
2245 // that the upper bits of the shift result are known to be zero,
2246 // which is equivalent to the narrow shift being NUW.
2247 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
2248 bool IsNSW = Known.countMinSignBits() > HalfWidth;
2249 SDNodeFlags Flags;
2250 Flags.setNoSignedWrap(IsNSW);
2251 Flags.setNoUnsignedWrap(IsNUW);
2252 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2253 SDValue NewShiftAmt =
2254 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2255 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
2256 NewShiftAmt, Flags);
2257 SDValue NewExt =
2258 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
2259 return TLO.CombineTo(Op, NewExt);
2260 }
2261 }
2262 }
2263 } else {
2264 // This is a variable shift, so we can't shift the demand mask by a known
2265 // amount. But if we are not demanding high bits, then we are not
2266 // demanding those bits from the pre-shifted operand either.
2267 if (unsigned CTLZ = DemandedBits.countl_zero()) {
2268 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
2269 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
2270 Depth + 1)) {
2271 // Disable the nsw and nuw flags. We can no longer guarantee that we
2272 // won't wrap after simplification.
2273 Op->dropFlags(SDNodeFlags::NoWrap);
2274 return true;
2275 }
2276 Known.resetAll();
2277 }
2278 }
2279
2280 // If we are only demanding sign bits then we can use the shift source
2281 // directly.
2282 if (std::optional<unsigned> MaxSA =
2283 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2284 unsigned ShAmt = *MaxSA;
2285 unsigned NumSignBits =
2286 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2287 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
2288 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
2289 return TLO.CombineTo(Op, Op0);
2290 }
2291 break;
2292 }
2293 case ISD::SRL: {
2294 SDValue Op0 = Op.getOperand(0);
2295 SDValue Op1 = Op.getOperand(1);
2296 EVT ShiftVT = Op1.getValueType();
2297
2298 if (std::optional<unsigned> KnownSA =
2299 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2300 unsigned ShAmt = *KnownSA;
2301 if (ShAmt == 0)
2302 return TLO.CombineTo(Op, Op0);
2303
2304 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
2305 // single shift. We can do this if the top bits (which are shifted out)
2306 // are never demanded.
2307 // TODO - support non-uniform vector amounts.
2308 if (Op0.getOpcode() == ISD::SHL) {
2309 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2310 if (std::optional<unsigned> InnerSA =
2311 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2312 unsigned C1 = *InnerSA;
2313 unsigned Opc = ISD::SRL;
2314 int Diff = ShAmt - C1;
2315 if (Diff < 0) {
2316 Diff = -Diff;
2317 Opc = ISD::SHL;
2318 }
2319 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2320 return TLO.CombineTo(
2321 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2322 }
2323 }
2324 }
2325
2326 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a
2327 // single sra. We can do this if the top bits are never demanded.
2328 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) {
2329 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2330 if (std::optional<unsigned> InnerSA =
2331 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2332 unsigned C1 = *InnerSA;
2333 // Clamp the combined shift amount if it exceeds the bit width.
2334 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1);
2335 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT);
2336 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT,
2337 Op0.getOperand(0), NewSA));
2338 }
2339 }
2340 }
2341
2342 APInt InDemandedMask = (DemandedBits << ShAmt);
2343
2344 // If the shift is exact, then it does demand the low bits (and knows that
2345 // they are zero).
2346 if (Op->getFlags().hasExact())
2347 InDemandedMask.setLowBits(ShAmt);
2348
2349 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2350 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
2351 if ((BitWidth % 2) == 0 && !VT.isVector()) {
2353 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
2354 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2355 isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2356 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2357 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
2358 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
2359 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
2360 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2361 SDValue NewShiftAmt =
2362 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2363 SDValue NewShift =
2364 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt,
2365 Op->getFlags() & SDNodeFlags::Exact);
2366 return TLO.CombineTo(
2367 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
2368 }
2369 }
2370
2371 // Compute the new bits that are at the top now.
2372 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2373 Depth + 1))
2374 return true;
2375 Known >>= ShAmt;
2376 // High bits known zero.
2377 Known.Zero.setHighBits(ShAmt);
2378
2379 // Attempt to avoid multi-use ops if we don't need anything from them.
2380 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2382 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2383 if (DemandedOp0) {
2384 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
2385 return TLO.CombineTo(Op, NewOp);
2386 }
2387 }
2388 } else {
2389 // Use generic knownbits computation as it has support for non-uniform
2390 // shift amounts.
2391 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2392 }
2393
2394 // If we are only demanding sign bits then we can use the shift source
2395 // directly.
2396 if (std::optional<unsigned> MaxSA =
2397 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2398 unsigned ShAmt = *MaxSA;
2399 // Must already be signbits in DemandedBits bounds, and can't demand any
2400 // shifted in zeroes.
2401 if (DemandedBits.countl_zero() >= ShAmt) {
2402 unsigned NumSignBits =
2403 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2404 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
2405 return TLO.CombineTo(Op, Op0);
2406 }
2407 }
2408
2409 // Try to match AVG patterns (after shift simplification).
2410 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2411 DemandedElts, Depth + 1))
2412 return TLO.CombineTo(Op, AVG);
2413 if (SDValue AVG = combineShiftToAVGSUB(Op, TLO, *this, DemandedBits,
2414 DemandedElts, Depth + 1))
2415 return TLO.CombineTo(Op, AVG);
2416
2417 break;
2418 }
2419 case ISD::SRA: {
2420 SDValue Op0 = Op.getOperand(0);
2421 SDValue Op1 = Op.getOperand(1);
2422 EVT ShiftVT = Op1.getValueType();
2423
2424 // If we only want bits that already match the signbit then we don't need
2425 // to shift.
2426 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
2427 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
2428 NumHiDemandedBits)
2429 return TLO.CombineTo(Op, Op0);
2430
2431 // If this is an arithmetic shift right and only the low-bit is set, we can
2432 // always convert this into a logical shr, even if the shift amount is
2433 // variable. The low bit of the shift cannot be an input sign bit unless
2434 // the shift amount is >= the size of the datatype, which is undefined.
2435 if (DemandedBits.isOne())
2436 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2437
2438 if (std::optional<unsigned> KnownSA =
2439 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2440 unsigned ShAmt = *KnownSA;
2441 if (ShAmt == 0)
2442 return TLO.CombineTo(Op, Op0);
2443
2444 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2445 // supports sext_inreg.
2446 if (Op0.getOpcode() == ISD::SHL) {
2447 if (std::optional<unsigned> InnerSA =
2448 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2449 unsigned LowBits = BitWidth - ShAmt;
2450 EVT ExtVT = VT.changeElementType(
2451 *TLO.DAG.getContext(),
2452 EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits));
2453
2454 if (*InnerSA == ShAmt) {
2455 if (!TLO.LegalOperations() ||
2457 return TLO.CombineTo(
2458 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2459 Op0.getOperand(0),
2460 TLO.DAG.getValueType(ExtVT)));
2461
2462 // Even if we can't convert to sext_inreg, we might be able to
2463 // remove this shift pair if the input is already sign extended.
2464 unsigned NumSignBits =
2465 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2466 if (NumSignBits > ShAmt)
2467 return TLO.CombineTo(Op, Op0.getOperand(0));
2468 }
2469 }
2470 }
2471
2472 APInt InDemandedMask = (DemandedBits << ShAmt);
2473
2474 // If the shift is exact, then it does demand the low bits (and knows that
2475 // they are zero).
2476 if (Op->getFlags().hasExact())
2477 InDemandedMask.setLowBits(ShAmt);
2478
2479 // If any of the demanded bits are produced by the sign extension, we also
2480 // demand the input sign bit.
2481 if (DemandedBits.countl_zero() < ShAmt)
2482 InDemandedMask.setSignBit();
2483
2484 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2485 Depth + 1))
2486 return true;
2487 Known >>= ShAmt;
2488
2489 // If the input sign bit is known to be zero, or if none of the top bits
2490 // are demanded, turn this into an unsigned shift right.
2491 if (Known.Zero[BitWidth - ShAmt - 1] ||
2492 DemandedBits.countl_zero() >= ShAmt) {
2493 SDNodeFlags Flags;
2494 Flags.setExact(Op->getFlags().hasExact());
2495 return TLO.CombineTo(
2496 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2497 }
2498
2499 int Log2 = DemandedBits.exactLogBase2();
2500 if (Log2 >= 0) {
2501 // The bit must come from the sign.
2502 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2503 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2504 }
2505
2506 if (Known.One[BitWidth - ShAmt - 1])
2507 // New bits are known one.
2508 Known.One.setHighBits(ShAmt);
2509
2510 // Attempt to avoid multi-use ops if we don't need anything from them.
2511 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2513 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2514 if (DemandedOp0) {
2515 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2516 return TLO.CombineTo(Op, NewOp);
2517 }
2518 }
2519 }
2520
2521 // Try to match AVG patterns (after shift simplification).
2522 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2523 DemandedElts, Depth + 1))
2524 return TLO.CombineTo(Op, AVG);
2525 if (SDValue AVG = combineShiftToAVGSUB(Op, TLO, *this, DemandedBits,
2526 DemandedElts, Depth + 1))
2527 return TLO.CombineTo(Op, AVG);
2528
2529 break;
2530 }
2531 case ISD::FSHL:
2532 case ISD::FSHR: {
2533 SDValue Op0 = Op.getOperand(0);
2534 SDValue Op1 = Op.getOperand(1);
2535 SDValue Op2 = Op.getOperand(2);
2536 bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2537
2538 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2539 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2540
2541 // For fshl, 0-shift returns the 1st arg.
2542 // For fshr, 0-shift returns the 2nd arg.
2543 if (Amt == 0) {
2544 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2545 Known, TLO, Depth + 1))
2546 return true;
2547 break;
2548 }
2549
2550 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2551 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2552 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2553 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2554 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2555 Depth + 1))
2556 return true;
2557 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2558 Depth + 1))
2559 return true;
2560
2561 Known2 <<= (IsFSHL ? Amt : (BitWidth - Amt));
2562 Known >>= (IsFSHL ? (BitWidth - Amt) : Amt);
2563 Known = Known.unionWith(Known2);
2564
2565 // Attempt to avoid multi-use ops if we don't need anything from them.
2566 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2567 !DemandedElts.isAllOnes()) {
2569 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2571 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2572 if (DemandedOp0 || DemandedOp1) {
2573 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2574 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2575 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2576 DemandedOp1, Op2);
2577 return TLO.CombineTo(Op, NewOp);
2578 }
2579 }
2580 }
2581
2582 if (isPowerOf2_32(BitWidth)) {
2583 // Fold FSHR(Op0,Op1,Op2) -> SRL(Op1,Op2)
2584 // iff we're guaranteed not to use Op0.
2585 // TODO: Add FSHL equivalent?
2586 if (!IsFSHL && !DemandedBits.isAllOnes() &&
2587 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT))) {
2588 KnownBits KnownAmt =
2589 TLO.DAG.computeKnownBits(Op2, DemandedElts, Depth + 1);
2590 unsigned MaxShiftAmt =
2591 KnownAmt.getMaxValue().getLimitedValue(BitWidth - 1);
2592 // Check we don't demand any shifted bits outside Op1.
2593 if (DemandedBits.countl_zero() >= MaxShiftAmt) {
2594 EVT AmtVT = Op2.getValueType();
2595 SDValue NewAmt =
2596 TLO.DAG.getNode(ISD::AND, dl, AmtVT, Op2,
2597 TLO.DAG.getConstant(BitWidth - 1, dl, AmtVT));
2598 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, Op1, NewAmt);
2599 return TLO.CombineTo(Op, NewOp);
2600 }
2601 }
2602
2603 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2604 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2605 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, Known2, TLO,
2606 Depth + 1))
2607 return true;
2608 }
2609 break;
2610 }
2611 case ISD::ROTL:
2612 case ISD::ROTR: {
2613 SDValue Op0 = Op.getOperand(0);
2614 SDValue Op1 = Op.getOperand(1);
2615 bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2616
2617 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2618 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2619 return TLO.CombineTo(Op, Op0);
2620
2621 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2622 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2623 unsigned RevAmt = BitWidth - Amt;
2624
2625 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2626 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2627 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2628 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2629 Depth + 1))
2630 return true;
2631
2632 // rot*(x, 0) --> x
2633 if (Amt == 0)
2634 return TLO.CombineTo(Op, Op0);
2635
2636 // See if we don't demand either half of the rotated bits.
2637 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2638 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2639 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2640 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2641 }
2642 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2643 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2644 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2645 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2646 }
2647 }
2648
2649 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2650 if (isPowerOf2_32(BitWidth)) {
2651 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2652 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2653 Depth + 1))
2654 return true;
2655 }
2656 break;
2657 }
2658 case ISD::SMIN:
2659 case ISD::SMAX:
2660 case ISD::UMIN:
2661 case ISD::UMAX: {
2662 unsigned Opc = Op.getOpcode();
2663 SDValue Op0 = Op.getOperand(0);
2664 SDValue Op1 = Op.getOperand(1);
2665
2666 // If we're only demanding signbits, then we can simplify to OR/AND node.
2667 unsigned BitOp =
2668 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2669 unsigned NumSignBits =
2670 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2671 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2672 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2673 if (NumSignBits >= NumDemandedUpperBits)
2674 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2675
2676 // Check if one arg is always less/greater than (or equal) to the other arg.
2677 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2678 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2679 switch (Opc) {
2680 case ISD::SMIN:
2681 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2682 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2683 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2684 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2685 Known = KnownBits::smin(Known0, Known1);
2686 break;
2687 case ISD::SMAX:
2688 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2689 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2690 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2691 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2692 Known = KnownBits::smax(Known0, Known1);
2693 break;
2694 case ISD::UMIN:
2695 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2696 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2697 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2698 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2699 Known = KnownBits::umin(Known0, Known1);
2700 break;
2701 case ISD::UMAX:
2702 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2703 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2704 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2705 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2706 Known = KnownBits::umax(Known0, Known1);
2707 break;
2708 }
2709 break;
2710 }
2711 case ISD::BITREVERSE: {
2712 SDValue Src = Op.getOperand(0);
2713 APInt DemandedSrcBits = DemandedBits.reverseBits();
2714 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2715 Depth + 1))
2716 return true;
2717 Known = Known2.reverseBits();
2718 break;
2719 }
2720 case ISD::BSWAP: {
2721 SDValue Src = Op.getOperand(0);
2722
2723 // If the only bits demanded come from one byte of the bswap result,
2724 // just shift the input byte into position to eliminate the bswap.
2725 unsigned NLZ = DemandedBits.countl_zero();
2726 unsigned NTZ = DemandedBits.countr_zero();
2727
2728 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
2729 // we need all the bits down to bit 8. Likewise, round NLZ. If we
2730 // have 14 leading zeros, round to 8.
2731 NLZ = alignDown(NLZ, 8);
2732 NTZ = alignDown(NTZ, 8);
2733 // If we need exactly one byte, we can do this transformation.
2734 if (BitWidth - NLZ - NTZ == 8) {
2735 // Replace this with either a left or right shift to get the byte into
2736 // the right place.
2737 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2738 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2739 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2740 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
2741 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2742 return TLO.CombineTo(Op, NewOp);
2743 }
2744 }
2745
2746 APInt DemandedSrcBits = DemandedBits.byteSwap();
2747 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2748 Depth + 1))
2749 return true;
2750 Known = Known2.byteSwap();
2751 break;
2752 }
2753 case ISD::CTPOP: {
2754 // If only 1 bit is demanded, replace with PARITY as long as we're before
2755 // op legalization.
2756 // FIXME: Limit to scalars for now.
2757 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2758 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2759 Op.getOperand(0)));
2760
2761 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2762 break;
2763 }
2764 case ISD::PDEP: {
2765 SDValue Op0 = Op.getOperand(0);
2766 SDValue Op1 = Op.getOperand(1);
2767
2768 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2769 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2770
2771 // If the demanded bits has leading zeroes, we don't demand those from the
2772 // mask.
2773 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
2774 return true;
2775
2776 // The number of possible 1s in the mask determines the number of LSBs of
2777 // operand 0 used. Undemanded bits from the mask don't matter so filter
2778 // them before counting.
2779 KnownBits Known2;
2780 uint64_t Count = (~Known.Zero & LoMask).popcount();
2781 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
2782 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
2783 return true;
2784
2785 // Zeroes are retained from the mask, but not ones.
2786 Known.One.clearAllBits();
2787 // The result will have at least as many trailing zeros as the non-mask
2788 // operand since bits can only map to the same or higher bit position.
2789 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
2790 break;
2791 }
2793 SDValue Op0 = Op.getOperand(0);
2794 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2795 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2796
2797 // If we only care about the highest bit, don't bother shifting right.
2798 if (DemandedBits.isSignMask()) {
2799 unsigned MinSignedBits =
2800 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2801 bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2802 // However if the input is already sign extended we expect the sign
2803 // extension to be dropped altogether later and do not simplify.
2804 if (!AlreadySignExtended) {
2805 // Compute the correct shift amount type, which must be getShiftAmountTy
2806 // for scalar types after legalization.
2807 SDValue ShiftAmt =
2808 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl);
2809 return TLO.CombineTo(Op,
2810 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2811 }
2812 }
2813
2814 // If none of the extended bits are demanded, eliminate the sextinreg.
2815 if (DemandedBits.getActiveBits() <= ExVTBits)
2816 return TLO.CombineTo(Op, Op0);
2817
2818 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2819
2820 // Since the sign extended bits are demanded, we know that the sign
2821 // bit is demanded.
2822 InputDemandedBits.setBit(ExVTBits - 1);
2823
2824 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2825 Depth + 1))
2826 return true;
2827
2828 // If the sign bit of the input is known set or clear, then we know the
2829 // top bits of the result.
2830
2831 // If the input sign bit is known zero, convert this into a zero extension.
2832 if (Known.Zero[ExVTBits - 1])
2833 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2834
2835 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2836 if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2837 Known.One.setBitsFrom(ExVTBits);
2838 Known.Zero &= Mask;
2839 } else { // Input sign bit unknown
2840 Known.Zero &= Mask;
2841 Known.One &= Mask;
2842 }
2843 break;
2844 }
2845 case ISD::BUILD_PAIR: {
2846 EVT HalfVT = Op.getOperand(0).getValueType();
2847 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2848
2849 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2850 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2851
2852 KnownBits KnownLo, KnownHi;
2853
2854 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2855 return true;
2856
2857 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2858 return true;
2859
2860 Known = KnownHi.concat(KnownLo);
2861 break;
2862 }
2864 if (VT.isScalableVector())
2865 return false;
2866 [[fallthrough]];
2867 case ISD::ZERO_EXTEND: {
2868 SDValue Src = Op.getOperand(0);
2869 EVT SrcVT = Src.getValueType();
2870 unsigned InBits = SrcVT.getScalarSizeInBits();
2871 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2872 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2873
2874 // If none of the top bits are demanded, convert this into an any_extend.
2875 if (DemandedBits.getActiveBits() <= InBits) {
2876 // If we only need the non-extended bits of the bottom element
2877 // then we can just bitcast to the result.
2878 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2879 VT.getSizeInBits() == SrcVT.getSizeInBits())
2880 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2881
2882 unsigned Opc =
2884 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2885 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2886 }
2887
2888 APInt InDemandedBits = DemandedBits.trunc(InBits);
2889 APInt InDemandedElts = DemandedElts.zext(InElts);
2890 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2891 Depth + 1)) {
2892 Op->dropFlags(SDNodeFlags::NonNeg);
2893 return true;
2894 }
2895 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2896 Known = Known.zext(BitWidth);
2897
2898 // Attempt to avoid multi-use ops if we don't need anything from them.
2900 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2901 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2902 break;
2903 }
2905 if (VT.isScalableVector())
2906 return false;
2907 [[fallthrough]];
2908 case ISD::SIGN_EXTEND: {
2909 SDValue Src = Op.getOperand(0);
2910 EVT SrcVT = Src.getValueType();
2911 unsigned InBits = SrcVT.getScalarSizeInBits();
2912 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2913 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2914
2915 APInt InDemandedElts = DemandedElts.zext(InElts);
2916 APInt InDemandedBits = DemandedBits.trunc(InBits);
2917
2918 // Since some of the sign extended bits are demanded, we know that the sign
2919 // bit is demanded.
2920 InDemandedBits.setBit(InBits - 1);
2921
2922 // If none of the top bits are demanded, convert this into an any_extend.
2923 if (DemandedBits.getActiveBits() <= InBits) {
2924 // If we only need the non-extended bits of the bottom element
2925 // then we can just bitcast to the result.
2926 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2927 VT.getSizeInBits() == SrcVT.getSizeInBits())
2928 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2929
2930 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans.
2932 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) !=
2933 InBits) {
2934 unsigned Opc =
2936 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2937 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2938 }
2939 }
2940
2941 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2942 Depth + 1))
2943 return true;
2944 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2945
2946 // If the sign bit is known one, the top bits match.
2947 Known = Known.sext(BitWidth);
2948
2949 // If the sign bit is known zero, convert this to a zero extend.
2950 if (Known.isNonNegative()) {
2951 unsigned Opc =
2953 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) {
2954 SDNodeFlags Flags;
2955 if (!IsVecInReg)
2956 Flags |= SDNodeFlags::NonNeg;
2957 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags));
2958 }
2959 }
2960
2961 // Attempt to avoid multi-use ops if we don't need anything from them.
2963 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2964 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2965 break;
2966 }
2968 if (VT.isScalableVector())
2969 return false;
2970 [[fallthrough]];
2971 case ISD::ANY_EXTEND: {
2972 SDValue Src = Op.getOperand(0);
2973 EVT SrcVT = Src.getValueType();
2974 unsigned InBits = SrcVT.getScalarSizeInBits();
2975 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2976 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2977
2978 // If we only need the bottom element then we can just bitcast.
2979 // TODO: Handle ANY_EXTEND?
2980 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2981 VT.getSizeInBits() == SrcVT.getSizeInBits())
2982 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2983
2984 APInt InDemandedBits = DemandedBits.trunc(InBits);
2985 APInt InDemandedElts = DemandedElts.zext(InElts);
2986 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2987 Depth + 1))
2988 return true;
2989 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2990 Known = Known.anyext(BitWidth);
2991
2992 // Attempt to avoid multi-use ops if we don't need anything from them.
2994 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2995 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2996 break;
2997 }
2998 case ISD::TRUNCATE: {
2999 SDValue Src = Op.getOperand(0);
3000
3001 // Simplify the input, using demanded bit information, and compute the known
3002 // zero/one bits live out.
3003 unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
3004 APInt TruncMask = DemandedBits.zext(OperandBitWidth);
3005 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
3006 Depth + 1)) {
3007 // Disable the nsw and nuw flags. We can no longer guarantee that we
3008 // won't wrap after simplification.
3009 Op->dropFlags(SDNodeFlags::NoWrap);
3010 return true;
3011 }
3012 Known = Known.trunc(BitWidth);
3013
3014 // Attempt to avoid multi-use ops if we don't need anything from them.
3016 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
3017 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
3018
3019 // If the input is only used by this truncate, see if we can shrink it based
3020 // on the known demanded bits.
3021 switch (Src.getOpcode()) {
3022 default:
3023 break;
3024 case ISD::SRL:
3025 // Shrink SRL by a constant if none of the high bits shifted in are
3026 // demanded.
3027 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
3028 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
3029 // undesirable.
3030 break;
3031
3032 if (Src.getNode()->hasOneUse()) {
3033 if (isTruncateFree(Src, VT) &&
3034 !isTruncateFree(Src.getValueType(), VT)) {
3035 // If truncate is only free at trunc(srl), do not turn it into
3036 // srl(trunc). The check is done by first check the truncate is free
3037 // at Src's opcode(srl), then check the truncate is not done by
3038 // referencing sub-register. In test, if both trunc(srl) and
3039 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only
3040 // trunc(srl)'s trunc is free, trunc(srl) is better.
3041 break;
3042 }
3043
3044 std::optional<unsigned> ShAmtC =
3045 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2);
3046 if (!ShAmtC || *ShAmtC >= BitWidth)
3047 break;
3048 unsigned ShVal = *ShAmtC;
3049
3050 APInt HighBits =
3051 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
3052 HighBits.lshrInPlace(ShVal);
3053 HighBits = HighBits.trunc(BitWidth);
3054 if (!(HighBits & DemandedBits)) {
3055 // None of the shifted in bits are needed. Add a truncate of the
3056 // shift input, then shift it.
3057 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
3058 SDValue NewTrunc =
3059 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
3060 return TLO.CombineTo(
3061 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
3062 }
3063 }
3064 break;
3065 }
3066
3067 break;
3068 }
3069 case ISD::AssertZext: {
3070 // AssertZext demands all of the high bits, plus any of the low bits
3071 // demanded by its users.
3072 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3074 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
3075 TLO, Depth + 1))
3076 return true;
3077
3078 Known.Zero |= ~InMask;
3079 Known.One &= (~Known.Zero);
3080 break;
3081 }
3083 SDValue Src = Op.getOperand(0);
3084 SDValue Idx = Op.getOperand(1);
3085 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
3086 unsigned EltBitWidth = Src.getScalarValueSizeInBits();
3087
3088 if (SrcEltCnt.isScalable())
3089 return false;
3090
3091 // Demand the bits from every vector element without a constant index.
3092 unsigned NumSrcElts = SrcEltCnt.getFixedValue();
3093 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3094 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
3095 if (CIdx->getAPIntValue().ult(NumSrcElts))
3096 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
3097
3098 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3099 // anything about the extended bits.
3100 APInt DemandedSrcBits = DemandedBits;
3101 if (BitWidth > EltBitWidth)
3102 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
3103
3104 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
3105 Depth + 1))
3106 return true;
3107
3108 // Attempt to avoid multi-use ops if we don't need anything from them.
3109 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
3110 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
3111 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
3112 SDValue NewOp =
3113 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
3114 return TLO.CombineTo(Op, NewOp);
3115 }
3116 }
3117
3118 Known = Known2;
3119 if (BitWidth > EltBitWidth)
3120 Known = Known.anyext(BitWidth);
3121 break;
3122 }
3123 case ISD::BITCAST: {
3124 if (VT.isScalableVector())
3125 return false;
3126 SDValue Src = Op.getOperand(0);
3127 EVT SrcVT = Src.getValueType();
3128 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
3129
3130 // If this is an FP->Int bitcast and if the sign bit is the only
3131 // thing demanded, turn this into a FGETSIGN.
3132 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
3133 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
3134 SrcVT.isFloatingPoint()) {
3136 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
3137 // place. We expect the SHL to be eliminated by other optimizations.
3138 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, VT, Src);
3139 unsigned ShVal = Op.getValueSizeInBits() - 1;
3140 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
3141 return TLO.CombineTo(Op,
3142 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
3143 }
3144 }
3145
3146 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
3147 // Demand the elt/bit if any of the original elts/bits are demanded.
3148 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
3149 unsigned Scale = BitWidth / NumSrcEltBits;
3150 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3151 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
3152 for (unsigned i = 0; i != Scale; ++i) {
3153 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
3154 unsigned BitOffset = EltOffset * NumSrcEltBits;
3155 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
3156 }
3157 // Recursive calls below may turn not demanded elements into poison, so we
3158 // need to demand all smaller source elements that maps to a demanded
3159 // destination element.
3160 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3161
3162 APInt KnownSrcUndef, KnownSrcZero;
3163 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
3164 KnownSrcZero, TLO, Depth + 1))
3165 return true;
3166
3167 KnownBits KnownSrcBits;
3168 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
3169 KnownSrcBits, TLO, Depth + 1))
3170 return true;
3171 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
3172 // TODO - bigendian once we have test coverage.
3173 unsigned Scale = NumSrcEltBits / BitWidth;
3174 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
3175 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
3176 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
3177 for (unsigned i = 0; i != NumElts; ++i)
3178 if (DemandedElts[i]) {
3179 unsigned Offset = (i % Scale) * BitWidth;
3180 DemandedSrcBits.insertBits(DemandedBits, Offset);
3181 DemandedSrcElts.setBit(i / Scale);
3182 }
3183
3184 if (SrcVT.isVector()) {
3185 APInt KnownSrcUndef, KnownSrcZero;
3186 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
3187 KnownSrcZero, TLO, Depth + 1))
3188 return true;
3189 }
3190
3191 KnownBits KnownSrcBits;
3192 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
3193 KnownSrcBits, TLO, Depth + 1))
3194 return true;
3195
3196 // Attempt to avoid multi-use ops if we don't need anything from them.
3197 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
3198 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
3199 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
3200 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
3201 return TLO.CombineTo(Op, NewOp);
3202 }
3203 }
3204 }
3205
3206 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
3207 // recursive call where Known may be useful to the caller.
3208 if (Depth > 0) {
3209 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3210 return false;
3211 }
3212 break;
3213 }
3214 case ISD::MUL:
3215 if (DemandedBits.isPowerOf2()) {
3216 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
3217 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
3218 // odd (has LSB set), then the left-shifted low bit of X is the answer.
3219 unsigned CTZ = DemandedBits.countr_zero();
3220 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
3221 if (C && C->getAPIntValue().countr_zero() == CTZ) {
3222 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl);
3223 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
3224 return TLO.CombineTo(Op, Shl);
3225 }
3226 }
3227 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
3228 // X * X is odd iff X is odd.
3229 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
3230 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
3231 SDValue One = TLO.DAG.getConstant(1, dl, VT);
3232 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
3233 return TLO.CombineTo(Op, And1);
3234 }
3235 [[fallthrough]];
3236 case ISD::PTRADD:
3237 if (Op.getOperand(0).getValueType() != Op.getOperand(1).getValueType())
3238 break;
3239 // PTRADD behaves like ADD if pointers are represented as integers.
3240 [[fallthrough]];
3241 case ISD::ADD:
3242 case ISD::SUB: {
3243 // Add, Sub, and Mul don't demand any bits in positions beyond that
3244 // of the highest bit demanded of them.
3245 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
3246 SDNodeFlags Flags = Op.getNode()->getFlags();
3247 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
3248 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
3249 KnownBits KnownOp0, KnownOp1;
3250 auto GetDemandedBitsLHSMask = [&](APInt Demanded,
3251 const KnownBits &KnownRHS) {
3252 if (Op.getOpcode() == ISD::MUL)
3253 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros());
3254 return Demanded;
3255 };
3256 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
3257 Depth + 1) ||
3258 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1),
3259 DemandedElts, KnownOp0, TLO, Depth + 1) ||
3260 // See if the operation should be performed at a smaller bit width.
3262 // Disable the nsw and nuw flags. We can no longer guarantee that we
3263 // won't wrap after simplification.
3264 Op->dropFlags(SDNodeFlags::NoWrap);
3265 return true;
3266 }
3267
3268 // neg x with only low bit demanded is simply x.
3269 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
3270 isNullConstant(Op0))
3271 return TLO.CombineTo(Op, Op1);
3272
3273 // Attempt to avoid multi-use ops if we don't need anything from them.
3274 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
3276 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3278 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3279 if (DemandedOp0 || DemandedOp1) {
3280 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
3281 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
3282 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
3283 Flags & ~SDNodeFlags::NoWrap);
3284 return TLO.CombineTo(Op, NewOp);
3285 }
3286 }
3287
3288 // If we have a constant operand, we may be able to turn it into -1 if we
3289 // do not demand the high bits. This can make the constant smaller to
3290 // encode, allow more general folding, or match specialized instruction
3291 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
3292 // is probably not useful (and could be detrimental).
3294 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
3295 if (C && !C->isAllOnes() && !C->isOne() &&
3296 (C->getAPIntValue() | HighMask).isAllOnes()) {
3297 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
3298 // Disable the nsw and nuw flags. We can no longer guarantee that we
3299 // won't wrap after simplification.
3300 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1,
3301 Flags & ~SDNodeFlags::NoWrap);
3302 return TLO.CombineTo(Op, NewOp);
3303 }
3304
3305 // Match a multiply with a disguised negated-power-of-2 and convert to a
3306 // an equivalent shift-left amount.
3307 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3308 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
3309 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
3310 return 0;
3311
3312 // Don't touch opaque constants. Also, ignore zero and power-of-2
3313 // multiplies. Those will get folded later.
3314 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
3315 if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
3316 !MulC->getAPIntValue().isPowerOf2()) {
3317 APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
3318 if (UnmaskedC.isNegatedPowerOf2())
3319 return (-UnmaskedC).logBase2();
3320 }
3321 return 0;
3322 };
3323
3324 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y,
3325 unsigned ShlAmt) {
3326 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl);
3327 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
3328 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
3329 return TLO.CombineTo(Op, Res);
3330 };
3331
3333 if (Op.getOpcode() == ISD::ADD) {
3334 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3335 if (unsigned ShAmt = getShiftLeftAmt(Op0))
3336 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
3337 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
3338 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3339 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
3340 }
3341 if (Op.getOpcode() == ISD::SUB) {
3342 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
3343 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3344 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
3345 }
3346 }
3347
3348 if (Op.getOpcode() == ISD::MUL) {
3349 Known = KnownBits::mul(KnownOp0, KnownOp1);
3350 } else { // Op.getOpcode() is either ISD::ADD, ISD::PTRADD, or ISD::SUB.
3352 Op.getOpcode() != ISD::SUB, Flags.hasNoSignedWrap(),
3353 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1);
3354 }
3355 break;
3356 }
3357 case ISD::FABS: {
3358 SDValue Op0 = Op.getOperand(0);
3359 EVT SVT = Op0.getValueType();
3360
3361 // The position of the sign bit for ppc_fp128 is endian-dependent.
3362 if (!APFloat::hasSignBitInMSB(SVT.getFltSemantics()) || SVT == MVT::ppcf128)
3363 break;
3364
3365 APInt SignMask = APInt::getSignMask(BitWidth);
3366 if (!DemandedBits.intersects(SignMask))
3367 return TLO.CombineTo(Op, Op0);
3368
3369 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3370 Depth + 1))
3371 return true;
3372
3373 if (Known.isNonNegative())
3374 return TLO.CombineTo(Op, Op0);
3375 if (Known.isNegative())
3376 return TLO.CombineTo(
3377 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT, Op0, Op->getFlags()));
3378
3379 Known.Zero |= SignMask;
3380 Known.One &= ~SignMask;
3381
3382 break;
3383 }
3384 case ISD::FCOPYSIGN: {
3385 SDValue Op0 = Op.getOperand(0);
3386 SDValue Op1 = Op.getOperand(1);
3387
3388 unsigned BitWidth0 = Op0.getScalarValueSizeInBits();
3389 unsigned BitWidth1 = Op1.getScalarValueSizeInBits();
3390 APInt SignMask0 = APInt::getSignMask(BitWidth0);
3391 APInt SignMask1 = APInt::getSignMask(BitWidth1);
3392
3393 if (!DemandedBits.intersects(SignMask0))
3394 return TLO.CombineTo(Op, Op0);
3395
3396 if (SimplifyDemandedBits(Op0, ~SignMask0 & DemandedBits, DemandedElts,
3397 Known, TLO, Depth + 1) ||
3398 SimplifyDemandedBits(Op1, SignMask1, DemandedElts, Known2, TLO,
3399 Depth + 1))
3400 return true;
3401
3402 if (Known2.isNonNegative())
3403 return TLO.CombineTo(
3404 Op, TLO.DAG.getNode(ISD::FABS, dl, VT, Op0, Op->getFlags()));
3405
3406 if (Known2.isNegative())
3407 return TLO.CombineTo(
3408 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT,
3409 TLO.DAG.getNode(ISD::FABS, SDLoc(Op0), VT, Op0)));
3410
3411 Known.Zero &= ~SignMask0;
3412 Known.One &= ~SignMask0;
3413 break;
3414 }
3415 case ISD::FNEG: {
3416 SDValue Op0 = Op.getOperand(0);
3417 EVT SVT = Op0.getValueType();
3418
3419 // The logic below assumes the sign bit is in the MSB.
3420 // ppc_fp128 has two sign bits (at bits 127 and 63).
3421 if (!APFloat::hasSignBitInMSB(SVT.getFltSemantics()) || SVT == MVT::ppcf128)
3422 break;
3423
3424 APInt SignMask = APInt::getSignMask(BitWidth);
3425
3426 if (!DemandedBits.intersects(SignMask))
3427 return TLO.CombineTo(Op, Op0);
3428
3429 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3430 Depth + 1))
3431 return true;
3432
3433 if (!Known.isSignUnknown()) {
3434 Known.Zero ^= SignMask;
3435 Known.One ^= SignMask;
3436 }
3437
3438 break;
3439 }
3440 default:
3441 // We also ask the target about intrinsics (which could be specific to it).
3442 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3443 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
3444 // TODO: Probably okay to remove after audit; here to reduce change size
3445 // in initial enablement patch for scalable vectors
3446 if (Op.getValueType().isScalableVector())
3447 break;
3449 Known, TLO, Depth))
3450 return true;
3451 break;
3452 }
3453
3454 // Just use computeKnownBits to compute output bits.
3455 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3456 break;
3457 }
3458
3459 // If we know the value of all of the demanded bits, return this as a
3460 // constant.
3462 DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
3463 // Avoid folding to a constant if any OpaqueConstant is involved.
3464 if (llvm::any_of(Op->ops(), [](SDValue V) {
3465 auto *C = dyn_cast<ConstantSDNode>(V);
3466 return C && C->isOpaque();
3467 }))
3468 return false;
3469 if (VT.isInteger())
3470 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
3471 if (VT.isFloatingPoint())
3472 return TLO.CombineTo(
3474 dl, VT));
3475 }
3476
3477 // A multi use 'all demanded elts' simplify failed to find any knownbits.
3478 // Try again just for the original demanded elts.
3479 // Ensure we do this AFTER constant folding above.
3480 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
3481 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
3482
3483 return false;
3484}
3485
3487 const APInt &DemandedElts,
3488 DAGCombinerInfo &DCI) const {
3489 SelectionDAG &DAG = DCI.DAG;
3490 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3491 !DCI.isBeforeLegalizeOps());
3492
3493 APInt KnownUndef, KnownZero;
3494 bool Simplified =
3495 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
3496 if (Simplified) {
3497 DCI.AddToWorklist(Op.getNode());
3498 DCI.CommitTargetLoweringOpt(TLO);
3499 }
3500
3501 return Simplified;
3502}
3503
3504/// Given a vector binary operation and known undefined elements for each input
3505/// operand, compute whether each element of the output is undefined.
3507 const APInt &UndefOp0,
3508 const APInt &UndefOp1) {
3509 EVT VT = BO.getValueType();
3511 "Vector binop only");
3512
3513 EVT EltVT = VT.getVectorElementType();
3514 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
3515 assert(UndefOp0.getBitWidth() == NumElts &&
3516 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
3517
3518 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
3519 const APInt &UndefVals) {
3520 if (UndefVals[Index])
3521 return DAG.getUNDEF(EltVT);
3522
3523 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
3524 // Try hard to make sure that the getNode() call is not creating temporary
3525 // nodes. Ignore opaque integers because they do not constant fold.
3526 SDValue Elt = BV->getOperand(Index);
3527 auto *C = dyn_cast<ConstantSDNode>(Elt);
3528 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
3529 return Elt;
3530 }
3531
3532 return SDValue();
3533 };
3534
3535 APInt KnownUndef = APInt::getZero(NumElts);
3536 for (unsigned i = 0; i != NumElts; ++i) {
3537 // If both inputs for this element are either constant or undef and match
3538 // the element type, compute the constant/undef result for this element of
3539 // the vector.
3540 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
3541 // not handle FP constants. The code within getNode() should be refactored
3542 // to avoid the danger of creating a bogus temporary node here.
3543 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
3544 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
3545 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
3546 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
3547 KnownUndef.setBit(i);
3548 }
3549 return KnownUndef;
3550}
3551
3553 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3554 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3555 bool AssumeSingleUse) const {
3556 EVT VT = Op.getValueType();
3557 unsigned Opcode = Op.getOpcode();
3558 APInt DemandedElts = OriginalDemandedElts;
3559 unsigned NumElts = DemandedElts.getBitWidth();
3560 assert(VT.isVector() && "Expected vector op");
3561
3562 KnownUndef = KnownZero = APInt::getZero(NumElts);
3563
3565 return false;
3566
3567 // TODO: For now we assume we know nothing about scalable vectors.
3568 if (VT.isScalableVector())
3569 return false;
3570
3571 assert(VT.getVectorNumElements() == NumElts &&
3572 "Mask size mismatches value type element count!");
3573
3574 // Undef operand.
3575 if (Op.isUndef()) {
3576 KnownUndef.setAllBits();
3577 return false;
3578 }
3579
3580 // If Op has other users, assume that all elements are needed.
3581 if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3582 DemandedElts.setAllBits();
3583
3584 // Not demanding any elements from Op.
3585 if (DemandedElts == 0) {
3586 KnownUndef.setAllBits();
3587 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3588 }
3589
3590 // Limit search depth.
3592 return false;
3593
3594 SDLoc DL(Op);
3595 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3596 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3597
3598 auto TryShrinkBinOp = [&](SDValue Op0, SDValue Op1) {
3599 unsigned ShrunkSize = getPreferredShrunkVectorSizeInBits(Op, DemandedElts);
3600 if (!ShrunkSize)
3601 return false;
3602
3603 assert(ShrunkSize % EltSizeInBits == 0 &&
3604 "Shrunk size not a multiple of element size");
3605 assert(ShrunkSize < VT.getSizeInBits() &&
3606 "Shrunk size must be < original vector size");
3607 assert(ShrunkSize >= EltSizeInBits * DemandedElts.getActiveBits() &&
3608 "Shrunk size must be >= demanded size");
3609
3610 EVT ShrunkVT = VT.changeVectorElementCount(
3611 *TLO.DAG.getContext(),
3612 ElementCount::getFixed(ShrunkSize / EltSizeInBits));
3613 Op0 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op0, 0);
3614 Op1 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op1, 0);
3615 SDValue NewOp =
3616 TLO.DAG.getNode(Opcode, DL, ShrunkVT, Op0, Op1, Op->getFlags());
3617 return TLO.CombineTo(
3618 Op, TLO.DAG.getInsertSubvector(DL, TLO.DAG.getUNDEF(VT), NewOp, 0));
3619 };
3620
3621 // Helper for demanding the specified elements and all the bits of both binary
3622 // operands.
3623 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3624 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3625 TLO.DAG, Depth + 1);
3626 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3627 TLO.DAG, Depth + 1);
3628 if (NewOp0 || NewOp1) {
3629 SDValue NewOp =
3630 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3631 NewOp1 ? NewOp1 : Op1, Op->getFlags());
3632 return TLO.CombineTo(Op, NewOp);
3633 }
3634
3635 if (TryShrinkBinOp(Op0, Op1))
3636 return true;
3637
3638 return false;
3639 };
3640
3641 switch (Opcode) {
3642 case ISD::SCALAR_TO_VECTOR: {
3643 if (!DemandedElts[0])
3644 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
3645 // Upper elements are poison, not undef - don't mark them as KnownUndef.
3646 break;
3647 }
3648 case ISD::BITCAST: {
3649 SDValue Src = Op.getOperand(0);
3650 EVT SrcVT = Src.getValueType();
3651
3652 if (!SrcVT.isVector()) {
3653 // TODO - bigendian once we have test coverage.
3654 if (IsLE) {
3655 APInt DemandedSrcBits = APInt::getZero(SrcVT.getSizeInBits());
3656 unsigned EltSize = VT.getScalarSizeInBits();
3657 for (unsigned I = 0; I != NumElts; ++I) {
3658 if (DemandedElts[I]) {
3659 unsigned Offset = I * EltSize;
3660 DemandedSrcBits.setBits(Offset, Offset + EltSize);
3661 }
3662 }
3664 if (SimplifyDemandedBits(Src, DemandedSrcBits, Known, TLO, Depth + 1))
3665 return true;
3666 }
3667 break;
3668 }
3669
3670 // Fast handling of 'identity' bitcasts.
3671 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3672 if (NumSrcElts == NumElts)
3673 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3674 KnownZero, TLO, Depth + 1);
3675
3676 APInt SrcDemandedElts, SrcZero, SrcUndef;
3677
3678 // Bitcast from 'large element' src vector to 'small element' vector, we
3679 // must demand a source element if any DemandedElt maps to it.
3680 if ((NumElts % NumSrcElts) == 0) {
3681 unsigned Scale = NumElts / NumSrcElts;
3682 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3683 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3684 TLO, Depth + 1))
3685 return true;
3686
3687 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3688 // of the large element.
3689 // TODO - bigendian once we have test coverage.
3690 if (IsLE) {
3691 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3692 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3693 for (unsigned i = 0; i != NumElts; ++i)
3694 if (DemandedElts[i]) {
3695 unsigned Ofs = (i % Scale) * EltSizeInBits;
3696 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3697 }
3698
3700 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3701 TLO, Depth + 1))
3702 return true;
3703
3704 // The bitcast has split each wide element into a number of
3705 // narrow subelements. We have just computed the Known bits
3706 // for wide elements. See if element splitting results in
3707 // some subelements being zero. Only for demanded elements!
3708 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3709 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3710 .isAllOnes())
3711 continue;
3712 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3713 unsigned Elt = Scale * SrcElt + SubElt;
3714 // A wholly-undef source lane is reported as undef below; don't also
3715 // flag it as zero, keeping the undef and zero sets disjoint.
3716 if (DemandedElts[Elt] && !SrcUndef[SrcElt])
3717 KnownZero.setBit(Elt);
3718 }
3719 }
3720 }
3721
3722 // If the src element is zero/undef then all the output elements will be -
3723 // only demanded elements are guaranteed to be correct.
3724 for (unsigned i = 0; i != NumSrcElts; ++i) {
3725 if (SrcDemandedElts[i]) {
3726 if (SrcZero[i])
3727 KnownZero.setBits(i * Scale, (i + 1) * Scale);
3728 if (SrcUndef[i])
3729 KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3730 }
3731 }
3732 }
3733
3734 // Bitcast from 'small element' src vector to 'large element' vector, we
3735 // demand all smaller source elements covered by the larger demanded element
3736 // of this vector.
3737 if ((NumSrcElts % NumElts) == 0) {
3738 unsigned Scale = NumSrcElts / NumElts;
3739 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3740 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3741 TLO, Depth + 1))
3742 return true;
3743
3744 // If all the src elements covering an output element are zero/undef, then
3745 // the output element will be as well, assuming it was demanded.
3746 for (unsigned i = 0; i != NumElts; ++i) {
3747 if (DemandedElts[i]) {
3748 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3749 KnownZero.setBit(i);
3750 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3751 KnownUndef.setBit(i);
3752 }
3753 }
3754 }
3755 break;
3756 }
3757 case ISD::FREEZE: {
3758 SDValue N0 = Op.getOperand(0);
3760 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
3761 return TLO.CombineTo(Op, N0);
3762
3763 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE
3764 // freeze(op(x, ...)) -> op(freeze(x), ...).
3765 // Don't sink the freeze below SCALAR_TO_VECTOR when the scalar is a load
3766 // of a promoted (wider than the element) type: freeze(load) can never be
3767 // folded away (the loaded value may be poison in memory), and the extra
3768 // freeze node then blocks ISel patterns matching scalar_to_vector of a
3769 // load, e.g. the AArch64 scalar_to_vector(extload) -> ldr b/h forms.
3770 // freeze(scalar_to_vector(load)) is equivalent for the demanded element
3771 // zero, and ISel selects the freeze as a plain copy.
3772 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) {
3773 SDValue Scalar = N0.getOperand(0);
3774 bool IsPromotedLoad = Scalar.getOpcode() == ISD::LOAD &&
3775 Scalar.getValueType() != VT.getVectorElementType();
3776 if (!IsPromotedLoad)
3777 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
3778 TLO.DAG.getFreeze(Scalar)));
3779 }
3780 break;
3781 }
3782 case ISD::BUILD_VECTOR: {
3783 // Check all elements and simplify any unused elements with UNDEF.
3784 if (!DemandedElts.isAllOnes()) {
3785 // Don't simplify BROADCASTS.
3786 if (llvm::any_of(Op->op_values(),
3787 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3789 bool Updated = false;
3790 for (unsigned i = 0; i != NumElts; ++i) {
3791 if (!DemandedElts[i] && !Ops[i].isUndef()) {
3792 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3793 KnownUndef.setBit(i);
3794 Updated = true;
3795 }
3796 }
3797 if (Updated)
3798 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3799 }
3800 }
3801 for (unsigned i = 0; i != NumElts; ++i) {
3802 SDValue SrcOp = Op.getOperand(i);
3803 if (SrcOp.isUndef()) {
3804 KnownUndef.setBit(i);
3805 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3807 KnownZero.setBit(i);
3808 }
3809 }
3810 break;
3811 }
3812 case ISD::CONCAT_VECTORS: {
3813 EVT SubVT = Op.getOperand(0).getValueType();
3814 unsigned NumSubVecs = Op.getNumOperands();
3815 unsigned NumSubElts = SubVT.getVectorNumElements();
3816 for (unsigned i = 0; i != NumSubVecs; ++i) {
3817 SDValue SubOp = Op.getOperand(i);
3818 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3819 APInt SubUndef, SubZero;
3820 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3821 Depth + 1))
3822 return true;
3823 KnownUndef.insertBits(SubUndef, i * NumSubElts);
3824 KnownZero.insertBits(SubZero, i * NumSubElts);
3825 }
3826
3827 // Attempt to avoid multi-use ops if we don't need anything from them.
3828 if (!DemandedElts.isAllOnes()) {
3829 bool FoundNewSub = false;
3830 SmallVector<SDValue, 2> DemandedSubOps;
3831 for (unsigned i = 0; i != NumSubVecs; ++i) {
3832 SDValue SubOp = Op.getOperand(i);
3833 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3835 SubOp, SubElts, TLO.DAG, Depth + 1);
3836 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3837 FoundNewSub = NewSubOp ? true : FoundNewSub;
3838 }
3839 if (FoundNewSub) {
3840 SDValue NewOp =
3841 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3842 return TLO.CombineTo(Op, NewOp);
3843 }
3844 }
3845 break;
3846 }
3847 case ISD::INSERT_SUBVECTOR: {
3848 // Demand any elements from the subvector and the remainder from the src it
3849 // is inserted into.
3850 SDValue Src = Op.getOperand(0);
3851 SDValue Sub = Op.getOperand(1);
3852 uint64_t Idx = Op.getConstantOperandVal(2);
3853 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3854 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3855 APInt DemandedSrcElts = DemandedElts;
3856 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3857
3858 // If none of the sub operand elements are demanded, bypass the insert.
3859 if (!DemandedSubElts)
3860 return TLO.CombineTo(Op, Src);
3861
3862 APInt SubUndef, SubZero;
3863 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3864 Depth + 1))
3865 return true;
3866
3867 // If none of the src operand elements are demanded, replace it with undef.
3868 if (!DemandedSrcElts && !Src.isUndef())
3869 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3870 TLO.DAG.getUNDEF(VT), Sub,
3871 Op.getOperand(2)));
3872
3873 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3874 TLO, Depth + 1))
3875 return true;
3876 KnownUndef.insertBits(SubUndef, Idx);
3877 KnownZero.insertBits(SubZero, Idx);
3878
3879 // Attempt to avoid multi-use ops if we don't need anything from them.
3880 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3882 Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3884 Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3885 if (NewSrc || NewSub) {
3886 NewSrc = NewSrc ? NewSrc : Src;
3887 NewSub = NewSub ? NewSub : Sub;
3888 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3889 NewSub, Op.getOperand(2));
3890 return TLO.CombineTo(Op, NewOp);
3891 }
3892 }
3893 break;
3894 }
3896 // Offset the demanded elts by the subvector index.
3897 SDValue Src = Op.getOperand(0);
3898 if (Src.getValueType().isScalableVector())
3899 break;
3900 uint64_t Idx = Op.getConstantOperandVal(1);
3901 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3902 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3903
3904 APInt SrcUndef, SrcZero;
3905 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3906 Depth + 1))
3907 return true;
3908 KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3909 KnownZero = SrcZero.extractBits(NumElts, Idx);
3910
3911 // Attempt to avoid multi-use ops if we don't need anything from them.
3912 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(Src, DemandedSrcElts,
3913 TLO.DAG, Depth + 1);
3914 if (NewSrc) {
3915 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3916 Op.getOperand(1));
3917 return TLO.CombineTo(Op, NewOp);
3918 }
3919 break;
3920 }
3922 SDValue Vec = Op.getOperand(0);
3923 SDValue Scl = Op.getOperand(1);
3924 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3925
3926 // For a legal, constant insertion index, if we don't need this insertion
3927 // then strip it, else remove it from the demanded elts.
3928 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3929 unsigned Idx = CIdx->getZExtValue();
3930 if (!DemandedElts[Idx])
3931 return TLO.CombineTo(Op, Vec);
3932
3933 APInt DemandedVecElts(DemandedElts);
3934 DemandedVecElts.clearBit(Idx);
3935 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3936 KnownZero, TLO, Depth + 1))
3937 return true;
3938
3939 KnownUndef.setBitVal(Idx, Scl.isUndef());
3940
3941 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3942 break;
3943 }
3944
3945 APInt VecUndef, VecZero;
3946 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3947 Depth + 1))
3948 return true;
3949 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3950 break;
3951 }
3952 case ISD::VSELECT: {
3953 SDValue Sel = Op.getOperand(0);
3954 SDValue LHS = Op.getOperand(1);
3955 SDValue RHS = Op.getOperand(2);
3956
3957 // Try to transform the select condition based on the current demanded
3958 // elements.
3959 APInt UndefSel, ZeroSel;
3960 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3961 Depth + 1))
3962 return true;
3963
3964 // See if we can simplify either vselect operand.
3965 APInt DemandedLHS(DemandedElts);
3966 APInt DemandedRHS(DemandedElts);
3967 APInt UndefLHS, ZeroLHS;
3968 APInt UndefRHS, ZeroRHS;
3969 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3970 Depth + 1))
3971 return true;
3972 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3973 Depth + 1))
3974 return true;
3975
3976 KnownUndef = UndefLHS & UndefRHS;
3977 KnownZero = ZeroLHS & ZeroRHS;
3978
3979 // FIXME: If we know that the selected element is always zero, we don't
3980 // need the select value element. However, we must not make any of the
3981 // originally demanded condition elements more poisonous, as
3982 // vselect(poison, 0, 0) is poison.
3983 break;
3984 }
3985 case ISD::VECTOR_SHUFFLE: {
3986 SDValue LHS = Op.getOperand(0);
3987 SDValue RHS = Op.getOperand(1);
3988 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3989
3990 // Collect demanded elements from shuffle operands..
3991 APInt DemandedLHS(NumElts, 0);
3992 APInt DemandedRHS(NumElts, 0);
3993 for (unsigned i = 0; i != NumElts; ++i) {
3994 int M = ShuffleMask[i];
3995 if (M < 0 || !DemandedElts[i])
3996 continue;
3997 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3998 if (M < (int)NumElts)
3999 DemandedLHS.setBit(M);
4000 else
4001 DemandedRHS.setBit(M - NumElts);
4002 }
4003
4004 // If either side isn't demanded, replace it by UNDEF. We handle this
4005 // explicitly here to also simplify in case of multiple uses (on the
4006 // contrary to the SimplifyDemandedVectorElts calls below).
4007 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
4008 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
4009 if (FoldLHS || FoldRHS) {
4010 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
4011 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
4012 SDValue NewOp =
4013 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
4014 return TLO.CombineTo(Op, NewOp);
4015 }
4016
4017 // See if we can simplify either shuffle operand.
4018 APInt UndefLHS, ZeroLHS;
4019 APInt UndefRHS, ZeroRHS;
4020 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
4021 Depth + 1))
4022 return true;
4023 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
4024 Depth + 1))
4025 return true;
4026
4027 // Simplify mask using undef elements from LHS/RHS.
4028 bool Updated = false;
4029 bool IdentityLHS = true, IdentityRHS = true;
4030 SmallVector<int, 32> NewMask(ShuffleMask);
4031 for (unsigned i = 0; i != NumElts; ++i) {
4032 int &M = NewMask[i];
4033 if (M < 0)
4034 continue;
4035 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
4036 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
4037 Updated = true;
4038 M = -1;
4039 }
4040 IdentityLHS &= (M < 0) || (M == (int)i);
4041 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
4042 }
4043
4044 // Update legal shuffle masks based on demanded elements if it won't reduce
4045 // to Identity which can cause premature removal of the shuffle mask.
4046 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
4047 SDValue LegalShuffle =
4048 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
4049 if (LegalShuffle)
4050 return TLO.CombineTo(Op, LegalShuffle);
4051 }
4052
4053 // Propagate undef/zero elements from LHS/RHS.
4054 for (unsigned i = 0; i != NumElts; ++i) {
4055 int M = ShuffleMask[i];
4056 if (M < 0) {
4057 KnownUndef.setBit(i);
4058 } else if (M < (int)NumElts) {
4059 if (UndefLHS[M])
4060 KnownUndef.setBit(i);
4061 if (ZeroLHS[M])
4062 KnownZero.setBit(i);
4063 } else {
4064 if (UndefRHS[M - NumElts])
4065 KnownUndef.setBit(i);
4066 if (ZeroRHS[M - NumElts])
4067 KnownZero.setBit(i);
4068 }
4069 }
4070 break;
4071 }
4073 SDValue Src = Op.getOperand(0);
4074 SDValue Mask = Op.getOperand(1);
4075
4076 // Result element i only depends on mask element i, so the elements required
4077 // from the mask are the same as the demanded result elements.
4078 APInt DemandedMask = DemandedElts;
4079 APInt UndefMask, ZeroMask;
4080 if (!DemandedMask.isAllOnes() &&
4081 SimplifyDemandedVectorElts(Mask, DemandedMask, UndefMask, ZeroMask, TLO,
4082 Depth + 1))
4083 return true;
4084
4085 // Only those source elements are required which are indexed by the demanded
4086 // elements of the mask. So source elements that are not in the range
4087 // specified by the following are not required.
4089 Mask, DemandedMask, /*ForSigned=*/false, Depth + 1);
4090 // Indexes >= NumElts produce poison, so they don't require any source
4091 // elements.
4092 unsigned Lo = KnownRange.getUnsignedMin().getLimitedValue(NumElts);
4093 unsigned Hi = KnownRange.getUnsignedMax().getLimitedValue(NumElts - 1) + 1;
4094
4095 APInt DemandedSrc = APInt::getBitsSet(NumElts, Lo, Hi);
4096 APInt UndefSrc, ZeroSrc;
4097 if (!DemandedSrc.isAllOnes() &&
4098 SimplifyDemandedVectorElts(Src, DemandedSrc, UndefSrc, ZeroSrc, TLO,
4099 Depth + 1))
4100 return true;
4101
4102 break;
4103 }
4107 APInt SrcUndef, SrcZero;
4108 SDValue Src = Op.getOperand(0);
4109 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4110 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
4111 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
4112 Depth + 1))
4113 return true;
4114 KnownZero = SrcZero.zextOrTrunc(NumElts);
4115 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
4116
4117 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
4118 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
4119 DemandedSrcElts == 1) {
4120 // aext - if we just need the bottom element then we can bitcast.
4121 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
4122 }
4123
4124 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
4125 // zext(undef) upper bits are guaranteed to be zero.
4126 if (DemandedElts.isSubsetOf(KnownUndef))
4127 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4128 KnownUndef.clearAllBits();
4129
4130 // zext - if we just need the bottom element then we can mask:
4131 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
4132 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
4133 Op->isOnlyUserOf(Src.getNode()) &&
4134 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
4135 SDLoc DL(Op);
4136 EVT SrcVT = Src.getValueType();
4137 EVT SrcSVT = SrcVT.getScalarType();
4138
4139 // If we're after type legalization and SrcSVT is not legal, use the
4140 // promoted type for creating constants to avoid creating nodes with
4141 // illegal types.
4142 if (TLO.LegalTypes())
4143 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
4144
4145 SmallVector<SDValue> MaskElts;
4146 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
4147 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
4148 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
4149 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
4150 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
4151 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
4152 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
4153 }
4154 }
4155 }
4156 break;
4157 }
4158
4159 // TODO: There are more binop opcodes that could be handled here - MIN,
4160 // MAX, saturated math, etc.
4161 case ISD::ADD: {
4162 SDValue Op0 = Op.getOperand(0);
4163 SDValue Op1 = Op.getOperand(1);
4164 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
4165 APInt UndefLHS, ZeroLHS;
4166 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4167 Depth + 1, /*AssumeSingleUse*/ true))
4168 return true;
4169 }
4170 [[fallthrough]];
4171 }
4172 case ISD::AVGCEILS:
4173 case ISD::AVGCEILU:
4174 case ISD::AVGFLOORS:
4175 case ISD::AVGFLOORU:
4176 case ISD::AVGSUBFLOORS:
4177 case ISD::AVGSUBFLOORU:
4178 case ISD::OR:
4179 case ISD::XOR:
4180 case ISD::SUB:
4181 case ISD::FADD:
4182 case ISD::FSUB:
4183 case ISD::FMUL:
4184 case ISD::FDIV:
4185 case ISD::FREM:
4186 case ISD::PSEUDO_FMIN:
4187 case ISD::PSEUDO_FMAX: {
4188 SDValue Op0 = Op.getOperand(0);
4189 SDValue Op1 = Op.getOperand(1);
4190
4191 APInt UndefRHS, ZeroRHS;
4192 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4193 Depth + 1))
4194 return true;
4195 APInt UndefLHS, ZeroLHS;
4196 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4197 Depth + 1))
4198 return true;
4199
4200 // 0.0 / 0.0 and frem(0.0, 0.0) are NaN, not zero.
4201 if (Opcode != ISD::FDIV && Opcode != ISD::FREM)
4202 KnownZero = ZeroLHS & ZeroRHS;
4203 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
4204
4205 // Attempt to avoid multi-use ops if we don't need anything from them.
4206 // TODO - use KnownUndef to relax the demandedelts?
4207 if (!DemandedElts.isAllOnes())
4208 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4209 return true;
4210 break;
4211 }
4212 case ISD::SHL:
4213 case ISD::SRL:
4214 case ISD::SRA:
4215 case ISD::ROTL:
4216 case ISD::ROTR: {
4217 SDValue Op0 = Op.getOperand(0);
4218 SDValue Op1 = Op.getOperand(1);
4219
4220 APInt UndefRHS, ZeroRHS;
4221 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4222 Depth + 1))
4223 return true;
4224 APInt UndefLHS, ZeroLHS;
4225 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4226 Depth + 1))
4227 return true;
4228
4229 KnownZero = ZeroLHS & ~UndefRHS;
4230 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
4231
4232 // Attempt to avoid multi-use ops if we don't need anything from them.
4233 // TODO - use KnownUndef to relax the demandedelts?
4234 if (!DemandedElts.isAllOnes())
4235 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4236 return true;
4237 break;
4238 }
4239 case ISD::MUL:
4240 case ISD::MULHU:
4241 case ISD::MULHS:
4242 case ISD::AND: {
4243 SDValue Op0 = Op.getOperand(0);
4244 SDValue Op1 = Op.getOperand(1);
4245
4246 APInt SrcUndef, SrcZero;
4247 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
4248 Depth + 1))
4249 return true;
4250 // FIXME: If we know that a demanded element was zero in Op1 we don't need
4251 // to demand it in Op0 - its guaranteed to be zero. There is however a
4252 // restriction, as we must not make any of the originally demanded elements
4253 // more poisonous. We could reduce amount of elements demanded, but then we
4254 // also need a to inform SimplifyDemandedVectorElts that some elements must
4255 // not be made more poisonous.
4256 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
4257 TLO, Depth + 1))
4258 return true;
4259
4260 KnownUndef &= DemandedElts;
4261 KnownZero &= DemandedElts;
4262
4263 // If every element pair has a zero/undef/poison then just fold to zero.
4264 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
4265 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
4266 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
4267 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4268
4269 // If either side has a zero element, then the result element is zero, even
4270 // if the other is an UNDEF.
4271 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
4272 // and then handle 'and' nodes with the rest of the binop opcodes.
4273 KnownZero |= SrcZero;
4274 KnownUndef &= SrcUndef;
4275 KnownUndef &= ~KnownZero;
4276
4277 // Attempt to avoid multi-use ops if we don't need anything from them.
4278 if (!DemandedElts.isAllOnes())
4279 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4280 return true;
4281 break;
4282 }
4283 case ISD::TRUNCATE:
4284 case ISD::SIGN_EXTEND:
4285 case ISD::ZERO_EXTEND:
4286 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4287 KnownZero, TLO, Depth + 1))
4288 return true;
4289
4290 if (!DemandedElts.isAllOnes())
4292 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
4293 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
4294
4295 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
4296 // zext(undef) upper bits are guaranteed to be zero.
4297 if (DemandedElts.isSubsetOf(KnownUndef))
4298 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4299 KnownUndef.clearAllBits();
4300 }
4301 break;
4302 case ISD::SINT_TO_FP:
4303 case ISD::UINT_TO_FP:
4304 case ISD::FP_TO_SINT:
4305 case ISD::FP_TO_UINT:
4306 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4307 KnownZero, TLO, Depth + 1))
4308 return true;
4309 // Don't fall through to generic undef -> undef handling.
4310 return false;
4311 default: {
4312 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
4313 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
4314 KnownZero, TLO, Depth))
4315 return true;
4316 } else {
4318 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
4319 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
4320 TLO, Depth, AssumeSingleUse))
4321 return true;
4322 }
4323 break;
4324 }
4325 }
4326
4327 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
4328
4329 // Constant fold all undef cases.
4330 // TODO: Handle zero cases as well.
4331 if (DemandedElts.isSubsetOf(KnownUndef))
4332 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
4333
4334 return false;
4335}
4336
4337/// Determine which of the bits specified in Mask are known to be either zero or
4338/// one and return them in the Known.
4341 const APInt &DemandedElts,
4342 const SelectionDAG &DAG,
4343 unsigned Depth) const {
4344 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4345 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4346 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4347 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4348 "Should use MaskedValueIsZero if you don't know whether Op"
4349 " is a target node!");
4350 Known.resetAll();
4351}
4352
4355 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4356 unsigned Depth) const {
4357 Known.resetAll();
4358}
4359
4362 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4363 unsigned Depth) const {
4364 Known.resetAll();
4365}
4366
4368 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4369 // The low bits are known zero if the pointer is aligned.
4370 Known.Zero.setLowBits(Log2(Alignment));
4371}
4372
4374 SelectionDAG &DAG,
4375 const SDLoc &DL,
4376 Align Alignment) const {
4377 // Materialize leading-zero stack object pointer facts as AssertZext.
4378 // Alignment-derived low zero bits are not represented on the returned DAG
4379 // value here.
4380 EVT PtrVT = Ptr.getValueType();
4381
4382 unsigned RegSize = PtrVT.getScalarSizeInBits();
4385 Alignment);
4386
4387 unsigned NumZeroBits = Known.countMinLeadingZeros();
4388 if (!NumZeroBits)
4389 return Ptr;
4390
4391 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4392 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4393}
4394
4400
4401/// This method can be implemented by targets that want to expose additional
4402/// information about sign bits to the DAG Combiner.
4404 const APInt &,
4405 const SelectionDAG &,
4406 unsigned Depth) const {
4407 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4408 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4409 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4410 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4411 "Should use ComputeNumSignBits if you don't know whether Op"
4412 " is a target node!");
4413 return 1;
4414}
4415
4417 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4418 const MachineRegisterInfo &MRI, unsigned Depth) const {
4419 return 1;
4420}
4421
4423 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4424 TargetLoweringOpt &TLO, unsigned Depth) const {
4425 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4426 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4427 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4428 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4429 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4430 " is a target node!");
4431 return false;
4432}
4433
4435 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4436 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4437 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4438 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4439 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4440 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4441 "Should use SimplifyDemandedBits if you don't know whether Op"
4442 " is a target node!");
4443 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4444 return false;
4445}
4446
4448 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4449 SelectionDAG &DAG, unsigned Depth) const {
4450 assert(
4451 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4452 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4453 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4454 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4455 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4456 " is a target node!");
4457 return SDValue();
4458}
4459
4460SDValue
4463 SelectionDAG &DAG) const {
4464 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4465 if (!LegalMask) {
4466 std::swap(N0, N1);
4468 LegalMask = isShuffleMaskLegal(Mask, VT);
4469 }
4470
4471 if (!LegalMask)
4472 return SDValue();
4473
4474 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4475}
4476
4478 return nullptr;
4479}
4480
4482 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4483 UndefPoisonKind Kind, unsigned Depth) const {
4484 assert(
4485 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4486 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4487 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4488 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4489 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4490 " is a target node!");
4491
4492 // If Op can't create undef/poison and none of its operands are undef/poison
4493 // then Op is never undef/poison.
4494 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4495 /*ConsiderFlags*/ true, Depth) &&
4496 all_of(Op->ops(), [&](SDValue V) {
4497 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4498 });
4499}
4500
4502 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4503 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4504 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4505 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4506 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4507 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4508 "Should use canCreateUndefOrPoison if you don't know whether Op"
4509 " is a target node!");
4510 // Be conservative and return true.
4511 return true;
4512}
4513
4516 const APInt &DemandedElts,
4517 const SelectionDAG &DAG,
4518 unsigned Depth) const {
4519 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4520 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4521 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4522 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4523 "Should use computeKnownFPClass if you don't know whether Op"
4524 " is a target node!");
4525}
4526
4528 const APInt &DemandedElts,
4529 const SelectionDAG &DAG,
4530 bool SNaN,
4531 unsigned Depth) const {
4532 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4533 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4534 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4535 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4536 "Should use isKnownNeverNaN if you don't know whether Op"
4537 " is a target node!");
4538 return false;
4539}
4540
4542 const APInt &DemandedElts,
4543 APInt &UndefElts,
4544 const SelectionDAG &DAG,
4545 unsigned Depth) const {
4546 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4547 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4548 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4549 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4550 "Should use isSplatValue if you don't know whether Op"
4551 " is a target node!");
4552 return false;
4553}
4554
4555// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4556// work with truncating build vectors and vectors with elements of less than
4557// 8 bits.
4559 if (!N)
4560 return false;
4561
4562 unsigned EltWidth;
4563 APInt CVal;
4564 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4565 /*AllowTruncation=*/true)) {
4566 CVal = CN->getAPIntValue();
4567 EltWidth = N.getValueType().getScalarSizeInBits();
4568 } else
4569 return false;
4570
4571 // If this is a truncating splat, truncate the splat value.
4572 // Otherwise, we may fail to match the expected values below.
4573 if (EltWidth < CVal.getBitWidth())
4574 CVal = CVal.trunc(EltWidth);
4575
4576 switch (getBooleanContents(N.getValueType())) {
4578 return CVal[0];
4580 return CVal.isOne();
4582 return CVal.isAllOnes();
4583 }
4584
4585 llvm_unreachable("Invalid boolean contents");
4586}
4587
4589 if (!N)
4590 return false;
4591
4593 if (!CN) {
4595 if (!BV)
4596 return false;
4597
4598 // Only interested in constant splats, we don't care about undef
4599 // elements in identifying boolean constants and getConstantSplatNode
4600 // returns NULL if all ops are undef;
4601 CN = BV->getConstantSplatNode();
4602 if (!CN)
4603 return false;
4604 }
4605
4606 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4607 return !CN->getAPIntValue()[0];
4608
4609 return CN->isZero();
4610}
4611
4613 bool SExt) const {
4614 if (VT == MVT::i1)
4615 return N->isOne();
4616
4618 switch (Cnt) {
4620 // An extended value of 1 is always true, unless its original type is i1,
4621 // in which case it will be sign extended to -1.
4622 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4625 return N->isAllOnes() && SExt;
4626 }
4627 llvm_unreachable("Unexpected enumeration.");
4628}
4629
4630/// This helper function of SimplifySetCC tries to optimize the comparison when
4631/// either operand of the SetCC node is a bitwise-and instruction.
4632SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4633 ISD::CondCode Cond, const SDLoc &DL,
4634 DAGCombinerInfo &DCI) const {
4635 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4636 std::swap(N0, N1);
4637
4638 SelectionDAG &DAG = DCI.DAG;
4639 EVT OpVT = N0.getValueType();
4640 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4641 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4642 return SDValue();
4643
4644 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4645 // iff everything but LSB is known zero:
4646 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4649 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4650 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4651 if (DAG.MaskedValueIsZero(N0, UpperBits))
4652 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4653 }
4654
4655 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4656 // test in a narrow type that we can truncate to with no cost. Examples:
4657 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4658 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4659 // TODO: This conservatively checks for type legality on the source and
4660 // destination types. That may inhibit optimizations, but it also
4661 // allows setcc->shift transforms that may be more beneficial.
4662 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4663 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4664 isTypeLegal(OpVT) && N0.hasOneUse()) {
4665 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4666 AndC->getAPIntValue().getActiveBits());
4667 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4668 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4669 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4670 return DAG.getSetCC(DL, VT, Trunc, Zero,
4672 }
4673 }
4674
4675 // Match these patterns in any of their permutations:
4676 // (X & Y) == Y
4677 // (X & Y) != Y
4678 SDValue X, Y;
4679 if (N0.getOperand(0) == N1) {
4680 X = N0.getOperand(1);
4681 Y = N0.getOperand(0);
4682 } else if (N0.getOperand(1) == N1) {
4683 X = N0.getOperand(0);
4684 Y = N0.getOperand(1);
4685 } else {
4686 return SDValue();
4687 }
4688
4689 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4690 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4691 // its liable to create and infinite loop.
4692 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4693 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4695 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4696 // Note that where Y is variable and is known to have at most one bit set
4697 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4698 // equivalent when Y == 0.
4699 assert(OpVT.isInteger());
4701 if (DCI.isBeforeLegalizeOps() ||
4703 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4704 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4705 // If the target supports an 'and-not' or 'and-complement' logic operation,
4706 // try to use that to make a comparison operation more efficient.
4707 // But don't do this transform if the mask is a single bit because there are
4708 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4709 // 'rlwinm' on PPC).
4710
4711 // Bail out if the compare operand that we want to turn into a zero is
4712 // already a zero (otherwise, infinite loop).
4713 if (isNullConstant(Y))
4714 return SDValue();
4715
4716 // Transform this into: ~X & Y == 0.
4717 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4718 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4719 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4720 }
4721
4722 return SDValue();
4723}
4724
4725/// This helper function of SimplifySetCC tries to optimize the comparison when
4726/// either operand of the SetCC node is a bitwise-or instruction.
4727/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4728SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4729 ISD::CondCode Cond, const SDLoc &DL,
4730 DAGCombinerInfo &DCI) const {
4731 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4732 std::swap(N0, N1);
4733
4734 SelectionDAG &DAG = DCI.DAG;
4735 EVT OpVT = N0.getValueType();
4736 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4737 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4738 return SDValue();
4739
4740 // (X | Y) == Y
4741 // (X | Y) != Y
4742 SDValue X;
4743 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4744 // If the target supports an 'and-not' or 'and-complement' logic operation,
4745 // try to use that to make a comparison operation more efficient.
4746
4747 // Bail out if the compare operand that we want to turn into a zero is
4748 // already a zero (otherwise, infinite loop).
4749 if (isNullConstant(N1))
4750 return SDValue();
4751
4752 // Transform this into: X & ~Y ==/!= 0.
4753 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4754 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4755 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4756 }
4757
4758 return SDValue();
4759}
4760
4761/// There are multiple IR patterns that could be checking whether certain
4762/// truncation of a signed number would be lossy or not. The pattern which is
4763/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4764/// We are looking for the following pattern: (KeptBits is a constant)
4765/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4766/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4767/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4768/// We will unfold it into the natural trunc+sext pattern:
4769/// ((%x << C) a>> C) dstcond %x
4770/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4771SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4772 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4773 const SDLoc &DL) const {
4774 // We must be comparing with a constant.
4775 ConstantSDNode *C1;
4776 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4777 return SDValue();
4778
4779 // N0 should be: add %x, (1 << (KeptBits-1))
4780 if (N0->getOpcode() != ISD::ADD)
4781 return SDValue();
4782
4783 // And we must be 'add'ing a constant.
4784 ConstantSDNode *C01;
4785 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4786 return SDValue();
4787
4788 SDValue X = N0->getOperand(0);
4789 EVT XVT = X.getValueType();
4790
4791 // Validate constants ...
4792
4793 APInt I1 = C1->getAPIntValue();
4794
4795 ISD::CondCode NewCond;
4796 if (Cond == ISD::CondCode::SETULT) {
4797 NewCond = ISD::CondCode::SETEQ;
4798 } else if (Cond == ISD::CondCode::SETULE) {
4799 NewCond = ISD::CondCode::SETEQ;
4800 // But need to 'canonicalize' the constant.
4801 I1 += 1;
4802 } else if (Cond == ISD::CondCode::SETUGT) {
4803 NewCond = ISD::CondCode::SETNE;
4804 // But need to 'canonicalize' the constant.
4805 I1 += 1;
4806 } else if (Cond == ISD::CondCode::SETUGE) {
4807 NewCond = ISD::CondCode::SETNE;
4808 } else
4809 return SDValue();
4810
4811 APInt I01 = C01->getAPIntValue();
4812
4813 auto checkConstants = [&I1, &I01]() -> bool {
4814 // Both of them must be power-of-two, and the constant from setcc is bigger.
4815 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4816 };
4817
4818 if (checkConstants()) {
4819 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4820 } else {
4821 // What if we invert constants? (and the target predicate)
4822 I1.negate();
4823 I01.negate();
4824 assert(XVT.isInteger());
4825 NewCond = getSetCCInverse(NewCond, XVT);
4826 if (!checkConstants())
4827 return SDValue();
4828 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4829 }
4830
4831 // They are power-of-two, so which bit is set?
4832 const unsigned KeptBits = I1.logBase2();
4833 const unsigned KeptBitsMinusOne = I01.logBase2();
4834
4835 // Magic!
4836 if (KeptBits != (KeptBitsMinusOne + 1))
4837 return SDValue();
4838 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4839
4840 // We don't want to do this in every single case.
4841 SelectionDAG &DAG = DCI.DAG;
4842 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4843 return SDValue();
4844
4845 // Unfold into: sext_inreg(%x) cond %x
4846 // Where 'cond' will be either 'eq' or 'ne'.
4847 SDValue SExtInReg = DAG.getNode(
4849 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4850 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4851}
4852
4853// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4854SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4855 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4856 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4858 "Should be a comparison with 0.");
4859 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4860 "Valid only for [in]equality comparisons.");
4861
4862 unsigned NewShiftOpcode;
4863 SDValue X, C, Y;
4864
4865 SelectionDAG &DAG = DCI.DAG;
4866
4867 // Look for '(C l>>/<< Y)'.
4868 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4869 // The shift should be one-use.
4870 if (!V.hasOneUse())
4871 return false;
4872 unsigned OldShiftOpcode = V.getOpcode();
4873 switch (OldShiftOpcode) {
4874 case ISD::SHL:
4875 NewShiftOpcode = ISD::SRL;
4876 break;
4877 case ISD::SRL:
4878 NewShiftOpcode = ISD::SHL;
4879 break;
4880 default:
4881 return false; // must be a logical shift.
4882 }
4883 // We should be shifting a constant.
4884 // FIXME: best to use isConstantOrConstantVector().
4885 C = V.getOperand(0);
4886 ConstantSDNode *CC =
4887 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4888 if (!CC)
4889 return false;
4890 Y = V.getOperand(1);
4891
4892 ConstantSDNode *XC =
4893 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4895 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4896 };
4897
4898 // LHS of comparison should be an one-use 'and'.
4899 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4900 return SDValue();
4901
4902 X = N0.getOperand(0);
4903 SDValue Mask = N0.getOperand(1);
4904
4905 // 'and' is commutative!
4906 if (!Match(Mask)) {
4907 std::swap(X, Mask);
4908 if (!Match(Mask))
4909 return SDValue();
4910 }
4911
4912 EVT VT = X.getValueType();
4913
4914 // Produce:
4915 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4916 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4917 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4918 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4919 return T2;
4920}
4921
4922/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4923/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4924/// handle the commuted versions of these patterns.
4925SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4926 ISD::CondCode Cond, const SDLoc &DL,
4927 DAGCombinerInfo &DCI) const {
4928 unsigned BOpcode = N0.getOpcode();
4929 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4930 "Unexpected binop");
4931 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4932
4933 // (X + Y) == X --> Y == 0
4934 // (X - Y) == X --> Y == 0
4935 // (X ^ Y) == X --> Y == 0
4936 SelectionDAG &DAG = DCI.DAG;
4937 EVT OpVT = N0.getValueType();
4938 SDValue X = N0.getOperand(0);
4939 SDValue Y = N0.getOperand(1);
4940 if (X == N1)
4941 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4942
4943 if (Y != N1)
4944 return SDValue();
4945
4946 // (X + Y) == Y --> X == 0
4947 // (X ^ Y) == Y --> X == 0
4948 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4949 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4950
4951 // The shift would not be valid if the operands are boolean (i1).
4952 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4953 return SDValue();
4954
4955 // (X - Y) == Y --> X == Y << 1
4956 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4957 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4958 if (!DCI.isCalledByLegalizer())
4959 DCI.AddToWorklist(YShl1.getNode());
4960 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4961}
4962
4964 SDValue N0, const APInt &C1,
4965 ISD::CondCode Cond, const SDLoc &dl,
4966 SelectionDAG &DAG) {
4967 // Look through truncs that don't change the value of a ctpop.
4968 // FIXME: Add vector support? Need to be careful with setcc result type below.
4969 SDValue CTPOP = N0;
4970 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4972 CTPOP = N0.getOperand(0);
4973
4974 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4975 return SDValue();
4976
4977 EVT CTVT = CTPOP.getValueType();
4978 SDValue CTOp = CTPOP.getOperand(0);
4979
4980 // Expand a power-of-2-or-zero comparison based on ctpop:
4981 // (ctpop x) u< 2 -> (x & x-1) == 0
4982 // (ctpop x) u> 1 -> (x & x-1) != 0
4983 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4984 // Keep the CTPOP if it is a cheap vector op.
4985 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4986 return SDValue();
4987
4988 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4989 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4990 return SDValue();
4991 if (C1 == 0 && (Cond == ISD::SETULT))
4992 return SDValue(); // This is handled elsewhere.
4993
4994 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4995
4996 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4997 SDValue Result = CTOp;
4998 for (unsigned i = 0; i < Passes; i++) {
4999 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
5000 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
5001 }
5003 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
5004 }
5005
5006 // Expand a power-of-2 comparison based on ctpop
5007 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
5008 // Keep the CTPOP if it is cheap.
5009 if (TLI.isCtpopFast(CTVT))
5010 return SDValue();
5011
5012 SDValue Zero = DAG.getConstant(0, dl, CTVT);
5013 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
5014 assert(CTVT.isInteger());
5015 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
5016
5017 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
5018 // check before emitting a potentially unnecessary op.
5019 if (DAG.isKnownNeverZero(CTOp)) {
5020 // (ctpop x) == 1 --> (x & x-1) == 0
5021 // (ctpop x) != 1 --> (x & x-1) != 0
5022 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
5023 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
5024 return RHS;
5025 }
5026
5027 // (ctpop x) == 1 --> (x ^ x-1) > x-1
5028 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
5029 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
5031 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
5032 }
5033
5034 return SDValue();
5035}
5036
5038 ISD::CondCode Cond, const SDLoc &dl,
5039 SelectionDAG &DAG) {
5040 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
5041 return SDValue();
5042
5043 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
5044 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
5045 return SDValue();
5046
5047 auto getRotateSource = [](SDValue X) {
5048 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
5049 return X.getOperand(0);
5050 return SDValue();
5051 };
5052
5053 // Peek through a rotated value compared against 0 or -1:
5054 // (rot X, Y) == 0/-1 --> X == 0/-1
5055 // (rot X, Y) != 0/-1 --> X != 0/-1
5056 if (SDValue R = getRotateSource(N0))
5057 return DAG.getSetCC(dl, VT, R, N1, Cond);
5058
5059 // Peek through an 'or' of a rotated value compared against 0:
5060 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
5061 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
5062 //
5063 // TODO: Add the 'and' with -1 sibling.
5064 // TODO: Recurse through a series of 'or' ops to find the rotate.
5065 EVT OpVT = N0.getValueType();
5066 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
5067 if (SDValue R = getRotateSource(N0.getOperand(0))) {
5068 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
5069 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5070 }
5071 if (SDValue R = getRotateSource(N0.getOperand(1))) {
5072 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
5073 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5074 }
5075 }
5076
5077 return SDValue();
5078}
5079
5081 ISD::CondCode Cond, const SDLoc &dl,
5082 SelectionDAG &DAG) {
5083 // If we are testing for all-bits-clear, we might be able to do that with
5084 // less shifting since bit-order does not matter.
5085 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
5086 return SDValue();
5087
5088 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
5089 if (!C1 || !C1->isZero())
5090 return SDValue();
5091
5092 if (!N0.hasOneUse() ||
5093 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
5094 return SDValue();
5095
5096 unsigned BitWidth = N0.getScalarValueSizeInBits();
5097 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
5098 if (!ShAmtC)
5099 return SDValue();
5100
5101 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
5102 if (ShAmt == 0)
5103 return SDValue();
5104
5105 // Canonicalize fshr as fshl to reduce pattern-matching.
5106 if (N0.getOpcode() == ISD::FSHR)
5107 ShAmt = BitWidth - ShAmt;
5108
5109 // Match an 'or' with a specific operand 'Other' in either commuted variant.
5110 SDValue X, Y;
5111 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
5112 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
5113 return false;
5114 if (Or.getOperand(0) == Other) {
5115 X = Or.getOperand(0);
5116 Y = Or.getOperand(1);
5117 return true;
5118 }
5119 if (Or.getOperand(1) == Other) {
5120 X = Or.getOperand(1);
5121 Y = Or.getOperand(0);
5122 return true;
5123 }
5124 return false;
5125 };
5126
5127 EVT OpVT = N0.getValueType();
5128 EVT ShAmtVT = N0.getOperand(2).getValueType();
5129 SDValue F0 = N0.getOperand(0);
5130 SDValue F1 = N0.getOperand(1);
5131 if (matchOr(F0, F1)) {
5132 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
5133 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
5134 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
5135 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
5136 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5137 }
5138 if (matchOr(F1, F0)) {
5139 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
5140 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
5141 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
5142 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
5143 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5144 }
5145
5146 return SDValue();
5147}
5148
5149/// Try to simplify a setcc built with the specified operands and cc. If it is
5150/// unable to simplify it, return a null SDValue.
5152 ISD::CondCode Cond, bool foldBooleans,
5153 DAGCombinerInfo &DCI,
5154 const SDLoc &dl) const {
5155 SelectionDAG &DAG = DCI.DAG;
5156 const DataLayout &Layout = DAG.getDataLayout();
5157 EVT OpVT = N0.getValueType();
5159
5160 // Constant fold or commute setcc.
5161 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
5162 return Fold;
5163
5164 bool N0ConstOrSplat =
5165 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5166 bool N1ConstOrSplat =
5167 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5168
5169 // Canonicalize toward having the constant on the RHS.
5170 // TODO: Handle non-splat vector constants. All undef causes trouble.
5171 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
5172 // infinite loop here when we encounter one.
5174 if (N0ConstOrSplat && !N1ConstOrSplat &&
5175 (DCI.isBeforeLegalizeOps() ||
5176 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
5177 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5178
5179 // If we have a subtract with the same 2 non-constant operands as this setcc
5180 // -- but in reverse order -- then try to commute the operands of this setcc
5181 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
5182 // instruction on some targets.
5183 if (!N0ConstOrSplat && !N1ConstOrSplat &&
5184 (DCI.isBeforeLegalizeOps() ||
5185 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
5186 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
5187 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
5188 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5189
5190 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
5191 return V;
5192
5193 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
5194 return V;
5195
5196 if (auto *N1C = isConstOrConstSplat(N1)) {
5197 const APInt &C1 = N1C->getAPIntValue();
5198
5199 // Optimize some CTPOP cases.
5200 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
5201 return V;
5202
5203 // For equality to 0 of a no-wrap multiply, decompose and test each op:
5204 // X * Y == 0 --> (X == 0) || (Y == 0)
5205 // X * Y != 0 --> (X != 0) && (Y != 0)
5206 // TODO: This bails out if minsize is set, but if the target doesn't have a
5207 // single instruction multiply for this type, it would likely be
5208 // smaller to decompose.
5209 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5210 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
5211 (N0->getFlags().hasNoUnsignedWrap() ||
5212 N0->getFlags().hasNoSignedWrap()) &&
5213 !Attr.hasFnAttr(Attribute::MinSize)) {
5214 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5215 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
5216 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
5217 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
5218 }
5219
5220 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
5221 // equality comparison, then we're just comparing whether X itself is
5222 // zero.
5223 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
5224 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
5226 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
5227 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5228 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
5229 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
5230 // (srl (ctlz x), 5) == 0 -> X != 0
5231 // (srl (ctlz x), 5) != 1 -> X != 0
5232 Cond = ISD::SETNE;
5233 } else {
5234 // (srl (ctlz x), 5) != 0 -> X == 0
5235 // (srl (ctlz x), 5) == 1 -> X == 0
5236 Cond = ISD::SETEQ;
5237 }
5238 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
5239 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
5240 Cond);
5241 }
5242 }
5243 }
5244 }
5245
5246 // setcc X, 0, setlt --> X (when X is all sign bits)
5247 // setcc X, 0, setne --> X (when X is all sign bits)
5248 //
5249 // When we know that X has 0 or -1 in each element (or scalar), this
5250 // comparison will produce X. This is only true when boolean contents are
5251 // represented via 0s and -1s.
5252 if (VT == OpVT &&
5253 // Check that the result of setcc is 0 and -1.
5255 // Match only for checks X < 0 and X != 0
5256 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
5257 // The identity holds iff we know all sign bits for all lanes.
5259 return N0;
5260
5261 // FIXME: Support vectors.
5262 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5263 const APInt &C1 = N1C->getAPIntValue();
5264
5265 // (zext x) == C --> x == (trunc C)
5266 // (sext x) == C --> x == (trunc C)
5267 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5268 DCI.isBeforeLegalize() && N0->hasOneUse()) {
5269 unsigned MinBits = N0.getValueSizeInBits();
5270 SDValue PreExt;
5271 bool Signed = false;
5272 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
5273 // ZExt
5274 MinBits = N0->getOperand(0).getValueSizeInBits();
5275 PreExt = N0->getOperand(0);
5276 } else if (N0->getOpcode() == ISD::AND) {
5277 // DAGCombine turns costly ZExts into ANDs
5278 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
5279 if ((C->getAPIntValue()+1).isPowerOf2()) {
5280 MinBits = C->getAPIntValue().countr_one();
5281 PreExt = N0->getOperand(0);
5282 }
5283 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
5284 // SExt
5285 MinBits = N0->getOperand(0).getValueSizeInBits();
5286 PreExt = N0->getOperand(0);
5287 Signed = true;
5288 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
5289 // ZEXTLOAD / SEXTLOAD
5290 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
5291 MinBits = LN0->getMemoryVT().getSizeInBits();
5292 PreExt = N0;
5293 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
5294 Signed = true;
5295 MinBits = LN0->getMemoryVT().getSizeInBits();
5296 PreExt = N0;
5297 }
5298 }
5299
5300 // Figure out how many bits we need to preserve this constant.
5301 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
5302
5303 // Make sure we're not losing bits from the constant.
5304 if (MinBits > 0 &&
5305 MinBits < C1.getBitWidth() &&
5306 MinBits >= ReqdBits) {
5307 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
5308 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
5309 // Will get folded away.
5310 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
5311 if (MinBits == 1 && C1 == 1)
5312 // Invert the condition.
5313 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
5315 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
5316 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
5317 }
5318
5319 // If truncating the setcc operands is not desirable, we can still
5320 // simplify the expression in some cases:
5321 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
5322 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
5323 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
5324 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
5325 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
5326 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
5327 SDValue TopSetCC = N0->getOperand(0);
5328 unsigned N0Opc = N0->getOpcode();
5329 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
5330 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
5331 TopSetCC.getOpcode() == ISD::SETCC &&
5332 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
5333 (isConstFalseVal(N1) ||
5334 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
5335
5336 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
5337 (!N1C->isZero() && Cond == ISD::SETNE);
5338
5339 if (!Inverse)
5340 return TopSetCC;
5341
5342 ISD::CondCode InvCond =
5344 TopSetCC.getOperand(0).getValueType());
5345 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
5346 TopSetCC.getOperand(1), InvCond);
5347 }
5348 }
5349 }
5350
5351 // If the LHS is '(and load, const)', the RHS is 0, the test is for
5352 // equality or unsigned, and all 1 bits of the const are in the same
5353 // partial word, see if we can shorten the load.
5354 if (DCI.isBeforeLegalize() &&
5356 N0.getOpcode() == ISD::AND && C1 == 0 &&
5357 N0.getNode()->hasOneUse() &&
5358 isa<LoadSDNode>(N0.getOperand(0)) &&
5359 N0.getOperand(0).getNode()->hasOneUse() &&
5361 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5362 APInt bestMask;
5363 unsigned bestWidth = 0, bestOffset = 0;
5364 if (Lod->isSimple() && Lod->isUnindexed() &&
5365 (Lod->getMemoryVT().isByteSized() ||
5366 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5367 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5368 unsigned origWidth = N0.getValueSizeInBits();
5369 unsigned maskWidth = origWidth;
5370 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5371 // 8 bits, but have to be careful...
5372 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5373 origWidth = Lod->getMemoryVT().getSizeInBits();
5374 const APInt &Mask = N0.getConstantOperandAPInt(1);
5375 // Only consider power-of-2 widths (and at least one byte) as candiates
5376 // for the narrowed load.
5377 for (unsigned width = 8; width < origWidth; width *= 2) {
5378 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5379 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5380 // Avoid accessing any padding here for now (we could use memWidth
5381 // instead of origWidth here otherwise).
5382 unsigned maxOffset = origWidth - width;
5383 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5384 if (Mask.isSubsetOf(newMask)) {
5385 unsigned ptrOffset =
5386 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5387 unsigned IsFast = 0;
5388 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5389 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5391 ptrOffset / 8) &&
5393 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5394 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5395 IsFast) {
5396 bestOffset = ptrOffset / 8;
5397 bestMask = Mask.lshr(offset);
5398 bestWidth = width;
5399 break;
5400 }
5401 }
5402 newMask <<= 8;
5403 }
5404 if (bestWidth)
5405 break;
5406 }
5407 }
5408 if (bestWidth) {
5409 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5410 SDValue Ptr = Lod->getBasePtr();
5411 if (bestOffset != 0)
5412 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5413 SDValue NewLoad =
5414 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5415 Lod->getPointerInfo().getWithOffset(bestOffset),
5416 Lod->getBaseAlign(), MachineMemOperand::MONone,
5417 Lod->getMMOMetadataForSubAccess());
5418 SDValue And =
5419 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5420 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5421 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5422 }
5423 }
5424
5425 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5426 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5427 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5428
5429 // If the comparison constant has bits in the upper part, the
5430 // zero-extended value could never match.
5431 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
5432 C1.getBitWidth() - InSize))) {
5433 switch (Cond) {
5434 case ISD::SETUGT:
5435 case ISD::SETUGE:
5436 case ISD::SETEQ:
5437 return DAG.getConstant(0, dl, VT);
5438 case ISD::SETULT:
5439 case ISD::SETULE:
5440 case ISD::SETNE:
5441 return DAG.getConstant(1, dl, VT);
5442 case ISD::SETGT:
5443 case ISD::SETGE:
5444 // True if the sign bit of C1 is set.
5445 return DAG.getConstant(C1.isNegative(), dl, VT);
5446 case ISD::SETLT:
5447 case ISD::SETLE:
5448 // True if the sign bit of C1 isn't set.
5449 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5450 default:
5451 break;
5452 }
5453 }
5454
5455 // Otherwise, we can perform the comparison with the low bits.
5456 switch (Cond) {
5457 case ISD::SETEQ:
5458 case ISD::SETNE:
5459 case ISD::SETUGT:
5460 case ISD::SETUGE:
5461 case ISD::SETULT:
5462 case ISD::SETULE: {
5463 EVT newVT = N0.getOperand(0).getValueType();
5464 // FIXME: Should use isNarrowingProfitable.
5465 if (DCI.isBeforeLegalizeOps() ||
5466 (isOperationLegal(ISD::SETCC, newVT) &&
5467 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5469 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5470 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5471
5472 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5473 NewConst, Cond);
5474 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5475 }
5476 break;
5477 }
5478 default:
5479 break; // todo, be more careful with signed comparisons
5480 }
5481 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5482 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5484 OpVT)) {
5485 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5486 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5487 EVT ExtDstTy = N0.getValueType();
5488 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5489
5490 // If the constant doesn't fit into the number of bits for the source of
5491 // the sign extension, it is impossible for both sides to be equal.
5492 if (C1.getSignificantBits() > ExtSrcTyBits)
5493 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5494
5495 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5496 ExtDstTy != ExtSrcTy && "Unexpected types!");
5497 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5498 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5499 DAG.getConstant(Imm, dl, ExtDstTy));
5500 if (!DCI.isCalledByLegalizer())
5501 DCI.AddToWorklist(ZextOp.getNode());
5502 // Otherwise, make this a use of a zext.
5503 return DAG.getSetCC(dl, VT, ZextOp,
5504 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5505 } else if ((N1C->isZero() || N1C->isOne()) &&
5506 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5507 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5508 // excluded as they are handled below whilst checking for foldBooleans.
5509 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5510 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5511 (N0.getValueType() == MVT::i1 ||
5515 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5516 if (TrueWhenTrue)
5517 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5518 // Invert the condition.
5519 if (N0.getOpcode() == ISD::SETCC) {
5522 if (DCI.isBeforeLegalizeOps() ||
5524 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5525 }
5526 }
5527
5528 if ((N0.getOpcode() == ISD::XOR ||
5529 (N0.getOpcode() == ISD::AND &&
5530 N0.getOperand(0).getOpcode() == ISD::XOR &&
5531 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5532 isOneConstant(N0.getOperand(1))) {
5533 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5534 // can only do this if the top bits are known zero.
5535 unsigned BitWidth = N0.getValueSizeInBits();
5536 if (DAG.MaskedValueIsZero(N0,
5538 BitWidth-1))) {
5539 // Okay, get the un-inverted input value.
5540 SDValue Val;
5541 if (N0.getOpcode() == ISD::XOR) {
5542 Val = N0.getOperand(0);
5543 } else {
5544 assert(N0.getOpcode() == ISD::AND &&
5545 N0.getOperand(0).getOpcode() == ISD::XOR);
5546 // ((X^1)&1)^1 -> X & 1
5547 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5548 N0.getOperand(0).getOperand(0),
5549 N0.getOperand(1));
5550 }
5551
5552 return DAG.getSetCC(dl, VT, Val, N1,
5554 }
5555 } else if (N1C->isOne()) {
5556 SDValue Op0 = N0;
5557 if (Op0.getOpcode() == ISD::TRUNCATE)
5558 Op0 = Op0.getOperand(0);
5559
5560 if ((Op0.getOpcode() == ISD::XOR) &&
5561 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5562 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5563 SDValue XorLHS = Op0.getOperand(0);
5564 SDValue XorRHS = Op0.getOperand(1);
5565 // Ensure that the input setccs return an i1 type or 0/1 value.
5566 if (Op0.getValueType() == MVT::i1 ||
5571 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5573 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5574 }
5575 }
5576 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5577 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5578 if (Op0.getValueType().bitsGT(VT))
5579 Op0 = DAG.getNode(ISD::AND, dl, VT,
5580 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5581 DAG.getConstant(1, dl, VT));
5582 else if (Op0.getValueType().bitsLT(VT))
5583 Op0 = DAG.getNode(ISD::AND, dl, VT,
5584 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5585 DAG.getConstant(1, dl, VT));
5586
5587 return DAG.getSetCC(dl, VT, Op0,
5588 DAG.getConstant(0, dl, Op0.getValueType()),
5590 }
5591 if (Op0.getOpcode() == ISD::AssertZext &&
5592 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5593 return DAG.getSetCC(dl, VT, Op0,
5594 DAG.getConstant(0, dl, Op0.getValueType()),
5596 }
5597 }
5598
5599 // Given:
5600 // icmp eq/ne (urem %x, %y), 0
5601 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5602 // icmp eq/ne %x, 0
5603 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5604 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5605 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5606 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5607 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5608 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5609 }
5610
5611 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5612 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5613 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5615 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5616 N1C->isAllOnes()) {
5617 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5618 DAG.getConstant(0, dl, OpVT),
5620 }
5621
5622 // fold (setcc (trunc x) c) -> (setcc x c)
5623 if (N0.getOpcode() == ISD::TRUNCATE &&
5625 (N0->getFlags().hasNoSignedWrap() &&
5628 EVT NewVT = N0.getOperand(0).getValueType();
5629 SDValue NewConst = DAG.getConstant(
5631 ? C1.sext(NewVT.getSizeInBits())
5632 : C1.zext(NewVT.getSizeInBits()),
5633 dl, NewVT);
5634 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5635 }
5636
5637 if (SDValue V =
5638 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5639 return V;
5640 }
5641
5642 // These simplifications apply to splat vectors as well.
5643 // TODO: Handle more splat vector cases.
5644 if (auto *N1C = isConstOrConstSplat(N1)) {
5645 const APInt &C1 = N1C->getAPIntValue();
5646
5647 APInt MinVal, MaxVal;
5648 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5650 MinVal = APInt::getSignedMinValue(OperandBitSize);
5651 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5652 } else {
5653 MinVal = APInt::getMinValue(OperandBitSize);
5654 MaxVal = APInt::getMaxValue(OperandBitSize);
5655 }
5656
5657 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5658 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5659 // X >= MIN --> true
5660 if (C1 == MinVal)
5661 return DAG.getBoolConstant(true, dl, VT, OpVT);
5662
5663 if (!VT.isVector()) { // TODO: Support this for vectors.
5664 // X >= C0 --> X > (C0 - 1)
5665 APInt C = C1 - 1;
5667 if ((DCI.isBeforeLegalizeOps() ||
5668 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5669 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5670 isLegalICmpImmediate(C.getSExtValue())))) {
5671 return DAG.getSetCC(dl, VT, N0,
5672 DAG.getConstant(C, dl, N1.getValueType()),
5673 NewCC);
5674 }
5675 }
5676 }
5677
5678 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5679 // X <= MAX --> true
5680 if (C1 == MaxVal)
5681 return DAG.getBoolConstant(true, dl, VT, OpVT);
5682
5683 // X <= C0 --> X < (C0 + 1)
5684 if (!VT.isVector()) { // TODO: Support this for vectors.
5685 APInt C = C1 + 1;
5687 if ((DCI.isBeforeLegalizeOps() ||
5688 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5689 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5690 isLegalICmpImmediate(C.getSExtValue())))) {
5691 return DAG.getSetCC(dl, VT, N0,
5692 DAG.getConstant(C, dl, N1.getValueType()),
5693 NewCC);
5694 }
5695 }
5696 }
5697
5698 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5699 if (C1 == MinVal)
5700 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5701
5702 // TODO: Support this for vectors after legalize ops.
5703 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5704 // Canonicalize setlt X, Max --> setne X, Max
5705 if (C1 == MaxVal)
5706 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5707
5708 // If we have setult X, 1, turn it into seteq X, 0
5709 if (C1 == MinVal+1)
5710 return DAG.getSetCC(dl, VT, N0,
5711 DAG.getConstant(MinVal, dl, N0.getValueType()),
5712 ISD::SETEQ);
5713 }
5714 }
5715
5716 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5717 if (C1 == MaxVal)
5718 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5719
5720 // TODO: Support this for vectors after legalize ops.
5721 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5722 // Canonicalize setgt X, Min --> setne X, Min
5723 if (C1 == MinVal)
5724 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5725
5726 // If we have setugt X, Max-1, turn it into seteq X, Max
5727 if (C1 == MaxVal-1)
5728 return DAG.getSetCC(dl, VT, N0,
5729 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5730 ISD::SETEQ);
5731 }
5732 }
5733
5734 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5735 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5736 if (C1.isZero())
5737 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5738 VT, N0, N1, Cond, DCI, dl))
5739 return CC;
5740
5741 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5742 // For example, when high 32-bits of i64 X are known clear:
5743 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5744 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5745 bool CmpZero = N1C->isZero();
5746 bool CmpNegOne = N1C->isAllOnes();
5747 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5748 // Match or(lo,shl(hi,bw/2)) pattern.
5749 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5750 unsigned EltBits = V.getScalarValueSizeInBits();
5751 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5752 return false;
5753 SDValue LHS = V.getOperand(0);
5754 SDValue RHS = V.getOperand(1);
5755 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5756 // Unshifted element must have zero upperbits.
5757 if (RHS.getOpcode() == ISD::SHL &&
5758 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5759 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5760 DAG.MaskedValueIsZero(LHS, HiBits)) {
5761 Lo = LHS;
5762 Hi = RHS.getOperand(0);
5763 return true;
5764 }
5765 if (LHS.getOpcode() == ISD::SHL &&
5766 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5767 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5768 DAG.MaskedValueIsZero(RHS, HiBits)) {
5769 Lo = RHS;
5770 Hi = LHS.getOperand(0);
5771 return true;
5772 }
5773 return false;
5774 };
5775
5776 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5777 unsigned EltBits = N0.getScalarValueSizeInBits();
5778 unsigned HalfBits = EltBits / 2;
5779 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5780 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5781 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5782 SDValue NewN0 =
5783 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5784 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5785 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5786 };
5787
5788 SDValue Lo, Hi;
5789 if (IsConcat(N0, Lo, Hi))
5790 return MergeConcat(Lo, Hi);
5791
5792 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5793 SDValue Lo0, Lo1, Hi0, Hi1;
5794 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5795 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5796 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5797 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5798 }
5799 }
5800 }
5801 }
5802
5803 // If we have "setcc X, C0", check to see if we can shrink the immediate
5804 // by changing cc.
5805 // TODO: Support this for vectors after legalize ops.
5806 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5807 // SETUGT X, SINTMAX -> SETLT X, 0
5808 // SETUGE X, SINTMIN -> SETLT X, 0
5809 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5810 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5811 return DAG.getSetCC(dl, VT, N0,
5812 DAG.getConstant(0, dl, N1.getValueType()),
5813 ISD::SETLT);
5814
5815 // SETULT X, SINTMIN -> SETGT X, -1
5816 // SETULE X, SINTMAX -> SETGT X, -1
5817 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5818 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5819 return DAG.getSetCC(dl, VT, N0,
5820 DAG.getAllOnesConstant(dl, N1.getValueType()),
5821 ISD::SETGT);
5822 }
5823 }
5824
5825 // Back to non-vector simplifications.
5826 // TODO: Can we do these for vector splats?
5827 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5828 const APInt &C1 = N1C->getAPIntValue();
5829 EVT ShValTy = N0.getValueType();
5830
5831 // Fold bit comparisons when we can. This will result in an
5832 // incorrect value when boolean false is negative one, unless
5833 // the bitsize is 1 in which case the false value is the same
5834 // in practice regardless of the representation.
5835 if ((VT.getSizeInBits() == 1 ||
5837 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5838 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5839 N0.getOpcode() == ISD::AND) {
5840 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5841 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5842 // Perform the xform if the AND RHS is a single bit.
5843 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5844 if (AndRHS->getAPIntValue().isPowerOf2() &&
5845 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5846 return DAG.getNode(
5847 ISD::TRUNCATE, dl, VT,
5848 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5849 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5850 }
5851 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5852 // (X & 8) == 8 --> (X & 8) >> 3
5853 // Perform the xform if C1 is a single bit.
5854 unsigned ShCt = C1.logBase2();
5855 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5856 return DAG.getNode(
5857 ISD::TRUNCATE, dl, VT,
5858 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5859 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5860 }
5861 }
5862 }
5863 }
5864
5865 if (C1.getSignificantBits() <= 64 &&
5866 !isLegalICmpImmediate(C1.getSExtValue())) {
5867 // (X & -256) == 256 -> (X >> 8) == 1
5868 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5869 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5870 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5871 const APInt &AndRHSC = AndRHS->getAPIntValue();
5872 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5873 unsigned ShiftBits = AndRHSC.countr_zero();
5874 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5875 // If using an unsigned shift doesn't yield a legal compare
5876 // immediate, try using sra instead.
5877 APInt NewC = C1.lshr(ShiftBits);
5878 if (NewC.getSignificantBits() <= 64 &&
5880 APInt SignedC = C1.ashr(ShiftBits);
5881 if (SignedC.getSignificantBits() <= 64 &&
5883 SDValue Shift = DAG.getNode(
5884 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5885 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5886 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5887 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5888 }
5889 }
5890 SDValue Shift = DAG.getNode(
5891 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5892 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5893 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5894 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5895 }
5896 }
5897 }
5898 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5899 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5900 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5901 // X < 0x100000000 -> (X >> 32) < 1
5902 // X >= 0x100000000 -> (X >> 32) >= 1
5903 // X <= 0x0ffffffff -> (X >> 32) < 1
5904 // X > 0x0ffffffff -> (X >> 32) >= 1
5905 unsigned ShiftBits;
5906 APInt NewC = C1;
5907 ISD::CondCode NewCond = Cond;
5908 if (AdjOne) {
5909 ShiftBits = C1.countr_one();
5910 NewC = NewC + 1;
5911 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5912 } else {
5913 ShiftBits = C1.countr_zero();
5914 }
5915 APInt RangeWidth = NewC;
5916 NewC.lshrInPlace(ShiftBits);
5917 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5919 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5920 // If this is an offset range check, try to move the offset after the
5921 // shift to avoid preserving the pre-shift add with a mask.
5922 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse()) {
5923 if (auto *AddC = isConstOrConstSplat(N0.getOperand(1))) {
5924 const APInt &AddVal = AddC->getAPIntValue();
5925 if (AddVal.countr_zero() >= ShiftBits) {
5926 APInt RangeLower = -AddVal;
5927 bool Overflow;
5928 (void)RangeLower.uadd_ov(RangeWidth, Overflow);
5929 if (!RangeWidth.isZero() && !Overflow) {
5930 SDValue Shift = DAG.getNode(
5931 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5932 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5933 APInt Offset = -RangeLower.lshr(ShiftBits);
5934 SDValue ShiftedAdd =
5935 DAG.getNode(ISD::ADD, dl, ShValTy, Shift,
5936 DAG.getConstant(Offset, dl, ShValTy));
5937 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5938 return DAG.getSetCC(dl, VT, ShiftedAdd, CmpRHS, NewCond);
5939 }
5940 }
5941 }
5942 }
5943 SDValue Shift =
5944 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5945 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5946 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5947 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5948 }
5949 }
5950 }
5951 }
5952
5954 auto *CFP = cast<ConstantFPSDNode>(N1);
5955 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5956
5957 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5958 // constant if knowing that the operand is non-nan is enough. We prefer to
5959 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5960 // materialize 0.0.
5961 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5962 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5963
5964 // setcc (fneg x), C -> setcc swap(pred) x, -C
5965 if (N0.getOpcode() == ISD::FNEG) {
5967 if (DCI.isBeforeLegalizeOps() ||
5968 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5969 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5970 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5971 }
5972 }
5973
5974 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5976 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5977 bool IsFabs = N0.getOpcode() == ISD::FABS;
5978 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5979 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5980 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5981 : (IsFabs ? fcInf : fcPosInf);
5982 if (Cond == ISD::SETUEQ)
5983 Flag |= fcNan;
5984 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5985 DAG.getTargetConstant(Flag, dl, MVT::i32));
5986 }
5987 }
5988
5989 // If the condition is not legal, see if we can find an equivalent one
5990 // which is legal.
5992 // If the comparison was an awkward floating-point == or != and one of
5993 // the comparison operands is infinity or negative infinity, convert the
5994 // condition to a less-awkward <= or >=.
5995 if (CFP->getValueAPF().isInfinity()) {
5996 bool IsNegInf = CFP->getValueAPF().isNegative();
5998 switch (Cond) {
5999 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
6000 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
6001 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
6002 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
6003 default: break;
6004 }
6005 if (NewCond != ISD::SETCC_INVALID &&
6006 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
6007 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
6008 }
6009 }
6010 }
6011
6012 if (N0 == N1) {
6013 // The sext(setcc()) => setcc() optimization relies on the appropriate
6014 // constant being emitted.
6015 assert(!N0.getValueType().isInteger() &&
6016 "Integer types should be handled by FoldSetCC");
6017
6018 bool EqTrue = ISD::isTrueWhenEqual(Cond);
6019 unsigned UOF = ISD::getUnorderedFlavor(Cond);
6020 if (UOF == 2) // FP operators that are undefined on NaNs.
6021 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
6022 if (UOF == unsigned(EqTrue))
6023 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
6024 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
6025 // if it is not already.
6026 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
6027 if (NewCond != Cond &&
6028 (DCI.isBeforeLegalizeOps() ||
6029 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
6030 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
6031 }
6032
6033 // ~X > ~Y --> Y > X
6034 // ~X < ~Y --> Y < X
6035 // ~X < C --> X > ~C
6036 // ~X > C --> X < ~C
6037 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
6038 N0.getValueType().isInteger()) {
6039 if (isBitwiseNot(N0)) {
6040 if (isBitwiseNot(N1))
6041 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
6042
6045 SDValue Not = DAG.getNOT(dl, N1, OpVT);
6046 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
6047 }
6048 }
6049 }
6050
6051 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6052 N0.getValueType().isInteger()) {
6053 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
6054 N0.getOpcode() == ISD::XOR) {
6055 // Simplify (X+Y) == (X+Z) --> Y == Z
6056 if (N0.getOpcode() == N1.getOpcode()) {
6057 if (N0.getOperand(0) == N1.getOperand(0))
6058 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
6059 if (N0.getOperand(1) == N1.getOperand(1))
6060 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6061 if (isCommutativeBinOp(N0.getOpcode())) {
6062 // If X op Y == Y op X, try other combinations.
6063 if (N0.getOperand(0) == N1.getOperand(1))
6064 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
6065 Cond);
6066 if (N0.getOperand(1) == N1.getOperand(0))
6067 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
6068 Cond);
6069 }
6070 }
6071
6072 // If RHS is a legal immediate value for a compare instruction, we need
6073 // to be careful about increasing register pressure needlessly.
6074 bool LegalRHSImm = false;
6075
6076 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
6077 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6078 // Turn (X+C1) == C2 --> X == C2-C1
6079 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
6080 return DAG.getSetCC(
6081 dl, VT, N0.getOperand(0),
6082 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
6083 dl, N0.getValueType()),
6084 Cond);
6085
6086 // Turn (X^C1) == C2 --> X == C1^C2
6087 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
6088 return DAG.getSetCC(
6089 dl, VT, N0.getOperand(0),
6090 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
6091 dl, N0.getValueType()),
6092 Cond);
6093 }
6094
6095 // Turn (C1-X) == C2 --> X == C1-C2
6096 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
6097 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
6098 return DAG.getSetCC(
6099 dl, VT, N0.getOperand(1),
6100 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
6101 dl, N0.getValueType()),
6102 Cond);
6103
6104 // Could RHSC fold directly into a compare?
6105 if (RHSC->getValueType(0).getSizeInBits() <= 64)
6106 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
6107 }
6108
6109 // (X+Y) == X --> Y == 0 and similar folds.
6110 // Don't do this if X is an immediate that can fold into a cmp
6111 // instruction and X+Y has other uses. It could be an induction variable
6112 // chain, and the transform would increase register pressure.
6113 if (!LegalRHSImm || N0.hasOneUse())
6114 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
6115 return V;
6116 }
6117
6118 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
6119 N1.getOpcode() == ISD::XOR)
6120 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
6121 return V;
6122
6123 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
6124 return V;
6125
6126 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
6127 return V;
6128 }
6129
6130 // Fold remainder of division by a constant.
6131 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
6132 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
6133 // When division is cheap or optimizing for minimum size,
6134 // fall through to DIVREM creation by skipping this fold.
6135 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
6136 if (N0.getOpcode() == ISD::UREM) {
6137 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
6138 return Folded;
6139 } else if (N0.getOpcode() == ISD::SREM) {
6140 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
6141 return Folded;
6142 }
6143 }
6144 }
6145
6146 // Fold away ALL boolean setcc's.
6147 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
6148 SDValue Temp;
6149 switch (Cond) {
6150 default: llvm_unreachable("Unknown integer setcc!");
6151 case ISD::SETEQ: // X == Y -> ~(X^Y)
6152 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
6153 N0 = DAG.getNOT(dl, Temp, OpVT);
6154 if (!DCI.isCalledByLegalizer())
6155 DCI.AddToWorklist(Temp.getNode());
6156 break;
6157 case ISD::SETNE: // X != Y --> (X^Y)
6158 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
6159 break;
6160 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
6161 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
6162 Temp = DAG.getNOT(dl, N0, OpVT);
6163 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
6164 if (!DCI.isCalledByLegalizer())
6165 DCI.AddToWorklist(Temp.getNode());
6166 break;
6167 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
6168 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
6169 Temp = DAG.getNOT(dl, N1, OpVT);
6170 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
6171 if (!DCI.isCalledByLegalizer())
6172 DCI.AddToWorklist(Temp.getNode());
6173 break;
6174 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
6175 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
6176 Temp = DAG.getNOT(dl, N0, OpVT);
6177 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
6178 if (!DCI.isCalledByLegalizer())
6179 DCI.AddToWorklist(Temp.getNode());
6180 break;
6181 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
6182 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
6183 Temp = DAG.getNOT(dl, N1, OpVT);
6184 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
6185 break;
6186 }
6187 if (VT.getScalarType() != MVT::i1) {
6188 if (!DCI.isCalledByLegalizer())
6189 DCI.AddToWorklist(N0.getNode());
6190 // FIXME: If running after legalize, we probably can't do this.
6192 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
6193 }
6194 return N0;
6195 }
6196
6197 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
6198 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
6199 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
6201 N1->getFlags().hasNoUnsignedWrap()) ||
6203 N1->getFlags().hasNoSignedWrap())) &&
6205 if (VT.getScalarType() == MVT::i1)
6206 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6207 // For (legal) non vXi1 cases - ensure we adjust the cmp and result types.
6208 EVT OldCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6209 N0.getValueType());
6210 if (VT == OldCCVT) {
6211 EVT NewCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6212 N0.getOperand(0).getValueType());
6213 return DAG.getBoolExtOrTrunc(
6214 DAG.getSetCC(dl, NewCCVT, N0.getOperand(0), N1.getOperand(0), Cond),
6215 dl, VT, N0.getOperand(0).getValueType());
6216 }
6217 }
6218
6219 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
6220 // TODO: Remove that .isVector() check
6221 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
6223 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
6224 }
6225
6226 // Could not fold it.
6227 return SDValue();
6228}
6229
6230/// Returns true (and the GlobalValue and the offset) if the node is a
6231/// GlobalAddress + offset.
6233 int64_t &Offset) const {
6234
6235 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
6236
6237 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
6238 GA = GASD->getGlobal();
6239 Offset += GASD->getOffset();
6240 return true;
6241 }
6242
6243 if (N->isAnyAdd()) {
6244 SDValue N1 = N->getOperand(0);
6245 SDValue N2 = N->getOperand(1);
6246 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
6247 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
6248 Offset += V->getSExtValue();
6249 return true;
6250 }
6251 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
6252 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
6253 Offset += V->getSExtValue();
6254 return true;
6255 }
6256 }
6257 }
6258
6259 return false;
6260}
6261
6263 DAGCombinerInfo &DCI) const {
6264 // Default implementation: no optimization.
6265 return SDValue();
6266}
6267
6268//===----------------------------------------------------------------------===//
6269// Inline Assembler Implementation Methods
6270//===----------------------------------------------------------------------===//
6271
6274 unsigned S = Constraint.size();
6275
6276 if (S == 1) {
6277 switch (Constraint[0]) {
6278 default: break;
6279 case 'r':
6280 return C_RegisterClass;
6281 case 'm': // memory
6282 case 'o': // offsetable
6283 case 'V': // not offsetable
6284 return C_Memory;
6285 case 'p': // Address.
6286 return C_Address;
6287 case 'n': // Simple Integer
6288 case 'E': // Floating Point Constant
6289 case 'F': // Floating Point Constant
6290 return C_Immediate;
6291 case 'i': // Simple Integer or Relocatable Constant
6292 case 's': // Relocatable Constant
6293 case 'X': // Allow ANY value.
6294 case 'I': // Target registers.
6295 case 'J':
6296 case 'K':
6297 case 'L':
6298 case 'M':
6299 case 'N':
6300 case 'O':
6301 case 'P':
6302 case '<':
6303 case '>':
6304 return C_Other;
6305 }
6306 }
6307
6308 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
6309 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
6310 return C_Memory;
6311 return C_Register;
6312 }
6313 return C_Unknown;
6314}
6315
6316/// Try to replace an X constraint, which matches anything, with another that
6317/// has more specific requirements based on the type of the corresponding
6318/// operand.
6319const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6320 if (ConstraintVT.isInteger())
6321 return "r";
6322 if (ConstraintVT.isFloatingPoint())
6323 return "f"; // works for many targets
6324 return nullptr;
6325}
6326
6328 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
6329 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
6330 return SDValue();
6331}
6332
6333/// Lower the specified operand into the Ops vector.
6334/// If it is invalid, don't add anything to Ops.
6336 StringRef Constraint,
6337 std::vector<SDValue> &Ops,
6338 SelectionDAG &DAG) const {
6339
6340 if (Constraint.size() > 1)
6341 return;
6342
6343 char ConstraintLetter = Constraint[0];
6344 switch (ConstraintLetter) {
6345 default: break;
6346 case 'X': // Allows any operand
6347 case 'i': // Simple Integer or Relocatable Constant
6348 case 'n': // Simple Integer
6349 case 's': { // Relocatable Constant
6350
6352 uint64_t Offset = 0;
6353
6354 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
6355 // etc., since getelementpointer is variadic. We can't use
6356 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
6357 // while in this case the GA may be furthest from the root node which is
6358 // likely an ISD::ADD.
6359 while (true) {
6360 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
6361 // gcc prints these as sign extended. Sign extend value to 64 bits
6362 // now; without this it would get ZExt'd later in
6363 // ScheduleDAGSDNodes::EmitNode, which is very generic.
6364 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
6365 BooleanContent BCont = getBooleanContents(/*isVec=*/false);
6366 ISD::NodeType ExtOpc =
6367 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
6368 int64_t ExtVal =
6369 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
6370 Ops.push_back(
6371 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
6372 return;
6373 }
6374 if (ConstraintLetter != 'n') {
6375 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6376 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6377 GA->getValueType(0),
6378 Offset + GA->getOffset()));
6379 return;
6380 }
6381 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
6382 Ops.push_back(DAG.getTargetBlockAddress(
6383 BA->getBlockAddress(), BA->getValueType(0),
6384 Offset + BA->getOffset(), BA->getTargetFlags()));
6385 return;
6386 }
6388 Ops.push_back(Op);
6389 return;
6390 }
6391 }
6392 const unsigned OpCode = Op.getOpcode();
6393 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6394 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6395 Op = Op.getOperand(1);
6396 // Subtraction is not commutative.
6397 else if (OpCode == ISD::ADD &&
6398 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6399 Op = Op.getOperand(0);
6400 else
6401 return;
6402 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6403 continue;
6404 }
6405 return;
6406 }
6407 break;
6408 }
6409 }
6410}
6411
6415
6416std::pair<unsigned, const TargetRegisterClass *>
6418 StringRef Constraint,
6419 MVT VT) const {
6420 if (!Constraint.starts_with("{"))
6421 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6422 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6423
6424 // Remove the braces from around the name.
6425 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6426
6427 std::pair<unsigned, const TargetRegisterClass *> R =
6428 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6429
6430 // Figure out which register class contains this reg.
6431 for (const TargetRegisterClass &RC : RI->regclasses()) {
6432 // If none of the value types for this register class are valid, we
6433 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6434 if (!isLegalRC(*RI, RC))
6435 continue;
6436
6437 for (const MCPhysReg &PR : RC) {
6438 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6439 std::pair<unsigned, const TargetRegisterClass *> S =
6440 std::make_pair(PR, &RC);
6441
6442 // If this register class has the requested value type, return it,
6443 // otherwise keep searching and return the first class found
6444 // if no other is found which explicitly has the requested type.
6445 if (RI->isTypeLegalForClass(RC, VT))
6446 return S;
6447 if (!R.second)
6448 R = S;
6449 }
6450 }
6451 }
6452
6453 return R;
6454}
6455
6456//===----------------------------------------------------------------------===//
6457// Constraint Selection.
6458
6459/// Return true of this is an input operand that is a matching constraint like
6460/// "4".
6462 assert(!ConstraintCode.empty() && "No known constraint!");
6463 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6464}
6465
6466/// If this is an input matching constraint, this method returns the output
6467/// operand it matches.
6469 assert(!ConstraintCode.empty() && "No known constraint!");
6470 return atoi(ConstraintCode.c_str());
6471}
6472
6473/// Split up the constraint string from the inline assembly value into the
6474/// specific constraints and their prefixes, and also tie in the associated
6475/// operand values.
6476/// If this returns an empty vector, and if the constraint string itself
6477/// isn't empty, there was an error parsing.
6480 const TargetRegisterInfo *TRI,
6481 const CallBase &Call) const {
6482 /// Information about all of the constraints.
6483 AsmOperandInfoVector ConstraintOperands;
6484 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6485 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6486
6487 // Do a prepass over the constraints, canonicalizing them, and building up the
6488 // ConstraintOperands list.
6489 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6490 unsigned ResNo = 0; // ResNo - The result number of the next output.
6491 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6492
6493 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6494 ConstraintOperands.emplace_back(std::move(CI));
6495 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6496
6497 // Update multiple alternative constraint count.
6498 if (OpInfo.multipleAlternatives.size() > maCount)
6499 maCount = OpInfo.multipleAlternatives.size();
6500
6501 OpInfo.ConstraintVT = MVT::Other;
6502
6503 // Compute the value type for each operand.
6504 switch (OpInfo.Type) {
6505 case InlineAsm::isOutput: {
6506 // Indirect outputs just consume an argument.
6507 if (OpInfo.isIndirect) {
6508 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6509 break;
6510 }
6511
6512 // The return value of the call is this value. As such, there is no
6513 // corresponding argument.
6514 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6515 EVT VT;
6516 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6517 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6518 } else {
6519 assert(ResNo == 0 && "Asm only has one result!");
6520 VT = getAsmOperandValueType(DL, Call.getType());
6521 }
6522 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6523 ++ResNo;
6524 break;
6525 }
6526 case InlineAsm::isInput:
6527 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6528 break;
6529 case InlineAsm::isLabel:
6530 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6531 ++LabelNo;
6532 continue;
6534 // Nothing to do.
6535 break;
6536 }
6537
6538 if (OpInfo.CallOperandVal) {
6539 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6540 if (OpInfo.isIndirect) {
6541 OpTy = Call.getParamElementType(ArgNo);
6542 assert(OpTy && "Indirect operand must have elementtype attribute");
6543 }
6544
6545 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6547 if (STy->getNumElements() == 1)
6548 OpTy = STy->getElementType(0);
6549
6550 // If OpTy is not a single value, it may be a struct/union that we
6551 // can tile with integers.
6552 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6553 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6554 switch (BitSize) {
6555 default: break;
6556 case 1:
6557 case 8:
6558 case 16:
6559 case 32:
6560 case 64:
6561 case 128:
6562 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6563 break;
6564 }
6565 }
6566
6567 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6568 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6569 ArgNo++;
6570 }
6571 }
6572
6573 // If we have multiple alternative constraints, select the best alternative.
6574 if (!ConstraintOperands.empty()) {
6575 if (maCount) {
6576 unsigned bestMAIndex = 0;
6577 int bestWeight = -1;
6578 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6579 int weight = -1;
6580 unsigned maIndex;
6581 // Compute the sums of the weights for each alternative, keeping track
6582 // of the best (highest weight) one so far.
6583 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6584 int weightSum = 0;
6585 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6586 cIndex != eIndex; ++cIndex) {
6587 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6588 if (OpInfo.Type == InlineAsm::isClobber)
6589 continue;
6590
6591 // If this is an output operand with a matching input operand,
6592 // look up the matching input. If their types mismatch, e.g. one
6593 // is an integer, the other is floating point, or their sizes are
6594 // different, flag it as an maCantMatch.
6595 if (OpInfo.hasMatchingInput()) {
6596 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6597 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6598 if ((OpInfo.ConstraintVT.isInteger() !=
6599 Input.ConstraintVT.isInteger()) ||
6600 (OpInfo.ConstraintVT.getSizeInBits() !=
6601 Input.ConstraintVT.getSizeInBits())) {
6602 weightSum = -1; // Can't match.
6603 break;
6604 }
6605 }
6606 }
6607 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6608 if (weight == -1) {
6609 weightSum = -1;
6610 break;
6611 }
6612 weightSum += weight;
6613 }
6614 // Update best.
6615 if (weightSum > bestWeight) {
6616 bestWeight = weightSum;
6617 bestMAIndex = maIndex;
6618 }
6619 }
6620
6621 // Now select chosen alternative in each constraint.
6622 for (AsmOperandInfo &cInfo : ConstraintOperands)
6623 if (cInfo.Type != InlineAsm::isClobber)
6624 cInfo.selectAlternative(bestMAIndex);
6625 }
6626 }
6627
6628 // Check and hook up tied operands, choose constraint code to use.
6629 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6630 cIndex != eIndex; ++cIndex) {
6631 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6632
6633 // If this is an output operand with a matching input operand, look up the
6634 // matching input. If their types mismatch, e.g. one is an integer, the
6635 // other is floating point, or their sizes are different, flag it as an
6636 // error.
6637 if (OpInfo.hasMatchingInput()) {
6638 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6639
6640 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6641 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6642 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6643 OpInfo.ConstraintVT);
6644 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6645 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6646 Input.ConstraintVT);
6647 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6648 OpInfo.ConstraintVT.isFloatingPoint();
6649 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6650 Input.ConstraintVT.isFloatingPoint();
6651 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6652 (MatchRC.second != InputRC.second)) {
6653 report_fatal_error("Unsupported asm: input constraint"
6654 " with a matching output constraint of"
6655 " incompatible type!");
6656 }
6657 }
6658 }
6659 }
6660
6661 return ConstraintOperands;
6662}
6663
6664/// Return a number indicating our preference for chosing a type of constraint
6665/// over another, for the purpose of sorting them. Immediates are almost always
6666/// preferrable (when they can be emitted). A higher return value means a
6667/// stronger preference for one constraint type relative to another.
6668/// FIXME: We should prefer registers over memory but doing so may lead to
6669/// unrecoverable register exhaustion later.
6670/// https://github.com/llvm/llvm-project/issues/20571
6672 switch (CT) {
6675 return 4;
6678 return 3;
6680 return 2;
6682 return 1;
6684 return 0;
6685 }
6686 llvm_unreachable("Invalid constraint type");
6687}
6688
6689/// Examine constraint type and operand type and determine a weight value.
6690/// This object must already have been set up with the operand type
6691/// and the current alternative constraint selected.
6694 AsmOperandInfo &info, int maIndex) const {
6696 if (maIndex >= (int)info.multipleAlternatives.size())
6697 rCodes = &info.Codes;
6698 else
6699 rCodes = &info.multipleAlternatives[maIndex].Codes;
6700 ConstraintWeight BestWeight = CW_Invalid;
6701
6702 // Loop over the options, keeping track of the most general one.
6703 for (const std::string &rCode : *rCodes) {
6705 getSingleConstraintMatchWeight(info, rCode.c_str());
6706 if (weight > BestWeight)
6707 BestWeight = weight;
6708 }
6709
6710 return BestWeight;
6711}
6712
6713/// Examine constraint type and operand type and determine a weight value.
6714/// This object must already have been set up with the operand type
6715/// and the current alternative constraint selected.
6718 AsmOperandInfo &info, const char *constraint) const {
6720 Value *CallOperandVal = info.CallOperandVal;
6721 // If we don't have a value, we can't do a match,
6722 // but allow it at the lowest weight.
6723 if (!CallOperandVal)
6724 return CW_Default;
6725 // Look at the constraint type.
6726 switch (*constraint) {
6727 case 'i': // immediate integer.
6728 case 'n': // immediate integer with a known value.
6729 if (isa<ConstantInt>(CallOperandVal))
6731 break;
6732 case 's': // non-explicit intregal immediate.
6733 if (isa<GlobalValue>(CallOperandVal))
6735 break;
6736 case 'E': // immediate float if host format.
6737 case 'F': // immediate float.
6738 if (isa<ConstantFP>(CallOperandVal))
6740 break;
6741 case '<': // memory operand with autodecrement.
6742 case '>': // memory operand with autoincrement.
6743 case 'm': // memory operand.
6744 case 'o': // offsettable memory operand
6745 case 'V': // non-offsettable memory operand
6746 weight = CW_Memory;
6747 break;
6748 case 'r': // general register.
6749 case 'g': // general register, memory operand or immediate integer.
6750 // note: Clang converts "g" to "imr".
6751 if (CallOperandVal->getType()->isIntegerTy())
6753 break;
6754 case 'X': // any operand.
6755 default:
6757 break;
6758 }
6759 return weight;
6760}
6761
6762/// If there are multiple different constraints that we could pick for this
6763/// operand (e.g. "imr") try to pick the 'best' one.
6764/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6765/// into seven classes:
6766/// Register -> one specific register
6767/// RegisterClass -> a group of regs
6768/// Memory -> memory
6769/// Address -> a symbolic memory reference
6770/// Immediate -> immediate values
6771/// Other -> magic values (such as "Flag Output Operands")
6772/// Unknown -> something we don't recognize yet and can't handle
6773/// Ideally, we would pick the most specific constraint possible: if we have
6774/// something that fits into a register, we would pick it. The problem here
6775/// is that if we have something that could either be in a register or in
6776/// memory that use of the register could cause selection of *other*
6777/// operands to fail: they might only succeed if we pick memory. Because of
6778/// this the heuristic we use is:
6779///
6780/// 1) If there is an 'other' constraint, and if the operand is valid for
6781/// that constraint, use it. This makes us take advantage of 'i'
6782/// constraints when available.
6783/// 2) Otherwise, pick the most general constraint present. This prefers
6784/// 'm' over 'r', for example.
6785///
6787 TargetLowering::AsmOperandInfo &OpInfo) const {
6788 ConstraintGroup Ret;
6789
6790 Ret.reserve(OpInfo.Codes.size());
6791 for (StringRef Code : OpInfo.Codes) {
6793
6794 // Indirect 'other' or 'immediate' constraints are not allowed.
6795 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6796 CType == TargetLowering::C_Register ||
6798 continue;
6799
6800 // Things with matching constraints can only be registers, per gcc
6801 // documentation. This mainly affects "g" constraints.
6802 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6803 continue;
6804
6805 Ret.emplace_back(Code, CType);
6806 }
6807
6809 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6810 });
6811
6812 return Ret;
6813}
6814
6815/// If we have an immediate, see if we can lower it. Return true if we can,
6816/// false otherwise.
6818 SDValue Op, SelectionDAG *DAG,
6819 const TargetLowering &TLI) {
6820
6821 assert((P.second == TargetLowering::C_Other ||
6822 P.second == TargetLowering::C_Immediate) &&
6823 "need immediate or other");
6824
6825 if (!Op.getNode())
6826 return false;
6827
6828 std::vector<SDValue> ResultOps;
6829 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6830 return !ResultOps.empty();
6831}
6832
6833/// Determines the constraint code and constraint type to use for the specific
6834/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6836 SDValue Op,
6837 SelectionDAG *DAG) const {
6838 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6839
6840 // Single-letter constraints ('r') are very common.
6841 if (OpInfo.Codes.size() == 1) {
6842 OpInfo.ConstraintCode = OpInfo.Codes[0];
6843 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6844 } else {
6846 if (G.empty())
6847 return;
6848
6849 unsigned BestIdx = 0;
6850 for (const unsigned E = G.size();
6851 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6852 G[BestIdx].second == TargetLowering::C_Immediate);
6853 ++BestIdx) {
6854 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6855 break;
6856 // If we're out of constraints, just pick the first one.
6857 if (BestIdx + 1 == E) {
6858 BestIdx = 0;
6859 break;
6860 }
6861 }
6862
6863 OpInfo.ConstraintCode = G[BestIdx].first;
6864 OpInfo.ConstraintType = G[BestIdx].second;
6865 }
6866
6867 // 'X' matches anything.
6868 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6869 // Constants are handled elsewhere. For Functions, the type here is the
6870 // type of the result, which is not what we want to look at; leave them
6871 // alone.
6872 Value *v = OpInfo.CallOperandVal;
6873 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6874 return;
6875 }
6876
6877 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6878 OpInfo.ConstraintCode = "i";
6879 return;
6880 }
6881
6882 // Otherwise, try to resolve it to something we know about by looking at
6883 // the actual operand type.
6884 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6885 OpInfo.ConstraintCode = Repl;
6886 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6887 }
6888 }
6889}
6890
6891/// Given an exact SDIV by a constant, create a multiplication
6892/// with the multiplicative inverse of the constant.
6893/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6895 const SDLoc &dl, SelectionDAG &DAG,
6896 SmallVectorImpl<SDNode *> &Created) {
6897 SDValue Op0 = N->getOperand(0);
6898 SDValue Op1 = N->getOperand(1);
6899 EVT VT = N->getValueType(0);
6900 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6901 EVT ShSVT = ShVT.getScalarType();
6902
6903 bool UseSRA = false;
6904 SmallVector<SDValue, 16> Shifts, Factors;
6905
6906 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6907 if (C->isZero())
6908 return false;
6909
6910 EVT CT = C->getValueType(0);
6911 APInt Divisor = C->getAPIntValue();
6912 unsigned Shift = Divisor.countr_zero();
6913 if (Shift) {
6914 Divisor.ashrInPlace(Shift);
6915 UseSRA = true;
6916 }
6917 APInt Factor = Divisor.multiplicativeInverse();
6918 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6919 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6920 return true;
6921 };
6922
6923 // Collect all magic values from the build vector.
6924 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6925 return SDValue();
6926
6927 SDValue Shift, Factor;
6928 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6929 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6930 Factor = DAG.getBuildVector(VT, dl, Factors);
6931 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6932 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6933 "Expected matchUnaryPredicate to return one element for scalable "
6934 "vectors");
6935 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6936 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6937 } else {
6938 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6939 Shift = Shifts[0];
6940 Factor = Factors[0];
6941 }
6942
6943 SDValue Res = Op0;
6944 if (UseSRA) {
6945 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6946 Created.push_back(Res.getNode());
6947 }
6948
6949 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6950}
6951
6952/// Given an exact UDIV by a constant, create a multiplication
6953/// with the multiplicative inverse of the constant.
6954/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6956 const SDLoc &dl, SelectionDAG &DAG,
6957 SmallVectorImpl<SDNode *> &Created) {
6958 EVT VT = N->getValueType(0);
6959 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6960 EVT ShSVT = ShVT.getScalarType();
6961
6962 bool UseSRL = false;
6963 SmallVector<SDValue, 16> Shifts, Factors;
6964
6965 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6966 if (C->isZero())
6967 return false;
6968
6969 EVT CT = C->getValueType(0);
6970 APInt Divisor = C->getAPIntValue();
6971 unsigned Shift = Divisor.countr_zero();
6972 if (Shift) {
6973 Divisor.lshrInPlace(Shift);
6974 UseSRL = true;
6975 }
6976 // Calculate the multiplicative inverse modulo BW.
6977 APInt Factor = Divisor.multiplicativeInverse();
6978 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6979 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6980 return true;
6981 };
6982
6983 SDValue Op1 = N->getOperand(1);
6984
6985 // Collect all magic values from the build vector.
6986 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6987 return SDValue();
6988
6989 SDValue Shift, Factor;
6990 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6991 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6992 Factor = DAG.getBuildVector(VT, dl, Factors);
6993 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6994 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6995 "Expected matchUnaryPredicate to return one element for scalable "
6996 "vectors");
6997 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6998 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6999 } else {
7000 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
7001 Shift = Shifts[0];
7002 Factor = Factors[0];
7003 }
7004
7005 SDValue Res = N->getOperand(0);
7006 if (UseSRL) {
7007 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
7008 Created.push_back(Res.getNode());
7009 }
7010
7011 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
7012}
7013
7015 SelectionDAG &DAG,
7016 SmallVectorImpl<SDNode *> &Created) const {
7018 if (isIntDivCheap(N->getValueType(0), Attr))
7019 return SDValue(N, 0); // Lower SDIV as SDIV
7020 return SDValue();
7021}
7022
7023SDValue
7025 SelectionDAG &DAG,
7026 SmallVectorImpl<SDNode *> &Created) const {
7028 if (isIntDivCheap(N->getValueType(0), Attr))
7029 return SDValue(N, 0); // Lower SREM as SREM
7030 return SDValue();
7031}
7032
7033/// Build sdiv by power-of-2 with conditional move instructions
7034/// Ref: "Hacker's Delight" by Henry Warren 10-1
7035/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
7036/// bgez x, label
7037/// add x, x, 2**k-1
7038/// label:
7039/// sra res, x, k
7040/// neg res, res (when the divisor is negative)
7042 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
7043 SmallVectorImpl<SDNode *> &Created) const {
7044 unsigned Lg2 = Divisor.countr_zero();
7045 EVT VT = N->getValueType(0);
7046
7047 SDLoc DL(N);
7048 SDValue N0 = N->getOperand(0);
7049 SDValue Zero = DAG.getConstant(0, DL, VT);
7050 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
7051 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
7052
7053 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
7054 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7055 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
7056 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7057 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
7058
7059 Created.push_back(Cmp.getNode());
7060 Created.push_back(Add.getNode());
7061 Created.push_back(CMov.getNode());
7062
7063 // Divide by pow2.
7064 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
7065 DAG.getShiftAmountConstant(Lg2, VT, DL));
7066
7067 // If we're dividing by a positive value, we're done. Otherwise, we must
7068 // negate the result.
7069 if (Divisor.isNonNegative())
7070 return SRA;
7071
7072 Created.push_back(SRA.getNode());
7073 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
7074}
7075
7076/// Given an ISD::SDIV node expressing a divide by constant,
7077/// return a DAG expression to select that will generate the same value by
7078/// multiplying by a magic number.
7079/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7081 bool IsAfterLegalization,
7082 bool IsAfterLegalTypes,
7083 SmallVectorImpl<SDNode *> &Created) const {
7084 SDLoc dl(N);
7085
7086 // If the sdiv has an 'exact' bit we can use a simpler lowering.
7087 if (N->getFlags().hasExact())
7088 return BuildExactSDIV(*this, N, dl, DAG, Created);
7089
7090 EVT VT = N->getValueType(0);
7091 EVT SVT = VT.getScalarType();
7092 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7093 EVT ShSVT = ShVT.getScalarType();
7094 unsigned EltBits = VT.getScalarSizeInBits();
7095 EVT MulVT;
7096
7097 // Check to see if we can do this.
7098 // FIXME: We should be more aggressive here.
7099 EVT QueryVT = VT;
7100 if (VT.isVector()) {
7101 // If the vector type will be legalized to a vector type with the same
7102 // element type, allow the transform before type legalization if MULHS or
7103 // SMUL_LOHI are supported.
7104 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7105 if (!QueryVT.isVector() ||
7107 return SDValue();
7108 } else if (!isTypeLegal(VT)) {
7109 // Limit this to simple scalars for now.
7110 if (!VT.isSimple())
7111 return SDValue();
7112
7113 // If this type will be promoted to a large enough type with a legal
7114 // multiply operation, we can go ahead and do this transform.
7116 return SDValue();
7117
7118 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7119 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7120 !isOperationLegal(ISD::MUL, MulVT))
7121 return SDValue();
7122 }
7123
7124 bool HasMULHS =
7125 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
7126 bool HasSMUL_LOHI =
7127 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
7128
7129 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
7130 // If type twice as wide legal, widen and use a mul plus a shift.
7131 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7132 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
7133 // custom lowered. This is very expensive so avoid it at all costs for
7134 // constant divisors.
7135 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
7138 MulVT = WideVT;
7139 }
7140
7141 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
7142 return SDValue();
7143
7144 // If we're after type legalization and SVT is not legal, use the
7145 // promoted type for creating constants to avoid creating nodes with
7146 // illegal types.
7147 if (IsAfterLegalTypes && VT.isVector()) {
7148 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7149 if (SVT.bitsLT(VT.getScalarType()))
7150 return SDValue();
7151 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7152 if (ShSVT.bitsLT(ShVT.getScalarType()))
7153 return SDValue();
7154 }
7155 const unsigned SVTBits = SVT.getSizeInBits();
7156
7157 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
7158
7159 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
7160 if (C->isZero())
7161 return false;
7162 // Truncate the divisor to the target scalar type in case it was promoted
7163 // during type legalization.
7164 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7166 int NumeratorFactor = 0;
7167 int ShiftMask = -1;
7168
7169 if (Divisor.isOne() || Divisor.isAllOnes()) {
7170 // If d is +1/-1, we just multiply the numerator by +1/-1.
7171 NumeratorFactor = Divisor.getSExtValue();
7172 magics.Magic = 0;
7173 magics.ShiftAmount = 0;
7174 ShiftMask = 0;
7175 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
7176 // If d > 0 and m < 0, add the numerator.
7177 NumeratorFactor = 1;
7178 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
7179 // If d < 0 and m > 0, subtract the numerator.
7180 NumeratorFactor = -1;
7181 }
7182
7183 MagicFactors.push_back(
7184 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
7185 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
7186 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
7187 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
7188 return true;
7189 };
7190
7191 SDValue N0 = N->getOperand(0);
7192 SDValue N1 = N->getOperand(1);
7193
7194 // Collect the shifts / magic values from each element.
7195 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
7196 /*AllowTruncation=*/true))
7197 return SDValue();
7198
7199 SDValue MagicFactor, Factor, Shift, ShiftMask;
7200 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7201 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7202 Factor = DAG.getBuildVector(VT, dl, Factors);
7203 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
7204 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
7205 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7206 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
7207 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
7208 "Expected matchUnaryPredicate to return one element for scalable "
7209 "vectors");
7210 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7211 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
7212 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
7213 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
7214 } else {
7215 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7216 MagicFactor = MagicFactors[0];
7217 Factor = Factors[0];
7218 Shift = Shifts[0];
7219 ShiftMask = ShiftMasks[0];
7220 }
7221
7222 // Multiply the numerator (operand 0) by the magic value.
7223 auto GetMULHS = [&](SDValue X, SDValue Y) {
7224 if (HasMULHS)
7225 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
7226 if (HasSMUL_LOHI) {
7227 SDValue LoHi =
7228 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7229 return LoHi.getValue(1);
7230 }
7231
7232 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
7233 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
7234 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7235 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7236 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7237 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7238 };
7239
7240 SDValue Q = GetMULHS(N0, MagicFactor);
7241 if (!Q)
7242 return SDValue();
7243
7244 Created.push_back(Q.getNode());
7245
7246 // (Optionally) Add/subtract the numerator using Factor.
7247 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
7248 Created.push_back(Factor.getNode());
7249 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
7250 Created.push_back(Q.getNode());
7251
7252 // Shift right algebraic by shift value.
7253 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
7254 Created.push_back(Q.getNode());
7255
7256 // Extract the sign bit, mask it and add it to the quotient.
7257 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
7258 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
7259 Created.push_back(T.getNode());
7260 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
7261 Created.push_back(T.getNode());
7262 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
7263}
7264
7265/// Given an ISD::UDIV node expressing a divide by constant,
7266/// return a DAG expression to select that will generate the same value by
7267/// multiplying by a magic number.
7268/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7270 bool IsAfterLegalization,
7271 bool IsAfterLegalTypes,
7272 SmallVectorImpl<SDNode *> &Created) const {
7273 SDLoc dl(N);
7274
7275 // If the udiv has an 'exact' bit we can use a simpler lowering.
7276 if (N->getFlags().hasExact())
7277 return BuildExactUDIV(*this, N, dl, DAG, Created);
7278
7279 EVT VT = N->getValueType(0);
7280 EVT SVT = VT.getScalarType();
7281 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7282 EVT ShSVT = ShVT.getScalarType();
7283 unsigned EltBits = VT.getScalarSizeInBits();
7284 EVT MulVT;
7285
7286 // Check to see if we can do this.
7287 // FIXME: We should be more aggressive here.
7288 EVT QueryVT = VT;
7289 if (VT.isVector()) {
7290 // If the vector type will be legalized to a vector type with the same
7291 // element type, allow the transform before type legalization if MULHU or
7292 // UMUL_LOHI are supported.
7293 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7294 if (!QueryVT.isVector() ||
7296 return SDValue();
7297 } else if (!isTypeLegal(VT)) {
7298 // Limit this to simple scalars for now.
7299 if (!VT.isSimple())
7300 return SDValue();
7301
7302 // If this type will be promoted to a large enough type with a legal
7303 // multiply operation, we can go ahead and do this transform.
7305 return SDValue();
7306
7307 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7308 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7309 !isOperationLegal(ISD::MUL, MulVT))
7310 return SDValue();
7311 }
7312
7313 bool HasMULHU =
7314 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
7315 bool HasUMUL_LOHI =
7316 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
7317
7318 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
7319 // If type twice as wide legal, widen and use a mul plus a shift.
7320 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7321 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
7322 // custom lowered. This is very expensive so avoid it at all costs for
7323 // constant divisors.
7324 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
7327 MulVT = WideVT;
7328 }
7329
7330 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
7331 return SDValue();
7332
7333 SDValue N0 = N->getOperand(0);
7334 SDValue N1 = N->getOperand(1);
7335
7336 // Try to use leading zeros of the dividend to reduce the multiplier and
7337 // avoid expensive fixups.
7338 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
7339
7340 // If we're after type legalization and SVT is not legal, use the
7341 // promoted type for creating constants to avoid creating nodes with
7342 // illegal types.
7343 if (IsAfterLegalTypes && VT.isVector()) {
7344 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7345 if (SVT.bitsLT(VT.getScalarType()))
7346 return SDValue();
7347 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7348 if (ShSVT.bitsLT(ShVT.getScalarType()))
7349 return SDValue();
7350 }
7351 const unsigned SVTBits = SVT.getSizeInBits();
7352
7353 // Allow scalars to be widened to twice their size for uncooperative divisors
7354 // if MULHU or UMUL_LOHI is supported for the wider type.
7355 const EVT WideSVT = EVT::getIntegerVT(*DAG.getContext(), 2 * EltBits);
7356 const bool HasWideMULHU =
7357 VT.isScalarInteger() &&
7358 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
7359 const bool HasWideUMUL_LOHI =
7360 VT.isScalarInteger() &&
7361 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
7362 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
7363
7364 // For even divisors with a 33-bit magic number, the widened high-multiply
7365 // path is only worthwhile over the even-divisor rewrite on targets that
7366 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
7367 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
7368 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
7369
7370 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
7371 bool UseWiden = false;
7372 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
7373
7374 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
7375 if (C->isZero())
7376 return false;
7377 // Truncate the divisor to the target scalar type in case it was promoted
7378 // during type legalization.
7379 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7380
7381 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
7382
7383 // Magic algorithm doesn't work for division by 1. We need to emit a select
7384 // at the end.
7385 if (Divisor.isOne()) {
7386 PreShift = PostShift = DAG.getUNDEF(ShSVT);
7387 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
7388 } else {
7391 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7392 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7393 /*AllowWidenOptimization=*/AllowWiden);
7394
7395 if (magics.Widen) {
7396 UseWiden = true;
7397 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7398 } else {
7399 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7400 }
7401
7402 assert(magics.PreShift < Divisor.getBitWidth() &&
7403 "We shouldn't generate an undefined shift!");
7404 assert(magics.PostShift < Divisor.getBitWidth() &&
7405 "We shouldn't generate an undefined shift!");
7406 assert((!magics.IsAdd || magics.PreShift == 0) &&
7407 "Unexpected pre-shift");
7408 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7409 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7410 NPQFactor = DAG.getConstant(
7411 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7412 : APInt::getZero(SVTBits),
7413 dl, SVT);
7414 UseNPQ |= magics.IsAdd;
7415 UsePreShift |= magics.PreShift != 0;
7416 UsePostShift |= magics.PostShift != 0;
7417 }
7418
7419 PreShifts.push_back(PreShift);
7420 MagicFactors.push_back(MagicFactor);
7421 NPQFactors.push_back(NPQFactor);
7422 PostShifts.push_back(PostShift);
7423 return true;
7424 };
7425
7426 // Collect the shifts/magic values from each element.
7427 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7428 /*AllowTruncation=*/true))
7429 return SDValue();
7430
7431 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7432 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7433 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7434 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7435 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7436 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7437 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7438 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7439 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7440 "Expected matchUnaryPredicate to return one for scalable vectors");
7441 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7442 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7443 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7444 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7445 } else {
7446 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7447 PreShift = PreShifts[0];
7448 MagicFactor = MagicFactors[0];
7449 PostShift = PostShifts[0];
7450 }
7451
7452 if (UseWiden) {
7453 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7454 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7455
7456 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7457 // WideSVT bits
7458 SDValue High;
7459 if (HasWideMULHU) {
7460 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7461 } else {
7462 assert(HasWideUMUL_LOHI);
7463 SDValue LoHi =
7464 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7465 WideN0, MagicFactor);
7466 High = LoHi.getValue(1);
7467 }
7468
7469 Created.push_back(High.getNode());
7470 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7471 }
7472
7473 SDValue Q = N0;
7474 if (UsePreShift) {
7475 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7476 Created.push_back(Q.getNode());
7477 }
7478
7479 auto GetMULHU = [&](SDValue X, SDValue Y) {
7480 if (HasMULHU)
7481 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7482 if (HasUMUL_LOHI) {
7483 SDValue LoHi =
7484 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7485 return LoHi.getValue(1);
7486 }
7487
7488 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7489 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7490 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7491 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7492 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7493 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7494 };
7495
7496 // Multiply the numerator (operand 0) by the magic value.
7497 Q = GetMULHU(Q, MagicFactor);
7498 if (!Q)
7499 return SDValue();
7500
7501 Created.push_back(Q.getNode());
7502
7503 if (UseNPQ) {
7504 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7505 Created.push_back(NPQ.getNode());
7506
7507 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7508 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7509 if (VT.isVector())
7510 NPQ = GetMULHU(NPQ, NPQFactor);
7511 else
7512 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7513
7514 Created.push_back(NPQ.getNode());
7515
7516 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7517 Created.push_back(Q.getNode());
7518 }
7519
7520 if (UsePostShift) {
7521 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7522 Created.push_back(Q.getNode());
7523 }
7524
7525 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7526
7527 SDValue One = DAG.getConstant(1, dl, VT);
7528 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7529 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7530}
7531
7532/// If all values in Values that *don't* match the predicate are same 'splat'
7533/// value, then replace all values with that splat value.
7534/// Else, if AlternativeReplacement was provided, then replace all values that
7535/// do match predicate with AlternativeReplacement value.
7536static void
7538 std::function<bool(SDValue)> Predicate,
7539 SDValue AlternativeReplacement = SDValue()) {
7540 SDValue Replacement;
7541 // Is there a value for which the Predicate does *NOT* match? What is it?
7542 auto SplatValue = llvm::find_if_not(Values, Predicate);
7543 if (SplatValue != Values.end()) {
7544 // Does Values consist only of SplatValue's and values matching Predicate?
7545 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7546 return Value == *SplatValue || Predicate(Value);
7547 })) // Then we shall replace values matching predicate with SplatValue.
7548 Replacement = *SplatValue;
7549 }
7550 if (!Replacement) {
7551 // Oops, we did not find the "baseline" splat value.
7552 if (!AlternativeReplacement)
7553 return; // Nothing to do.
7554 // Let's replace with provided value then.
7555 Replacement = AlternativeReplacement;
7556 }
7557 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7558}
7559
7560/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7561/// where the divisor and comparison target are constants,
7562/// return a DAG expression that will generate the same comparison result
7563/// using only multiplications, additions and shifts/rotations.
7564/// Ref: "Hacker's Delight" 10-17.
7565SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7566 SDValue CompTargetNode,
7568 DAGCombinerInfo &DCI,
7569 const SDLoc &DL) const {
7571 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7572 DCI, DL, Built)) {
7573 for (SDNode *N : Built)
7574 DCI.AddToWorklist(N);
7575 return Folded;
7576 }
7577
7578 return SDValue();
7579}
7580
7581SDValue
7582TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7583 SDValue CompTargetNode, ISD::CondCode Cond,
7584 DAGCombinerInfo &DCI, const SDLoc &DL,
7585 SmallVectorImpl<SDNode *> &Created) const {
7586 // fold (seteq/ne (urem N, D), C) ->
7587 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7588 // - D must be constant, with D = D0 * 2^K where D0 is odd
7589 // - P is the multiplicative inverse of D0 modulo 2^W
7590 // - Q = floor(((2^W) - 1) / D)
7591 // where W is the width of the common type of N and D.
7592 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7593 "Only applicable for (in)equality comparisons.");
7594
7595 SelectionDAG &DAG = DCI.DAG;
7596
7597 EVT VT = REMNode.getValueType();
7598 EVT SVT = VT.getScalarType();
7599 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7600 EVT ShSVT = ShVT.getScalarType();
7601
7602 // If MUL is unavailable, we cannot proceed in any case.
7603 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7604 return SDValue();
7605
7606 bool ComparingWithAllZeros = true;
7607 bool AllComparisonsWithNonZerosAreTautological = true;
7608 bool HadTautologicalLanes = false;
7609 bool AllLanesAreTautological = true;
7610 bool HadEvenDivisor = false;
7611 bool AllDivisorsArePowerOfTwo = true;
7612 bool HadTautologicalInvertedLanes = false;
7613 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7614
7615 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7616 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7617 if (CDiv->isZero())
7618 return false;
7619
7620 const APInt &D = CDiv->getAPIntValue();
7621 const APInt &Cmp = CCmp->getAPIntValue();
7622
7623 ComparingWithAllZeros &= Cmp.isZero();
7624
7625 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7626 // if C2 is not less than C1, the comparison is always false.
7627 // But we will only be able to produce the comparison that will give the
7628 // opposive tautological answer. So this lane would need to be fixed up.
7629 bool TautologicalInvertedLane = D.ule(Cmp);
7630 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7631
7632 // If all lanes are tautological (either all divisors are ones, or divisor
7633 // is not greater than the constant we are comparing with),
7634 // we will prefer to avoid the fold.
7635 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7636 HadTautologicalLanes |= TautologicalLane;
7637 AllLanesAreTautological &= TautologicalLane;
7638
7639 // If we are comparing with non-zero, we need'll need to subtract said
7640 // comparison value from the LHS. But there is no point in doing that if
7641 // every lane where we are comparing with non-zero is tautological..
7642 if (!Cmp.isZero())
7643 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7644
7645 // Decompose D into D0 * 2^K
7646 unsigned K = D.countr_zero();
7647 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7648 APInt D0 = D.lshr(K);
7649
7650 // D is even if it has trailing zeros.
7651 HadEvenDivisor |= (K != 0);
7652 // D is a power-of-two if D0 is one.
7653 // If all divisors are power-of-two, we will prefer to avoid the fold.
7654 AllDivisorsArePowerOfTwo &= D0.isOne();
7655
7656 // P = inv(D0, 2^W)
7657 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7658 unsigned W = D.getBitWidth();
7659 APInt P = D0.multiplicativeInverse();
7660 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7661
7662 // Q = floor((2^W - 1) u/ D)
7663 // R = ((2^W - 1) u% D)
7664 APInt Q, R;
7666
7667 // If we are comparing with zero, then that comparison constant is okay,
7668 // else it may need to be one less than that.
7669 if (Cmp.ugt(R))
7670 Q -= 1;
7671
7673 "We are expecting that K is always less than all-ones for ShSVT");
7674
7675 // If the lane is tautological the result can be constant-folded.
7676 if (TautologicalLane) {
7677 // Set P and K amount to a bogus values so we can try to splat them.
7678 P = 0;
7679 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7680 // And ensure that comparison constant is tautological,
7681 // it will always compare true/false.
7682 Q.setAllBits();
7683 } else {
7684 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7685 }
7686
7687 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7688 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7689 return true;
7690 };
7691
7692 SDValue N = REMNode.getOperand(0);
7693 SDValue D = REMNode.getOperand(1);
7694
7695 // Collect the values from each element.
7696 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7697 return SDValue();
7698
7699 // If all lanes are tautological, the result can be constant-folded.
7700 if (AllLanesAreTautological)
7701 return SDValue();
7702
7703 // If this is a urem by a powers-of-two, avoid the fold since it can be
7704 // best implemented as a bit test.
7705 if (AllDivisorsArePowerOfTwo)
7706 return SDValue();
7707
7708 SDValue PVal, KVal, QVal;
7709 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7710 if (HadTautologicalLanes) {
7711 // Try to turn PAmts into a splat, since we don't care about the values
7712 // that are currently '0'. If we can't, just keep '0'`s.
7714 // Try to turn KAmts into a splat, since we don't care about the values
7715 // that are currently '-1'. If we can't, change them to '0'`s.
7717 DAG.getConstant(0, DL, ShSVT));
7718 }
7719
7720 PVal = DAG.getBuildVector(VT, DL, PAmts);
7721 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7722 QVal = DAG.getBuildVector(VT, DL, QAmts);
7723 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7724 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7725 "Expected matchBinaryPredicate to return one element for "
7726 "SPLAT_VECTORs");
7727 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7728 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7729 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7730 } else {
7731 PVal = PAmts[0];
7732 KVal = KAmts[0];
7733 QVal = QAmts[0];
7734 }
7735
7736 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7737 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7738 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7739 assert(CompTargetNode.getValueType() == N.getValueType() &&
7740 "Expecting that the types on LHS and RHS of comparisons match.");
7741 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7742 }
7743
7744 // (mul N, P)
7745 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7746 Created.push_back(Op0.getNode());
7747
7748 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7749 // divisors as a performance improvement, since rotating by 0 is a no-op.
7750 if (HadEvenDivisor) {
7751 // We need ROTR to do this.
7752 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7753 return SDValue();
7754 // UREM: (rotr (mul N, P), K)
7755 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7756 Created.push_back(Op0.getNode());
7757 }
7758
7759 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7760 SDValue NewCC =
7761 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7763 if (!HadTautologicalInvertedLanes)
7764 return NewCC;
7765
7766 // If any lanes previously compared always-false, the NewCC will give
7767 // always-true result for them, so we need to fixup those lanes.
7768 // Or the other way around for inequality predicate.
7769 assert(VT.isVector() && "Can/should only get here for vectors.");
7770 Created.push_back(NewCC.getNode());
7771
7772 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7773 // if C2 is not less than C1, the comparison is always false.
7774 // But we have produced the comparison that will give the
7775 // opposive tautological answer. So these lanes would need to be fixed up.
7776 SDValue TautologicalInvertedChannels =
7777 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7778 Created.push_back(TautologicalInvertedChannels.getNode());
7779
7780 // NOTE: we avoid letting illegal types through even if we're before legalize
7781 // ops – legalization has a hard time producing good code for this.
7782 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7783 // If we have a vector select, let's replace the comparison results in the
7784 // affected lanes with the correct tautological result.
7785 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7786 DL, SETCCVT, SETCCVT);
7787 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7788 Replacement, NewCC);
7789 }
7790
7791 // Else, we can just invert the comparison result in the appropriate lanes.
7792 //
7793 // NOTE: see the note above VSELECT above.
7794 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7795 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7796 TautologicalInvertedChannels);
7797
7798 return SDValue(); // Don't know how to lower.
7799}
7800
7801/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7802/// where the divisor is constant and the comparison target is zero,
7803/// return a DAG expression that will generate the same comparison result
7804/// using only multiplications, additions and shifts/rotations.
7805/// Ref: "Hacker's Delight" 10-17.
7806SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7807 SDValue CompTargetNode,
7809 DAGCombinerInfo &DCI,
7810 const SDLoc &DL) const {
7812 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7813 DCI, DL, Built)) {
7814 assert(Built.size() <= 7 && "Max size prediction failed.");
7815 for (SDNode *N : Built)
7816 DCI.AddToWorklist(N);
7817 return Folded;
7818 }
7819
7820 return SDValue();
7821}
7822
7823SDValue
7824TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7825 SDValue CompTargetNode, ISD::CondCode Cond,
7826 DAGCombinerInfo &DCI, const SDLoc &DL,
7827 SmallVectorImpl<SDNode *> &Created) const {
7828 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7829 // Fold:
7830 // (seteq/ne (srem N, D), 0)
7831 // To:
7832 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7833 //
7834 // - D must be constant, with D = D0 * 2^K where D0 is odd
7835 // - P is the multiplicative inverse of D0 modulo 2^W
7836 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7837 // - Q = floor((2 * A) / (2^K))
7838 // where W is the width of the common type of N and D.
7839 //
7840 // When D is a power of two (and thus D0 is 1), the normal
7841 // formula for A and Q don't apply, because the derivation
7842 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7843 // does not apply. This specifically fails when N = INT_MIN.
7844 //
7845 // Instead, for power-of-two D, we use:
7846 // - A = 0
7847 // | -> No offset needed. We're effectively treating it the same as urem.
7848 // - Q = 2^(W-K) - 1
7849 // |-> Test that the top K bits are zero after rotation
7850 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7851 "Only applicable for (in)equality comparisons.");
7852
7853 SelectionDAG &DAG = DCI.DAG;
7854
7855 EVT VT = REMNode.getValueType();
7856 EVT SVT = VT.getScalarType();
7857 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7858 EVT ShSVT = ShVT.getScalarType();
7859
7860 // If we are after ops legalization, and MUL is unavailable, we can not
7861 // proceed.
7862 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7863 return SDValue();
7864
7865 // TODO: Could support comparing with non-zero too.
7866 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7867 if (!CompTarget || !CompTarget->isZero())
7868 return SDValue();
7869
7870 bool HadOneDivisor = false;
7871 bool AllDivisorsAreOnes = true;
7872 bool HadEvenDivisor = false;
7873 bool AllDivisorsArePowerOfTwo = true;
7874 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7875
7876 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7877 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7878 if (C->isZero())
7879 return false;
7880
7881 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7882
7883 // WARNING: this fold is only valid for positive divisors!
7884 // `rem %X, -C` is equivalent to `rem %X, C`
7885 APInt D = C->getAPIntValue().abs();
7886
7887 // If all divisors are ones, we will prefer to avoid the fold.
7888 HadOneDivisor |= D.isOne();
7889 AllDivisorsAreOnes &= D.isOne();
7890
7891 // Decompose D into D0 * 2^K
7892 unsigned K = D.countr_zero();
7893 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7894 APInt D0 = D.lshr(K);
7895
7896 // D is even if it has trailing zeros.
7897 HadEvenDivisor |= (K != 0);
7898
7899 // D is a power-of-two if D0 is one. This includes INT_MIN.
7900 // If all divisors are power-of-two, we will prefer to avoid the fold.
7901 AllDivisorsArePowerOfTwo &= D0.isOne();
7902
7903 // P = inv(D0, 2^W)
7904 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7905 unsigned W = D.getBitWidth();
7906 APInt P = D0.multiplicativeInverse();
7907 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7908
7909 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7910 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7911 A.clearLowBits(K);
7912
7913 // Q = floor((2 * A) / (2^K))
7914 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7915
7917 "We are expecting that A is always less than all-ones for SVT");
7919 "We are expecting that K is always less than all-ones for ShSVT");
7920
7921 // If D was a power of two, apply the alternate constant derivation.
7922 if (D0.isOne()) {
7923 // A = 0
7924 A = APInt(W, 0);
7925 // - Q = 2^(W-K) - 1
7926 Q = APInt::getLowBitsSet(W, W - K);
7927 }
7928
7929 // If the divisor is 1 the result can be constant-folded.
7930 if (D.isOne()) {
7931 // Set P, A and K to a bogus values so we can try to splat them.
7932 P = 0;
7933 A.setAllBits();
7934 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7935
7936 // x ?% 1 == 0 <--> true <--> x u<= -1
7937 Q.setAllBits();
7938 } else {
7939 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7940 }
7941
7942 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7943 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7944 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7945 return true;
7946 };
7947
7948 SDValue N = REMNode.getOperand(0);
7949 SDValue D = REMNode.getOperand(1);
7950
7951 // Collect the values from each element.
7952 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7953 return SDValue();
7954
7955 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7956 if (AllDivisorsAreOnes)
7957 return SDValue();
7958
7959 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7960 // since it can be best implemented as a bit test.
7961 if (AllDivisorsArePowerOfTwo)
7962 return SDValue();
7963
7964 SDValue PVal, AVal, KVal, QVal;
7965 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7966 if (HadOneDivisor) {
7967 // Try to turn PAmts into a splat, since we don't care about the values
7968 // that are currently '0'. If we can't, just keep '0'`s.
7970 // Try to turn AAmts into a splat, since we don't care about the
7971 // values that are currently '-1'. If we can't, change them to '0'`s.
7973 DAG.getConstant(0, DL, SVT));
7974 // Try to turn KAmts into a splat, since we don't care about the values
7975 // that are currently '-1'. If we can't, change them to '0'`s.
7977 DAG.getConstant(0, DL, ShSVT));
7978 }
7979
7980 PVal = DAG.getBuildVector(VT, DL, PAmts);
7981 AVal = DAG.getBuildVector(VT, DL, AAmts);
7982 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7983 QVal = DAG.getBuildVector(VT, DL, QAmts);
7984 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7985 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7986 QAmts.size() == 1 &&
7987 "Expected matchUnaryPredicate to return one element for scalable "
7988 "vectors");
7989 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7990 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7991 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7992 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7993 } else {
7994 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7995 PVal = PAmts[0];
7996 AVal = AAmts[0];
7997 KVal = KAmts[0];
7998 QVal = QAmts[0];
7999 }
8000
8001 // (mul N, P)
8002 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
8003 Created.push_back(Op0.getNode());
8004
8005 // We need ADD to do this.
8006 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
8007 return SDValue();
8008
8009 // (add (mul N, P), A)
8010 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
8011 Created.push_back(Op0.getNode());
8012
8013 // Rotate right only if any divisor was even. We avoid rotates for all-odd
8014 // divisors as a performance improvement, since rotating by 0 is a no-op.
8015 if (HadEvenDivisor) {
8016 // We need ROTR to do this.
8017 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
8018 return SDValue();
8019 // SREM: (rotr (add (mul N, P), A), K)
8020 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
8021 Created.push_back(Op0.getNode());
8022 }
8023
8024 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
8025 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
8027}
8028
8030 const DenormalMode &Mode,
8031 SDNodeFlags Flags) const {
8032 SDLoc DL(Op);
8033 EVT VT = Op.getValueType();
8034 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8035 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
8036
8037 // This is specifically a check for the handling of denormal inputs, not the
8038 // result.
8039 if (Mode.Input == DenormalMode::PreserveSign ||
8040 Mode.Input == DenormalMode::PositiveZero) {
8041 // Test = X == 0.0
8042 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
8043 /*Signaling=*/false, Flags);
8044 }
8045
8046 // Testing it with denormal inputs to avoid wrong estimate.
8047 //
8048 // Test = fabs(X) < SmallestNormal
8049 const fltSemantics &FltSem = VT.getFltSemantics();
8050 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
8051 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
8052 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
8053 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
8054 /*Signaling=*/false, Flags);
8055}
8056
8058 bool LegalOps, bool OptForSize,
8060 unsigned Depth) const {
8061 // fneg is removable even if it has multiple uses.
8062 if (Op.getOpcode() == ISD::FNEG) {
8064 return Op.getOperand(0);
8065 }
8066
8067 // Don't recurse exponentially.
8069 return SDValue();
8070
8071 // Pre-increment recursion depth for use in recursive calls.
8072 ++Depth;
8073 const SDNodeFlags Flags = Op->getFlags();
8074 EVT VT = Op.getValueType();
8075 unsigned Opcode = Op.getOpcode();
8076
8077 // Don't allow anything with multiple uses unless we know it is free.
8078 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
8079 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
8080 isFPExtFree(VT, Op.getOperand(0).getValueType());
8081 if (!IsFreeExtend)
8082 return SDValue();
8083 }
8084
8085 auto RemoveDeadNode = [&](SDValue N) {
8086 if (N && N.getNode()->use_empty())
8087 DAG.RemoveDeadNode(N.getNode());
8088 };
8089
8090 SDLoc DL(Op);
8091
8092 // Because getNegatedExpression can delete nodes we need a handle to keep
8093 // temporary nodes alive in case the recursion manages to create an identical
8094 // node.
8095 std::list<HandleSDNode> Handles;
8096
8097 switch (Opcode) {
8098 case ISD::ConstantFP: {
8099 // Don't invert constant FP values after legalization unless the target says
8100 // the negated constant is legal.
8101 bool IsOpLegal =
8103 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
8104 OptForSize);
8105
8106 if (LegalOps && !IsOpLegal)
8107 break;
8108
8109 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
8110 V.changeSign();
8111 SDValue CFP = DAG.getConstantFP(V, DL, VT);
8112
8113 // If we already have the use of the negated floating constant, it is free
8114 // to negate it even it has multiple uses.
8115 if (!Op.hasOneUse() && CFP.use_empty())
8116 break;
8118 return CFP;
8119 }
8120 case ISD::SPLAT_VECTOR: {
8121 // fold splat_vector(fneg(X)) -> splat_vector(-X)
8122 SDValue X = Op.getOperand(0);
8124 break;
8125
8126 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
8127 if (!NegX)
8128 break;
8130 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
8131 }
8132 case ISD::BUILD_VECTOR: {
8133 // Only permit BUILD_VECTOR of constants.
8134 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
8135 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
8136 }))
8137 break;
8138
8139 bool IsOpLegal =
8142 llvm::all_of(Op->op_values(), [&](SDValue N) {
8143 return N.isUndef() ||
8144 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
8145 OptForSize);
8146 });
8147
8148 if (LegalOps && !IsOpLegal)
8149 break;
8150
8152 for (SDValue C : Op->op_values()) {
8153 if (C.isUndef()) {
8154 Ops.push_back(C);
8155 continue;
8156 }
8157 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
8158 V.changeSign();
8159 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
8160 }
8162 return DAG.getBuildVector(VT, DL, Ops);
8163 }
8164 case ISD::FADD: {
8165 if (!Flags.hasNoSignedZeros())
8166 break;
8167
8168 // After operation legalization, it might not be legal to create new FSUBs.
8169 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
8170 break;
8171 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8172
8173 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
8175 SDValue NegX =
8176 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8177 // Prevent this node from being deleted by the next call.
8178 if (NegX)
8179 Handles.emplace_back(NegX);
8180
8181 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
8183 SDValue NegY =
8184 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8185
8186 // We're done with the handles.
8187 Handles.clear();
8188
8189 // Negate the X if its cost is less or equal than Y.
8190 if (NegX && (CostX <= CostY)) {
8191 Cost = CostX;
8192 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
8193 if (NegY != N)
8194 RemoveDeadNode(NegY);
8195 return N;
8196 }
8197
8198 // Negate the Y if it is not expensive.
8199 if (NegY) {
8200 Cost = CostY;
8201 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
8202 if (NegX != N)
8203 RemoveDeadNode(NegX);
8204 return N;
8205 }
8206 break;
8207 }
8208 case ISD::FSUB: {
8209 // We can't turn -(A-B) into B-A when we honor signed zeros.
8210 if (!Flags.hasNoSignedZeros())
8211 break;
8212
8213 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8214 // fold (fneg (fsub 0, Y)) -> Y
8215 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
8216 if (C->isZero()) {
8218 return Y;
8219 }
8220
8221 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
8223 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
8224 }
8225 case ISD::FMUL:
8226 case ISD::FDIV: {
8227 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8228
8229 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
8231 SDValue NegX =
8232 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8233 // Prevent this node from being deleted by the next call.
8234 if (NegX)
8235 Handles.emplace_back(NegX);
8236
8237 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
8239 SDValue NegY =
8240 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8241
8242 // We're done with the handles.
8243 Handles.clear();
8244
8245 // Negate the X if its cost is less or equal than Y.
8246 if (NegX && (CostX <= CostY)) {
8247 Cost = CostX;
8248 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
8249 if (NegY != N)
8250 RemoveDeadNode(NegY);
8251 return N;
8252 }
8253
8254 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
8255 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
8256 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
8257 break;
8258
8259 // Negate the Y if it is not expensive.
8260 if (NegY) {
8261 Cost = CostY;
8262 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
8263 if (NegX != N)
8264 RemoveDeadNode(NegX);
8265 return N;
8266 }
8267 break;
8268 }
8269 case ISD::FMA:
8270 case ISD::FMULADD:
8271 case ISD::FMAD: {
8272 if (!Flags.hasNoSignedZeros())
8273 break;
8274
8275 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
8277 SDValue NegZ =
8278 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
8279 // Give up if fail to negate the Z.
8280 if (!NegZ)
8281 break;
8282
8283 // Prevent this node from being deleted by the next two calls.
8284 Handles.emplace_back(NegZ);
8285
8286 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
8288 SDValue NegX =
8289 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8290 // Prevent this node from being deleted by the next call.
8291 if (NegX)
8292 Handles.emplace_back(NegX);
8293
8294 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
8296 SDValue NegY =
8297 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8298
8299 // We're done with the handles.
8300 Handles.clear();
8301
8302 // Negate the X if its cost is less or equal than Y.
8303 if (NegX && (CostX <= CostY)) {
8304 Cost = std::min(CostX, CostZ);
8305 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
8306 if (NegY != N)
8307 RemoveDeadNode(NegY);
8308 return N;
8309 }
8310
8311 // Negate the Y if it is not expensive.
8312 if (NegY) {
8313 Cost = std::min(CostY, CostZ);
8314 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
8315 if (NegX != N)
8316 RemoveDeadNode(NegX);
8317 return N;
8318 }
8319 break;
8320 }
8321
8322 case ISD::FP_EXTEND:
8323 case ISD::FSIN:
8324 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8325 OptForSize, Cost, Depth))
8326 return DAG.getNode(Opcode, DL, VT, NegV);
8327 break;
8328 case ISD::FP_ROUND:
8329 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8330 OptForSize, Cost, Depth))
8331 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
8332 break;
8333 case ISD::SELECT:
8334 case ISD::VSELECT: {
8335 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
8336 // iff at least one cost is cheaper and the other is neutral/cheaper
8337 SDValue LHS = Op.getOperand(1);
8339 SDValue NegLHS =
8340 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
8341 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
8342 RemoveDeadNode(NegLHS);
8343 break;
8344 }
8345
8346 // Prevent this node from being deleted by the next call.
8347 Handles.emplace_back(NegLHS);
8348
8349 SDValue RHS = Op.getOperand(2);
8351 SDValue NegRHS =
8352 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
8353
8354 // We're done with the handles.
8355 Handles.clear();
8356
8357 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
8358 (CostLHS != NegatibleCost::Cheaper &&
8359 CostRHS != NegatibleCost::Cheaper)) {
8360 RemoveDeadNode(NegLHS);
8361 RemoveDeadNode(NegRHS);
8362 break;
8363 }
8364
8365 Cost = std::min(CostLHS, CostRHS);
8366 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
8367 }
8368 }
8369
8370 return SDValue();
8371}
8372
8373//===----------------------------------------------------------------------===//
8374// Legalization Utilities
8375//===----------------------------------------------------------------------===//
8376
8377bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
8378 SDValue LHS, SDValue RHS,
8380 EVT HiLoVT, SelectionDAG &DAG,
8381 MulExpansionKind Kind, SDValue LL,
8382 SDValue LH, SDValue RL, SDValue RH) const {
8383 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
8384 Opcode == ISD::SMUL_LOHI);
8385
8386 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
8388 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8390 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8392 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8394
8395 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8396 return false;
8397
8398 unsigned OuterBitSize = VT.getScalarSizeInBits();
8399 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8400
8401 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8402 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8403 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8404
8405 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8406 bool Signed) -> bool {
8407 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8408 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8409 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8410 Hi = Lo.getValue(1);
8411 return true;
8412 }
8413 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8414 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8415 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8416 return true;
8417 }
8418 return false;
8419 };
8420
8421 SDValue Lo, Hi;
8422
8423 if (!LL.getNode() && !RL.getNode() &&
8425 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8426 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8427 }
8428
8429 if (!LL.getNode())
8430 return false;
8431
8432 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8433 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8434 DAG.MaskedValueIsZero(RHS, HighMask)) {
8435 // The inputs are both zero-extended.
8436 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8437 Result.push_back(Lo);
8438 Result.push_back(Hi);
8439 if (Opcode != ISD::MUL) {
8440 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8441 Result.push_back(Zero);
8442 Result.push_back(Zero);
8443 }
8444 return true;
8445 }
8446 }
8447
8448 if (!VT.isVector() && Opcode == ISD::MUL &&
8449 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8450 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8451 // The input values are both sign-extended.
8452 // TODO non-MUL case?
8453 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8454 Result.push_back(Lo);
8455 Result.push_back(Hi);
8456 return true;
8457 }
8458 }
8459
8460 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8461 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8462
8463 if (!LH.getNode() && !RH.getNode() &&
8466 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8467 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8468 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8469 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8470 }
8471
8472 if (!LH.getNode())
8473 return false;
8474
8475 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8476 return false;
8477
8478 Result.push_back(Lo);
8479
8480 if (Opcode == ISD::MUL) {
8481 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8482 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8483 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8484 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8485 Result.push_back(Hi);
8486 return true;
8487 }
8488
8489 // Compute the full width result.
8490 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8491 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8492 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8493 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8494 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8495 };
8496
8497 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8498 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8499 return false;
8500
8501 // This is effectively the add part of a multiply-add of half-sized operands,
8502 // so it cannot overflow.
8503 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8504
8505 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8506 return false;
8507
8508 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8509 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8510
8511 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8513 if (UseGlue)
8514 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8515 Merge(Lo, Hi));
8516 else
8517 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8518 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8519
8520 SDValue Carry = Next.getValue(1);
8521 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8522 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8523
8524 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8525 return false;
8526
8527 if (UseGlue)
8528 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8529 Carry);
8530 else
8531 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8532 Zero, Carry);
8533
8534 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8535
8536 if (Opcode == ISD::SMUL_LOHI) {
8537 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8538 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8539 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8540
8541 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8542 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8543 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8544 }
8545
8546 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8547 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8548 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8549 return true;
8550}
8551
8553 SelectionDAG &DAG, MulExpansionKind Kind,
8554 SDValue LL, SDValue LH, SDValue RL,
8555 SDValue RH) const {
8557 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8558 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8559 DAG, Kind, LL, LH, RL, RH);
8560 if (Ok) {
8561 assert(Result.size() == 2);
8562 Lo = Result[0];
8563 Hi = Result[1];
8564 }
8565 return Ok;
8566}
8567
8568// Optimize unsigned division or remainder by constants for types twice as large
8569// as a legal VT.
8570//
8571// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8572// can be computed
8573// as:
8574// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8575// Remainder = Sum % Constant;
8576//
8577// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8578// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8579// High:Low into 3 chunks of W bits and compute remainder as
8580// Sum = Chunk0 + Chunk1 + Chunk2;
8581// Remainder = Sum % Constant;
8582//
8583// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8584//
8585// For division, we can compute the remainder using the algorithm described
8586// above, subtract it from the dividend to get an exact multiple of Constant.
8587// Then multiply that exact multiply by the multiplicative inverse modulo
8588// (1 << (BitWidth / 2)) to get the quotient.
8589
8590// If Constant is even, we can shift right the dividend and the divisor by the
8591// number of trailing zeros in Constant before applying the remainder algorithm.
8592// If we're after the quotient, we can subtract this value from the shifted
8593// dividend and multiply by the multiplicative inverse of the shifted divisor.
8594// If we want the remainder, we shift the value left by the number of trailing
8595// zeros and add the bits that were shifted out of the dividend.
8596bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8597 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8598 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8599 unsigned Opcode = N->getOpcode();
8600 EVT VT = N->getValueType(0);
8601
8602 unsigned BitWidth = Divisor.getBitWidth();
8603 unsigned HBitWidth = BitWidth / 2;
8605 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8606
8607 // If the divisor is even, shift it until it becomes odd.
8608 unsigned TrailingZeros = 0;
8609 if (!Divisor[0]) {
8610 TrailingZeros = Divisor.countr_zero();
8611 Divisor.lshrInPlace(TrailingZeros);
8612 }
8613
8614 // After removing trailing zeros, the divisor needs to be less than
8615 // (1 << HBitWidth).
8616 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8617 if (Divisor.uge(HalfMaxPlus1))
8618 return false;
8619
8620 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8621 // (1 << W) % Divisor == -1.
8622 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8623 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8624 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8625 if (I == HBitWidth - 1)
8626 continue;
8627
8628 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8629
8630 if (Mod.isOne()) {
8631 BestChunkWidth = I;
8632 break;
8633 }
8634
8635 // We have an alternate strategy for Remainder == Divisor - 1.
8636 // FIXME: Support HBitWidth.
8637 if (I != HBitWidth && Mod == Divisor - 1)
8638 AltChunkWidth = I;
8639 }
8640
8641 bool Alternate = false;
8642 if (!BestChunkWidth) {
8643 if (!AltChunkWidth)
8644 return false;
8645 Alternate = true;
8646 BestChunkWidth = AltChunkWidth;
8647 }
8648
8649 SDLoc dl(N);
8650
8651 assert(!LL == !LH && "Expected both input halves or no input halves!");
8652 if (!LL)
8653 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8654
8655 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8656
8657 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8658 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8659 if (HasFSHR)
8660 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8661 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8662 return DAG.getNode(
8663 ISD::OR, dl, HiLoVT,
8664 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8665 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8666 DAG.getNode(
8667 ISD::SHL, dl, HiLoVT, Hi,
8668 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8669 };
8670
8671 // Helper to perform a right shift on a 128-bit value split into two halves.
8672 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8673 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8674 if (ShiftAmt == 0)
8675 return;
8676 if (ShiftAmt < HBitWidth) {
8677 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8678 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8679 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8680 } else if (ShiftAmt == HBitWidth) {
8681 Lo = Hi;
8682 Hi = DAG.getConstant(0, dl, HiLoVT);
8683 } else {
8684 Lo = DAG.getNode(
8685 ISD::SRL, dl, HiLoVT, Hi,
8686 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8687 Hi = DAG.getConstant(0, dl, HiLoVT);
8688 }
8689 };
8690
8691 // Shift the input by the number of TrailingZeros in the divisor. The
8692 // shifted out bits will be added to the remainder later.
8693 SDValue PartialRemL, PartialRemH;
8694 if (TrailingZeros && Opcode != ISD::UDIV) {
8695 // Save the shifted off bits if we need the remainder.
8696 if (TrailingZeros < HBitWidth) {
8697 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8698 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8699 DAG.getConstant(Mask, dl, HiLoVT));
8700 } else if (TrailingZeros == HBitWidth) {
8701 // All of LL is part of the remainder.
8702 PartialRemL = LL;
8703 } else {
8704 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8705 PartialRemL = LL;
8706 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8707 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8708 DAG.getConstant(Mask, dl, HiLoVT));
8709 }
8710 }
8711
8712 SDValue Sum;
8713 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8714 // out, add that to the final sum.
8715 if (BestChunkWidth == HBitWidth) {
8716 assert(!Alternate);
8717 // Shift LH:LL right if there were trailing zeros in the divisor.
8718 ShiftRight(LL, LH, TrailingZeros);
8719
8720 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8721 EVT SetCCType =
8722 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8724 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8725 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8726 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8727 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8728 } else {
8729 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8730 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8731 // If the boolean for the target is 0 or 1, we can add the setcc result
8732 // directly.
8733 if (getBooleanContents(HiLoVT) ==
8735 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8736 else
8737 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8738 DAG.getConstant(0, dl, HiLoVT));
8739 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8740 }
8741 } else {
8742 // Otherwise split into multple chunks and add them together. We chose
8743 // BestChunkWidth so that the sum will not overflow.
8744 SDValue Mask = DAG.getConstant(
8745 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8746
8747 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8748 // If there were trailing zeros in the divisor, increase the shift amount.
8749 unsigned Shift = I + TrailingZeros;
8750 SDValue Chunk;
8751 if (Shift == 0)
8752 Chunk = LL;
8753 else if (Shift >= HBitWidth)
8754 Chunk = DAG.getNode(
8755 ISD::SRL, dl, HiLoVT, LH,
8756 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8757 else
8758 Chunk = GetFSHR(LL, LH, Shift);
8759 // If we're on the last chunk, we don't need an AND.
8760 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8761 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8762 if (!Sum) {
8763 Sum = Chunk;
8764 } else {
8765 // For Alternate, we need to subtract odd chunks.
8766 unsigned ChunkNum = I / BestChunkWidth;
8767 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8768 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8769 }
8770 }
8771
8772 // For Alternate, the sum may be negative, but we need a positive sum. We
8773 // can increase it by a multiple of the divisor to make it positive. For 3
8774 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8775 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8776 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8777 // positive.
8778 if (Alternate) {
8779 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8780 assert(NumChunks <= 4);
8781
8782 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8783 Adjust.setBit(0);
8784 // If there are 4 chunks, we need to adjust twice.
8785 if (NumChunks == 4)
8786 Adjust <<= 1;
8787 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8788 DAG.getConstant(Adjust, dl, HiLoVT));
8789 }
8790 }
8791
8792 // Perform a HiLoVT urem on the Sum using truncated divisor.
8793 SDValue RemL =
8794 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8795 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8796 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8797
8798 if (Opcode != ISD::UREM) {
8799 // If we didn't shift LH/LR earlier, do it now.
8800 if (BestChunkWidth != HBitWidth)
8801 ShiftRight(LL, LH, TrailingZeros);
8802
8803 // Subtract the remainder from the shifted dividend.
8804 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8805 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8806
8807 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8808
8809 // Multiply by the multiplicative inverse of the divisor modulo
8810 // (1 << BitWidth).
8811 APInt MulFactor = Divisor.multiplicativeInverse();
8812
8813 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8814 DAG.getConstant(MulFactor, dl, VT));
8815
8816 // Split the quotient into low and high parts.
8817 SDValue QuotL, QuotH;
8818 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8819 Result.push_back(QuotL);
8820 Result.push_back(QuotH);
8821 }
8822
8823 if (Opcode != ISD::UDIV) {
8824 // If we shifted the input, shift the remainder left and add the bits we
8825 // shifted off the input.
8826 if (TrailingZeros) {
8827 if (TrailingZeros < HBitWidth) {
8828 // Shift RemH:RemL left by TrailingZeros.
8829 // RemH gets the high bits shifted out of RemL.
8830 RemH = DAG.getNode(
8831 ISD::SRL, dl, HiLoVT, RemL,
8832 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8833 RemL =
8834 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8835 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8836 // OR in the partial remainder.
8837 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8839 } else if (TrailingZeros == HBitWidth) {
8840 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8841 // PartialRemL.
8842 RemH = RemL;
8843 RemL = PartialRemL;
8844 } else {
8845 // Shift left by more than HBitWidth.
8846 RemH = DAG.getNode(
8847 ISD::SHL, dl, HiLoVT, RemL,
8848 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8849 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8851 RemL = PartialRemL;
8852 }
8853 }
8854 Result.push_back(RemL);
8855 Result.push_back(RemH);
8856 }
8857
8858 return true;
8859}
8860
8861bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8862 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8863 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8864
8865 SDValue N0 = N->getOperand(0);
8866 EVT VT = N0->getValueType(0);
8867 SDLoc DL{N};
8868
8869 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8870
8871 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8872 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8873 const APInt &Const,
8874 SmallVectorImpl<SDValue> &Result) {
8875 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8876 SDValue RHS = DAG.getConstant(Const, DL, VT);
8877 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8878 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8880 LL, LH, RL, RH);
8881 };
8882
8883 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8884 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8885 SDValue RH) {
8886 SDValue AddSubNode =
8888 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8889 SDValue OutL = AddSubNode.getValue(0);
8890 SDValue Overflow = AddSubNode.getValue(1);
8891 SDValue AddSubWithOverflow =
8893 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8894 SDValue OutH = AddSubWithOverflow.getValue(0);
8895 return std::make_pair(OutL, OutH);
8896 };
8897
8898 // This helper creates a SRL of the pair (LL, LH) by Shift.
8899 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8900 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8901 if (Shift < HBitWidth) {
8902 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8903 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8904 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8905 return std::make_pair(ResL, ResH);
8906 }
8907 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8908 if (Shift == HBitWidth)
8909 return std::make_pair(LH, Zero);
8910 assert(Shift - HBitWidth < HBitWidth &&
8911 "We shouldn't generate an undefined shift");
8912 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8913 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8914 };
8915
8916 // Knowledge of leading zeros may help to reduce the multiplier.
8917 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8918
8919 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8920 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8921
8922 assert(!LL == !LH && "Expected both input halves or no input halves!");
8923 if (!LL)
8924 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8925 SDValue QL = LL;
8926 SDValue QH = LH;
8927 if (Magics.PreShift != 0)
8928 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8929
8930 SmallVector<SDValue, 4> UMulResult;
8931 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8932 return false;
8933
8934 QL = UMulResult[2];
8935 QH = UMulResult[3];
8936
8937 if (Magics.IsAdd) {
8938 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8939 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8940 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8941 }
8942
8943 if (Magics.PostShift != 0)
8944 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8945
8946 unsigned Opcode = N->getOpcode();
8947 if (Opcode != ISD::UREM) {
8948 Result.push_back(QL);
8949 Result.push_back(QH);
8950 }
8951
8952 if (Opcode != ISD::UDIV) {
8953 SmallVector<SDValue, 2> MulResult;
8954 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8955 return false;
8956
8957 assert(MulResult.size() == 2);
8958
8959 auto [RemL, RemH] =
8960 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8961
8962 Result.push_back(RemL);
8963 Result.push_back(RemH);
8964 }
8965
8966 return true;
8967}
8968
8971 EVT HiLoVT, SelectionDAG &DAG,
8972 SDValue LL, SDValue LH) const {
8973 unsigned Opcode = N->getOpcode();
8974
8975 // TODO: Support signed division/remainder.
8976 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8977 return false;
8978 assert(
8979 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8980 "Unexpected opcode");
8981
8982 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8983 if (!CN)
8984 return false;
8985
8986 APInt Divisor = CN->getAPIntValue();
8987
8988 // The generated half-width UREM is normally optimized using high multiply.
8989 // If the wide UREM libcall is unavailable, a legal or custom half-width
8990 // UDIVREM can lower it instead.
8991 bool CanDecomposeUREMWithoutMulHi =
8992 Opcode == ISD::UREM &&
8993 DAG.getLibcalls().getLibcallImpl(RTLIB::getUREM(N->getValueType(0))) ==
8994 RTLIB::Unsupported &&
8996 if (!CanDecomposeUREMWithoutMulHi &&
8999 return false;
9000
9001 // Prefer the smaller libcall when one is available.
9002 if (DAG.shouldOptForSize() && !CanDecomposeUREMWithoutMulHi)
9003 return false;
9004
9005 // Early out for 0 or 1 divisors.
9006 if (Divisor.ule(1))
9007 return false;
9008
9009 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
9010 DAG, LL, LH))
9011 return true;
9012
9013 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
9014 LH))
9015 return true;
9016
9017 return false;
9018}
9019
9020// Check that (every element of) Z is undef or not an exact multiple of BW.
9021static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
9023 Z,
9024 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
9025 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
9026}
9027
9029 SelectionDAG &DAG) const {
9030 EVT VT = Node->getValueType(0);
9031
9032 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
9036 return SDValue();
9037
9038 SDValue X = Node->getOperand(0);
9039 SDValue Y = Node->getOperand(1);
9040 SDValue Z = Node->getOperand(2);
9041
9042 unsigned BW = VT.getScalarSizeInBits();
9043 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
9044 SDLoc DL(SDValue(Node, 0));
9045
9046 EVT ShVT = Z.getValueType();
9047
9048 // If a funnel shift in the other direction is more supported, use it.
9049 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
9050 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
9051 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
9052 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
9053 // fshl X, Y, Z -> fshr X, Y, -Z
9054 // fshr X, Y, Z -> fshl X, Y, -Z
9055 Z = DAG.getNegative(Z, DL, ShVT);
9056 } else {
9057 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
9058 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
9059 SDValue One = DAG.getConstant(1, DL, ShVT);
9060 if (IsFSHL) {
9061 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
9062 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
9063 } else {
9064 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
9065 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
9066 }
9067 Z = DAG.getNOT(DL, Z, ShVT);
9068 }
9069 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
9070 }
9071
9072 SDValue ShX, ShY;
9073 SDValue ShAmt, InvShAmt;
9074 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
9075 // fshl: X << C | Y >> (BW - C)
9076 // fshr: X << (BW - C) | Y >> C
9077 // where C = Z % BW is not zero
9078 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
9079 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
9080 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
9081 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
9082 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
9083 } else {
9084 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
9085 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
9086 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
9087 if (isPowerOf2_32(BW)) {
9088 // Z % BW -> Z & (BW - 1)
9089 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
9090 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
9091 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
9092 } else {
9093 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
9094 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
9095 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
9096 }
9097
9098 SDValue One = DAG.getConstant(1, DL, ShVT);
9099 if (IsFSHL) {
9100 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
9101 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
9102 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
9103 } else {
9104 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
9105 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
9106 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
9107 }
9108 }
9109 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
9110}
9111
9112// TODO: Merge with expandFunnelShift.
9114 SelectionDAG &DAG) const {
9115 EVT VT = Node->getValueType(0);
9116 unsigned EltSizeInBits = VT.getScalarSizeInBits();
9117 bool IsLeft = Node->getOpcode() == ISD::ROTL;
9118 SDValue Op0 = Node->getOperand(0);
9119 SDValue Op1 = Node->getOperand(1);
9120 SDLoc DL(SDValue(Node, 0));
9121
9122 EVT ShVT = Op1.getValueType();
9123 SDValue Zero = DAG.getConstant(0, DL, ShVT);
9124
9125 // If a rotate in the other direction is more supported, use it.
9126 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
9127 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
9128 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
9129 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
9130 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
9131 }
9132
9133 if (!AllowVectorOps && VT.isVector() &&
9139 return SDValue();
9140
9141 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
9142 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
9143 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
9144 SDValue ShVal;
9145 SDValue HsVal;
9146 if (isPowerOf2_32(EltSizeInBits)) {
9147 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
9148 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
9149 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
9150 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
9151 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
9152 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
9153 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
9154 } else {
9155 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
9156 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
9157 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
9158 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
9159 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
9160 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
9161 SDValue One = DAG.getConstant(1, DL, ShVT);
9162 HsVal =
9163 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
9164 }
9165 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
9166}
9167
9168/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
9169/// a chain of halving decompositions (halving element width) and/or vector
9170/// widening (doubling element count). This guides expansion strategy selection:
9171/// if true, the halving/widening path produces better code than bit-by-bit.
9172///
9173/// HalveDepth tracks halving steps only (each creates ~4x more operations).
9174/// Widening steps are cheap (O(1) pad/extract) and don't count.
9175/// Limiting halvings to 2 prevents exponential blowup:
9176/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
9177/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
9178/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
9180 EVT VT, unsigned HalveDepth = 0,
9181 unsigned TotalDepth = 0) {
9182 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
9183 return false;
9184 if (TLI.isOperationLegalOrCustom(ISD::CLMUL, VT))
9185 return true;
9186 if (!TLI.isTypeLegal(VT))
9187 return false;
9188
9189 unsigned BW = VT.getScalarSizeInBits();
9190
9191 // Halve: halve element width, same element count.
9192 // This is the expensive step -- each halving creates ~4x more operations.
9193 if (BW % 2 == 0) {
9194 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
9195 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
9196 if (TLI.isTypeLegal(HalfVT) &&
9197 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
9198 return true;
9199 }
9200
9201 // Widen: double element count (fixed-width vectors only).
9202 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
9203 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
9204 if (TLI.isTypeLegal(WideVT) &&
9205 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
9206 return true;
9207
9208 return false;
9209}
9210
9212 SDLoc DL(Node);
9213 EVT VT = Node->getValueType(0);
9214 SDValue X = Node->getOperand(0);
9215 SDValue Y = Node->getOperand(1);
9216 unsigned BW = VT.getScalarSizeInBits();
9217 unsigned Opcode = Node->getOpcode();
9218 LLVMContext &Ctx = *DAG.getContext();
9219
9220 switch (Opcode) {
9221 case ISD::CLMUL: {
9222 // For vector types, try decomposition strategies that leverage legal
9223 // CLMUL on narrower or wider element types, avoiding the expensive
9224 // bit-by-bit expansion.
9225 if (VT.isVector()) {
9226 // Strategy 1: Halving decomposition to half-element-width CLMUL.
9227 // Applies ExpandIntRes_CLMUL's identity element-wise:
9228 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
9229 // where:
9230 // Lo = CLMUL(XLo, YLo)
9231 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9232 unsigned HalfBW = BW / 2;
9233 if (BW % 2 == 0) {
9234 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
9235 EVT HalfVT =
9236 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
9237 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
9238 /*HalveDepth=*/1)) {
9239 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
9240
9241 // Extract low and high halves of each element.
9242 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
9243 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9244 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
9245 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
9246 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9247 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
9248
9249 // Lo = CLMUL(XLo, YLo)
9250 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
9251
9252 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9253 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
9254 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
9255 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
9256 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
9257 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
9258
9259 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
9260 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
9261 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
9262 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
9263 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
9264 }
9265 }
9266
9267 // Strategy 2: Promote to double-element-width CLMUL.
9268 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
9269 {
9270 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9271 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
9272 // If CLMUL on ExtVT is Custom (not Legal), the target may
9273 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
9274 // fallback costs O(BW) vectorized iterations. Only widen when
9275 // element count is small enough that scalarization is cheaper.
9276 unsigned NumElts = VT.getVectorMinNumElements();
9277 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
9278 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
9279 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
9280 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9281 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
9282 }
9283 }
9284 }
9285
9286 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
9287 // vector, extract lower result). CLMUL is element-wise, so upper
9288 // (undef) lanes don't affect the lower results.
9289 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
9290 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
9291 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
9292 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
9293 SDValue Undef = DAG.getUNDEF(WideVT);
9294 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9295 X, DAG.getVectorIdxConstant(0, DL));
9296 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9297 Y, DAG.getVectorIdxConstant(0, DL));
9298 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
9299 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
9300 DAG.getVectorIdxConstant(0, DL));
9301 }
9302 }
9303 }
9304
9305 // Special case: clmul(X, Y) where Y is a known constant (splat) that forms
9306 // a contiguous block of trailing ones whose length N is a power of two
9307 // (e.g. i8 0xFF, i8 0x0F, ...) or equal to the operand width. In this
9308 // special case, clmul(X, Y) is equivalent to a "parallel prefix XOR" or
9309 // "bitwise parity" operation on X.
9310 //
9311 // Note: This special currently dose NOT apply when the mask is neither a
9312 // power of two nor equal to the operand width because the loop inside
9313 // behaves as if the mask was bit-ceiled, and "undoing" the XOR with parts
9314 // of that CLMUL is a recursive problem (e.g. CLMUL with a 20-bit mask
9315 // requires correction XOR with CLMUL with 12-bit mask).
9316 if (auto *C = isConstOrConstSplat(Y, /*AllowUndefs=*/true)) {
9317 const APInt &YVal = C->getAPIntValue();
9318 unsigned N = YVal.countr_one();
9319 if (YVal.isAllOnes() || (YVal.isMask() && isPowerOf2_32(N))) {
9320 SDValue R = X;
9321 for (unsigned I = 1; I < N; I <<= 1) {
9322 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
9323 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
9324 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
9325 }
9326 return R;
9327 }
9328 }
9329
9330 // NOTE: If you change this expansion, please update the cost model
9331 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
9332 // Intrinsic::clmul.
9333
9334 // Strategy 4: multiplication with holes.
9335 //
9336 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
9337 // do occur, they wind up in a "hole" and are subsequently masked out of the
9338 // result.
9339 //
9340 // https://www.bearssl.org/constanttime.html#ghash-for-gcm describes this
9341 // approach.
9342
9343 // Stride S handles operands up to S·2^S bits using S² multiplies.
9344 //
9345 // * BW <= 8 uses S = 2 (holes of 1 bit)
9346 // * BW <= 24 uses S = 3 (holes of 2 bits)
9347 // * BW <= 64 uses S = 4 (holes of 3 bits)
9348 // * BW <= 160 uses S = 5 (holes of 4 bits)
9349 // * BW <= 384 uses S = 6 (holes of 5 bits)
9350 //
9351 // We distribute the BW bits over S phases:
9352 //
9353 // phase 0 keeps bits: 0, S, 2S, ...
9354 // phase 1 keeps bits: 1, S + 1, 2S + 1, ...
9355 // ...
9356 //
9357 // Each phase has up to n = ceil(BW / S) bits set, and the holes are S-1
9358 // bits wide.
9359 //
9360 // Take BW = 4, S = 2, n = 2. The worst case is a fully populated phase (all
9361 // non-hole bits are set to 1) multiplied by itself, 0b0101 * 0b0101. Each
9362 // set bit of one operand shifts a copy of the other, and we add the copies:
9363 //
9364 // col: 4 3 2 1 0
9365 // 0b0101 << 0: 0 0 1 0 1
9366 // 0b0101 << 2: 1 0 1 0 0
9367 // ----------------- +
9368 // count: 1 0 2 0 1
9369 //
9370 // Counting the number of one-bits in each column gives a triangle: the
9371 // counts climb 1, 2, ..., n and back down (here 1, 2, 1 across the data
9372 // columns). So a column holds at most n one-bits, and that maximum n is
9373 // reached in only one column: the peak. Every other column holds at most n
9374 // - 1 one-bits.
9375 //
9376 // A stack of one-bits in a column turns into carries: column 2 above really
9377 // stores the value 1 + 1 = 2 = n. A column spans S bits, its kept bit
9378 // plus S-1 hole bits, and the count is written from the kept bit upward,
9379 // so any count <= 2^S - 1 stays within the column and never interferes with
9380 // the next data bit S positions up. Every non-peak column holds at most n -
9381 // 1, so they all fit as soon as n - 1 <= 2^S - 1.
9382 //
9383 // That leaves only the peak column. Because both operands set all data
9384 // bits, the triangle peaks at the top of the word at the highest data bit
9385 // still inside BW. Here the count reaches exactly n = 2^S and overflows.
9386 // But its carry lands at bit n*S >= BW, off the top, where it (and the
9387 // whole descending half of the triangle) is truncated.
9388 //
9389 // Hence the holes suffice exactly when n = ceil(BW / S) <= 2^S, i.e. BW <=
9390 // S*2^S.
9391 //
9392 // Here we find the smallest S that satisfies this inequality.
9393 unsigned S = 1;
9394 while (S < 32 && divideCeil(BW, S) > (1u << S))
9395 ++S;
9396
9397 // The "multiplication with holes" expansion emits S*S MULs, 3*S ANDs,
9398 // S*(S-1) XORs and S-1 ORs.
9399 unsigned HolesCost = S * S + 3 * S + S * (S - 1) + (S - 1);
9400
9401 // Estimate the cost of the naive algorithm.
9402 KnownBits KnownY = DAG.computeKnownBits(Y);
9403 unsigned NaiveCost = 0;
9404 for (unsigned I = 0; I < BW; ++I) {
9405 // The iteration folds away entirely and is free.
9406 if (KnownY.Zero[I])
9407 continue;
9408
9409 // On targets with a fast bit test instruction more instructions are used
9410 // to not need a (potentially expensive) multiplication. See also below.
9411 if (hasBitTest(Y, DAG.getShiftAmountConstant(I, VT, DL))) {
9412 // AND + SETCC + SHL + SELECT + XOR.
9413 NaiveCost += 5;
9414 } else {
9415 // AND + MUL + XOR.
9416 NaiveCost += 3;
9417 }
9418 }
9419
9420 // Only use multiplication with holes when it is cheaper, else use the naive
9421 // fallback below.
9422 if (HolesCost < NaiveCost &&
9424
9425 // Set a bit every S positions, e.g. for S = 4 this is equivalent to
9426 // 0b...00010001...0001.
9427 APInt MaskVal = APInt::getSplat(BW, APInt(S, 1));
9428
9429 // Create versions of X and Y that keep only the I-th bit of each S-bit
9430 // slice.
9431 SmallVector<SDValue, 4> M(S), Xp(S), Yp(S);
9432 for (unsigned I = 0; I < S; ++I) {
9433 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9434 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9435 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9436 }
9437
9438 // Codegens these expressions (S*S multiplications), e.g. for S=4:
9439 //
9440 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9441 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9442 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9443 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9444 SDValue Res = DAG.getConstant(0, DL, VT);
9445 for (unsigned I = 0; I < S; ++I) {
9446 SDValue Zi = DAG.getConstant(0, DL, VT);
9447 for (unsigned J = 0; J < S; ++J) {
9448 unsigned K = (I + S - J) % S;
9449 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9450 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9451 }
9452
9453 // Keep only the bits belonging to this iteration, and bitwise or it all
9454 // together.
9455 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9456 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9457 }
9458 return Res;
9459 }
9460
9461 // Strategy 5: the naive fallback.
9462 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9463
9464 SDValue Res = DAG.getConstant(0, DL, VT);
9465 for (unsigned I = 0; I < BW; ++I) {
9466 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9467 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9468 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9469
9470 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9471 // multiply, use a shift-based expansion to avoid expensive MUL
9472 // instructions.
9473 SDValue Part;
9474 if (!hasBitTest(Y, ShiftAmt) &&
9477 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9478 } else {
9479 // Canonical bit test: (Y & (1 << I)) != 0
9480 SDValue Zero = DAG.getConstant(0, DL, VT);
9481 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9482 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9483 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9484 }
9485 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9486 }
9487 return Res;
9488 }
9489 case ISD::CLMULR:
9490 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9493 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9494 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9495 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9496 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9497 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9498 DAG.getShiftAmountConstant(1, VT, DL));
9499 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9500 }
9501 [[fallthrough]];
9502 case ISD::CLMULH: {
9503 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9504 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9505 // when any of these hold:
9506 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9507 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9508 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9509 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9510 // path creates CLMUL(VT) which will be expanded efficiently. The
9511 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9512 // causing a cycle.
9513 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9514 // => trunc path is preferred over the bitreverse path, as it avoids the
9515 // cost of 3 bitreverse operations.
9520 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9521 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9522 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9523 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9524 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9525 if (Opcode == ISD::CLMULH)
9526 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9527 DAG.getShiftAmountConstant(1, VT, DL));
9528 return Res;
9529 }
9530 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9531 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9532 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9533 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9534 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9535 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9536 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9537 }
9538 }
9539 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9540}
9541
9544 SDLoc dl(Node);
9545 SDValue Val = Node->getOperand(0);
9546 EVT VT = Val.getValueType();
9547 SDNodeFlags Flags = Node->getFlags();
9548
9549 SDValue IntPart = DAG.getNode(ISD::FTRUNC, dl, VT, Val, Flags);
9550 SDValue FracPart = DAG.getNode(ISD::FSUB, dl, VT, Val, IntPart, Flags);
9551
9552 SDValue FracToUse = FracPart;
9553 if (!Flags.hasNoInfs()) {
9554 SDValue Abs = DAG.getNode(ISD::FABS, dl, VT, Val, Flags);
9555 SDValue Inf =
9557 EVT SetCCVT =
9558 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9559 SDValue IsInf = DAG.getSetCC(dl, SetCCVT, Abs, Inf, ISD::SETOEQ);
9560 SDValue Zero = DAG.getConstantFP(0.0, dl, VT);
9561 FracToUse = DAG.getSelect(dl, VT, IsInf, Zero, FracPart);
9562 }
9563
9564 SDValue ResultFrac =
9565 DAG.getNode(ISD::FCOPYSIGN, dl, VT, FracToUse, Val, Flags);
9566 Results.push_back(ResultFrac);
9567 Results.push_back(IntPart);
9568 return true;
9569}
9570
9572 SDLoc DL(Node);
9573 EVT VT = Node->getValueType(0);
9574 SDValue Val = Node->getOperand(0);
9575 SDValue Msk = Node->getOperand(1);
9576 unsigned BW = VT.getScalarSizeInBits();
9577
9578 // Just scalarize if scalar PEXT is legal
9580 return DAG.UnrollVectorOp(Node);
9581
9582 // Hacker's Delight §7-4: Compress, or Generalized Extract
9583 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9584 SDValue M = Msk;
9585 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9586 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9587
9588 // Repeatedly compute which bits would shift to the right by an odd amount,
9589 // shift all such bits in parallel using a mask, and double the shift amount.
9590 for (unsigned I = 1; I < BW; I *= 2) {
9591 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9592 SDValue Mp =
9593 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9594 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9595 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9596 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9597 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9599 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9600 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9601 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9603 if (I * 2 < BW)
9604 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9605 }
9606
9607 return X;
9608}
9609
9611 SDLoc DL(Node);
9612 EVT VT = Node->getValueType(0);
9613 SDValue Val = Node->getOperand(0);
9614 SDValue Msk = Node->getOperand(1);
9615 unsigned BW = VT.getScalarSizeInBits();
9616
9617 // Just scalarize if scalar PDEP is legal
9619 return DAG.UnrollVectorOp(Node);
9620
9621 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9622 unsigned LogBW = Log2_32_Ceil(BW);
9623 SmallVector<SDValue, 8> MvArray(LogBW);
9624 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9625 SDValue Mc = Msk;
9626 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9627
9628 // First pass: compute move masks for each power of two that a bit moves by.
9629 for (unsigned S = 0; S < LogBW; ++S) {
9630 unsigned ShiftS = 1u << S;
9631 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9632 SDValue Mp =
9633 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9634 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9635 MvArray[S] = Mv;
9636 if (S + 1 < LogBW) {
9637 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9638 SDValue MvShifted = DAG.getNode(
9639 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9640 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9642 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9643 }
9644 }
9645
9646 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9647 // Each pass handles half the shift amount of the previous pass.
9648 SDValue X = Val;
9649 for (int S = (int)LogBW - 1; S >= 0; --S) {
9650 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9651 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9652 SDValue UnshiftedBits =
9653 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9654 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9655 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9657 }
9658
9659 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9660}
9661
9663 SelectionDAG &DAG) const {
9664 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9665 EVT VT = Node->getValueType(0);
9666 unsigned VTBits = VT.getScalarSizeInBits();
9667 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9668
9669 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9670 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9671 SDValue ShOpLo = Node->getOperand(0);
9672 SDValue ShOpHi = Node->getOperand(1);
9673 SDValue ShAmt = Node->getOperand(2);
9674 EVT ShAmtVT = ShAmt.getValueType();
9675 EVT ShAmtCCVT =
9676 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9677 SDLoc dl(Node);
9678
9679 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9680 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9681 // away during isel.
9682 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9683 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9684 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9685 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9686 : DAG.getConstant(0, dl, VT);
9687
9688 SDValue Tmp2, Tmp3;
9689 if (IsSHL) {
9690 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9691 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9692 } else {
9693 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9694 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9695 }
9696
9697 // If the shift amount is larger or equal than the width of a part we don't
9698 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9699 // values for large shift amounts.
9700 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9701 DAG.getConstant(VTBits, dl, ShAmtVT));
9702 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9703 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9704
9705 if (IsSHL) {
9706 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9707 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9708 } else {
9709 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9710 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9711 }
9712}
9713
9715 SelectionDAG &DAG) const {
9716 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9717 // suggested in
9718 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9719 // It uses strict_fp operations even outside a strict_fp context in order
9720 // to guarantee that the canonicalization is not optimized away by later
9721 // passes. The result chain introduced by that is intentionally ignored
9722 // since no ordering requirement is intended here.
9723 EVT VT = Node->getValueType(0);
9724 SDLoc DL(Node);
9725 SDNodeFlags Flags = Node->getFlags();
9726 Flags.setNoFPExcept(true);
9727 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9728 SDValue Mul =
9729 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9730 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9731 return Mul;
9732}
9733
9735 SelectionDAG &DAG) const {
9736 // Expand conversion from a native IEEE float type to an arbitrary FP format
9737 // returning the result as an integer using bit manipulation.
9738 EVT ResVT = Node->getValueType(0);
9739 SDLoc dl(Node);
9740
9741 SDValue FloatVal = Node->getOperand(0);
9742 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9743 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9744 const auto RoundMode =
9745 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9746 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9747
9748 // Supported destination formats.
9749 switch (Sem) {
9756 break;
9757 default:
9758 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9759 "destination format (semantics enum " +
9760 Twine(SemEnum) + ")");
9761 return SDValue();
9762 }
9763
9764 // Supported rounding modes.
9765 switch (RoundMode) {
9771 break;
9772 default:
9773 DAG.getContext()->emitError(
9774 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9775 Twine(static_cast<int>(RoundMode)) + ")");
9776 return SDValue();
9777 }
9778
9779 // Destination format parameters.
9780 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9781 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9782 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9783 const unsigned DstMant = DstPrecision - 1;
9784 // Unsigned formats spend no bit on the sign.
9785 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9786 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9787 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9788 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9789 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9790 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9791 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9792
9793 // Compute the maximum normal exponent for the destination format.
9794 const unsigned DstExpMaxNormal =
9795 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9796 : DstExpMax;
9797
9798 // For NanOnly formats the max exponent field for finite values
9799 // is DstExpMax, but the encoding with exp = DstExpMax and
9800 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9801 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9802 // avoid the NaN encoding.
9803 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9804 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9805 DstNanEnc == fltNanEncoding::AllOnes)
9806 DstMaxMantAtMaxExp = DstMantMask - 1;
9807
9808 // Source format parameters.
9809 EVT SrcVT = FloatVal.getValueType();
9810 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9811 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9812 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9813 const unsigned SrcMant = SrcPrecision - 1;
9814 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9815
9816 // Work in the source integer type. Match the destination shape so the
9817 // expansion stays vector when ResVT is a vector.
9818 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9819 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9820 EVT SetCCVT =
9821 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9822 EVT FPSetCCVT =
9823 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9824
9825 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9826 SDValue One = DAG.getConstant(1, dl, IntVT);
9827
9828 // Bitcast source float to integer to extract the sign bit.
9829 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9830 SDValue SignBit =
9831 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9832 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9833
9834 // Classify the input.
9835 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9836 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9837 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9838 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9839 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9840 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9841
9842 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9843 // source denormals automatically. The result is unspecified for Inf/NaN, but
9844 // those inputs are detected above and override the final result.
9845 EVT FrexpExpScalarVT =
9847 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9848 SDValue Frexp =
9849 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9850 SDValue FrexpFrac = Frexp.getValue(0);
9851 SDValue FrexpExp = Frexp.getValue(1);
9852
9853 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9854 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9855 DAG.getConstant(SrcMantMask, dl, IntVT));
9856
9857 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9858 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9859 DAG.getConstant(DstBias - 1, dl, IntVT));
9860
9861 // Compute rounding increment given the round bit, sticky bits, and LSB
9862 // of the truncated mantissa.
9863 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9864 SDValue LSB) -> SDValue {
9865 switch (RoundMode) {
9867 // Round up if round_bit && (sticky || lsb)
9868 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9869 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9870 }
9872 return Zero;
9874 // Round up if positive and any truncated bits are set.
9875 SDValue AnyTruncBits =
9876 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9877 SDValue HasTruncBits =
9878 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9879 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9880 SDValue DoRound =
9881 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9882 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9883 }
9885 // Round up if negative and any truncated bits are set (to -Inf).
9886 SDValue AnyTruncBits =
9887 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9888 SDValue HasTruncBits =
9889 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9890 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9891 SDValue DoRound =
9892 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9893 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9894 }
9896 return RoundBit;
9897 default:
9898 llvm_unreachable("unsupported rounding mode");
9899 }
9900 };
9901
9902 // Round mantissa from SrcMant bits to DstMant bits.
9903 SDValue TruncMant;
9904 SDValue RoundUp;
9905 if (SrcMant > DstMant) {
9906 const unsigned Shift = SrcMant - DstMant;
9907 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9908 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9909
9910 // Check bit at position Shift - 1 aka the round bit.
9911 SDValue RoundBit;
9912 if (Shift >= 1) {
9913 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9914 SDValue ShiftedMant =
9915 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9916 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9917 } else {
9918 RoundBit = Zero;
9919 }
9920
9921 // OR of all bits below the round bit to get sticky bits.
9922 SDValue StickyBits;
9923 if (Shift >= 2) {
9924 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9925 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9926 DAG.getConstant(StickyMask, dl, IntVT));
9927 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9928 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9929 } else {
9930 StickyBits = Zero;
9931 }
9932
9933 // LSB of truncated mantissa.
9934 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9935
9936 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9937 } else {
9938 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9939 SDValue MantShift =
9940 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9941 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9942 RoundUp = Zero;
9943 }
9944
9945 // Apply rounding.
9946 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9947
9948 // Handle mantissa overflow from rounding.
9949 // If rounded_mant > DstMantMask, carry into exponent.
9950 SDValue MantOverflow =
9951 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9952 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9953 // On overflow: mant = 0, exp += 1.
9954 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9955 SDValue AdjExp =
9956 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9957 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9958
9959 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9960 // sign bit to merge in.
9961 SDValue SignShifted =
9962 DstHasSign
9963 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9964 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9965 : Zero;
9966
9967 // Destination denormal conversion (when new_exp <= 0).
9968 // Shift the mantissa right by 1 - new_exp additional bits and set the
9969 // exponent field to 0.
9970 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9971 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9972
9973 SDValue DenormResult;
9974 {
9975 // denorm_shift = 1 - NewExp.
9976 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9977
9978 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9979 SDValue ImplicitOne =
9980 DAG.getNode(ISD::SHL, dl, IntVT, One,
9981 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9982 SDValue FullSrcMant =
9983 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9984
9985 // Total right shift = DenormShift + (SrcMant - DstMant).
9986 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9987 SDValue TotalShift =
9988 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9989 DAG.getSignedConstant(MantDelta, dl, IntVT));
9990
9991 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9992 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9993 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9994 SDValue ClampedShift =
9995 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9996 SDValue DenormTruncMant =
9997 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9998 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9999
10000 // Rounding for denorm path.
10001 SDValue DenormRoundUp;
10002 {
10003 // Round bit is at position TotalShift - 1 of FullSrcMant.
10004 // Clamp to at least 1 so the subtraction doesn't underflow and create
10005 // shift nodes with invalid shift amounts.
10006 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
10007 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
10008 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
10009 SDValue DenormRoundBit = DAG.getNode(
10010 ISD::AND, dl, IntVT,
10011 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
10012
10013 // Sticky: all bits below round bit.
10014 // sticky_mask = (1 << RoundBitPos) - 1
10015 SDValue StickyMask = DAG.getNode(
10016 ISD::SUB, dl, IntVT,
10017 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
10018 SDValue DenormStickyBits =
10019 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
10020 SDValue HasSticky = DAG.getNode(
10021 ISD::ZERO_EXTEND, dl, IntVT,
10022 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
10023
10024 SDValue DenormLSB =
10025 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
10026
10027 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
10028
10029 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
10030 SDValue ShiftGEOne =
10031 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
10032 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
10033 }
10034
10035 SDValue DenormRoundedMant =
10036 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
10037
10038 // If rounding caused overflow into the normal range, then we get the
10039 // smallest normal number.
10040 SDValue DenormMantOF =
10041 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
10042 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
10043 SDValue DenormFinalMant =
10044 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
10045 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
10046
10047 // Assemble: sign | (exp << DstMant) | mant
10048 SDValue DenormExpShifted =
10049 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
10050 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
10051 DenormResult = DAG.getNode(
10052 ISD::OR, dl, IntVT,
10053 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10054 DenormFinalMant);
10055 }
10056
10057 // Exponent overflow detection.
10058 SDValue ExpOF =
10059 DAG.getSetCC(dl, SetCCVT, AdjExp,
10060 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
10061
10062 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
10063 // a value that exceeds the max allowed mantissa at that exponent.
10064 SDValue ExpAtMax =
10065 DAG.getSetCC(dl, SetCCVT, AdjExp,
10066 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
10067 SDValue MantExceedsMax =
10068 DAG.getSetCC(dl, SetCCVT, AdjMant,
10069 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
10070 SDValue ExpMantOF =
10071 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
10072 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
10073
10074 // Build overflow result.
10076
10077 if (Saturate) {
10078 // Clamp to max finite value:
10079 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
10080 uint64_t MaxFinite =
10081 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
10082 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10083 DAG.getConstant(MaxFinite, dl, IntVT));
10084 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10085 // Produce infinity.
10086 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
10087 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10088 DAG.getConstant(InfBits, dl, IntVT));
10089 } else {
10090 // Emit poison if no Inf in format and not saturating.
10091 OverflowResult = DAG.getPOISON(IntVT);
10092 }
10093
10094 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
10095 SDValue NormExpShifted =
10096 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
10097 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
10098 SDValue NormResult = DAG.getNode(
10099 ISD::OR, dl, IntVT,
10100 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
10101
10102 // Build special-value results.
10103 SDValue NaNResult;
10104 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10105 // Produce canonical NaN.
10106 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10107 NaNResult =
10108 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
10109 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
10110 DstNanEnc == fltNanEncoding::AllOnes) {
10111 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
10112 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
10113 dl, IntVT);
10114 } else {
10115 // NaN -> poison for finite only values.
10116 NaNResult = DAG.getPOISON(IntVT);
10117 }
10118
10119 // Inf handling.
10120 SDValue InfResult;
10121 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10122 // Produce signed infinity.
10123 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
10124 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10125 DAG.getConstant(InfBits, dl, IntVT));
10126 } else if (Saturate) {
10127 // Inf saturates to max finite.
10128 uint64_t MaxFinite =
10129 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
10130 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10131 DAG.getConstant(MaxFinite, dl, IntVT));
10132 } else {
10133 // No Inf and not saturating -> poison.
10134 InfResult = DAG.getPOISON(IntVT);
10135 }
10136
10137 SDValue ZeroResult = SignShifted;
10138
10139 // Final selection in an order: NaN takes priority, then Inf, then Zero.
10140 SDValue FiniteResult =
10141 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
10142 FiniteResult =
10143 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
10144
10145 SDValue Result = FiniteResult;
10146 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10147 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10148
10149 // Negative values are unrepresentable in an unsigned format: clamp to zero
10150 // when saturating, poison otherwise so no select is needed. -0.0 is handled
10151 // by IsZero above. Run before the NaN case so a negative NaN still yields
10152 // NaN.
10153 if (!DstHasSign && Saturate) {
10154 SDValue IsNegative =
10155 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
10156 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
10157 }
10158
10159 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10160
10161 // Truncate to destination integer type.
10162 return DAG.getZExtOrTrunc(Result, dl, ResVT);
10163}
10164
10165SDValue
10167 SelectionDAG &DAG) const {
10168 SDLoc dl(Node);
10169 EVT DstVT = Node->getValueType(0);
10170 EVT DstScalarVT = DstVT.getScalarType();
10171
10172 SDValue IntVal = Node->getOperand(0);
10173 const uint64_t SemEnum = Node->getConstantOperandVal(1);
10174 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
10175
10176 // Supported source formats.
10177 switch (Sem) {
10184 break;
10185 default:
10186 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
10187 "source format (semantics enum " +
10188 Twine(SemEnum) + ")");
10189 return SDValue();
10190 }
10191
10192 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
10193 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
10194 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
10195 const unsigned SrcMant = SrcPrecision - 1;
10196 // Unsigned formats spend no bit on the sign.
10197 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
10198 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
10199 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
10200 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
10201
10202 // Destination format parameters.
10203 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
10204 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
10205 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
10206 const unsigned DstExpBits = DstBits - DstMant - 1;
10207 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
10208 const int DstBias = 1 - DstMinExp;
10209 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
10210
10211 // Work in an integer type matching the destination float width.
10212 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
10213 EVT IntVT = IntScalarVT;
10214 if (DstVT.isVector()) {
10215 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
10216 DstVT.getVectorElementCount());
10217 } else if (!isTypeLegal(IntScalarVT)) {
10218 // Avoid generating illegal type as there is no other places that'll
10219 // legalize it. Vector types don't have this problem because they
10220 // are subject to LegalizeVectorOps and another type legalization phase
10221 // will follow.
10222 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
10223 // We only know how to handle situations where the legal type is wider.
10224 DAG.getContext()->emitError(
10225 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
10226 "legalization is not supported");
10227 return SDValue();
10228 }
10229 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
10230 }
10231
10232 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
10233
10234 EVT SetCCVT =
10235 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
10236
10237 SDValue Zero = DAG.getConstant(0, dl, IntVT);
10238 SDValue One = DAG.getConstant(1, dl, IntVT);
10239
10240 // Extract bit fields.
10241 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
10242 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
10243
10244 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
10245 DAG.getConstant(MantMask, dl, IntVT));
10246
10247 SDValue ExpField =
10248 DAG.getNode(ISD::AND, dl, IntVT,
10249 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10250 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
10251 DAG.getConstant(ExpMask, dl, IntVT));
10252
10253 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
10254 // exponent.
10255 SDValue SignShifted =
10256 SrcHasSign
10257 ? DAG.getNode(
10258 ISD::SHL, dl, IntVT,
10259 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10260 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
10261 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
10262 : Zero;
10263
10264 // Classify the input.
10265 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
10266 SDValue IsExpAllOnes =
10267 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
10268 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
10269 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
10270 SDValue IsMantNonZero =
10271 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
10272
10273 SDValue IsNaN;
10274 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
10275 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10276 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
10277 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
10278 } else {
10280 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
10281 SDValue IsMantAllOnes =
10282 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
10283 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
10284 }
10285
10286 SDValue IsInf;
10287 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
10288 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
10289 else
10290 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10291
10292 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
10293 SDValue IsDenorm =
10294 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
10295
10296 // Normal value conversion.
10297 const int BiasAdjust = DstBias - SrcBias;
10298 SDValue NormDstExp = DAG.getNode(
10299 ISD::ADD, dl, IntVT, ExpField,
10300 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
10301 IntVT));
10302
10303 SDValue NormDstMant;
10304 if (DstMant > SrcMant) {
10305 SDValue NormDstMantShift =
10306 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
10307 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
10308 } else {
10309 NormDstMant = MantField;
10310 }
10311
10312 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
10313 SDValue NormExpShifted =
10314 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
10315 SDValue NormResult =
10316 DAG.getNode(ISD::OR, dl, IntVT,
10317 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
10318 NormDstMant);
10319
10320 // With identical exponent biases, denormal values remain denormal and the
10321 // normal conversion's mantissa shift is sufficient.
10322 SDValue DenormResult = NormResult;
10323 if (BiasAdjust != 0) {
10324 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
10325 SDValue LeadingZeros =
10326 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
10327
10328 const int DenormExpConst =
10329 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
10330 SDValue DenormDstExp = DAG.getNode(
10331 ISD::SUB, dl, IntVT,
10332 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
10333 LeadingZeros);
10334
10335 SDValue MantMSB =
10336 DAG.getNode(ISD::SUB, dl, IntVT,
10337 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
10338
10339 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
10340 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
10341
10342 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
10343 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
10344 DAG.getConstant(ShiftSub, dl, IntVT));
10345
10346 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
10347
10348 SDValue DenormExpShifted =
10349 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
10350 DenormResult = DAG.getNode(
10351 ISD::OR, dl, IntVT,
10352 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10353 DenormDstMant);
10354 }
10355
10356 SDValue FiniteResult =
10357 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
10358
10359 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10360 SDValue NaNResult =
10361 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
10362
10363 SDValue InfResult =
10364 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10365 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
10366
10367 // A source format may have a larger finite exponent range despite having
10368 // fewer bits, as with Float8E5M3FNU converted to half. Its overflowing finite
10369 // values become infinity. The NaN selection below still takes precedence.
10370 if (APFloat::semanticsMaxExponent(SrcSem) >
10372 SDValue IsOverflow =
10373 DAG.getSetCC(dl, SetCCVT, NormDstExp,
10374 DAG.getConstant(DstExpAllOnes, dl, IntVT), ISD::SETUGE);
10375 FiniteResult =
10376 DAG.getSelect(dl, IntVT, IsOverflow, InfResult, FiniteResult);
10377 }
10378
10379 SDValue ZeroResult = SignShifted;
10380
10381 SDValue Result = FiniteResult;
10382 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10383 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10384 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10385
10386 if (!DstVT.bitsEq(IntVT)) {
10387 // Store to stack before loading it back.
10388 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
10389 // IntScalarVT is the original type that has the same width as DstVT.
10390 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
10391 SDValue StackPtr =
10392 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
10393 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10395 MachinePointerInfo PtrInfo =
10396 MachinePointerInfo::getFixedStack(MF, FrameIndex);
10397 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
10398 PtrInfo, IntScalarVT, Alignment);
10399
10400 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
10401 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
10402 }
10403
10404 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
10405}
10406
10408 SelectionDAG &DAG) const {
10409 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10410 SDValue Src = Node->getOperand(OpNo);
10411 EVT SrcVT = Src.getValueType();
10412 EVT DstVT = Node->getValueType(0);
10413 SDLoc dl(SDValue(Node, 0));
10414
10415 // FIXME: Only f32 to i64 conversions are supported.
10416 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
10417 return false;
10418
10419 if (Node->isStrictFPOpcode())
10420 // When a NaN is converted to an integer a trap is allowed. We can't
10421 // use this expansion here because it would eliminate that trap. Other
10422 // traps are also allowed and cannot be eliminated. See
10423 // IEEE 754-2008 sec 5.8.
10424 return false;
10425
10426 // Expand f32 -> i64 conversion
10427 // This algorithm comes from compiler-rt's implementation of fixsfdi:
10428 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
10429 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
10430 EVT IntVT = SrcVT.changeTypeToInteger();
10431 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
10432
10433 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
10434 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
10435 SDValue Bias = DAG.getConstant(127, dl, IntVT);
10436 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
10437 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
10438 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
10439
10440 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
10441
10442 SDValue ExponentBits = DAG.getNode(
10443 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
10444 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
10445 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
10446
10447 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
10448 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
10449 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
10450 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10451
10452 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10453 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10454 DAG.getConstant(0x00800000, dl, IntVT));
10455
10456 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10457
10458 R = DAG.getSelectCC(
10459 dl, Exponent, ExponentLoBit,
10460 DAG.getNode(ISD::SHL, dl, DstVT, R,
10461 DAG.getZExtOrTrunc(
10462 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10463 dl, IntShVT)),
10464 DAG.getNode(ISD::SRL, dl, DstVT, R,
10465 DAG.getZExtOrTrunc(
10466 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10467 dl, IntShVT)),
10468 ISD::SETGT);
10469
10470 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10471 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10472
10473 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10474 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10475 return true;
10476}
10477
10479 SDValue &Chain,
10480 SelectionDAG &DAG) const {
10481 SDLoc dl(SDValue(Node, 0));
10482 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10483 SDValue Src = Node->getOperand(OpNo);
10484
10485 EVT SrcVT = Src.getValueType();
10486 EVT DstVT = Node->getValueType(0);
10487 EVT SetCCVT =
10488 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10489 EVT DstSetCCVT =
10490 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10491
10492 // Only expand vector types if we have the appropriate vector bit operations.
10493 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10495 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10497 return false;
10498
10499 // If the maximum float value is smaller then the signed integer range,
10500 // the destination signmask can't be represented by the float, so we can
10501 // just use FP_TO_SINT directly.
10502 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10503 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10504 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10506 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10507 if (Node->isStrictFPOpcode()) {
10508 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10509 { Node->getOperand(0), Src });
10510 Chain = Result.getValue(1);
10511 } else
10512 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10513 return true;
10514 }
10515
10516 // Don't expand it if there isn't cheap fsub instruction.
10518 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10519 return false;
10520
10521 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10522 SDValue Sel;
10523
10524 if (Node->isStrictFPOpcode()) {
10525 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10526 Node->getOperand(0), /*IsSignaling*/ true);
10527 Chain = Sel.getValue(1);
10528 } else {
10529 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10530 }
10531
10532 bool Strict = Node->isStrictFPOpcode() ||
10533 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10534
10535 if (Strict) {
10536 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10537 // signmask then offset (the result of which should be fully representable).
10538 // Sel = Src < 0x8000000000000000
10539 // FltOfs = select Sel, 0, 0x8000000000000000
10540 // IntOfs = select Sel, 0, 0x8000000000000000
10541 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10542
10543 // TODO: Should any fast-math-flags be set for the FSUB?
10544 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10545 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10546 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10547 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10548 DAG.getConstant(0, dl, DstVT),
10549 DAG.getConstant(SignMask, dl, DstVT));
10550 SDValue SInt;
10551 if (Node->isStrictFPOpcode()) {
10552 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10553 { Chain, Src, FltOfs });
10554 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10555 { Val.getValue(1), Val });
10556 Chain = SInt.getValue(1);
10557 } else {
10558 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10559 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10560 }
10561 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10562 } else {
10563 // Expand based on maximum range of FP_TO_SINT:
10564 // True = fp_to_sint(Src)
10565 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10566 // Result = select (Src < 0x8000000000000000), True, False
10567
10568 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10569 // TODO: Should any fast-math-flags be set for the FSUB?
10570 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10571 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10572 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10573 DAG.getConstant(SignMask, dl, DstVT));
10574 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10575 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10576 }
10577 return true;
10578}
10579
10581 SDValue &Chain, SelectionDAG &DAG) const {
10582 // This transform is not correct for converting 0 when rounding mode is set
10583 // to round toward negative infinity which will produce -0.0. So disable
10584 // under strictfp.
10585 if (Node->isStrictFPOpcode())
10586 return false;
10587
10588 SDValue Src = Node->getOperand(0);
10589 EVT SrcVT = Src.getValueType();
10590 EVT DstVT = Node->getValueType(0);
10591
10592 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10593 // it.
10594 if (Node->getFlags().hasNonNeg() &&
10596 Result =
10597 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10598 return true;
10599 }
10600
10601 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10602 return false;
10603
10604 // Only expand vector types if we have the appropriate vector bit
10605 // operations.
10606 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10611 return false;
10612
10613 SDLoc dl(SDValue(Node, 0));
10614
10615 // Implementation of unsigned i64 to f64 following the algorithm in
10616 // __floatundidf in compiler_rt. This implementation performs rounding
10617 // correctly in all rounding modes with the exception of converting 0
10618 // when rounding toward negative infinity. In that case the fsub will
10619 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10620 // incorrect.
10621 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10622 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10623 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10624 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10625 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10626 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10627
10628 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10629 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10630 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10631 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10632 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10633 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10634 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10635 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10636 return true;
10637}
10638
10639SDValue
10641 SelectionDAG &DAG) const {
10642 unsigned Opcode = Node->getOpcode();
10643 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10644 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10645 "Wrong opcode");
10646
10647 if (Node->getFlags().hasNoNaNs()) {
10648 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10649 EVT VT = Node->getValueType(0);
10650 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10652 VT.isVector())
10653 return SDValue();
10654 SDValue Op1 = Node->getOperand(0);
10655 SDValue Op2 = Node->getOperand(1);
10656 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10657 Node->getFlags());
10658 }
10659
10660 return SDValue();
10661}
10662
10664 SelectionDAG &DAG) const {
10665 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10666 return Expanded;
10667
10668 EVT VT = Node->getValueType(0);
10669 if (VT.isScalableVector())
10671 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10672
10673 SDLoc dl(Node);
10674 unsigned NewOp =
10676
10677 if (isOperationLegalOrCustom(NewOp, VT)) {
10678 SDValue Quiet0 = Node->getOperand(0);
10679 SDValue Quiet1 = Node->getOperand(1);
10680
10681 if (!Node->getFlags().hasNoNaNs()) {
10682 // Insert canonicalizes if it's possible we need to quiet to get correct
10683 // sNaN behavior.
10684 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10685 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10686 Node->getFlags());
10687 }
10688 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10689 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10690 Node->getFlags());
10691 }
10692 }
10693
10694 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10695 }
10696
10697 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10698 // instead if there are no NaNs.
10699 if (Node->getFlags().hasNoNaNs() ||
10700 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10701 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10702 unsigned IEEE2018Op =
10703 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10704 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10705 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10706 Node->getOperand(1), Node->getFlags());
10707 }
10708
10710 return SelCC;
10711
10712 return SDValue();
10713}
10714
10716 const TargetLowering &TLI,
10717 const SDLoc &DL, SDValue Val,
10718 FPClassTest FPClass) {
10719 EVT VT = Val.getValueType();
10720 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10721 EVT IntVT = VT.changeTypeToInteger();
10722 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10723 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10724 if (!TLI.isTypeLegal(IntVT) &&
10725 !TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, VT))
10726 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10727 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10728 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10729}
10730
10732 SelectionDAG &DAG) const {
10733 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10734 return Expanded;
10735
10736 SDLoc DL(N);
10737 SDValue LHS = N->getOperand(0);
10738 SDValue RHS = N->getOperand(1);
10739 unsigned Opc = N->getOpcode();
10740 EVT VT = N->getValueType(0);
10741 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10742 bool IsMax = Opc == ISD::FMAXIMUM;
10743 SDNodeFlags Flags = N->getFlags();
10744
10745 // First, implement comparison not propagating NaN. If no native fmin or fmax
10746 // available, use plain select with setcc instead.
10748 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10749 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10750
10751 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10752 // signed zero behavior.
10753 bool MinMaxMustRespectOrderedZero = false;
10754
10755 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10756 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10757 MinMaxMustRespectOrderedZero = true;
10758 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10759 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10760 } else {
10762 return DAG.UnrollVectorOp(N);
10763
10764 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10765 SDValue Compare =
10766 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10767 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10768 }
10769
10770 // Propagate any NaN of both operands
10771 if (!N->getFlags().hasNoNaNs() &&
10772 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10773 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10775 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10776 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10777 }
10778
10779 // fminimum/fmaximum requires -0.0 less than +0.0
10780 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10781 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10782 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10784 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10785 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10786 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10787 }
10788
10789 return MinMax;
10790}
10791
10793 SelectionDAG &DAG) const {
10794 SDLoc DL(Node);
10795 SDValue LHS = Node->getOperand(0);
10796 SDValue RHS = Node->getOperand(1);
10797 unsigned Opc = Node->getOpcode();
10798 EVT VT = Node->getValueType(0);
10799 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10800 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10801 SDNodeFlags Flags = Node->getFlags();
10802
10803 unsigned NewOp =
10805
10806 if (isOperationLegalOrCustom(NewOp, VT)) {
10807 if (!Flags.hasNoNaNs()) {
10808 // Insert canonicalizes if it's possible we need to quiet to get correct
10809 // sNaN behavior.
10810 if (!DAG.isKnownNeverSNaN(LHS)) {
10811 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10812 }
10813 if (!DAG.isKnownNeverSNaN(RHS)) {
10814 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10815 }
10816 }
10817
10818 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10819 }
10820
10821 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10822 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10823 if (Flags.hasNoNaNs() ||
10824 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10825 unsigned IEEE2019Op =
10827 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10828 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10829 }
10830
10831 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10832 // either one for +0.0 vs -0.0.
10833 if ((Flags.hasNoNaNs() ||
10834 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10835 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10836 DAG.isKnownNeverLogicalZero(RHS))) {
10837 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10838 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10839 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10840 }
10841
10842 if (VT.isVector() &&
10845 return DAG.UnrollVectorOp(Node);
10846
10847 // If only one operand is NaN, override it with another operand.
10848 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10849 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10850 }
10851 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10852 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10853 }
10854
10855 // Always prefer RHS if equal.
10856 SDValue MinMax =
10857 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10858
10859 // TODO: We need quiet sNaN if strictfp.
10860
10861 // Fixup signed zero behavior.
10862 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10863 DAG.isKnownNeverLogicalZero(RHS)) {
10864 return MinMax;
10865 }
10866 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10867 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10869 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10870 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10871 // we preferred RHS when generate MinMax, if the operands are equal.
10872 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10873 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10874}
10875
10876/// Returns a true value if if this FPClassTest can be performed with an ordered
10877/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10878/// std::nullopt if it cannot be performed as a compare with 0.
10879static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10880 const fltSemantics &Semantics,
10881 const MachineFunction &MF) {
10882 FPClassTest OrderedMask = Test & ~fcNan;
10883 FPClassTest NanTest = Test & fcNan;
10884 bool IsOrdered = NanTest == fcNone;
10885 bool IsUnordered = NanTest == fcNan;
10886
10887 // Skip cases that are testing for only a qnan or snan.
10888 if (!IsOrdered && !IsUnordered)
10889 return std::nullopt;
10890
10891 if (OrderedMask == fcZero &&
10892 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10893 return IsOrdered;
10894 if (OrderedMask == (fcZero | fcSubnormal) &&
10895 MF.getDenormalMode(Semantics).inputsAreZero())
10896 return IsOrdered;
10897 return std::nullopt;
10898}
10899
10901 const FPClassTest OrigTestMask,
10902 SDNodeFlags Flags, const SDLoc &DL,
10903 SelectionDAG &DAG) const {
10904 EVT OperandVT = Op.getValueType();
10905 assert(OperandVT.isFloatingPoint());
10906 FPClassTest Test = OrigTestMask;
10907
10908 // Degenerated cases.
10909 if (Test == fcNone)
10910 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10911 if (Test == fcAllFlags)
10912 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10913
10914 // PPC double double is a pair of doubles, of which the higher part determines
10915 // the value class.
10916 if (OperandVT == MVT::ppcf128) {
10917 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10918 DAG.getConstant(1, DL, MVT::i32));
10919 OperandVT = MVT::f64;
10920 }
10921
10922 // Floating-point type properties.
10923 EVT ScalarFloatVT = OperandVT.getScalarType();
10924 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10925 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10926 bool IsF80 = (ScalarFloatVT == MVT::f80);
10927
10928 // Some checks can be implemented using float comparisons, if floating point
10929 // exceptions are ignored.
10930 if (Flags.hasNoFPExcept() &&
10932 FPClassTest FPTestMask = Test;
10933 bool IsInvertedFP = false;
10934
10935 if (FPClassTest InvertedFPCheck =
10936 invertFPClassTestIfSimpler(FPTestMask, true)) {
10937 FPTestMask = InvertedFPCheck;
10938 IsInvertedFP = true;
10939 }
10940
10941 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10942 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10943
10944 // See if we can fold an | fcNan into an unordered compare.
10945 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10946
10947 // Can't fold the ordered check if we're only testing for snan or qnan
10948 // individually.
10949 if ((FPTestMask & fcNan) != fcNan)
10950 OrderedFPTestMask = FPTestMask;
10951
10952 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10953
10954 if (std::optional<bool> IsCmp0 =
10955 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10956 IsCmp0 && (isCondCodeLegalOrCustom(
10957 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10958 OperandVT.getScalarType().getSimpleVT()))) {
10959
10960 // If denormals could be implicitly treated as 0, this is not equivalent
10961 // to a compare with 0 since it will also be true for denormals.
10962 return DAG.getSetCC(DL, ResultVT, Op,
10963 DAG.getConstantFP(0.0, DL, OperandVT),
10964 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10965 }
10966
10967 if (FPTestMask == fcNan &&
10969 OperandVT.getScalarType().getSimpleVT()))
10970 return DAG.getSetCC(DL, ResultVT, Op, Op,
10971 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10972
10973 bool IsOrderedInf = FPTestMask == fcInf;
10974 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10975 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10976 : UnorderedCmpOpcode,
10977 OperandVT.getScalarType().getSimpleVT()) &&
10980 (OperandVT.isVector() &&
10982 // isinf(x) --> fabs(x) == inf
10983 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10984 SDValue Inf =
10985 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10986 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10987 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10988 }
10989
10990 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10991 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10992 : UnorderedCmpOpcode,
10993 OperandVT.getSimpleVT())) {
10994 // isposinf(x) --> x == inf
10995 // isneginf(x) --> x == -inf
10996 // isposinf(x) || nan --> x u== inf
10997 // isneginf(x) || nan --> x u== -inf
10998
10999 SDValue Inf = DAG.getConstantFP(
11000 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
11001 OperandVT);
11002 return DAG.getSetCC(DL, ResultVT, Op, Inf,
11003 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
11004 }
11005
11006 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
11007 // TODO: Could handle ordered case, but it produces worse code for
11008 // x86. Maybe handle ordered if fabs is free?
11009
11010 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
11011 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
11012
11013 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
11014 OperandVT.getScalarType().getSimpleVT())) {
11015 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
11016
11017 // TODO: Maybe only makes sense if fabs is free. Integer test of
11018 // exponent bits seems better for x86.
11019 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
11020 SDValue SmallestNormal = DAG.getConstantFP(
11021 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
11022 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
11023 IsOrdered ? OrderedOp : UnorderedOp);
11024 }
11025 }
11026
11027 if (FPTestMask == fcNormal) {
11028 // TODO: Handle unordered
11029 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
11030 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
11031
11032 if (isCondCodeLegalOrCustom(IsFiniteOp,
11033 OperandVT.getScalarType().getSimpleVT()) &&
11034 isCondCodeLegalOrCustom(IsNormalOp,
11035 OperandVT.getScalarType().getSimpleVT()) &&
11036 isFAbsFree(OperandVT)) {
11037 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
11038 SDValue Inf =
11039 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
11040 SDValue SmallestNormal = DAG.getConstantFP(
11041 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
11042
11043 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
11044 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
11045 SDValue IsNormal =
11046 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
11047 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
11048 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
11049 }
11050 }
11051 }
11052
11053 // Some checks may be represented as inversion of simpler check, for example
11054 // "inf|normal|subnormal|zero" => !"nan".
11055 bool IsInverted = false;
11056
11057 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
11058 Test = InvertedCheck;
11059 IsInverted = true;
11060 }
11061
11062 // In the general case use integer operations.
11063 unsigned BitSize = OperandVT.getScalarSizeInBits();
11064 EVT IntVT = OperandVT.changeElementType(
11065 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
11066 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
11067
11068 // Various masks.
11069 APInt SignBit = APInt::getSignMask(BitSize);
11070 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
11071 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
11072 const unsigned ExplicitIntBitInF80 = 63;
11073 APInt ExpMask = Inf;
11074 if (IsF80)
11075 ExpMask.clearBit(ExplicitIntBitInF80);
11076 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
11077 APInt QNaNBitMask =
11078 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
11079 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
11080
11081 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
11082 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
11083 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
11084 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
11085 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
11086 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
11087
11088 SDValue Res;
11089 const auto appendResult = [&](SDValue PartialRes) {
11090 if (PartialRes) {
11091 if (Res)
11092 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
11093 else
11094 Res = PartialRes;
11095 }
11096 };
11097
11098 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
11099 const auto getIntBitIsSet = [&]() -> SDValue {
11100 if (!IntBitIsSetV) {
11101 APInt IntBitMask(BitSize, 0);
11102 IntBitMask.setBit(ExplicitIntBitInF80);
11103 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
11104 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
11105 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
11106 }
11107 return IntBitIsSetV;
11108 };
11109
11110 // Split the value into sign bit and absolute value.
11111 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
11112 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
11113 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
11114
11115 // Tests that involve more than one class should be processed first.
11116 SDValue PartialRes;
11117
11118 if (IsF80)
11119 ; // Detect finite numbers of f80 by checking individual classes because
11120 // they have different settings of the explicit integer bit.
11121 else if ((Test & fcFinite) == fcFinite) {
11122 // finite(V) ==> (a << 1) < (inf << 1)
11123 //
11124 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
11125 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
11126
11128 "finite check requires IEEE-like FP");
11129
11130 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
11131 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
11132 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
11133
11134 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
11135 Test &= ~fcFinite;
11136 } else if ((Test & fcFinite) == fcPosFinite) {
11137 // finite(V) && V > 0 ==> V < exp_mask
11138 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
11139 Test &= ~fcPosFinite;
11140 } else if ((Test & fcFinite) == fcNegFinite) {
11141 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
11142 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
11143 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11144 Test &= ~fcNegFinite;
11145 }
11146 appendResult(PartialRes);
11147
11148 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
11149 // fcZero | fcSubnormal => test all exponent bits are 0
11150 // TODO: Handle sign bit specific cases
11151 if (PartialCheck == (fcZero | fcSubnormal)) {
11152 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
11153 SDValue ExpIsZero =
11154 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11155 appendResult(ExpIsZero);
11156 Test &= ~PartialCheck & fcAllFlags;
11157 }
11158 }
11159
11160 // Check for individual classes.
11161
11162 if (unsigned PartialCheck = Test & fcZero) {
11163 if (PartialCheck == fcPosZero)
11164 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
11165 else if (PartialCheck == fcZero)
11166 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
11167 else // ISD::fcNegZero
11168 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
11169 appendResult(PartialRes);
11170 }
11171
11172 if (unsigned PartialCheck = Test & fcSubnormal) {
11173 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
11174 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
11175 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
11176 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
11177 SDValue VMinusOneV =
11178 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
11179 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
11180 if (PartialCheck == fcNegSubnormal)
11181 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11182 appendResult(PartialRes);
11183 }
11184
11185 if (unsigned PartialCheck = Test & fcInf) {
11186 if (PartialCheck == fcPosInf)
11187 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
11188 else if (PartialCheck == fcInf)
11189 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
11190 else { // ISD::fcNegInf
11191 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
11192 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
11193 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
11194 }
11195 appendResult(PartialRes);
11196 }
11197
11198 if (unsigned PartialCheck = Test & fcNan) {
11199 APInt InfWithQnanBit = Inf | QNaNBitMask;
11200 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
11201 if (PartialCheck == fcNan) {
11202 // isnan(V) ==> abs(V) > int(inf)
11203 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11204 if (IsF80) {
11205 // Recognize unsupported values as NaNs for compatibility with glibc.
11206 // In them (exp(V)==0) == int_bit.
11207 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
11208 SDValue ExpIsZero =
11209 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11210 SDValue IsPseudo =
11211 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
11212 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
11213 }
11214 } else if (PartialCheck == fcQNan) {
11215 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
11216 PartialRes =
11217 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
11218 } else { // ISD::fcSNan
11219 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
11220 // abs(V) < (unsigned(Inf) | quiet_bit)
11221 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11222 SDValue IsNotQnan =
11223 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
11224 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
11225 }
11226 appendResult(PartialRes);
11227 }
11228
11229 if (unsigned PartialCheck = Test & fcNormal) {
11230 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
11231 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
11232 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
11233 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
11234 APInt ExpLimit = ExpMask - ExpLSB;
11235 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
11236 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
11237 if (PartialCheck == fcNegNormal)
11238 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11239 else if (PartialCheck == fcPosNormal) {
11240 SDValue PosSignV =
11241 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
11242 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
11243 }
11244 if (IsF80)
11245 PartialRes =
11246 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
11247 appendResult(PartialRes);
11248 }
11249
11250 if (!Res)
11251 return DAG.getConstant(IsInverted, DL, ResultVT);
11252 if (IsInverted)
11253 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
11254 return Res;
11255}
11256
11257// Only expand vector types if we have the appropriate vector bit operations.
11259 assert(VT.isVector() && "Expected vector type");
11260 unsigned Len = VT.getScalarSizeInBits();
11261 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
11262 TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
11263 TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
11264 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
11265 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
11266}
11267
11269 SDLoc dl(Node);
11270 EVT VT = Node->getValueType(0);
11271 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11272 SDValue Op = Node->getOperand(0);
11273 unsigned Len = VT.getScalarSizeInBits();
11274
11275 // Compute effective bit width from known bits, allowing us to shift the
11276 // active bits down if necessary to fit into smaller specialized expansions.
11278 unsigned LZ = Known.countMinLeadingZeros();
11279 unsigned TZ = Known.countMinTrailingZeros();
11280 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
11281
11282 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
11283 unsigned EffectiveLen = Len;
11284 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
11285 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
11286
11287 assert(VT.isInteger() && "CTPOP not implemented for this type.");
11288
11289 // TODO: Add support for irregular type lengths.
11290 if (!(Len <= 128 && Len % 8 == 0))
11291 return SDValue();
11292
11293 // Only expand vector types if we have the appropriate vector bit operations.
11294 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
11295 return SDValue();
11296
11297 // If the active bits are not at the low end, shift them down
11298 if (EffectiveLen < Len && TZ > 0) {
11299 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
11300 DAG.getShiftAmountConstant(TZ, VT, dl));
11301 }
11302
11303 // This is the "best" algorithm from
11304 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
11305 SDValue Mask55 =
11306 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
11307 SDValue Mask33 =
11308 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
11309 SDValue Mask0F =
11310 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
11311
11312 // v = v - ((v >> 1) & 0x55555555...)
11313 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
11314 DAG.getNode(ISD::AND, dl, VT,
11315 DAG.getNode(ISD::SRL, dl, VT, Op,
11316 DAG.getConstant(1, dl, ShVT)),
11317 Mask55));
11318 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
11319 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
11320 DAG.getNode(ISD::AND, dl, VT,
11321 DAG.getNode(ISD::SRL, dl, VT, Op,
11322 DAG.getConstant(2, dl, ShVT)),
11323 Mask33));
11324 // v = (v + (v >> 4)) & 0x0F0F0F0F...
11325 Op = DAG.getNode(ISD::AND, dl, VT,
11326 DAG.getNode(ISD::ADD, dl, VT, Op,
11327 DAG.getNode(ISD::SRL, dl, VT, Op,
11328 DAG.getConstant(4, dl, ShVT))),
11329 Mask0F);
11330
11331 if (EffectiveLen <= 8)
11332 return Op;
11333
11334 // Avoid the multiply if we only have 2 bytes to add.
11335 // TODO: Only doing this for scalars because vectors weren't as obviously
11336 // improved.
11337 if (EffectiveLen == 16 && !VT.isVector()) {
11338 // v = (v + (v >> 8)) & 0x00FF;
11339 return DAG.getNode(ISD::AND, dl, VT,
11340 DAG.getNode(ISD::ADD, dl, VT, Op,
11341 DAG.getNode(ISD::SRL, dl, VT, Op,
11342 DAG.getConstant(8, dl, ShVT))),
11343 DAG.getConstant(0xFF, dl, VT));
11344 }
11345
11346 // v = (v * 0x01010101...) >> (Len - 8)
11347 SDValue V;
11350 SDValue Mask01 =
11351 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
11352 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
11353 } else {
11354 V = Op;
11355 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
11356 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
11357 V = DAG.getNode(ISD::ADD, dl, VT, V,
11358 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
11359 }
11360 }
11361 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
11362}
11363
11365 SDLoc dl(Node);
11366 EVT VT = Node->getValueType(0);
11367 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11368 SDValue Op = Node->getOperand(0);
11369 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11370
11371 // If the non-ZERO_POISON version is supported we can use that instead.
11372 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
11374 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
11375
11376 // If the ZERO_POISON version is supported use that and handle the zero case.
11378 EVT SetCCVT =
11379 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11380 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
11381 SDValue Zero = DAG.getConstant(0, dl, VT);
11382 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11383 return DAG.getSelect(dl, VT, SrcIsZero,
11384 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
11385 }
11386
11387 // Only expand vector types if we have the appropriate vector bit operations.
11388 // This includes the operations needed to expand CTPOP if it isn't supported.
11389 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11391 !canExpandVectorCTPOP(*this, VT)) ||
11394 return SDValue();
11395
11396 // for now, we do this:
11397 // x = x | (x >> 1);
11398 // x = x | (x >> 2);
11399 // ...
11400 // x = x | (x >>16);
11401 // x = x | (x >>32); // for 64-bit input
11402 // return popcount(~x);
11403 //
11404 // Ref: "Hacker's Delight" by Henry Warren
11405 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
11406 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
11407 Op = DAG.getNode(ISD::OR, dl, VT, Op,
11408 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
11409 }
11410 Op = DAG.getNOT(dl, Op, VT);
11411 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
11412}
11413
11415 SDLoc dl(Node);
11416 EVT VT = Node->getValueType(0);
11417 SDValue Op = DAG.getFreeze(Node->getOperand(0));
11418 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11419
11420 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
11421 // This transforms the sign bits into leading zeros that can be counted.
11422 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
11423 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
11424 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
11425 SDValue Shl =
11426 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11427 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
11428 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
11429}
11430
11432 const SDLoc &DL, EVT VT, SDValue Op,
11433 unsigned BitWidth) const {
11434 if (BitWidth != 32 && BitWidth != 64)
11435 return SDValue();
11436
11437 const DataLayout &TD = DAG.getDataLayout();
11439 return SDValue();
11440
11441 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
11442 : APInt(64, 0x0218A392CD3D5DBFULL);
11443 MachinePointerInfo PtrInfo =
11445 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
11446 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11447 SDValue Lookup = DAG.getNode(
11448 ISD::SRL, DL, VT,
11449 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
11450 DAG.getConstant(DeBruijn, DL, VT)),
11451 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11453
11455 for (unsigned i = 0; i < BitWidth; i++) {
11456 APInt Shl = DeBruijn.shl(i);
11457 APInt Lshr = Shl.lshr(ShiftAmt);
11458 Table[Lshr.getZExtValue()] = i;
11459 }
11460
11461 // Create a ConstantArray in Constant Pool
11462 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11463 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11464 TD.getPrefTypeAlign(CA->getType()));
11465 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11466 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11467 PtrInfo, MVT::i8);
11468 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11469 return ExtLoad;
11470
11471 EVT SetCCVT =
11472 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11473 SDValue Zero = DAG.getConstant(0, DL, VT);
11474 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11475 return DAG.getSelect(DL, VT, SrcIsZero,
11476 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11477}
11478
11480 SDLoc dl(Node);
11481 EVT VT = Node->getValueType(0);
11482 SDValue Op = Node->getOperand(0);
11483 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11484
11485 // If the non-ZERO_POISON version is supported we can use that instead.
11486 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11488 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11489
11490 // If the ZERO_POISON version is supported use that and handle the zero case.
11492 EVT SetCCVT =
11493 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11494 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11495 SDValue Zero = DAG.getConstant(0, dl, VT);
11496 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11497 return DAG.getSelect(dl, VT, SrcIsZero,
11498 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11499 }
11500
11501 // Only expand vector types if we have the appropriate vector bit operations.
11502 // This includes the operations needed to expand CTPOP if it isn't supported.
11503 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11506 !canExpandVectorCTPOP(*this, VT)) ||
11510 return SDValue();
11511
11512 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11513 // to be expanded or converted to a libcall.
11516 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11517 return V;
11518
11519 bool UseCTLZ =
11521
11522 // When only ctlz is available and the operand is nonzero we can use:
11523 // { return nlz(x & -x) ^ 31; }
11524 // which is more efficient than:
11525 // { return 32 - nlz(~x & (x - 1)); }.
11526 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11527 SDValue LowestBit =
11528 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11529 return DAG.getNode(ISD::XOR, dl, VT,
11530 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11531 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11532 }
11533
11534 // If ctpop is available, we use:
11535 // { return popcount(~x & (x-1)); }
11536 // If the target has ctlz but not ctpop, we use:
11537 // { return 32 - nlz(~x & (x-1)); }
11538 // Ref: "Hacker's Delight" by Henry Warren
11539 SDValue Tmp = DAG.getNode(
11540 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11541 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11542
11543 if (UseCTLZ)
11544 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11545 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11546
11547 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11548}
11549
11551 SelectionDAG &DAG) const {
11552 // %cond = to_bool_vec %source
11553 // %splat = splat /*val=*/VL
11554 // %tz = step_vector
11555 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11556 // %r = vp.reduce.umin %v
11557 SDLoc DL(N);
11558 SDValue Source = N->getOperand(0);
11559 SDValue Mask = N->getOperand(1);
11560 SDValue EVL = N->getOperand(2);
11561 EVT SrcVT = Source.getValueType();
11562 EVT ResVT = N->getValueType(0);
11563 EVT ResVecVT =
11564 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11565
11566 // Convert to boolean vector.
11567 if (SrcVT.getScalarType() != MVT::i1) {
11568 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11569 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11570 SrcVT.getVectorElementCount());
11571 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11572 }
11573
11574 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11575 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11576 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11577 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11578 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11579}
11580
11581/// Returns a type-legalized version of \p Mask as the first item in the
11582/// pair. The second item contains a type-legalized step vector that's
11583/// guaranteed to fit the number of elements in \p Mask.
11584/// If the stepvector would require splitting, returns an empty SDValue
11585/// as the second item to signal that the operation should be split instead.
11586static std::pair<SDValue, SDValue>
11588 SelectionDAG &DAG) {
11589 EVT MaskVT = Mask.getValueType();
11590 EVT BoolVT = MaskVT.getScalarType();
11591
11592 // Find a suitable type for a stepvector.
11593 // If zero is poison, we can assume the upper limit of the result is VF-1.
11594 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11595 if (MaskVT.isScalableVector())
11596 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11598 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11599 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11600 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11601 // If the step vector element type is smaller than the mask element type,
11602 // use the mask type directly to avoid widening issues.
11603 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11604 EVT StepVT = MVT::getIntegerVT(EltWidth);
11605 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11606
11607 // If promotion or widening is required to make the type legal, do it here.
11608 // Promotion of integers within LegalizeVectorOps is looking for types of
11609 // the same size but with a smaller number of larger elements, not the usual
11610 // larger size with the same number of larger elements.
11612 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11613 SDValue StepVec;
11614 if (TypeAction == TargetLowering::TypePromoteInteger) {
11615 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11616 StepVec = DAG.getStepVector(DL, StepVecVT);
11617 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11618 // For widening, the element count changes. Create a step vector with only
11619 // the original elements valid and zeros for padding. Also widen the mask.
11620 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11621 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11622
11623 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11624 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11625 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11626 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11627
11628 // Widen mask: pad with zeros.
11629 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11630 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11631 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11632 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11633 // The stepvector type would require splitting. Signal to the caller
11634 // that the operation should be split instead of expanded.
11635 return {Mask, SDValue()};
11636 } else {
11637 StepVec = DAG.getStepVector(DL, StepVecVT);
11638 }
11639
11640 return {Mask, StepVec};
11641}
11642
11644 SelectionDAG &DAG) const {
11645 SDLoc DL(N);
11646 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11647 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11648
11649 // If StepVec is empty, the stepvector would require splitting.
11650 // Split the operation instead and let it be recursively legalized.
11651 if (!StepVec) {
11652 EVT MaskVT = N->getOperand(0).getValueType();
11653 EVT ResVT = N->getValueType(0);
11654
11655 // Split the mask
11656 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11657 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11658
11659 // Create split VECTOR_FIND_LAST_ACTIVE operations
11660 SDValue LoResult =
11661 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11662 SDValue HiResult =
11663 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11664
11665 // Check if any lane is active in the high mask.
11666 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11668 AnyHiActive, DL,
11669 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11670 MVT::i1);
11671
11672 // Adjust HiResult by adding the number of elements in Lo
11673 SDValue LoNumElts =
11674 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11675 SDValue AdjustedHiResult =
11676 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11677
11678 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11679 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11680 LoResult);
11681 }
11682
11683 EVT StepVecVT = StepVec.getValueType();
11684 EVT StepVT = StepVec.getValueType().getVectorElementType();
11685
11686 // Zero out lanes with inactive elements, then find the highest remaining
11687 // value from the stepvector.
11688 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11689 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11690 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11691 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11692}
11693
11695 SelectionDAG &DAG) const {
11696 SDLoc DL(N);
11697
11698 SDValue Start = N->getOperand(0);
11699 SDValue End = N->getOperand(1);
11700 EVT VT = N->getValueType(0);
11701 EVT OpVT = Start.getValueType();
11702
11703 auto [Mask, StepVector] = getLegalMaskAndStepVector(
11704 DAG.getPOISON(VT), /*ZeroIsPoison=*/false, DL, DAG);
11705
11706 // No legal step vector: split the mask in half and recombine the results.
11707 // Lo = get_active_lane_mask Start, End
11708 // Hi = get_active_lane_mask (uaddsat Start, LoNumElts), End
11709 if (!StepVector) {
11710 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
11711 SDValue Lo = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, LoVT, Start, End);
11712 SDValue LoNumElts =
11713 DAG.getElementCount(DL, OpVT, LoVT.getVectorElementCount());
11714 SDValue HiStart = DAG.getNode(ISD::UADDSAT, DL, OpVT, Start, LoNumElts);
11715 SDValue Hi = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, HiVT, HiStart, End);
11716 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
11717 }
11718
11719 // Rebase and saturate the termination value.
11720 SDValue Max =
11721 DAG.getConstant(maxUIntN(std::min(StepVector.getScalarValueSizeInBits(),
11722 OpVT.getScalarSizeInBits())),
11723 DL, OpVT);
11724 End = DAG.getNode(ISD::USUBSAT, DL, OpVT, End, Start);
11725 End = DAG.getNode(ISD::UMIN, DL, OpVT, End, Max);
11726 End = DAG.getZExtOrTrunc(End, DL, StepVector.getValueType().getScalarType());
11727
11728 // cmp <0, 1, 2, 3...>, End
11729 SDValue EndV = DAG.getSplat(StepVector.getValueType(), DL, End);
11730 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11731 StepVector.getValueType());
11732 SDValue Cmp = DAG.getSetCC(DL, CCVT, StepVector, EndV, ISD::SETULT);
11733 SDValue Res = DAG.getBoolExtOrTrunc(Cmp, DL, Mask.getValueType(),
11734 StepVector.getValueType());
11735 if (Mask.getValueType() != VT)
11736 Res = DAG.getExtractSubvector(DL, VT, Res, 0);
11737 return Res;
11738}
11739
11741 SelectionDAG &DAG) const {
11742 SDLoc DL(N);
11743 EVT VT = N->getValueType(0);
11744 SDValue SourceValue = N->getOperand(0);
11745 SDValue SinkValue = N->getOperand(1);
11746 SDValue EltSizeInBytes = N->getOperand(2);
11747
11748 // Note: The lane offset is scalable if the mask is scalable.
11749 ElementCount LaneOffsetEC =
11750 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11751
11752 EVT AddrVT = SourceValue->getValueType(0);
11753 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11754
11755 EVT CmpVT =
11756 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11757
11758 // Unsigned compare: Source >= Sink.
11759 SDValue SourceAheadOfOrEqualToSink =
11760 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11761
11762 // Take the difference between the pointers and divided by the element size,
11763 // to see how many lanes separate them.
11764 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11765
11766 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11767 if (IsReadAfterWrite)
11768 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11769 DAG.getNegative(Diff, DL, AddrVT), Diff);
11770
11771 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11772
11773 // The pointers do not alias if:
11774 // - Source >= Sink (WAR_MASK)
11775 // - Source == Sink (RAW_MASK)
11776 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11777 if (IsReadAfterWrite)
11778 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11779
11780 // The pointers do not alias if:
11781 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11782 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11783 SDValue MaskN = DAG.getSelect(
11784 DL, AddrVT, NoAlias,
11786 AddrVT),
11787 Diff);
11788
11789 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11790}
11791
11793 bool IsNegative) const {
11794 SDLoc dl(N);
11795 EVT VT = N->getValueType(0);
11796 SDValue Op = N->getOperand(0);
11797
11798 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11799 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11801 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11802 if (IsNegative)
11803 return DAG.getNegative(AbsVal, dl, VT);
11804 return AbsVal;
11805 }
11806
11807 // abs(x) -> smax(x,sub(0,x))
11808 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11810 SDValue Zero = DAG.getConstant(0, dl, VT);
11811 Op = DAG.getFreeze(Op);
11812 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11813 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11814 }
11815
11816 // abs(x) -> umin(x,sub(0,x))
11817 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11819 SDValue Zero = DAG.getConstant(0, dl, VT);
11820 Op = DAG.getFreeze(Op);
11821 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11822 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11823 }
11824
11825 // 0 - abs(x) -> smin(x, sub(0,x))
11826 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11828 SDValue Zero = DAG.getConstant(0, dl, VT);
11829 Op = DAG.getFreeze(Op);
11830 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11831 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11832 }
11833
11834 // Only expand vector types if we have the appropriate vector operations.
11835 if (VT.isVector() &&
11837 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11838 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11840 return SDValue();
11841
11842 Op = DAG.getFreeze(Op);
11843 SDValue Shift = DAG.getNode(
11844 ISD::SRA, dl, VT, Op,
11845 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11846 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11847
11848 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11849 if (!IsNegative)
11850 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11851
11852 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11853 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11854}
11855
11857 SDLoc dl(N);
11858 EVT VT = N->getValueType(0);
11859 SDValue LHS = N->getOperand(0);
11860 SDValue RHS = N->getOperand(1);
11861 bool IsSigned = N->getOpcode() == ISD::ABDS;
11862
11863 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11864 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11865 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11866 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11867 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11868 LHS = DAG.getFreeze(LHS);
11869 RHS = DAG.getFreeze(RHS);
11870 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11871 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11872 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11873 }
11874
11875 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11876 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11877 LHS = DAG.getFreeze(LHS);
11878 RHS = DAG.getFreeze(RHS);
11879 return DAG.getNode(ISD::OR, dl, VT,
11880 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11881 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11882 }
11883
11884 // abds: if the sub is nsw -> abs(sub)
11885 // abdu with non-negative operands -> abs(sub)
11886 // The abdu case where the sub is nuw is handled in DAGCombine.
11887 // For scalars, only do this if ABS is legal/custom, otherwise the expansion
11888 // of ABS is no better than the select/branchless expansion below. Retain the
11889 // existing ABS-based expansion for vectors.
11890 bool PreferAbs = VT.isVector() || isOperationLegalOrCustom(ISD::ABS, VT);
11891 if (PreferAbs) {
11892 if (IsSigned) {
11893 if (DAG.willNotOverflowSub(/*IsSigned=*/true, LHS, RHS))
11894 return DAG.getNode(ISD::ABS, dl, VT,
11895 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11896
11897 if (DAG.willNotOverflowSub(/*IsSigned=*/true, RHS, LHS))
11898 return DAG.getNode(ISD::ABS, dl, VT,
11899 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11900 } else if (DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS)) {
11901 return DAG.getNode(ISD::ABS, dl, VT,
11902 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11903 }
11904 }
11905
11906 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11908 LHS = DAG.getFreeze(LHS);
11909 RHS = DAG.getFreeze(RHS);
11910 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11911
11912 // Branchless expansion iff cmp result is allbits:
11913 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11914 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11915 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11916 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11917 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11918 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11919 }
11920
11921 // Similar to the branchless expansion, if we don't prefer selects, use the
11922 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11923 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11924 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11925 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11927 SDValue USubO =
11928 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11929 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11930 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11931 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11932 }
11933
11934 // FIXME: Should really try to split the vector in case it's legal on a
11935 // subvector.
11937 return DAG.UnrollVectorOp(N);
11938
11939 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11940 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11941 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11942 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11943}
11944
11946 SDLoc dl(N);
11947 EVT VT = N->getValueType(0);
11948 SDValue LHS = N->getOperand(0);
11949 SDValue RHS = N->getOperand(1);
11950
11951 unsigned Opc = N->getOpcode();
11952 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11953 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11954 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11955 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11956 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11957 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11959 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11960 "Unknown AVG node");
11961
11962 // If the operands are already extended, we can add+shift.
11963 bool IsExt =
11964 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11965 DAG.ComputeNumSignBits(RHS) >= 2) ||
11966 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11967 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11968 if (IsExt) {
11969 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11970 if (!IsFloor)
11971 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11972 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11973 DAG.getShiftAmountConstant(1, VT, dl));
11974 }
11975
11976 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11977 if (VT.isScalarInteger()) {
11978 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11979 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11980 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11981 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11982 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11983 if (!IsFloor)
11984 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11985 DAG.getConstant(1, dl, ExtVT));
11986 // Just use SRL as we will be truncating away the extended sign bits.
11987 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11988 DAG.getShiftAmountConstant(1, ExtVT, dl));
11989 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11990 }
11991 }
11992
11993 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11994 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11997 SDValue UAddWithOverflow =
11998 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11999
12000 SDValue Sum = UAddWithOverflow.getValue(0);
12001 SDValue Overflow = UAddWithOverflow.getValue(1);
12002
12003 // Right shift the sum by 1
12004 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
12005 DAG.getShiftAmountConstant(1, VT, dl));
12006
12007 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
12008 SDValue OverflowShl = DAG.getNode(
12009 ISD::SHL, dl, VT, ZeroExtOverflow,
12010 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
12011
12012 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
12013 }
12014
12015 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
12016 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
12017 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
12018 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
12019 LHS = DAG.getFreeze(LHS);
12020 RHS = DAG.getFreeze(RHS);
12021 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
12022 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
12023 SDValue Shift =
12024 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
12025 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
12026}
12027
12029 SDLoc dl(N);
12030 EVT VT = N->getValueType(0);
12031 SDValue Op = N->getOperand(0);
12032
12033 if (!VT.isSimple())
12034 return SDValue();
12035
12036 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
12037 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
12038 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
12039 default:
12040 return SDValue();
12041 case MVT::i16:
12042 // Use a rotate by 8. This can be further expanded if necessary.
12043 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12044 case MVT::i32:
12045 // This is meant for ARM specifically, which has ROTR but no ROTL.
12046 // t = x ^ rotr(x, 16)
12047 // t = bic(t, 0x00ff0000)
12048 // t = lshr(t, 8)
12049 // x = t ^ rotr(x, 8)
12051 SDValue Rotr16 =
12052 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
12053 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
12054 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
12055 DAG.getConstant(0xFF00FFFF, dl, VT));
12056 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
12057 SDValue Rotr8 =
12058 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12059 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
12060 }
12061 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12062 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
12063 DAG.getConstant(0xFF00, dl, VT));
12064 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
12065 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12066 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
12067 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12068 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
12069 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
12070 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
12071 case MVT::i64:
12072 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
12073 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
12074 DAG.getConstant(255ULL<<8, dl, VT));
12075 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
12076 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
12077 DAG.getConstant(255ULL<<16, dl, VT));
12078 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
12079 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
12080 DAG.getConstant(255ULL<<24, dl, VT));
12081 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
12082 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12083 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
12084 DAG.getConstant(255ULL<<24, dl, VT));
12085 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12086 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
12087 DAG.getConstant(255ULL<<16, dl, VT));
12088 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
12089 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
12090 DAG.getConstant(255ULL<<8, dl, VT));
12091 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
12092 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
12093 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
12094 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
12095 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
12096 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
12097 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
12098 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
12099 }
12100}
12101
12103 SDLoc dl(N);
12104 EVT VT = N->getValueType(0);
12105 SDValue Op = N->getOperand(0);
12106 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
12107 unsigned Sz = VT.getScalarSizeInBits();
12108
12109 SDValue Tmp, Tmp2, Tmp3;
12110
12111 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
12112 // and finally the i1 pairs.
12113 // TODO: We can easily support i4/i2 legal types if any target ever does.
12114 if (Sz >= 8 && isPowerOf2_32(Sz)) {
12115 // Create the masks - repeating the pattern every byte.
12116 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
12117 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
12118 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
12119
12120 // BSWAP if the type is wider than a single byte.
12121 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
12122
12123 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
12124 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
12125 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
12126 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
12127 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
12128 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12129
12130 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
12131 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
12132 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
12133 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
12134 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
12135 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12136
12137 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
12138 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
12139 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
12140 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
12141 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
12142 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12143 return Tmp;
12144 }
12145
12146 Tmp = DAG.getConstant(0, dl, VT);
12147 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
12148 if (I < J)
12149 Tmp2 =
12150 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
12151 else
12152 Tmp2 =
12153 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
12154
12155 APInt Shift = APInt::getOneBitSet(Sz, J);
12156 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
12157 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
12158 }
12159
12160 return Tmp;
12161}
12162
12163std::pair<SDValue, SDValue>
12165 SelectionDAG &DAG) const {
12166 SDLoc SL(LD);
12167 SDValue Chain = LD->getChain();
12168 SDValue BasePTR = LD->getBasePtr();
12169 EVT SrcVT = LD->getMemoryVT();
12170 EVT DstVT = LD->getValueType(0);
12171 ISD::LoadExtType ExtType = LD->getExtensionType();
12172
12173 if (SrcVT.isScalableVector())
12174 report_fatal_error("Cannot scalarize scalable vector loads");
12175
12176 unsigned NumElem = SrcVT.getVectorNumElements();
12177
12178 EVT SrcEltVT = SrcVT.getScalarType();
12179 EVT DstEltVT = DstVT.getScalarType();
12180
12181 // A vector must always be stored in memory as-is, i.e. without any padding
12182 // between the elements, since various code depend on it, e.g. in the
12183 // handling of a bitcast of a vector type to int, which may be done with a
12184 // vector store followed by an integer load. A vector that does not have
12185 // elements that are byte-sized must therefore be stored as an integer
12186 // built out of the extracted vector elements.
12187 if (!SrcEltVT.isByteSized()) {
12188 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
12189 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
12190
12191 unsigned NumSrcBits = SrcVT.getSizeInBits();
12192 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
12193
12194 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
12195 SDValue SrcEltBitMask = DAG.getConstant(
12196 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
12197
12198 // Load the whole vector and avoid masking off the top bits as it makes
12199 // the codegen worse.
12200 SDValue Load = DAG.getExtLoad(
12201 ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, LD->getPointerInfo(),
12202 SrcIntVT, LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12203 LD->getMMOMetadataForSubAccess());
12204
12206 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12207 unsigned ShiftIntoIdx =
12208 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12209 SDValue ShiftAmount = DAG.getShiftAmountConstant(
12210 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
12211 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
12212 SDValue Elt =
12213 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
12214 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
12215
12216 if (ExtType != ISD::NON_EXTLOAD) {
12217 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
12218 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
12219 }
12220
12221 Vals.push_back(Scalar);
12222 }
12223
12224 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12225 return std::make_pair(Value, Load.getValue(1));
12226 }
12227
12228 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
12229 assert(SrcEltVT.isByteSized());
12230
12232 SmallVector<SDValue, 8> LoadChains;
12233
12234 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12235 SDValue ScalarLoad = DAG.getExtLoad(
12236 ExtType, SL, DstEltVT, Chain, BasePTR,
12237 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
12238 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12239 LD->getMMOMetadataForSubAccess());
12240
12241 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
12242
12243 Vals.push_back(ScalarLoad.getValue(0));
12244 LoadChains.push_back(ScalarLoad.getValue(1));
12245 }
12246
12247 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
12248 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12249
12250 return std::make_pair(Value, NewChain);
12251}
12252
12254 SelectionDAG &DAG) const {
12255 SDLoc SL(ST);
12256
12257 SDValue Chain = ST->getChain();
12258 SDValue BasePtr = ST->getBasePtr();
12259 SDValue Value = ST->getValue();
12260 EVT StVT = ST->getMemoryVT();
12261
12262 if (StVT.isScalableVector())
12263 report_fatal_error("Cannot scalarize scalable vector stores");
12264
12265 // The type of the data we want to save
12266 EVT RegVT = Value.getValueType();
12267 EVT RegSclVT = RegVT.getScalarType();
12268
12269 // The type of data as saved in memory.
12270 EVT MemSclVT = StVT.getScalarType();
12271
12272 unsigned NumElem = StVT.getVectorNumElements();
12273
12274 // A vector must always be stored in memory as-is, i.e. without any padding
12275 // between the elements, since various code depend on it, e.g. in the
12276 // handling of a bitcast of a vector type to int, which may be done with a
12277 // vector store followed by an integer load. A vector that does not have
12278 // elements that are byte-sized must therefore be stored as an integer
12279 // built out of the extracted vector elements.
12280 if (!MemSclVT.isByteSized()) {
12281 unsigned NumBits = StVT.getSizeInBits();
12282 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
12283
12284 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
12285
12286 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12287 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12288 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
12289 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
12290 unsigned ShiftIntoIdx =
12291 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12292 SDValue ShiftAmount =
12293 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
12294 SDValue ShiftedElt =
12295 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
12296 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
12297 }
12298
12299 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
12300 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12301 ST->getMMOMetadataForSubAccess());
12302 }
12303
12304 // Store Stride in bytes
12305 unsigned Stride = MemSclVT.getSizeInBits() / 8;
12306 assert(Stride && "Zero stride!");
12307 // Extract each of the elements from the original vector and save them into
12308 // memory individually.
12310 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12311 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12312
12313 SDValue Ptr =
12314 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
12315
12316 // This scalar TruncStore may be illegal, but we legalize it later.
12318 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
12319 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12320 ST->getMMOMetadataForSubAccess());
12321
12322 Stores.push_back(Store);
12323 }
12324
12325 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
12326}
12327
12328std::pair<SDValue, SDValue>
12330 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
12331 "unaligned indexed loads not implemented!");
12332 SDValue Chain = LD->getChain();
12333 SDValue Ptr = LD->getBasePtr();
12334 EVT VT = LD->getValueType(0);
12335 EVT LoadedVT = LD->getMemoryVT();
12336 SDLoc dl(LD);
12337 auto &MF = DAG.getMachineFunction();
12338
12339 if (VT.isFloatingPoint() || VT.isVector()) {
12340 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
12341 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
12342 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
12343 LoadedVT.isVector()) {
12344 // Scalarize the load and let the individual components be handled.
12345 return scalarizeVectorLoad(LD, DAG);
12346 }
12347
12348 // Expand to a (misaligned) integer load of the same size,
12349 // then bitconvert to floating point or vector.
12350 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
12351 LD->getMemOperand());
12352 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
12353 if (LoadedVT != VT)
12354 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
12355 ISD::ANY_EXTEND, dl, VT, Result);
12356
12357 return std::make_pair(Result, newLoad.getValue(1));
12358 }
12359
12360 // Copy the value to a (aligned) stack slot using (unaligned) integer
12361 // loads and stores, then do a (aligned) load from the stack slot.
12362 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
12363 unsigned LoadedBytes = LoadedVT.getStoreSize();
12364 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12365 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
12366
12367 // Make sure the stack slot is also aligned for the register type.
12368 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
12369 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
12371 SDValue StackPtr = StackBase;
12372 unsigned Offset = 0;
12373
12374 EVT PtrVT = Ptr.getValueType();
12375 EVT StackPtrVT = StackPtr.getValueType();
12376
12377 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12378 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12379
12380 // Do all but one copies using the full register width.
12381 for (unsigned i = 1; i < NumRegs; i++) {
12382 // Load one integer register's worth from the original location.
12383 SDValue Load = DAG.getLoad(
12384 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12385 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12386 LD->getMMOMetadataForSubAccess());
12387 // Follow the load with a store to the stack slot. Remember the store.
12388 Stores.push_back(DAG.getStore(
12389 Load.getValue(1), dl, Load, StackPtr,
12390 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12391 // Increment the pointers.
12392 Offset += RegBytes;
12393
12394 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12395 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12396 }
12397
12398 // The last copy may be partial. Do an extending load.
12399 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12400 8 * (LoadedBytes - Offset));
12401 SDValue Load = DAG.getExtLoad(
12402 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12403 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12404 LD->getMemOperand()->getFlags(), LD->getMMOMetadataForSubAccess());
12405 // Follow the load with a store to the stack slot. Remember the store.
12406 // On big-endian machines this requires a truncating store to ensure
12407 // that the bits end up in the right place.
12408 Stores.push_back(DAG.getTruncStore(
12409 Load.getValue(1), dl, Load, StackPtr,
12410 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12411
12412 // The order of the stores doesn't matter - say it with a TokenFactor.
12413 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12414
12415 // Finally, perform the original load only redirected to the stack slot.
12416 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12417 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12418 LoadedVT);
12419
12420 // Callers expect a MERGE_VALUES node.
12421 return std::make_pair(Load, TF);
12422 }
12423
12424 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12425 "Unaligned load of unsupported type.");
12426
12427 // Compute the new VT that is half the size of the old one. This is an
12428 // integer MVT.
12429 unsigned NumBits = LoadedVT.getSizeInBits();
12430 EVT NewLoadedVT;
12431 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12432 NumBits >>= 1;
12433
12434 Align Alignment = LD->getBaseAlign();
12435 unsigned IncrementSize = NumBits / 8;
12436 ISD::LoadExtType HiExtType = LD->getExtensionType();
12437
12438 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12439 if (HiExtType == ISD::NON_EXTLOAD)
12440 HiExtType = ISD::ZEXTLOAD;
12441
12442 // Load the value in two parts
12443 SDValue Lo, Hi;
12444 if (DAG.getDataLayout().isLittleEndian()) {
12445 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12446 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12447 LD->getMMOMetadataForSubAccess());
12448
12449 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12450 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12451 LD->getPointerInfo().getWithOffset(IncrementSize),
12452 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12453 LD->getMMOMetadataForSubAccess());
12454 } else {
12455 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12456 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12457 LD->getMMOMetadataForSubAccess());
12458
12459 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12460 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12461 LD->getPointerInfo().getWithOffset(IncrementSize),
12462 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12463 LD->getMMOMetadataForSubAccess());
12464 }
12465
12466 // aggregate the two parts
12467 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12468 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12469 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12470
12471 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12472 Hi.getValue(1));
12473
12474 return std::make_pair(Result, TF);
12475}
12476
12478 SelectionDAG &DAG) const {
12479 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12480 "unaligned indexed stores not implemented!");
12481 SDValue Chain = ST->getChain();
12482 SDValue Ptr = ST->getBasePtr();
12483 SDValue Val = ST->getValue();
12484 EVT VT = Val.getValueType();
12485 Align Alignment = ST->getBaseAlign();
12486 auto &MF = DAG.getMachineFunction();
12487 EVT StoreMemVT = ST->getMemoryVT();
12488
12489 SDLoc dl(ST);
12490 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12491 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12492 if (isTypeLegal(intVT)) {
12493 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12494 StoreMemVT.isVector()) {
12495 // Scalarize the store and let the individual components be handled.
12496 SDValue Result = scalarizeVectorStore(ST, DAG);
12497 return Result;
12498 }
12499 // Expand to a bitconvert of the value to the integer type of the
12500 // same size, then a (misaligned) int store.
12501 // FIXME: Does not handle truncating floating point stores!
12502 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12503 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12504 Alignment, ST->getMemOperand()->getFlags(),
12505 ST->getMMOMetadataForSubAccess());
12506 return Result;
12507 }
12508 // Do a (aligned) store to a stack slot, then copy from the stack slot
12509 // to the final destination using (unaligned) integer loads and stores.
12510 MVT RegVT = getRegisterType(
12511 *DAG.getContext(),
12512 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12513 EVT PtrVT = Ptr.getValueType();
12514 unsigned StoredBytes = StoreMemVT.getStoreSize();
12515 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12516 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12517
12518 // Make sure the stack slot is also aligned for the register type.
12519 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12520 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12521
12522 // Perform the original store, only redirected to the stack slot.
12524 Chain, dl, Val, StackPtr,
12525 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12526
12527 EVT StackPtrVT = StackPtr.getValueType();
12528
12529 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12530 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12532 unsigned Offset = 0;
12533
12534 // Do all but one copies using the full register width.
12535 for (unsigned i = 1; i < NumRegs; i++) {
12536 // Load one integer register's worth from the stack slot.
12537 SDValue Load = DAG.getLoad(
12538 RegVT, dl, Store, StackPtr,
12539 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12540 // Store it to the final location. Remember the store.
12541 Stores.push_back(DAG.getStore(
12542 Load.getValue(1), dl, Load, Ptr,
12543 ST->getPointerInfo().getWithOffset(Offset), ST->getBaseAlign(),
12544 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess()));
12545 // Increment the pointers.
12546 Offset += RegBytes;
12547 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12548 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12549 }
12550
12551 // The last store may be partial. Do a truncating store. On big-endian
12552 // machines this requires an extending load from the stack slot to ensure
12553 // that the bits are in the right place.
12554 EVT LoadMemVT =
12555 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12556
12557 // Load from the stack slot.
12558 SDValue Load = DAG.getExtLoad(
12559 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12560 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12561
12562 Stores.push_back(
12563 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
12564 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12565 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12566 ST->getMMOMetadataForSubAccess()));
12567 // The order of the stores doesn't matter - say it with a TokenFactor.
12568 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12569 return Result;
12570 }
12571
12572 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12573 "Unaligned store of unknown type.");
12574 // Get the half-size VT
12575 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12576 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12577 unsigned IncrementSize = NumBits / 8;
12578
12579 // Divide the stored value in two parts.
12580 SDValue ShiftAmount =
12581 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12582 SDValue Lo = Val;
12583 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12584 // fold and not use the upper bits. A smaller constant may be easier to
12585 // materialize.
12586 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12587 Lo = DAG.getNode(
12588 ISD::AND, dl, VT, Lo,
12589 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12590 VT));
12591 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12592
12593 // Store the two parts
12594 SDValue Store1, Store2;
12595 Store1 = DAG.getTruncStore(
12596 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Lo : Hi, Ptr,
12597 ST->getPointerInfo(), NewStoredVT, Alignment,
12598 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12599
12600 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12601 Store2 = DAG.getTruncStore(
12602 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12603 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12604 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12605
12606 SDValue Result =
12607 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12608 return Result;
12609}
12610
12611SDValue
12613 const SDLoc &DL, EVT DataVT,
12614 SelectionDAG &DAG,
12615 bool IsCompressedMemory) const {
12617 EVT AddrVT = Addr.getValueType();
12618 EVT MaskVT = Mask.getValueType();
12619 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12620 "Incompatible types of Data and Mask");
12621 if (IsCompressedMemory) {
12622 // Incrementing the pointer according to number of '1's in the mask.
12623 if (DataVT.isScalableVector()) {
12624 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12625 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12626 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12627 } else {
12628 EVT MaskIntVT =
12629 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12630 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12631 if (MaskIntVT.getSizeInBits() < 32) {
12632 MaskInIntReg =
12633 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12634 MaskIntVT = MVT::i32;
12635 }
12636 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12637 }
12638 // Scale is an element size in bytes.
12639 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12640 AddrVT);
12641 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12642 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12643 } else
12644 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12645
12646 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12647}
12648
12650 EVT VecVT, const SDLoc &DL,
12651 ElementCount SubEC) {
12652 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12653 "Cannot index a scalable vector within a fixed-width vector");
12654 ElementCount NElts = VecVT.getVectorElementCount();
12655 EVT IdxVT = Idx.getValueType();
12656
12657 // Attempt to prove all accessed lanes sit within VecVT.
12658 ElementCount IdxAsEC;
12659 if (sd_match(Idx, m_ElementCount(IdxAsEC))) {
12660 if (SubEC.isScalar() && ElementCount::isKnownLT(IdxAsEC, NElts))
12661 return Idx;
12662 // Calculate end index as TypeSize to remove possibility of overflow.
12663 if (IdxAsEC.isScalable() == SubEC.isScalable() &&
12664 TypeSize::isKnownLE(TypeSize(IdxAsEC) + TypeSize(SubEC),
12665 TypeSize(NElts)))
12666 return Idx;
12667 }
12668
12669 // Can we mask Idx rather than clamp it.
12670 if (SubEC.isScalar() && NElts.isPowerOf2()) {
12671 SDValue EC = DAG.getElementCount(DL, IdxVT, NElts);
12672 SDValue Mask =
12673 DAG.getNode(ISD::SUB, DL, IdxVT, EC, DAG.getConstant(1, DL, IdxVT));
12674 return DAG.getNode(ISD::AND, DL, IdxVT, Idx, Mask);
12675 }
12676
12677 unsigned SubOpcode =
12679 SDValue MaxSafeIndex =
12680 DAG.getNode(SubOpcode, DL, IdxVT, DAG.getElementCount(DL, IdxVT, NElts),
12681 DAG.getElementCount(DL, IdxVT, SubEC));
12682 return DAG.getNode(ISD::UMIN, DL, IdxVT, Idx, MaxSafeIndex);
12683}
12684
12685SDValue
12687 EVT VecVT, SDValue Index,
12688 const SDNodeFlags PtrArithFlags) const {
12690 DAG, VecPtr, VecVT,
12692 Index, PtrArithFlags);
12693}
12694
12695SDValue
12697 EVT VecVT, EVT SubVecVT, SDValue Index,
12698 const SDNodeFlags PtrArithFlags) const {
12699 SDLoc dl(Index);
12700 // Make sure the index type is big enough to compute in.
12701 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12702
12703 EVT EltVT = VecVT.getVectorElementType();
12704
12705 // Calculate the element offset and add it to the pointer.
12706 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12707 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12708 "Converting bits to bytes lost precision");
12709 assert(SubVecVT.getVectorElementType() == EltVT &&
12710 "Sub-vector must be a vector with matching element type");
12711 assert((SubVecVT.getVectorElementCount().isScalar() ||
12712 isa<ConstantSDNode>(Index)) &&
12713 "Subvector Index must be constant!");
12714
12715 // An out-of-range index only makes the vector operation return poison, but
12716 // a load/store through the pointer computed below would be immediate UB, so
12717 // freeze the index before clamping it into range.
12718 Index = DAG.getFreeze(Index, UndefPoisonKind::PoisonOnly);
12719
12720 EVT IdxVT = Index.getValueType();
12721 if (SubVecVT.isScalableVector())
12722 Index =
12723 DAG.getVScale(dl, IdxVT, cast<ConstantSDNode>(Index)->getAPIntValue());
12724
12725 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12726 SubVecVT.getVectorElementCount());
12727 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12728 DAG.getConstant(EltSize, dl, IdxVT));
12729 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12730}
12731
12732//===----------------------------------------------------------------------===//
12733// Implementation of Emulated TLS Model
12734//===----------------------------------------------------------------------===//
12735
12737 SelectionDAG &DAG) const {
12738 // Access to address of TLS varialbe xyz is lowered to a function call:
12739 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12740 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12741 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12742 SDLoc dl(GA);
12743
12744 ArgListTy Args;
12745 const GlobalValue *GV =
12747 SmallString<32> NameString("__emutls_v.");
12748 NameString += GV->getName();
12749 StringRef EmuTlsVarName(NameString);
12750 const GlobalVariable *EmuTlsVar =
12751 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12752 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12753 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12754
12755 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12756
12758 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12759 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12760 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12761
12762 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12763 // At last for X86 targets, maybe good for other targets too?
12765 MFI.setAdjustsStack(true); // Is this only for X86 target?
12766 MFI.setHasCalls(true);
12767
12768 assert((GA->getOffset() == 0) &&
12769 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12770 return CallResult.first;
12771}
12772
12774 SelectionDAG &DAG) const {
12775 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12776 if (!isCtlzFast())
12777 return SDValue();
12778 ISD::CondCode CC = Op.getOperandCondCode(2);
12779 SDLoc dl(Op);
12780 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12781 EVT VT = Op.getOperand(0).getValueType();
12782 SDValue Zext = Op.getOperand(0);
12783 if (VT.bitsLT(MVT::i32)) {
12784 VT = MVT::i32;
12785 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12786 }
12787 unsigned Log2b = Log2_32(VT.getSizeInBits());
12788 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12789 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12790 DAG.getConstant(Log2b, dl, MVT::i32));
12791 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12792 }
12793 return SDValue();
12794}
12795
12797 SDValue Op0 = Node->getOperand(0);
12798 SDValue Op1 = Node->getOperand(1);
12799 EVT VT = Op0.getValueType();
12800 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12801 unsigned Opcode = Node->getOpcode();
12802 SDLoc DL(Node);
12803
12804 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12805 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12806 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12807 DAG.SignBitIsZero(Op1))
12808 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12809
12810 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12811 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12813 Op0 = DAG.getFreeze(Op0);
12814 SDValue Zero = DAG.getConstant(0, DL, VT);
12815 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12816 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12817 }
12818
12819 // umin(x,y) -> sub(x,usubsat(x,y))
12820 // TODO: Missing freeze(Op0)?
12821 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12823 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12824 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12825 }
12826
12827 // umax(x,y) -> add(x,usubsat(y,x))
12828 // TODO: Missing freeze(Op0)?
12829 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12831 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12832 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12833 }
12834
12835 // FIXME: Should really try to split the vector in case it's legal on a
12836 // subvector.
12838 return DAG.UnrollVectorOp(Node);
12839
12840 // Attempt to find an existing SETCC node that we can reuse.
12841 // TODO: Do we need a generic doesSETCCNodeExist?
12842 // TODO: Missing freeze(Op0)/freeze(Op1)?
12843 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12844 ISD::CondCode PrefCommuteCC,
12845 ISD::CondCode AltCommuteCC) {
12846 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12847 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12848 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12849 {Op0, Op1, DAG.getCondCode(CC)})) {
12850 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12851 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12852 }
12853 }
12854 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12855 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12856 {Op0, Op1, DAG.getCondCode(CC)})) {
12857 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12858 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12859 }
12860 }
12861 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12862 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12863 };
12864
12865 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12866 // -> Y = (A < B) ? B : A
12867 // -> Y = (A >= B) ? A : B
12868 // -> Y = (A <= B) ? B : A
12869 switch (Opcode) {
12870 case ISD::SMAX:
12871 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12872 case ISD::SMIN:
12873 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12874 case ISD::UMAX:
12875 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12876 case ISD::UMIN:
12877 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12878 }
12879
12880 llvm_unreachable("How did we get here?");
12881}
12882
12884 unsigned Opcode = Node->getOpcode();
12885 SDValue LHS = Node->getOperand(0);
12886 SDValue RHS = Node->getOperand(1);
12887 EVT VT = LHS.getValueType();
12888 SDLoc dl(Node);
12889
12890 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12891 assert(VT.isInteger() && "Expected operands to be integers");
12892
12893 // usub.sat(a, b) -> umax(a, b) - b
12894 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12895 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12896 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12897 }
12898
12899 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12900 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12901 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12903 LHS = DAG.getFreeze(LHS);
12904 SDValue Zero = DAG.getConstant(0, dl, VT);
12905 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12906 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12907 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12908 Subtrahend =
12909 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12910 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12911 }
12912
12913 // uadd.sat(a, b) -> umin(a, ~b) + b
12914 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12915 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12916 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12917 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12918 }
12919
12920 unsigned OverflowOp;
12921 switch (Opcode) {
12922 case ISD::SADDSAT:
12923 OverflowOp = ISD::SADDO;
12924 break;
12925 case ISD::UADDSAT:
12926 OverflowOp = ISD::UADDO;
12927 break;
12928 case ISD::SSUBSAT:
12929 OverflowOp = ISD::SSUBO;
12930 break;
12931 case ISD::USUBSAT:
12932 OverflowOp = ISD::USUBO;
12933 break;
12934 default:
12935 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12936 "addition or subtraction node.");
12937 }
12938
12939 // FIXME: Should really try to split the vector in case it's legal on a
12940 // subvector.
12942 return DAG.UnrollVectorOp(Node);
12943
12944 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12945 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12946 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12947 SDValue SumDiff = Result.getValue(0);
12948 SDValue Overflow = Result.getValue(1);
12949 SDValue Zero = DAG.getConstant(0, dl, VT);
12950 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12951
12952 if (Opcode == ISD::UADDSAT) {
12954 // (LHS + RHS) | OverflowMask
12955 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12956 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12957 }
12958 // Overflow ? 0xffff.... : (LHS + RHS)
12959 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12960 }
12961
12962 if (Opcode == ISD::USUBSAT) {
12964 // (LHS - RHS) & ~OverflowMask
12965 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12966 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12967 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12968 }
12969 // Overflow ? 0 : (LHS - RHS)
12970 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12971 }
12972
12973 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12974 "Expected signed saturating add/sub opcode");
12975
12976 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12977 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12978
12979 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12980 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12981
12982 // If either of the operand signs are known, then they are guaranteed to
12983 // only saturate in one direction. If non-negative they will saturate
12984 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12985 //
12986 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12987 // sign of 'y' has to be flipped.
12988
12989 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12990 bool RHSIsNonNegative =
12991 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12992 if (LHSIsNonNegative || RHSIsNonNegative) {
12993 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12994 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12995 }
12996
12997 bool LHSIsNegative = KnownLHS.isNegative();
12998 bool RHSIsNegative =
12999 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
13000 if (LHSIsNegative || RHSIsNegative) {
13001 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13002 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
13003 }
13004
13005 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
13006 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13007 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
13008 DAG.getConstant(BitWidth - 1, dl, VT));
13009 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
13010 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
13011}
13012
13014 unsigned Opcode = Node->getOpcode();
13015 SDValue LHS = Node->getOperand(0);
13016 SDValue RHS = Node->getOperand(1);
13017 EVT VT = LHS.getValueType();
13018 EVT ResVT = Node->getValueType(0);
13019 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13020 SDLoc dl(Node);
13021
13022 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
13023 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
13024 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
13025 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
13026
13027 // We can't perform arithmetic on i1 values. Extending them would
13028 // probably result in worse codegen, so let's just use two selects instead.
13029 // Some targets are also just better off using selects rather than subtraction
13030 // because one of the conditions can be merged with one of the selects.
13031 // And finally, if we don't know the contents of high bits of a boolean value
13032 // we can't perform any arithmetic either.
13034 BoolVT.getScalarSizeInBits() == 1 ||
13036 SDValue SelectZeroOrOne =
13037 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
13038 DAG.getConstant(0, dl, ResVT));
13039 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
13040 SelectZeroOrOne);
13041 }
13042
13044 std::swap(IsGT, IsLT);
13045 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
13046 ResVT);
13047}
13048
13050 unsigned Opcode = Node->getOpcode();
13051 bool IsSigned = Opcode == ISD::SSHLSAT;
13052 SDValue LHS = Node->getOperand(0);
13053 SDValue RHS = Node->getOperand(1);
13054 EVT VT = LHS.getValueType();
13055 SDLoc dl(Node);
13056
13057 assert((Node->getOpcode() == ISD::SSHLSAT ||
13058 Node->getOpcode() == ISD::USHLSAT) &&
13059 "Expected a SHLSAT opcode");
13060 assert(VT.isInteger() && "Expected operands to be integers");
13061
13063 return DAG.UnrollVectorOp(Node);
13064
13065 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
13066
13067 unsigned BW = VT.getScalarSizeInBits();
13068 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13069 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
13070 SDValue Orig =
13071 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
13072
13073 SDValue SatVal;
13074 if (IsSigned) {
13075 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
13076 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
13077 SDValue Cond =
13078 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
13079 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
13080 } else {
13081 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
13082 }
13083 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
13084 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
13085}
13086
13088 bool Signed, SDValue &Lo, SDValue &Hi,
13089 SDValue LHS, SDValue RHS,
13090 SDValue HiLHS, SDValue HiRHS) const {
13091 EVT VT = LHS.getValueType();
13092 assert(RHS.getValueType() == VT && "Mismatching operand types");
13093
13094 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
13095 assert((!Signed || !HiLHS) &&
13096 "Signed flag should only be set when HiLHS and RiRHS are null");
13097
13098 // We'll expand the multiplication by brute force because we have no other
13099 // options. This is a trivially-generalized version of the code from
13100 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
13101 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
13102 // sign bits while calculating the Hi half.
13103 unsigned Bits = VT.getScalarSizeInBits();
13104 unsigned HalfBits = Bits / 2;
13105 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
13106 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
13107 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
13108
13109 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
13110 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
13111
13112 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
13113 // This is always an unsigned shift.
13114 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
13115
13116 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
13117 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
13118 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
13119
13120 SDValue U =
13121 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
13122 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
13123 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
13124
13125 SDValue V =
13126 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
13127 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
13128
13129 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
13130 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
13131
13132 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
13133 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
13134
13135 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
13136 // the products to Hi.
13137 if (HiLHS) {
13138 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
13139 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
13140 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
13141 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
13142 }
13143}
13144
13146 bool Signed, const SDValue LHS,
13147 const SDValue RHS, SDValue &Lo,
13148 SDValue &Hi) const {
13149 EVT VT = LHS.getValueType();
13150 assert(RHS.getValueType() == VT && "Mismatching operand types");
13151 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13152 // We can fall back to a libcall with an illegal type for the MUL if we
13153 // have a libcall big enough.
13154 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
13155 if (WideVT == MVT::i16)
13156 LC = RTLIB::MUL_I16;
13157 else if (WideVT == MVT::i32)
13158 LC = RTLIB::MUL_I32;
13159 else if (WideVT == MVT::i64)
13160 LC = RTLIB::MUL_I64;
13161 else if (WideVT == MVT::i128)
13162 LC = RTLIB::MUL_I128;
13163
13164 RTLIB::LibcallImpl LibcallImpl = DAG.getLibcalls().getLibcallImpl(LC);
13165 if (LibcallImpl == RTLIB::Unsupported) {
13166 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
13167 return;
13168 }
13169
13170 // The libcall takes and returns WideVT values as packed VT halves. This only
13171 // works if VT is legal and WideVT isn't. Otherwise, emit a wide multiply and
13172 // let it legalise normally, possibly into a wider libcall.
13173 if (isTypeLegal(WideVT) || !isTypeLegal(VT)) {
13174 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT,
13175 DAG.getExtOrTrunc(Signed, LHS, dl, WideVT),
13176 DAG.getExtOrTrunc(Signed, RHS, dl, WideVT));
13177 SDValue Shift =
13178 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13179 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13180 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT,
13181 DAG.getNode(ISD::SRL, dl, WideVT, Mul, Shift));
13182 return;
13183 }
13184
13185 SDValue HiLHS, HiRHS;
13186 if (Signed) {
13187 // The high part is obtained by SRA'ing all but one of the bits of low
13188 // part.
13189 unsigned LoSize = VT.getFixedSizeInBits();
13190 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
13191 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
13192 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
13193 } else {
13194 HiLHS = DAG.getConstant(0, dl, VT);
13195 HiRHS = DAG.getConstant(0, dl, VT);
13196 }
13197
13198 // Attempt a libcall.
13199 SDValue Ret;
13201 CallOptions.setIsSigned(Signed);
13202 CallOptions.setIsPostTypeLegalization(true);
13204 // Halves of WideVT are packed into registers in different order
13205 // depending on platform endianness. This is usually handled by
13206 // the C calling convention, but we can't defer to it in
13207 // the legalizer.
13208 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
13209 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13210 } else {
13211 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
13212 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13213 }
13215 "Ret value is a collection of constituent nodes holding result.");
13216 if (DAG.getDataLayout().isLittleEndian()) {
13217 // Same as above.
13218 Lo = Ret.getOperand(0);
13219 Hi = Ret.getOperand(1);
13220 } else {
13221 Lo = Ret.getOperand(1);
13222 Hi = Ret.getOperand(0);
13223 }
13224}
13225
13226SDValue
13228 assert((Node->getOpcode() == ISD::SMULFIX ||
13229 Node->getOpcode() == ISD::UMULFIX ||
13230 Node->getOpcode() == ISD::SMULFIXSAT ||
13231 Node->getOpcode() == ISD::UMULFIXSAT) &&
13232 "Expected a fixed point multiplication opcode");
13233
13234 SDLoc dl(Node);
13235 SDValue LHS = Node->getOperand(0);
13236 SDValue RHS = Node->getOperand(1);
13237 EVT VT = LHS.getValueType();
13238 unsigned Scale = Node->getConstantOperandVal(2);
13239 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
13240 Node->getOpcode() == ISD::UMULFIXSAT);
13241 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
13242 Node->getOpcode() == ISD::SMULFIXSAT);
13243 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13244 unsigned VTSize = VT.getScalarSizeInBits();
13245
13246 if (!Scale) {
13247 // [us]mul.fix(a, b, 0) -> mul(a, b)
13248 if (!Saturating) {
13250 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13251 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
13252 SDValue Result =
13253 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13254 SDValue Product = Result.getValue(0);
13255 SDValue Overflow = Result.getValue(1);
13256 SDValue Zero = DAG.getConstant(0, dl, VT);
13257
13258 APInt MinVal = APInt::getSignedMinValue(VTSize);
13259 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
13260 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13261 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13262 // Xor the inputs, if resulting sign bit is 0 the product will be
13263 // positive, else negative.
13264 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
13265 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
13266 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
13267 return DAG.getSelect(dl, VT, Overflow, Result, Product);
13268 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
13269 SDValue Result =
13270 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13271 SDValue Product = Result.getValue(0);
13272 SDValue Overflow = Result.getValue(1);
13273
13274 APInt MaxVal = APInt::getMaxValue(VTSize);
13275 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13276 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
13277 }
13278 }
13279
13280 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
13281 "Expected scale to be less than the number of bits if signed or at "
13282 "most the number of bits if unsigned.");
13283 assert(LHS.getValueType() == RHS.getValueType() &&
13284 "Expected both operands to be the same type");
13285
13286 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
13287 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
13288 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
13289 SDValue Val, ISD::CondCode CC) {
13290 if (VT.isVector())
13291 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
13292 Sat, Val);
13293 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
13294 };
13295
13296 // Get the upper and lower bits of the result.
13297 SDValue Lo, Hi;
13298 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13299 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
13300 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13301 if (isOperationLegalOrCustom(LoHiOp, VT)) {
13302 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
13303 Lo = Result.getValue(0);
13304 Hi = Result.getValue(1);
13305 } else if (isOperationLegalOrCustom(HiOp, VT)) {
13306 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13307 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
13308 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13309 // Try for a multiplication using a wider type.
13310 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13311 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
13312 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
13313 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
13314 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
13315 SDValue Shifted =
13316 DAG.getNode(ISD::SRA, dl, WideVT, Res,
13317 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
13318 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
13319 } else if (VT.isVector()) {
13320 return SDValue();
13321 } else {
13322 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
13323 }
13324
13325 if (Scale == VTSize)
13326 // Result is just the top half since we'd be shifting by the width of the
13327 // operand. Overflow impossible so this works for both UMULFIX and
13328 // UMULFIXSAT.
13329 return Hi;
13330
13331 // The result will need to be shifted right by the scale since both operands
13332 // are scaled. The result is given to us in 2 halves, so we only want part of
13333 // both in the result.
13334 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
13335 DAG.getShiftAmountConstant(Scale, VT, dl));
13336 if (!Saturating)
13337 return Result;
13338
13339 if (!Signed) {
13340 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
13341 // widened multiplication) aren't all zeroes.
13342
13343 // Saturate to max if ((Hi >> Scale) != 0),
13344 // which is the same as if (Hi > ((1 << Scale) - 1))
13345 APInt MaxVal = APInt::getMaxValue(VTSize);
13346 SDValue LowMask =
13347 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
13348 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
13349 Result, ISD::SETUGT);
13350 }
13351
13352 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
13353 // widened multiplication) aren't all ones or all zeroes.
13354
13355 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
13356 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
13357
13358 if (Scale == 0) {
13359 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
13360 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
13361 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
13362 // Saturated to SatMin if wide product is negative, and SatMax if wide
13363 // product is positive ...
13364 SDValue Zero = DAG.getConstant(0, dl, VT);
13365 SDValue ResultIfOverflow =
13366 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
13367 // ... but only if we overflowed.
13368 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
13369 }
13370
13371 // We handled Scale==0 above so all the bits to examine is in Hi.
13372
13373 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
13374 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
13375 SDValue LowMask =
13376 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
13377 // Saturate to min if (Hi >> (Scale - 1)) < -1),
13378 // which is the same as if (HI < (-1 << (Scale - 1))
13379 SDValue HighMask = DAG.getConstant(
13380 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
13381 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
13382 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
13383 return Result;
13384}
13385
13386SDValue
13388 SDValue LHS, SDValue RHS,
13389 unsigned Scale, SelectionDAG &DAG) const {
13390 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
13391 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
13392 "Expected a fixed point division opcode");
13393
13394 EVT VT = LHS.getValueType();
13395 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
13396 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
13397 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13398
13399 // If there is enough room in the type to upscale the LHS or downscale the
13400 // RHS before the division, we can perform it in this type without having to
13401 // resize. For signed operations, the LHS headroom is the number of
13402 // redundant sign bits, and for unsigned ones it is the number of zeroes.
13403 // The headroom for the RHS is the number of trailing zeroes.
13404 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
13406 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
13407
13408 // For signed saturating operations, we need to be able to detect true integer
13409 // division overflow; that is, when you have MIN / -EPS. However, this
13410 // is undefined behavior and if we emit divisions that could take such
13411 // values it may cause undesired behavior (arithmetic exceptions on x86, for
13412 // example).
13413 // Avoid this by requiring an extra bit so that we never get this case.
13414 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13415 // signed saturating division, we need to emit a whopping 32-bit division.
13416 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13417 return SDValue();
13418
13419 unsigned LHSShift = std::min(LHSLead, Scale);
13420 unsigned RHSShift = Scale - LHSShift;
13421
13422 // At this point, we know that if we shift the LHS up by LHSShift and the
13423 // RHS down by RHSShift, we can emit a regular division with a final scaling
13424 // factor of Scale.
13425
13426 if (LHSShift)
13427 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13428 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13429 if (RHSShift)
13430 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13431 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13432
13433 SDValue Quot;
13434 if (Signed) {
13435 // For signed operations, if the resulting quotient is negative and the
13436 // remainder is nonzero, subtract 1 from the quotient to round towards
13437 // negative infinity.
13438 SDValue Rem;
13439 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13440 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13441 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13442 if (isTypeLegal(VT) &&
13444 Quot = DAG.getNode(ISD::SDIVREM, dl,
13445 DAG.getVTList(VT, VT),
13446 LHS, RHS);
13447 Rem = Quot.getValue(1);
13448 Quot = Quot.getValue(0);
13449 } else {
13450 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13451 LHS, RHS);
13452 Rem = DAG.getNode(ISD::SREM, dl, VT,
13453 LHS, RHS);
13454 }
13455 SDValue Zero = DAG.getConstant(0, dl, VT);
13456 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13457 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13458 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13459 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13460 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13461 DAG.getConstant(1, dl, VT));
13462 Quot = DAG.getSelect(dl, VT,
13463 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13464 Sub1, Quot);
13465 } else
13466 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13467 LHS, RHS);
13468
13469 return Quot;
13470}
13471
13473 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13474 SDLoc dl(Node);
13475 SDValue LHS = Node->getOperand(0);
13476 SDValue RHS = Node->getOperand(1);
13477 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13478
13479 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13480 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13481 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13482 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13483 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13484 { LHS, RHS, CarryIn });
13485 Result = SDValue(NodeCarry.getNode(), 0);
13486 Overflow = SDValue(NodeCarry.getNode(), 1);
13487 return;
13488 }
13489
13490 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13491 LHS.getValueType(), LHS, RHS);
13492
13493 EVT ResultType = Node->getValueType(1);
13494 EVT SetCCType = getSetCCResultType(
13495 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13496 SDValue SetCC;
13497 if (IsAdd && isOneConstant(RHS)) {
13498 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13499 // the live range of X. We assume comparing with 0 is cheap.
13500 // The general case (X + C) < C is not necessarily beneficial. Although we
13501 // reduce the live range of X, we may introduce the materialization of
13502 // constant C.
13503 SetCC =
13504 DAG.getSetCC(dl, SetCCType, Result,
13505 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13506 } else if (IsAdd && isAllOnesConstant(RHS)) {
13507 // Special case: uaddo X, -1 overflows if X != 0.
13508 SetCC =
13509 DAG.getSetCC(dl, SetCCType, LHS,
13510 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13511 } else {
13513 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13514 }
13515 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13516}
13517
13519 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13520 SDLoc dl(Node);
13521 SDValue LHS = Node->getOperand(0);
13522 SDValue RHS = Node->getOperand(1);
13523 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13524
13525 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13526 LHS.getValueType(), LHS, RHS);
13527
13528 EVT ResultType = Node->getValueType(1);
13529 EVT OType = getSetCCResultType(
13530 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13531
13532 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13533 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13534 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13535 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13536 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13537 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13538 return;
13539 }
13540
13541 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13542
13543 if (IsAdd) {
13544 // For an addition, the result should be less than one of the operands (LHS)
13545 // if and only if the other operand (RHS) is negative, otherwise there will
13546 // be overflow.
13547 SDValue ResultLowerThanLHS =
13548 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13549 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13550 Overflow = DAG.getBoolExtOrTrunc(
13551 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13552 ResultType, ResultType);
13553 } else {
13554 // For subtraction, overflow occurs when the signed comparison of operands
13555 // doesn't match the sign of the result.
13556 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13557 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13558 Overflow = DAG.getBoolExtOrTrunc(
13559 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13560 ResultType, ResultType);
13561 }
13562}
13563
13565 SDValue &Overflow, SelectionDAG &DAG) const {
13566 SDLoc dl(Node);
13567 EVT VT = Node->getValueType(0);
13568 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13569 SDValue LHS = Node->getOperand(0);
13570 SDValue RHS = Node->getOperand(1);
13571 bool isSigned = Node->getOpcode() == ISD::SMULO;
13572
13573 // For power-of-two multiplications we can use a simpler shift expansion.
13574 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13575 const APInt &C = RHSC->getAPIntValue();
13576 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13577 if (C.isPowerOf2()) {
13578 // smulo(x, signed_min) is same as umulo(x, signed_min).
13579 bool UseArithShift = isSigned && !C.isMinSignedValue();
13580 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13581 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13582 Overflow = DAG.getSetCC(dl, SetCCVT,
13583 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13584 dl, VT, Result, ShiftAmt),
13585 LHS, ISD::SETNE);
13586 return true;
13587 }
13588 }
13589
13590 SDValue BottomHalf;
13591 SDValue TopHalf;
13592 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13593
13594 static const unsigned Ops[2][3] =
13597 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13598 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13599 RHS);
13600 TopHalf = BottomHalf.getValue(1);
13601 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13602 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13603 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13604 } else if (isTypeLegal(WideVT)) {
13605 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13606 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13607 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13608 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13609 SDValue ShiftAmt =
13610 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13611 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13612 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13613 } else {
13614 if (VT.isVector())
13615 return false;
13616
13617 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13618 }
13619
13620 Result = BottomHalf;
13621 if (isSigned) {
13622 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13623 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13624 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13625 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13626 } else {
13627 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13628 DAG.getConstant(0, dl, VT), ISD::SETNE);
13629 }
13630
13631 // Truncate the result if SetCC returns a larger type than needed.
13632 EVT RType = Node->getValueType(1);
13633 if (RType.bitsLT(Overflow.getValueType()))
13634 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13635
13636 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13637 "Unexpected result type for S/UMULO legalization");
13638 return true;
13639}
13640
13642 SDLoc dl(Node);
13643 EVT VT = Node->getValueType(0);
13644 SDValue LHS = Node->getOperand(0);
13645 SDValue RHS = Node->getOperand(1);
13646 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13647
13648 // Use MUL_LOHI if legal/custom for the original type.
13649 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13650 if (isOperationLegalOrCustom(LoHiOp, VT))
13651 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13652
13653 // Use a wide multiply if available.
13654 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13655 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13656 unsigned BW = VT.getScalarSizeInBits();
13657 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13658 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13659 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13660 DAG.getNode(ISD::SRL, dl, WideVT,
13661 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13662 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13663 }
13664
13665 // Let fixed-length vectors be scalarised by the caller.
13666 // Expand everything else with a wide multiply.
13667 if (!VT.isFixedLengthVector()) {
13668 SDValue Lo, Hi;
13669 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13670 return Hi;
13671 }
13672
13673 return SDValue();
13674}
13675
13677 SDLoc dl(Node);
13678 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13679 SDValue Op = Node->getOperand(0);
13680 SDNodeFlags Flags = Node->getFlags();
13681 EVT VT = Op.getValueType();
13682
13683 // Try to use a shuffle reduction for power of two vectors.
13684 if (VT.isPow2VectorType()) {
13685 // See if the reduction opcode is safe to use with widened types.
13686 bool WidenSrc = false;
13687 switch (Node->getOpcode()) {
13690 case ISD::VECREDUCE_ADD:
13691 case ISD::VECREDUCE_MUL:
13692 case ISD::VECREDUCE_AND:
13693 case ISD::VECREDUCE_OR:
13694 case ISD::VECREDUCE_XOR:
13699 WidenSrc = VT.isFixedLengthVector();
13700 break;
13701 }
13702
13704 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13705 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13706 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13707 // Attempt to widen the source vectors to a legal op.
13708 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13709 if (WideVT.isVector() &&
13710 WideVT.getScalarType() == HalfVT.getScalarType() &&
13711 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13712 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13713 SDValue Lo, Hi;
13714 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13715 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13716 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13717 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13718 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13719 VT = HalfVT;
13720 continue;
13721 }
13722 }
13723 break;
13724 }
13725
13726 SDValue Lo, Hi;
13727 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13728 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13729 VT = HalfVT;
13730
13731 // Stop if splitting is enough to make the reduction legal.
13732 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13733 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13734 Flags);
13735 }
13736 }
13737
13738 if (VT.isScalableVector())
13740 "Expanding reductions for scalable vectors is undefined.");
13741
13742 EVT EltVT = VT.getVectorElementType();
13743 unsigned NumElts = VT.getVectorNumElements();
13744
13746 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13747
13748 SDValue Res = Ops[0];
13749 for (unsigned i = 1; i < NumElts; i++)
13750 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13751
13752 // Result type may be wider than element type.
13753 if (EltVT != Node->getValueType(0))
13754 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13755 return Res;
13756}
13757
13759 SDLoc dl(Node);
13760 SDValue AccOp = Node->getOperand(0);
13761 SDValue VecOp = Node->getOperand(1);
13762 SDNodeFlags Flags = Node->getFlags();
13763
13764 EVT VT = VecOp.getValueType();
13765 EVT EltVT = VT.getVectorElementType();
13766
13767 if (VT.isScalableVector())
13769 "Expanding reductions for scalable vectors is undefined.");
13770
13771 unsigned NumElts = VT.getVectorNumElements();
13772
13774 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13775
13776 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13777
13778 SDValue Res = AccOp;
13779 for (unsigned i = 0; i < NumElts; i++)
13780 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13781
13782 return Res;
13783}
13784
13786 SelectionDAG &DAG) const {
13787 EVT VT = Node->getValueType(0);
13788 SDLoc dl(Node);
13789 bool isSigned = Node->getOpcode() == ISD::SREM;
13790 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13791 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13792 SDValue Dividend = Node->getOperand(0);
13793 SDValue Divisor = Node->getOperand(1);
13794 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13795 SDVTList VTs = DAG.getVTList(VT, VT);
13796 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13797 return true;
13798 }
13799 if (isOperationLegalOrCustom(DivOpc, VT)) {
13800 // X % Y -> X-X/Y*Y
13801 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13802 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13803 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13804 return true;
13805 }
13806 return false;
13807}
13808
13810 SelectionDAG &DAG) const {
13811 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13812 SDLoc dl(SDValue(Node, 0));
13813 SDValue Src = Node->getOperand(0);
13814
13815 // DstVT is the result type, while SatVT is the size to which we saturate
13816 EVT SrcVT = Src.getValueType();
13817 EVT DstVT = Node->getValueType(0);
13818
13819 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13820 unsigned SatWidth = SatVT.getScalarSizeInBits();
13821 unsigned DstWidth = DstVT.getScalarSizeInBits();
13822 assert(SatWidth <= DstWidth &&
13823 "Expected saturation width smaller than result width");
13824
13825 // Determine minimum and maximum integer values and their corresponding
13826 // floating-point values.
13827 APInt MinInt, MaxInt;
13828 if (IsSigned) {
13829 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13830 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13831 } else {
13832 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13833 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13834 }
13835
13836 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13837 // libcall emission cannot handle this. Large result types will fail.
13838 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13839 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13840 SrcVT = Src.getValueType();
13841 }
13842
13843 const fltSemantics &Sem = SrcVT.getFltSemantics();
13844 APFloat MinFloat(Sem);
13845 APFloat MaxFloat(Sem);
13846
13847 APFloat::opStatus MinStatus =
13848 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13849 APFloat::opStatus MaxStatus =
13850 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13851 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13852 !(MaxStatus & APFloat::opStatus::opInexact);
13853
13854 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13855 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13856
13857 // If the integer bounds are exactly representable as floats and min/max are
13858 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13859 // of comparisons and selects.
13860 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13861 bool MayPropagateNaN) {
13862 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13863 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13864 if (!MinMaxLegal)
13865 return SDValue();
13866
13867 SDValue Clamped = Src;
13868
13869 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13870 // then the result is MinFloat.
13871 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13872 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13873 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13874 // Convert clamped value to integer.
13875 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13876 dl, DstVT, Clamped);
13877
13878 // If !MayPropagateNan and the conversion is unsigned case we're done,
13879 // because we mapped NaN to MinFloat, which will cast to zero.
13880 if (!MayPropagateNaN && !IsSigned)
13881 return FpToInt;
13882
13883 // Otherwise, select 0 if Src is NaN.
13884 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13885 EVT SetCCVT =
13886 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13887 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13888 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13889 };
13890 if (AreExactFloatBounds) {
13891 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13892 /*MayPropagateNaN=*/false))
13893 return Res;
13894 // These may propagate NaN for sNaN operands.
13895 if (SDValue Res =
13896 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13897 return Res;
13898 // These always propagate NaN.
13899 if (SDValue Res =
13900 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13901 return Res;
13902 }
13903
13904 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13905 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13906
13907 // Result of direct conversion. The assumption here is that the operation is
13908 // non-trapping and it's fine to apply it to an out-of-range value if we
13909 // select it away later.
13910 SDValue FpToInt =
13911 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13912
13913 SDValue Select = FpToInt;
13914
13915 EVT SetCCVT =
13916 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13917
13918 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13919 // MinInt if Src is NaN.
13920 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13921 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13922 // If Src OGT MaxFloat, select MaxInt.
13923 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13924 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13925
13926 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13927 // is already zero.
13928 if (!IsSigned)
13929 return Select;
13930
13931 // Otherwise, select 0 if Src is NaN.
13932 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13933 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13934 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13935}
13936
13938 const SDLoc &dl,
13939 SelectionDAG &DAG) const {
13940 EVT OperandVT = Op.getValueType();
13941 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13942 return Op;
13943 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13944 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13945 // can induce double-rounding which may alter the results. We can
13946 // correct for this using a trick explained in: Boldo, Sylvie, and
13947 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13948 // World Congress. 2005.
13949 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13950 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13951
13952 // We can keep the narrow value as-is if narrowing was exact (no
13953 // rounding error), the wide value was NaN (the narrow value is also
13954 // NaN and should be preserved) or if we rounded to the odd value.
13955 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13956 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13957 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13958 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13959 EVT ResultIntVTCCVT = getSetCCResultType(
13960 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13961 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13962 // The result is already odd so we don't need to do anything.
13963 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13964
13965 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13966 Op.getValueType());
13967 // We keep results which are exact, odd or NaN.
13968 SDValue KeepNarrow =
13969 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13970 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13971 // We morally performed a round-down if AbsNarrow is smaller than
13972 // AbsWide.
13973 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13974 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13975 SDValue NarrowIsRd =
13976 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13977 // If the narrow value is odd or exact, pick it.
13978 // Otherwise, narrow is even and corresponds to either the rounded-up
13979 // or rounded-down value. If narrow is the rounded-down value, we want
13980 // the rounded-up value as it will be odd.
13981 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13982 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13983 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13984 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13985}
13986
13988 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13989 SDValue Op = Node->getOperand(0);
13990 EVT VT = Node->getValueType(0);
13991 SDLoc dl(Node);
13992 if (VT.getScalarType() == MVT::bf16) {
13993 if (Node->getConstantOperandVal(1) == 1) {
13994 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13995 }
13996 EVT OperandVT = Op.getValueType();
13997
13998 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13999 // can induce double-rounding which may alter the results. We can
14000 // correct for this using a trick explained in: Boldo, Sylvie, and
14001 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
14002 // World Congress. 2005.
14003 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
14004 EVT I32 = F32.changeTypeToInteger();
14005 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
14006 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
14007
14008 // Factor in the contribution of the low 16 bits.
14009 SDValue One = DAG.getConstant(1, dl, I32);
14010 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
14011 DAG.getShiftAmountConstant(16, I32, dl));
14012 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
14013 SDValue RoundingBias =
14014 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
14015 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
14016
14017 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
14018 // 0x80000000.
14019 if (!Node->getFlags().hasNoNaNs() &&
14020 !DAG.isKnownNeverNaN(Node->getOperand(0))) {
14021 // Conversions should set NaN's quiet bit. This also prevents NaNs from
14022 // turning into infinities.
14023 SDValue NaN =
14024 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
14025
14026 SDValue IsNaN = DAG.getSetCC(
14027 dl,
14028 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
14029 Node->getOperand(0), Node->getOperand(0), ISD::SETUO);
14030 Add = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
14031 }
14032
14033 // Now that we have rounded, shift the bits into position.
14034 Op = DAG.getNode(ISD::SRL, dl, I32, Add,
14035 DAG.getShiftAmountConstant(16, I32, dl));
14036 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
14037 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
14038 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14039 }
14040 return SDValue();
14041}
14042
14045 SelectionDAG &DAG) const {
14046 assert(Node->getOpcode() == ISD::VECTOR_INTERLEAVE && "Unexpected opcode");
14047 EVT VT = Node->getValueType(0);
14048 unsigned Factor = Node->getNumOperands();
14049 SDLoc DL(Node);
14050
14051 // Convert interleave of two lane operands to paired shuffles
14052 if (VT.isFixedLengthVector() && VT.getVectorNumElements() == 2) {
14053 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx) {
14054 unsigned FirstEltIdx = 2 * ResultIdx;
14055 int FirstMaskIdx = FirstEltIdx / Factor;
14056 int SecondMaskIdx = (FirstEltIdx + 1) / Factor + 2;
14057 Results.push_back(
14058 DAG.getVectorShuffle(VT, DL, Node->getOperand(FirstEltIdx % Factor),
14059 Node->getOperand((FirstEltIdx + 1) % Factor),
14060 {FirstMaskIdx, SecondMaskIdx}));
14061 }
14062 return;
14063 }
14064
14065 if (Factor > 2 && Factor % 2 == 0) {
14066 SmallVector<EVT> HalfVTs(Factor / 2, VT);
14067 SmallVector<SDValue, 8> LOps, ROps;
14068 // Interleave so we have 2 factors per result:
14069 // a0a1 b0b1 c0c1 d0d1 -> [a0c0 b0d0] [a1c1 b1d1]
14070 for (unsigned I = 0; I < Factor / 2; I++) {
14071 SDValue Interleave =
14072 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, {VT, VT},
14073 {Node->getOperand(I), Node->getOperand(I + Factor / 2)});
14074 LOps.push_back(Interleave.getValue(0));
14075 ROps.push_back(Interleave.getValue(1));
14076 }
14077 // Interleave at Factor/2:
14078 // [a0c0 b0d0] [a1c1 b1d1] -> a0b0 c0d0 a1b1 c1d1
14079 SDValue L = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, LOps);
14080 SDValue R = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, ROps);
14081 for (unsigned I = 0; I < Factor / 2; I++)
14082 Results.push_back(L.getValue(I));
14083 for (unsigned I = 0; I < Factor / 2; I++)
14084 Results.push_back(R.getValue(I));
14085 return;
14086 }
14087
14088 if (!VT.isFixedLengthVector())
14089 return;
14090
14091 unsigned NumElts = VT.getVectorNumElements();
14092 EVT EltVT = VT.getVectorElementType();
14093
14094 // A factor of two needs only same-width, two-input shuffles.
14095 if (Factor == 2) {
14096 SmallVector<int, 8> Mask = createInterleaveMask(NumElts, Factor);
14097 for (unsigned I = 0; I != Factor; ++I)
14098 Results.push_back(DAG.getVectorShuffle(
14099 VT, DL, Node->getOperand(0), Node->getOperand(1),
14100 ArrayRef<int>(Mask).slice(I * NumElts, NumElts)));
14101 return;
14102 }
14103
14104 SmallVector<SDValue> InterleavedElts;
14105 InterleavedElts.reserve(Factor * NumElts);
14106 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14107 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
14108 InterleavedElts.push_back(DAG.getExtractVectorElt(
14109 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
14110
14111 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx)
14112 Results.push_back(DAG.getBuildVector(
14113 VT, DL, ArrayRef(InterleavedElts).slice(ResultIdx * NumElts, NumElts)));
14114}
14115
14118 SelectionDAG &DAG) const {
14119 assert(Node->getOpcode() == ISD::VECTOR_DEINTERLEAVE && "Unexpected opcode");
14120 EVT VT = Node->getValueType(0);
14121 unsigned Factor = Node->getNumOperands();
14122 SDLoc DL(Node);
14123
14124 // Convert deinterleave of two lane operands to paired shuffles
14125 if (VT.isFixedLengthVector() && VT.getVectorNumElements() == 2) {
14126 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx) {
14127 int FirstMaskIdx = ResultIdx % 2;
14128 int SecondMaskIdx = (ResultIdx + Factor) % 2 + 2;
14129 Results.push_back(
14130 DAG.getVectorShuffle(VT, DL, Node->getOperand(ResultIdx / 2),
14131 Node->getOperand((ResultIdx + Factor) / 2),
14132 {FirstMaskIdx, SecondMaskIdx}));
14133 }
14134 return;
14135 }
14136
14137 if (Factor > 2 && Factor % 2 == 0) {
14139 SmallVector<EVT> HalfVTs(Factor / 2, VT);
14140 // Deinterleave at Factor/2 so each result contains two factors interleaved:
14141 // a0b0 c0d0 a1b1 c1d1 -> [a0c0 b0d0] [a1c1 b1d1]
14142 SDValue L = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
14143 ArrayRef(Ops).take_front(Factor / 2));
14144 SDValue R = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
14145 ArrayRef(Ops).take_back(Factor / 2));
14146 Results.resize(Factor);
14147 // Deinterleave the 2 factors out:
14148 // [a0c0 a1c1] [b0d0 b1d1] -> a0a1 b0b1 c0c1 d0d1
14149 for (unsigned I = 0; I < Factor / 2; ++I) {
14151 {L.getValue(I), R.getValue(I)});
14152 Results[I] = Deinterleave.getValue(0);
14153 Results[I + Factor / 2] = Deinterleave.getValue(1);
14154 }
14155 return;
14156 }
14157
14158 if (!VT.isFixedLengthVector())
14159 return;
14160
14161 unsigned NumElts = VT.getVectorNumElements();
14162 EVT EltVT = VT.getVectorElementType();
14163
14164 // A factor of two needs only same-width, two-input shuffles.
14165 if (Factor == 2) {
14166 for (unsigned I = 0; I != Factor; ++I)
14167 Results.push_back(
14168 DAG.getVectorShuffle(VT, DL, Node->getOperand(0), Node->getOperand(1),
14169 createStrideMask(I, Factor, NumElts)));
14170 return;
14171 }
14172
14173 SmallVector<SDValue> ConcatElts;
14174 ConcatElts.reserve(Factor * NumElts);
14175 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
14176 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14177 ConcatElts.push_back(DAG.getExtractVectorElt(
14178 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
14179
14180 SmallVector<SDValue> DeinterleavedElts;
14181 DeinterleavedElts.reserve(Factor * NumElts);
14182 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx) {
14183 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14184 DeinterleavedElts.push_back(ConcatElts[ResultIdx + EltIdx * Factor]);
14185 Results.push_back(DAG.getBuildVector(
14186 VT, DL,
14187 ArrayRef(DeinterleavedElts).slice(ResultIdx * NumElts, NumElts)));
14188 }
14189}
14190
14192 SelectionDAG &DAG) const {
14193 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
14194 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
14195 "Unexpected opcode!");
14196 assert((Node->getValueType(0).isScalableVector() ||
14197 !isa<ConstantSDNode>(Node->getOperand(2))) &&
14198 "Fixed length vector types with constant offsets expected to use "
14199 "SHUFFLE_VECTOR!");
14200
14201 EVT VT = Node->getValueType(0);
14202 SDValue V1 = Node->getOperand(0);
14203 SDValue V2 = Node->getOperand(1);
14204 SDValue Offset = Node->getOperand(2);
14205 SDLoc DL(Node);
14206
14207 // Expand through memory thusly:
14208 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
14209 // Store V1, Ptr
14210 // Store V2, Ptr + sizeof(V1)
14211 // if (VECTOR_SPLICE_LEFT)
14212 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
14213 // else
14214 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
14215 // Res = Load Ptr
14216
14217 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
14218
14220 VT.getVectorElementCount() * 2);
14221 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
14222 EVT PtrVT = StackPtr.getValueType();
14223 auto &MF = DAG.getMachineFunction();
14224 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14225 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
14226
14227 // Store the lo part of CONCAT_VECTORS(V1, V2)
14228 SDValue StoreV1 =
14229 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
14230 // Store the hi part of CONCAT_VECTORS(V1, V2)
14231 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
14232 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
14233 SDValue StoreV2 =
14234 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
14235
14236 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
14237 SDValue EltByteSize =
14238 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
14239 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
14240 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
14241
14242 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
14243
14244 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
14245 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
14246 else
14247 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
14248
14249 // Load the spliced result
14250 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
14252}
14253
14255 SelectionDAG &DAG) const {
14256 SDLoc DL(Node);
14257 SDValue Vec = Node->getOperand(0);
14258 SDValue Mask = Node->getOperand(1);
14259 SDValue Passthru = Node->getOperand(2);
14260
14261 EVT VecVT = Vec.getValueType();
14262 EVT ScalarVT = VecVT.getScalarType();
14263 EVT MaskVT = Mask.getValueType();
14264 EVT MaskScalarVT = MaskVT.getScalarType();
14265
14266 // Needs to be handled by targets that have scalable vector types.
14267 if (VecVT.isScalableVector())
14268 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
14269
14270 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
14271 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
14272
14273 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
14274 SDValue Chain = DAG.getEntryNode();
14275 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
14276
14277 unsigned NumElms = VecVT.getVectorNumElements();
14278 for (unsigned I = 0; I < NumElms; I++) {
14279 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
14280 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14281 Chain = DAG.getStore(
14282 Chain, DL, ValI, OutPtr,
14284
14285 // Get the mask value and add it to the current output position. This
14286 // either increments by 1 if MaskI is true or adds 0 otherwise.
14287 // Freeze in case we have poison/undef mask entries.
14288 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
14289 MaskI = DAG.getFreeze(MaskI);
14290 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
14291 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
14292 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
14293 }
14294
14295 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14296 MachinePointerInfo PtrInfo =
14298
14299 SDValue Load = DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
14300 if (Passthru.isUndef())
14301 return Load;
14302
14303 EVT PopcountVT = ScalarVT.changeTypeToInteger();
14304 SDValue Popcount = DAG.getNode(
14306 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
14307 Popcount = DAG.getNode(
14309 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT), Popcount);
14310 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
14311
14312 SDValue Zero = DAG.getConstant(0, DL, PopcountVT);
14313 SDValue CompressedMask =
14314 DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT, Zero, Popcount);
14315
14316 return DAG.getSelect(DL, VecVT, CompressedMask, Load, Passthru);
14317}
14318
14320 SelectionDAG &DAG) const {
14321 SDLoc DL(Node);
14322 SDValue V = Node->getOperand(0);
14323 SDValue Mask = Node->getOperand(1);
14324
14325 EVT VecVT = Node->getValueType(0);
14326 EVT ScalarVT = VecVT.getScalarType();
14327
14328 // Needs to be handled by targets that have scalable vector types.
14329 if (VecVT.isScalableVector())
14331 "Cannot expand vector_shuffle_var for scalable vectors.");
14332
14333 if (VecVT.getVectorNumElements() == 2) {
14334 // Select between V and V with its lanes swapped.
14335 EVT IdxVT = VecVT.changeVectorElementTypeToInteger();
14336 SDValue Idx = DAG.getZExtOrTrunc(Mask, DL, IdxVT);
14337 EVT CCVT =
14338 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IdxVT);
14339 SDValue Keep =
14340 DAG.getSetCC(DL, CCVT, Idx, DAG.getStepVector(DL, IdxVT), ISD::SETEQ);
14341 SDValue Swapped = DAG.getVectorShuffle(VecVT, DL, V, V, {1, 0});
14342 return DAG.getNode(ISD::VSELECT, DL, VecVT, Keep, V, Swapped);
14343 }
14344
14345 // Res[i] = V[Mask[i]]. Out-of-range extracts are undefined, as required.
14346 MVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
14348 DAG.ExtractVectorElements(Mask, Elts);
14349 for (SDValue &Elt : Elts) {
14350 SDValue Idx = DAG.getZExtOrTrunc(Elt, DL, IdxVT);
14351 Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, V, Idx);
14352 }
14353 return DAG.getBuildVector(VecVT, DL, Elts);
14354}
14355
14357 SDLoc DL(Node);
14358 EVT VT = Node->getValueType(0);
14359 SDValue Op = Node->getOperand(0);
14360 ElementCount EC = Op.getValueType().getVectorElementCount();
14361
14362 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
14363 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
14364
14365 // No legal step vector: split mask in half and recombine results.
14366 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
14367 // (== LoNumElts when no active lane), allowing the SETNE comparison.
14368 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
14369 if (!StepVec) {
14370 EVT ResVT = Node->getValueType(0);
14371 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
14372 SDValue LoNumElts = DAG.getElementCount(
14373 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
14374 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
14375 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
14376 SDValue ResLoNotNumElts = DAG.getSetCC(
14377 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
14378 ResLo, LoNumElts, ISD::SETNE);
14379 // Per LangRef, ResVT must be wide enough to hold the total element count,
14380 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
14381 // the count is only required to fit unsigned.
14382 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
14384 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
14385 }
14386
14387 EVT StepVecVT = StepVec.getValueType();
14388 EVT StepVT = StepVecVT.getVectorElementType();
14389
14390 // Promote the scalar result type early to avoid redundant zexts.
14392 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
14393
14394 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
14395 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
14396 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
14397 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
14398 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
14400 StepVecVT.getVectorElementType(), Select);
14401 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
14402 DAG.getZExtOrTrunc(Max, DL, StepVT));
14403
14404 return DAG.getZExtOrTrunc(Sub, DL, VT);
14405}
14406
14408 SDLoc DL(N);
14409 SDValue Source = N->getOperand(0);
14410 SDValue Needle = N->getOperand(1);
14411 SDValue Mask = N->getOperand(2);
14412 EVT SourceVT = Source.getValueType();
14413 EVT NeedleVT = Needle.getValueType();
14414 EVT ResVT = N->getValueType(0);
14415 EVT CmpVT =
14416 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
14417
14418 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
14419
14420 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
14421 EVT NeedleEltVT = NeedleVT.getVectorElementType();
14422 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
14423 SDValue Splat;
14424 if (NeedleVT == SourceVT) {
14425 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
14426 Splat = DAG.getVectorShuffle(
14427 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
14429 } else {
14430 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
14431 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
14432 }
14433 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
14434 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
14435 }
14436
14437 EVT UseVT = ResVT;
14438 // If the result is immediately truncated, only extend to that type (to avoid
14439 // unnecessary sign/zero extends).
14440 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
14441 UseVT = N->user_begin()->getValueType(0);
14442
14443 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
14444 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
14445
14446 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
14447 if (UseVT != ResVT)
14448 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
14449 return Ret;
14450}
14451
14453 SelectionDAG &DAG) const {
14454 SDLoc DL(N);
14455 SDValue Acc = N->getOperand(0);
14456 SDValue MulLHS = N->getOperand(1);
14457 SDValue MulRHS = N->getOperand(2);
14458 EVT AccVT = Acc.getValueType();
14459 EVT MulOpVT = MulLHS.getValueType();
14460
14461 EVT ExtMulOpVT =
14463 MulOpVT.getVectorElementCount());
14464
14465 unsigned ExtOpcLHS, ExtOpcRHS;
14466 switch (N->getOpcode()) {
14467 default:
14468 llvm_unreachable("Unexpected opcode");
14470 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
14471 break;
14473 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
14474 break;
14476 ExtOpcLHS = ISD::SIGN_EXTEND;
14477 ExtOpcRHS = ISD::ZERO_EXTEND;
14478 break;
14480 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
14481 break;
14482 }
14483
14484 // A wide partial reduction is built from a ladder of narrower ones, a rung
14485 // at a time, each halving the element count and doubling the width.
14486 unsigned Opc = N->getOpcode();
14487 ElementCount MulEC = MulOpVT.getVectorElementCount();
14488 ElementCount AccEC = AccVT.getVectorElementCount();
14489 unsigned CountRatio =
14490 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
14491 unsigned WidthRatio =
14492 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
14493 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
14494 LLVMContext &Ctx = *DAG.getContext();
14495 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
14496
14497 // A pure reduction peels one rung and re-enters.
14498 if (llvm::isOneOrOneSplat(MulRHS)) {
14499 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
14500 return DAG.getNode(Opc, DL, AccVT, Acc,
14501 DAG.getNode(Opc, DL, RungVT,
14502 DAG.getConstant(0, DL, RungVT), MulLHS,
14503 MulRHS),
14504 DAG.getConstant(1, DL, RungVT));
14505 }
14506
14507 // A multiply widens the products by one rung, which legalizes back into a
14508 // widening multiply per half, and the ladder re-enters as a plain sum.
14509 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
14510 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
14511 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
14512 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
14513 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
14514
14515 // The halves meet at the narrowest rung, so the accumulator is added once.
14516 EVT MidVT = Lo.getValueType()
14517 .widenIntegerVectorElementType(Ctx)
14518 .getHalfNumVectorElementsVT(Ctx);
14520 return DAG.getNode(Opc, DL, AccVT,
14521 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
14522 SDValue Mid =
14523 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
14524 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
14525 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
14526 }
14527
14528 if (ExtMulOpVT != MulOpVT) {
14529 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
14530 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
14531 }
14532 SDValue Input = MulLHS;
14533 // Maintain the FP flags (if any).
14534 SDNodeFlags Flags = N->getFlags();
14535 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
14536 if (!llvm::isOneOrOneSplatFP(MulRHS))
14537 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS, Flags);
14538 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
14539 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14540 }
14541
14542 unsigned Stride = AccVT.getVectorMinNumElements();
14543 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
14544
14545 // Collect all of the subvectors
14546 std::deque<SDValue> Subvectors = {Acc};
14547 for (unsigned I = 0; I < ScaleFactor; I++)
14548 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
14549
14550 unsigned FlatNode =
14551 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
14552
14553 // Flatten the subvector tree
14554 while (Subvectors.size() > 1) {
14555 Subvectors.push_back(DAG.getNode(FlatNode, DL, AccVT,
14556 {Subvectors[0], Subvectors[1]}, Flags));
14557 Subvectors.pop_front();
14558 Subvectors.pop_front();
14559 }
14560
14561 assert(Subvectors.size() == 1 &&
14562 "There should only be one subvector after tree flattening");
14563
14564 return Subvectors[0];
14565}
14566
14567/// Given a store node \p StoreNode, return true if it is safe to fold that node
14568/// into \p FPNode, which expands to a library call with output pointers.
14570 SDNode *FPNode,
14571 unsigned MaxSteps) {
14573 SmallVector<const SDNode *, 8> DeferredNodes;
14575
14576 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
14577 for (SDValue Op : StoreNode->ops())
14578 if (Op.getNode() != FPNode)
14579 Worklist.push_back(Op.getNode());
14580
14581 while (!Worklist.empty()) {
14582 const SDNode *Node = Worklist.pop_back_val();
14583 auto [_, Inserted] = Visited.insert(Node);
14584 if (!Inserted)
14585 continue;
14586
14587 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
14588 return false;
14589
14590 // Reached the FPNode (would result in a cycle).
14591 // OR Reached CALLSEQ_START (would result in nested call sequences).
14592 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
14593 return false;
14594
14595 if (Node->getOpcode() == ISD::CALLSEQ_END) {
14596 // Defer looking into call sequences (so we can check we're outside one).
14597 // We still need to look through these for the predecessor check.
14598 DeferredNodes.push_back(Node);
14599 continue;
14600 }
14601
14602 for (SDValue Op : Node->ops())
14603 Worklist.push_back(Op.getNode());
14604 }
14605
14606 // True if we're outside a call sequence and don't have the FPNode as a
14607 // predecessor. No cycles or nested call sequences possible.
14608 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
14609 MaxSteps);
14610}
14611
14613 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
14615 std::optional<unsigned> CallRetResNo) const {
14616 if (LC == RTLIB::UNKNOWN_LIBCALL)
14617 return false;
14618
14619 RTLIB::LibcallImpl LibcallImpl =
14621 if (LibcallImpl == RTLIB::Unsupported)
14622 return false;
14623
14624 LLVMContext &Ctx = *DAG.getContext();
14625 EVT VT = Node->getValueType(0);
14626 unsigned NumResults = Node->getNumValues();
14627 unsigned MaxSteps = DAG.getHasPredecessorMaxSteps();
14628
14629 // Find users of the node that store the results (and share input chains). The
14630 // destination pointers can be used instead of creating stack allocations.
14631 SDValue StoresInChain;
14632 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
14633 for (SDNode *User : Node->users()) {
14635 continue;
14636 auto *ST = cast<StoreSDNode>(User);
14637 SDValue StoreValue = ST->getValue();
14638 unsigned ResNo = StoreValue.getResNo();
14639 // Ensure the store corresponds to an output pointer.
14640 if (CallRetResNo == ResNo)
14641 continue;
14642 // Ensure the store to the default address space and not atomic or volatile.
14643 if (!ST->isSimple() || ST->getAddressSpace() != 0)
14644 continue;
14645 // Ensure all store chains are the same (so they don't alias).
14646 if (StoresInChain && ST->getChain() != StoresInChain)
14647 continue;
14648 // Ensure the store is properly aligned.
14649 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
14650 if (ST->getAlign() <
14651 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
14652 continue;
14653 // Avoid:
14654 // 1. Creating cyclic dependencies.
14655 // 2. Expanding the node to a call within a call sequence.
14656 if (!canFoldStoreIntoLibCallOutputPointers(ST, Node, MaxSteps))
14657 continue;
14658 ResultStores[ResNo] = ST;
14659 StoresInChain = ST->getChain();
14660 }
14661
14662 ArgListTy Args;
14663
14664 // Pass the arguments.
14665 for (const SDValue &Op : Node->op_values()) {
14666 EVT ArgVT = Op.getValueType();
14667 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
14668 Args.emplace_back(Op, ArgTy);
14669 }
14670
14671 // Pass the output pointers.
14672 SmallVector<SDValue, 2> ResultPtrs(NumResults);
14674 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
14675 if (ResNo == CallRetResNo)
14676 continue;
14677 EVT ResVT = Node->getValueType(ResNo);
14678 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
14679 ResultPtrs[ResNo] = ResultPtr;
14680 Args.emplace_back(ResultPtr, PointerTy);
14681 }
14682
14683 SDLoc DL(Node);
14684
14686 // Pass the vector mask (if required).
14687 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
14688 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
14689 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14690 }
14691
14692 Type *RetType = CallRetResNo.has_value()
14693 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14694 : Type::getVoidTy(Ctx);
14695 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14696 SDValue Callee =
14697 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14699 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14700 DAG.getLibcalls().getLibcallImplCallingConv(LibcallImpl), RetType, Callee,
14701 std::move(Args));
14702
14703 auto [Call, CallChain] = LowerCallTo(CLI);
14704
14705 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14706 if (ResNo == CallRetResNo) {
14707 Results.push_back(Call);
14708 continue;
14709 }
14710 MachinePointerInfo PtrInfo;
14711 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14712 ResultPtr, PtrInfo);
14713 SDValue OutChain = LoadResult.getValue(1);
14714
14715 if (StoreSDNode *ST = ResultStores[ResNo]) {
14716 // Replace store with the library call.
14717 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14718 PtrInfo = ST->getPointerInfo();
14719 } else {
14721 DAG.getMachineFunction(),
14722 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14723 }
14724
14725 Results.push_back(LoadResult);
14726 }
14727
14728 return true;
14729}
14730
14732 SDValue &LHS, SDValue &RHS,
14733 SDValue &CC, bool &NeedInvert,
14734 const SDLoc &dl, SDValue &Chain,
14735 bool IsSignaling) const {
14736 MVT OpVT = LHS.getSimpleValueType();
14737 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14738 NeedInvert = false;
14739 switch (getCondCodeAction(CCCode, OpVT)) {
14740 default:
14741 llvm_unreachable("Unknown condition code action!");
14743 // Nothing to do.
14744 break;
14747 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14748 std::swap(LHS, RHS);
14749 CC = DAG.getCondCode(InvCC);
14750 return true;
14751 }
14752 // Swapping operands didn't work. Try inverting the condition.
14753 bool NeedSwap = false;
14754 InvCC = getSetCCInverse(CCCode, OpVT);
14755 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14756 // If inverting the condition is not enough, try swapping operands
14757 // on top of it.
14758 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14759 NeedSwap = true;
14760 }
14761 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14762 CC = DAG.getCondCode(InvCC);
14763 NeedInvert = true;
14764 if (NeedSwap)
14765 std::swap(LHS, RHS);
14766 return true;
14767 }
14768
14769 // Special case: expand i1 comparisons using logical operations.
14770 if (OpVT == MVT::i1) {
14771 SDValue Ret;
14772 switch (CCCode) {
14773 default:
14774 llvm_unreachable("Unknown integer setcc!");
14775 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14776 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14777 MVT::i1);
14778 break;
14779 case ISD::SETNE: // X != Y --> (X ^ Y)
14780 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14781 break;
14782 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14783 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14784 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14785 DAG.getNOT(dl, LHS, MVT::i1));
14786 break;
14787 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14788 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14789 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14790 DAG.getNOT(dl, RHS, MVT::i1));
14791 break;
14792 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14793 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14794 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14795 DAG.getNOT(dl, LHS, MVT::i1));
14796 break;
14797 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14798 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14799 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14800 DAG.getNOT(dl, RHS, MVT::i1));
14801 break;
14802 }
14803
14804 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14805 RHS = SDValue();
14806 CC = SDValue();
14807 return true;
14808 }
14809
14811 unsigned Opc = 0;
14812 switch (CCCode) {
14813 default:
14814 llvm_unreachable("Don't know how to expand this condition!");
14815 case ISD::SETUO:
14816 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14817 CC1 = ISD::SETUNE;
14818 CC2 = ISD::SETUNE;
14819 Opc = ISD::OR;
14820 break;
14821 }
14823 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14824 NeedInvert = true;
14825 [[fallthrough]];
14826 case ISD::SETO:
14828 "If SETO is expanded, SETOEQ must be legal!");
14829 CC1 = ISD::SETOEQ;
14830 CC2 = ISD::SETOEQ;
14831 Opc = ISD::AND;
14832 break;
14833 case ISD::SETONE:
14834 case ISD::SETUEQ:
14835 // If the SETUO or SETO CC isn't legal, we might be able to use
14836 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14837 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14838 // the operands.
14839 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14840 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14841 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14842 CC1 = ISD::SETOGT;
14843 CC2 = ISD::SETOLT;
14844 Opc = ISD::OR;
14845 NeedInvert = ((unsigned)CCCode & 0x8U);
14846 break;
14847 }
14848 [[fallthrough]];
14849 case ISD::SETOEQ:
14850 case ISD::SETOGT:
14851 case ISD::SETOGE:
14852 case ISD::SETOLT:
14853 case ISD::SETOLE:
14854 case ISD::SETUNE:
14855 case ISD::SETUGT:
14856 case ISD::SETUGE:
14857 case ISD::SETULT:
14858 case ISD::SETULE:
14859 // If we are floating point, assign and break, otherwise fall through.
14860 if (!OpVT.isInteger()) {
14861 // We can use the 4th bit to tell if we are the unordered
14862 // or ordered version of the opcode.
14863 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14864 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14865 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14866 break;
14867 }
14868 // Fallthrough if we are unsigned integer.
14869 [[fallthrough]];
14870 case ISD::SETLE:
14871 case ISD::SETGT:
14872 case ISD::SETGE:
14873 case ISD::SETLT:
14874 case ISD::SETNE:
14875 case ISD::SETEQ:
14876 // If all combinations of inverting the condition and swapping operands
14877 // didn't work then we have no means to expand the condition.
14878 llvm_unreachable("Don't know how to expand this condition!");
14879 }
14880
14881 SDValue SetCC1, SetCC2;
14882 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14883 // If we aren't the ordered or unorder operation,
14884 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14885 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14886 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14887 } else {
14888 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14889 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14890 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14891 }
14892 if (Chain)
14893 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14894 SetCC2.getValue(1));
14895 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14896 RHS = SDValue();
14897 CC = SDValue();
14898 return true;
14899 }
14900 }
14901 return false;
14902}
14903
14905 SelectionDAG &DAG) const {
14906 EVT VT = Node->getValueType(0);
14907 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14908 // split into two equal parts.
14909 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14910 return SDValue();
14911
14912 // Restrict expansion to cases where both parts can be concatenated.
14913 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14914 if (LoVT != HiVT || !isTypeLegal(LoVT))
14915 return SDValue();
14916
14917 SDLoc DL(Node);
14918 unsigned Opcode = Node->getOpcode();
14919
14920 // Don't expand if the result is likely to be unrolled anyway.
14921 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14922 return SDValue();
14923
14924 SmallVector<SDValue, 4> LoOps, HiOps;
14925 for (const SDValue &V : Node->op_values()) {
14926 if (!V.getValueType().isVector()) {
14927 // Scalar operands pass through to both halves unchanged.
14928 LoOps.push_back(V);
14929 HiOps.push_back(V);
14930 continue;
14931 }
14932 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14933 LoOps.push_back(Lo);
14934 HiOps.push_back(Hi);
14935 }
14936
14937 bool IsStrict = Node->isStrictFPOpcode();
14938 SDVTList LoVTs =
14939 IsStrict ? DAG.getVTList(LoVT, MVT::Other) : DAG.getVTList(LoVT);
14940 SDVTList HiVTs =
14941 IsStrict ? DAG.getVTList(HiVT, MVT::Other) : DAG.getVTList(HiVT);
14942 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVTs, LoOps, Node->getFlags());
14943 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVTs, HiOps, Node->getFlags());
14944 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14945
14946 if (!IsStrict)
14947 return Res;
14948
14949 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14950 SplitOpLo.getValue(1), SplitOpHi.getValue(1));
14951 return DAG.getMergeValues({Res, Chain}, DL);
14952}
14953
14955 const SDLoc &DL,
14956 EVT InVecVT, SDValue EltNo,
14957 LoadSDNode *OriginalLoad,
14958 SelectionDAG &DAG) const {
14959 assert(OriginalLoad->isSimple());
14960
14961 EVT VecEltVT = InVecVT.getVectorElementType();
14962
14963 // If the vector element type is not a multiple of a byte then we are unable
14964 // to correctly compute an address to load only the extracted element as a
14965 // scalar.
14966 if (!VecEltVT.isByteSized())
14967 return SDValue();
14968
14969 ISD::LoadExtType ExtTy =
14970 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14971 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14972 return SDValue();
14973
14974 std::optional<unsigned> ByteOffset;
14975 Align Alignment = OriginalLoad->getAlign();
14977 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14978 int Elt = ConstEltNo->getZExtValue();
14979 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14980 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14981 Alignment = commonAlignment(Alignment, *ByteOffset);
14982 } else {
14983 // Discard the pointer info except the address space because the memory
14984 // operand can't represent this new access since the offset is variable.
14985 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14986 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14987 }
14988
14989 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14990 return SDValue();
14991
14992 unsigned IsFast = 0;
14993 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14994 OriginalLoad->getAddressSpace(), Alignment,
14995 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14996 !IsFast)
14997 return SDValue();
14998
14999 // The original DAG loaded the entire vector from memory, so arithmetic
15000 // within it must be inbounds.
15002 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
15003
15004 // We are replacing a vector load with a scalar load. The new load must have
15005 // identical memory op ordering to the original.
15006 SDValue Load;
15007 if (ResultVT.bitsGT(VecEltVT)) {
15008 // If the result type of vextract is wider than the load, then issue an
15009 // extending load instead.
15010 ISD::LoadExtType ExtType =
15011 isLoadLegal(ResultVT, VecEltVT, Alignment,
15012 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
15014 : ISD::EXTLOAD;
15015 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
15016 NewPtr, MPI, VecEltVT, Alignment,
15017 OriginalLoad->getMemOperand()->getFlags(),
15018 OriginalLoad->getMMOMetadataForSubAccess());
15019 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
15020 } else {
15021 // The result type is narrower or the same width as the vector element
15022 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
15023 Alignment, OriginalLoad->getMemOperand()->getFlags(),
15024 OriginalLoad->getMMOMetadataForSubAccess());
15025 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
15026 if (ResultVT.bitsLT(VecEltVT))
15027 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
15028 else
15029 Load = DAG.getBitcast(ResultVT, Load);
15030 }
15031
15032 return Load;
15033}
15034
15035// Set type id for call site info and metadata 'call_target'.
15036// We are filtering for:
15037// a) The call-graph-section use case that wants to know about indirect
15038// calls, or
15039// b) We want to annotate indirect calls.
15041 const CallBase *CB, MachineFunction &MF,
15042 MachineFunction::CallSiteInfo &CSInfo) const {
15043 if (CB && CB->isIndirectCall() &&
15046 CSInfo = MachineFunction::CallSiteInfo(*CB);
15047}
return SDValue()
const TargetLowering & TLI
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
constexpr LLT F32
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
block Block Frequency Analysis
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
static bool isSigned(unsigned Opcode)
#define _
hexagon merge activate weight
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
lazy value info
static bool isNonZeroModBitWidthOrUndef(const MachineRegisterInfo &MRI, Register Reg, unsigned BW)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static bool isUndef(const MachineInstr &MI)
Register const TargetRegisterInfo * TRI
#define T
#define T1
uint64_t High
#define P(N)
Function const char * Passes
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
R600 Clause Merge
int64_t C1
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
int64_t C0
Contains matchers for matching SelectionDAG nodes and values.
This file contains some templates that are useful if you are working with the STL at all.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static std::pair< SDValue, SDValue > getLegalMaskAndStepVector(SDValue Mask, bool ZeroIsPoison, SDLoc DL, SelectionDAG &DAG)
Returns a type-legalized version of Mask as the first item in the pair.
static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static bool lowerImmediateIfPossible(TargetLowering::ConstraintPair &P, SDValue Op, SelectionDAG *DAG, const TargetLowering &TLI)
If we have an immediate, see if we can lower it.
#define FP_CMP_LIBCALL(BASE)
static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, const APInt &UndefOp0, const APInt &UndefOp1)
Given a vector binary operation and known undefined elements for each input operand,...
static SDValue BuildExactUDIV(const TargetLowering &TLI, SDNode *N, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created)
Given an exact UDIV by a constant, create a multiplication with the multiplicative inverse of the con...
static void setArgListEntryAttributes(TargetLoweringBase::ArgListEntry &Entry, const SourceT &Src, unsigned ArgIdx)
Set CallLoweringInfo attribute flags based on a call instruction and called function attributes.
static bool canFoldStoreIntoLibCallOutputPointers(StoreSDNode *StoreNode, SDNode *FPNode, unsigned MaxSteps)
Given a store node StoreNode, return true if it is safe to fold that node into FPNode,...
static std::pair< RTLIB::Libcall, ISD::CondCode > selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC, RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC, ISD::CondCode TriStateCC)
Select the libcall and the condition code to test its result against 0 for an ordered floating-point ...
static SDValue isSpecificZeroAfterMaybeRounding(SelectionDAG &DAG, const TargetLowering &TLI, const SDLoc &DL, SDValue Val, FPClassTest FPClass)
static bool canNarrowCLMULToLegal(const TargetLowering &TLI, LLVMContext &Ctx, EVT VT, unsigned HalveDepth=0, unsigned TotalDepth=0)
Check if CLMUL on VT can eventually reach a type with legal CLMUL through a chain of halving decompos...
static SDValue combineShiftToAVGSUB(SDValue Op, TargetLowering::TargetLoweringOpt &TLO, const TargetLowering &TLI, const APInt &DemandedBits, const APInt &DemandedElts, unsigned Depth)
static unsigned getConstraintPiority(TargetLowering::ConstraintType CT)
Return a number indicating our preference for chosing a type of constraint over another,...
static std::optional< EVT > getNarrowAVGType(EVT VT, unsigned KnownBits, LLVMContext &Ctx)
static std::optional< bool > isFCmpEqualZero(FPClassTest Test, const fltSemantics &Semantics, const MachineFunction &MF)
Returns a true value if if this FPClassTest can be performed with an ordered fcmp to 0,...
static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, EVT VecVT, const SDLoc &DL, ElementCount SubEC)
static void turnVectorIntoSplatVector(MutableArrayRef< SDValue > Values, std::function< bool(SDValue)> Predicate, SDValue AlternativeReplacement=SDValue())
If all values in Values that don't match the predicate are same 'splat' value, then replace all value...
static MaybeAlign getParamAlign(const CallBase &Call, unsigned ArgIdx)
static MaybeAlign getParamStackAlign(const CallBase &Call, unsigned ArgIdx)
static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT)
static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created)
Given an exact SDIV by a constant, create a multiplication with the multiplicative inverse of the con...
static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, SDValue N0, const APInt &C1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static SDValue combineShiftToAVG(SDValue Op, TargetLowering::TargetLoweringOpt &TLO, const TargetLowering &TLI, const APInt &DemandedBits, const APInt &DemandedElts, unsigned Depth)
static bool paramHasAttr(const CallBase &Call, unsigned ArgIdx, Attribute::AttrKind Kind)
This file describes how to lower LLVM code to machine code.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT, SelectionDAG &DAG)
Scalarize a vector store, bitcasting to TargetVT to determine the scalar type.
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static LLVM_ABI const llvm::fltSemantics & EnumToSemantics(Semantics S)
Definition APFloat.cpp:451
static constexpr roundingMode rmTowardZero
Definition APFloat.h:383
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:617
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:638
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:673
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
static LLVM_ABI bool hasSignBitInMSB(const fltSemantics &)
Definition APFloat.cpp:655
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:613
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:609
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:650
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:395
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1484
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1295
APInt bitcastToAPInt() const
Definition APFloat.h:1508
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1275
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1235
void changeSign()
Definition APFloat.h:1434
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1246
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1360
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1416
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:836
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
void negate()
Negate this APInt in place.
Definition APInt.h:1488
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
unsigned countLeadingZeros() const
Definition APInt.h:1626
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1472
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1455
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
void setAllBits()
Set every bit to 1.
Definition APInt.h:1339
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool isMask(unsigned numBits) const
Definition APInt.h:484
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1387
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1437
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1408
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
void clearHighBits(unsigned hiBits)
Set top hiBits bits to 0.
Definition APInt.h:1462
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1676
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
void setBitVal(unsigned BitPosition, bool BitValue)
Set a given bit to a given value.
Definition APInt.h:1363
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
@ None
No attributes have been set.
Definition Attributes.h:127
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI ConstantSDNode * getConstantSplatNode(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted constant or null if this is not a constant splat.
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This class represents a range of values.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
const APInt & getAPIntValue() const
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:219
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
constexpr bool isPowerOf2() const
Definition TypeSize.h:324
Class to represent function types.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
const GlobalValue * getGlobal() const
Module * getParent()
Get the module that this global value is contained inside of...
std::vector< std::string > ConstraintCodeVector
Definition InlineAsm.h:105
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Tracks which library functions to use for a particular subtarget or function.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
RTLIB::LibcallImpl getVectorLibcallImplOrMasked(RTLIB::Libcall Call) const
Return the implementation for Call, or for its masked variant if Call has no implementation.
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
Context object for machine code objects.
Definition MCContext.h:84
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:31
iterator_range< regclass_iterator > regclasses() const
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:210
Machine Value Type.
SimpleValueType SimpleTy
bool isInteger() const
Return true if this is an integer or a vector integer type.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static MVT getIntegerVT(unsigned BitWidth)
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
Flags getFlags() const
Return the raw flags of the source value,.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
unsigned getAddressSpace() const
Return the address space for the associated pointer.
Align getAlign() const
bool isSimple() const
Returns true if the memory operation is neither atomic or volatile.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
MMOMetadata getMMOMetadataForSubAccess() const
Returns metadata that can be copied unchanged to an access covering all or part of this access's byte...
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition Module.h:534
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Class to represent pointers.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
ArrayRef< SDUse > ops() const
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
SDNodeFlags getFlags() const
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
ISD::CondCode getOperandCondCode(unsigned i) const
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getElementCount(const SDLoc &DL, EVT VT, ElementCount EC)
bool willNotOverflowAdd(bool IsSigned, SDValue N0, SDValue N1) const
Determine if the result of the addition of 2 nodes can never overflow.
LLVM_ABI Align getReducedAlign(EVT VT, bool UseABI)
In most cases this function returns the ABI alignment for a given type, except for illegal vector typ...
LLVM_ABI bool isKnownNeverLogicalZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Test whether the given floating point SDValue (or all elements of it, if it is a vector) is known to ...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Extract element at Idx from Vec.
LLVM_ABI unsigned ComputeMaxSignificantBits(SDValue Op, unsigned Depth=0) const
Get the upper bound on bit size for this Value Op as a signed integer.
LLVM_ABI unsigned getHasPredecessorMaxSteps() const
LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl, SDNodeFlags Flags={})
Constant fold a setcc to true or false.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI SDValue getJumpTableDebugInfo(int JTI, SDValue Chain, const SDLoc &DL)
LLVM_ABI std::optional< unsigned > getValidMaximumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getVScale(const SDLoc &DL, EVT VT, APInt MulImm)
Return a node that represents the runtime scaling 'MulImm * RuntimeVL'.
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
bool willNotOverflowSub(bool IsSigned, SDValue N0, SDValue N1) const
Determine if the result of the sub of 2 nodes can never overflow.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI std::optional< unsigned > getValidShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has a uniform shift amount that is less than the element bit-width of the shi...
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
Check if a node exists without modifying its flags.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(SDValue Op, bool ForSigned, unsigned Depth=0) const
Combine constant ranges from computeConstantRange() and computeKnownBits().
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, bool isTargetGA=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI bool isIdentityElement(unsigned Opc, SDNodeFlags Flags, SDValue V, unsigned OperandNo, unsigned Depth=0) const
Returns true if V is an identity element of Opc with Flags.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, unsigned Depth=0) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFreeze(SDValue V, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison)
Return a freeze of V using the SDLoc of the value operand.
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI bool isKnownToBeAPowerOfTwo(SDValue Val, bool OrZero=false, unsigned Depth=0) const
Test if the given value is known to have exactly one bit set.
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op)
Returns a node representing a splat of one value into all lanes of the provided vector type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
static void commuteMask(MutableArrayRef< int > Mask)
Change values in a shuffle permute mask assuming the two vector operands have swapped position.
size_type size() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
iterator end() const
Definition StringRef.h:116
Class to represent struct types.
LLVM_ABI void setExtAttribute(Attribute::AttrKind Attr)
LLVM_ABI void setAttributes(const CallBase *Call, unsigned ArgIdx)
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
virtual IntegerType * getCmpLibcallReturnType(LLVMContext &Ctx) const
Return the integer type returned by comparison libcalls.
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
virtual bool shouldRemoveRedundantExtend(SDValue Op) const
Return true (the default) if it is profitable to remove a sext_inreg(x) where the sext is redundant,...
virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT, std::optional< unsigned > ByteOffset=std::nullopt) const
Return true if it is profitable to reduce a load to a smaller type.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool preferSelectsOverBooleanArithmetic(EVT VT) const
Should we prefer selects to doing arithmetic on boolean types.
virtual bool isLegalICmpImmediate(int64_t) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
virtual bool isSafeMemOpType(MVT) const
Returns true if it's safe to use load / store of the specified type to expand memcpy / memset inline.
const TargetMachine & getTargetMachine() const
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool isPaddedAtMostSignificantBitsWhenStored(EVT VT) const
Indicates if any padding is guaranteed to go at the most significant bits when storing the type to me...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
bool isFPImmLegal(const APFloat &Imm, EVT VT, bool ForCodeSize=false) const
Returns true if the specified FP immediate can be materialized without a load from the constant pool.
virtual bool hasBitTest(SDValue X, SDValue Y) const
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
EVT getLegalTypeToTransformTo(LLVMContext &Context, EVT VT) const
Perform getTypeToTransformTo repeatedly until a legal type is obtained.
LegalizeAction getCondCodeAction(ISD::CondCode CC, MVT VT) const
Return how the condition code should be treated: either it is legal, needs to be expanded to some oth...
virtual bool isCommutativeBinOp(unsigned Opcode) const
Returns true if the opcode is a commutative binary operation.
virtual bool shouldTransformSignedTruncationCheck(EVT XVT, unsigned KeptBits) const
Should we tranform the IR-optimal check for whether given truncation down into KeptBits would be trun...
bool isLegalRC(const TargetRegisterInfo &TRI, const TargetRegisterClass &RC) const
Return true if the value types that can be represented by the specified register class are all legal.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
virtual bool shouldExtendTypeInLibCall(EVT Type) const
Returns true if arguments should be extended in lib calls.
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const
Return true if creating a shift of the type by the given amount is not profitable.
virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const
Return true if an fpext operation is free (for instance, because single-precision floating-point numb...
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
BooleanContent getBooleanContents(bool isVec) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
TargetLoweringBase(const TargetMachine &TM, const TargetSubtargetInfo &STI)
NOTE: The TargetMachine owns TLOF.
virtual bool shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, unsigned OldShiftOpcode, unsigned NewShiftOpcode, SelectionDAG &DAG) const
Given the pattern (X & (C l>>/<< Y)) ==/!= 0 return true if it should be transformed into: ((X <</l>>...
BooleanContent
Enum that describes how the target represents true/false values.
virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const
Return true if integer divide is usually cheaper than a sequence of several shifts,...
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
virtual bool hasAndNotCompare(SDValue Y) const
Return true if the target should transform: (X & Y) == Y ---> (~X & Y) == 0 (X & Y) !...
virtual bool isNarrowingProfitable(SDNode *N, EVT SrcVT, EVT DestVT) const
Return true if it's profitable to narrow operations of type SrcVT to DestVT.
virtual bool isBinOp(unsigned Opcode) const
Return true if the node is a math/logic binary operator.
virtual bool isCtlzFast() const
Return true if ctlz instruction is fast.
virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT, bool IsSigned) const
Return true if it is more correct/profitable to use strict FP_TO_INT conversion operations - canonica...
NegatibleCost
Enum that specifies when a float negation is beneficial.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
virtual EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &) const
Returns the target specific optimal type for load and store operations as a result of memset,...
virtual EVT getAsmOperandValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal or custom for a comparison of the specified type...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
MulExpansionKind
Enum that specifies when a multiplication should be expanded.
static ISD::NodeType getExtendForContent(BooleanContent Content)
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT.
SDValue buildSDIVPow2WithCMov(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created) const
Build sdiv by power-of-2 with conditional move instructions Ref: "Hacker's Delight" by Henry Warren 1...
virtual ConstraintWeight getMultipleConstraintMatchWeight(AsmOperandInfo &info, int maIndex) const
Examine constraint type and operand type and determine a weight value.
void expandVectorDeinterleave(SDNode *Node, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
Expand a VECTOR_DEINTERLEAVE without introducing wider vector types.
bool expandMultipleResultFPLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node, SmallVectorImpl< SDValue > &Results, std::optional< unsigned > CallRetResNo={}) const
Expands a node with multiple results to an FP or vector libcall.
bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]MULO.
bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, SelectionDAG &DAG, MulExpansionKind Kind, SDValue LL=SDValue(), SDValue LH=SDValue(), SDValue RL=SDValue(), SDValue RH=SDValue()) const
Expand a MUL into two nodes.
SmallVector< ConstraintPair > ConstraintGroup
virtual const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
virtual Align computeKnownAlignForTargetInstr(GISelValueTracking &Analysis, Register R, const MachineRegisterInfo &MRI, unsigned Depth=0) const
Determine the known alignment for the pointer value R.
bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask, APInt &KnownUndef, APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Vector Op.
virtual bool isUsedByReturnOnly(SDNode *, SDValue &) const
Return true if result of the specified node is used by a return node only.
bool LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC, bool &NeedInvert, const SDLoc &dl, SDValue &Chain, bool IsSignaling=false) const
Legalize a SETCC with given LHS and RHS and condition code CC on the current target.
SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const
virtual unsigned getPreferredShrunkVectorSizeInBits(SDValue Op, const APInt &DemandedElts) const
If only low elements of a vector are demanded, shrink the operation to the returned size in bits by c...
virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const
This method can be implemented by targets that want to expose additional information about sign bits ...
SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const
void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS, SDValue &NewRHS, ISD::CondCode &CCCode, const SDLoc &DL, const SDValue OldLHS, const SDValue OldRHS) const
Soften the operands of a comparison.
void forceExpandWideMUL(SelectionDAG &DAG, const SDLoc &dl, bool Signed, const SDValue LHS, const SDValue RHS, SDValue &Lo, SDValue &Hi) const
Calculate full product of LHS and RHS either via a libcall or through brute force expansion of the mu...
SDValue expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const
Expand a VECREDUCE_SEQ_* into an explicit ordered calculation.
SDValue expandFCANONICALIZE(SDNode *Node, SelectionDAG &DAG) const
Expand FCANONICALIZE to FMUL with 1.
SDValue expandCTLZ(SDNode *N, SelectionDAG &DAG) const
Expand CTLZ/CTLZ_ZERO_POISON nodes.
SDValue expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const
Expand BITREVERSE nodes.
SDValue expandCTTZ(SDNode *N, SelectionDAG &DAG) const
Expand CTTZ/CTTZ_ZERO_POISON nodes.
virtual SDValue expandIndirectJTBranch(const SDLoc &dl, SDValue Value, SDValue Addr, int JTI, SelectionDAG &DAG) const
Expands target specific indirect branch for the case of JumpTable expansion.
SDValue expandABD(SDNode *N, SelectionDAG &DAG) const
Expand ABDS/ABDU nodes.
virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, TargetLoweringOpt &TLO) const
std::vector< AsmOperandInfo > AsmOperandInfoVector
SDValue expandGetActiveLaneMask(SDNode *N, SelectionDAG &DAG) const
Expand GET_ACTIVE_LANE_MASK nodes.
SDValue expandCLMUL(SDNode *N, SelectionDAG &DAG) const
Expand carryless multiply.
SDValue expandShlSat(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]SHLSAT.
SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, FPClassTest Test, SDNodeFlags Flags, const SDLoc &DL, SelectionDAG &DAG) const
Expand check for floating point class.
virtual bool isTargetCanonicalConstantNode(SDValue Op) const
Returns true if the given Opc is considered a canonical constant for the target, which should not be ...
SDValue expandVECTOR_SHUFFLE_VAR(SDNode *Node, SelectionDAG &DAG) const
Expand a VECTOR_SHUFFLE_VAR into variable-index element extracts.
SDValue expandFP_TO_INT_SAT(SDNode *N, SelectionDAG &DAG) const
Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
SDValue expandCttzElts(SDNode *Node, SelectionDAG &DAG) const
Expand a CTTZ_ELTS or CTTZ_ELTS_ZERO_POISON by calculating (VL - i) for each active lane (i),...
SDValue getCheaperNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, unsigned Depth=0) const
This is the helper function to return the newly negated expression only when the cost is cheaper.
virtual unsigned computeNumSignBitsForTargetInstr(GISelValueTracking &Analysis, Register R, const APInt &DemandedElts, const MachineRegisterInfo &MRI, unsigned Depth=0) const
This method can be implemented by targets that want to expose additional information about sign bits ...
SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth=0) const
More limited version of SimplifyDemandedBits that can be used to "lookthrough" ops that don't contrib...
SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const
Expands an unaligned store to 2 half-size stores for integer values, and possibly more for vectors.
SDValue SimplifyMultipleUseDemandedVectorElts(SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth=0) const
Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all bits from only some vector eleme...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const
Determines the optimal series of memory ops to replace the memset / memcpy.
virtual SDValue unwrapAddress(SDValue N) const
void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::S(ADD|SUB)O.
SDValue expandABS(SDNode *N, SelectionDAG &DAG, bool IsNegative=false) const
Expand ABS nodes.
SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const
Expand a VECREDUCE_* into an explicit calculation.
bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, TargetLoweringOpt &TLO) const
Check to see if the specified operand of the specified instruction is a constant integer.
virtual bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, unsigned Depth) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
SDValue expandMULH(SDNode *Node, SelectionDAG &DAG) const
SDValue expandVPCTTZElements(SDNode *N, SelectionDAG &DAG) const
Expand VP_CTTZ_ELTS/VP_CTTZ_ELTS_ZERO_POISON nodes.
SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization, bool IsAfterLegalTypes, SmallVectorImpl< SDNode * > &Created) const
Given an ISD::SDIV node expressing a divide by constant, return a DAG expression to select that will ...
virtual const char * getTargetNodeName(unsigned Opcode) const
This method returns the name of a target specific DAG node.
bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain, SelectionDAG &DAG) const
Expand float to UINT conversion.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< SDValue > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
virtual bool SimplifyDemandedVectorEltsForTargetNode(SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth=0) const
Attempt to simplify any target nodes based on the demanded vector elements, returning true on success...
bool expandREM(SDNode *Node, SDValue &Result, SelectionDAG &DAG) const
Expand an SREM or UREM using SDIV/UDIV or SDIVREM/UDIVREM, if legal.
std::pair< SDValue, SDValue > expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Expands an unaligned load to 2 half-size loads for an integer, and possibly more for vectors.
SDValue expandFMINIMUMNUM_FMAXIMUMNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimumnum/fmaximumnum into multiple comparison with selects.
void expandVectorInterleave(SDNode *Node, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
Expand a VECTOR_INTERLEAVE without introducing wider vector types.
void forceExpandMultiply(SelectionDAG &DAG, const SDLoc &dl, bool Signed, SDValue &Lo, SDValue &Hi, SDValue LHS, SDValue RHS, SDValue HiLHS=SDValue(), SDValue HiRHS=SDValue()) const
Calculate the product twice the width of LHS and RHS.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
SDValue expandVectorSplice(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::VECTOR_SPLICE.
SDValue getVectorSubVecPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, EVT SubVecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to a sub-vector of type SubVecVT at index Idx located in memory for a vector of type Ve...
SDValue expandLoopDependenceMask(SDNode *N, SelectionDAG &DAG) const
Expand LOOP_DEPENDENCE_MASK nodes.
virtual const char * LowerXConstraint(EVT ConstraintVT) const
Try to replace an X constraint, which matches anything, with another that has more specific requireme...
SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const
Expand CTPOP nodes.
virtual void computeKnownBitsForTargetInstr(GISelValueTracking &Analysis, Register R, KnownBits &Known, const APInt &DemandedElts, const MachineRegisterInfo &MRI, unsigned Depth=0) const
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization, bool IsAfterLegalTypes, SmallVectorImpl< SDNode * > &Created) const
Given an ISD::UDIV node expressing a divide by constant, return a DAG expression to select that will ...
SDValue expandVectorNaryOpBySplitting(SDNode *Node, SelectionDAG &DAG) const
~TargetLowering() override
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const
Expand BSWAP nodes.
SDValue expandFMINIMUM_FMAXIMUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimum/fmaximum into multiple comparison with selects.
SDValue CTTZTableLookup(SDNode *N, SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Op, unsigned NumBitsPerElt) const
Expand CTTZ via Table Lookup.
bool expandDIVREMByConstant(SDNode *N, SmallVectorImpl< SDValue > &Result, EVT HiLoVT, SelectionDAG &DAG, SDValue LL=SDValue(), SDValue LH=SDValue()) const
Attempt to expand an n-bit div/rem/divrem by constant using an n/2-bit algorithm.
virtual void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
bool isPositionIndependent() const
std::pair< StringRef, TargetLowering::ConstraintType > ConstraintPair
virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, NegatibleCost &Cost, unsigned Depth=0) const
Return the newly negated expression if the cost is not expensive and set the cost in Cost to indicate...
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
ConstraintGroup getConstraintPreferences(AsmOperandInfo &OpInfo) const
Given an OpInfo with list of constraints codes as strings, return a sorted Vector of pairs of constra...
bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const
Expand float(f32) to SINT(i64) conversion.
virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth) const
More limited version of SimplifyDemandedBits that can be used to "lookthrough" ops that don't contrib...
virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Glue, const SDLoc &DL, const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const
SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, SDValue N1, MutableArrayRef< int > Mask, SelectionDAG &DAG) const
Tries to build a legal vector shuffle using the provided parameters or equivalent variations.
static ArgListTy getArgListForFunctionType(FunctionType *FuncTy, const AttributeList &FuncAttrs, ArrayRef< SDValue > Ops)
Build a call argument list for FuncTy, taking the argument node values from Ops and the parameter typ...
virtual void computeKnownBitsForStackObjectPointer(KnownBits &Known, const MachineFunction &MF, Align Alignment) const
Determine known bits of a pointer to a known valid stack object.
virtual SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const
Returns relocation base for the given PIC jumptable.
std::pair< SDValue, SDValue > scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Turn load of vector type into a load of the individual elements.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Op.
virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0) const
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const
Return true if it is profitable to combine an XOR of a logical shift to create a logical shift of NOT...
TargetLowering(const TargetLowering &)=delete
virtual bool shouldSimplifyDemandedVectorElts(SDValue Op, const TargetLoweringOpt &TLO) const
Return true if the target supports simplifying demanded vector elements by converting them to undefs.
bool isConstFalseVal(SDValue N) const
Return if the N is a constant or constant vector equal to the false value from getBooleanContents().
SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL, EVT DataVT, SelectionDAG &DAG, bool IsCompressedMemory) const
Increments memory address Addr according to the type of the value DataVT that should be stored.
SDValue expandVectorMatch(SDNode *N, SelectionDAG &DAG) const
Expand VECTOR_MATCH nodes.
bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, SDValue &Chain) const
Check whether a given call node is in tail position within its function.
SDValue expandCONVERT_TO_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const
Expand CONVERT_TO_ARBITRARY_FP using bit manipulation.
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual bool isSplatValueForTargetNode(SDValue Op, const APInt &DemandedElts, APInt &UndefElts, const SelectionDAG &DAG, unsigned Depth=0) const
Return true if vector Op has the same value across all DemandedElts, indicating any elements which ma...
SDValue expandRoundInexactToOdd(EVT ResultVT, SDValue Op, const SDLoc &DL, SelectionDAG &DAG) const
Truncate Op to ResultVT.
virtual bool shouldSplitFunctionArgumentsAsLittleEndian(const DataLayout &DL) const
For most targets, an LLVM type must be broken down into multiple smaller types.
SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, bool foldBooleans, DAGCombinerInfo &DCI, const SDLoc &dl) const
Try to simplify a setcc built with the specified operands and cc.
SDValue expandFunnelShift(SDNode *N, SelectionDAG &DAG) const
Expand funnel shift.
virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const
Return true if folding a constant offset with the given GlobalAddress is legal.
bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const
Return if N is a True value when extended to VT.
bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &DemandedBits, TargetLoweringOpt &TLO) const
Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
bool isConstTrueVal(SDValue N) const
Return if the N is a constant or constant vector equal to the true value from getBooleanContents().
SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, SDValue LHS, SDValue RHS, unsigned Scale, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]DIVFIX[SAT].
SDValue expandPEXT(SDNode *N, SelectionDAG &DAG) const
Expand parallel bit extract (compress).
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual void CollectTargetIntrinsicOperands(const CallInst &I, SmallVectorImpl< SDValue > &Ops, SelectionDAG &DAG) const
virtual bool canCreateUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
bool expandMODF(SDNode *N, SelectionDAG &DAG, SmallVectorImpl< SDValue > &Results) const
Expand MODF node into fractional and integer parts.
SDValue expandVECTOR_COMPRESS(SDNode *Node, SelectionDAG &DAG) const
Expand a vector VECTOR_COMPRESS into a sequence of extract element, store temporarily,...
virtual const Constant * getTargetConstantFromLoad(LoadSDNode *LD) const
This method returns the constant pool value that will be loaded by LD.
SDValue expandFP_ROUND(SDNode *Node, SelectionDAG &DAG) const
Expand round(fp) to fp conversion.
SDValue createSelectForFMINNUM_FMAXNUM(SDNode *Node, SelectionDAG &DAG) const
Try to convert the fminnum/fmaxnum to a compare/select sequence.
SDValue expandCONVERT_FROM_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const
Expand CONVERT_FROM_ARBITRARY_FP using bit manipulation.
SDValue expandROT(SDNode *N, bool AllowVectorOps, SelectionDAG &DAG) const
Expand rotations.
SDValue annotateStackObjectPointer(SDValue Ptr, SelectionDAG &DAG, const SDLoc &DL, Align Alignment) const
Annotate a stack object pointer with known-bits assertions.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG, const DenormalMode &Mode, SDNodeFlags Flags={}) const
Return a target-dependent comparison result if the input operand is suitable for use with a square ro...
SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
virtual bool isGAPlusOffset(SDNode *N, const GlobalValue *&GA, int64_t &Offset) const
Returns true (and the GlobalValue and the offset) if the node is a GlobalAddress + offset.
virtual void computeKnownFPClassForTargetNode(const SDValue Op, KnownFPClass &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const
Determine floating-point class information for a target node.
virtual unsigned getJumpTableEncoding() const
Return the entry encoding for a jump table in the current function.
virtual void computeKnownFPClassForTargetInstr(GISelValueTracking &Analysis, Register R, KnownFPClass &Known, const APInt &DemandedElts, const MachineRegisterInfo &MRI, unsigned Depth=0) const
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
SDValue expandCMP(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]CMP.
void expandShiftParts(SDNode *N, SDValue &Lo, SDValue &Hi, SelectionDAG &DAG) const
Expand shift-by-parts.
virtual bool isKnownNeverNaNForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, bool SNaN=false, unsigned Depth=0) const
If SNaN is false,.
virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT].
SDValue getInboundsVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
SDValue expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US][MIN|MAX].
SDValue expandVectorFindLastActive(SDNode *N, SelectionDAG &DAG) const
Expand VECTOR_FIND_LAST_ACTIVE nodes.
SDValue expandPartialReduceMLA(SDNode *Node, SelectionDAG &DAG) const
Expands PARTIAL_REDUCE_S/UMLA nodes to a series of simpler operations, consisting of zext/sext,...
void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::U(ADD|SUB)O.
SDValue expandPDEP(SDNode *N, SelectionDAG &DAG) const
Expand parallel bit deposit (expand).
virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created) const
Targets may override this function to provide custom SDIV lowering for power-of-2 denominators.
SDValue scalarizeExtractedVectorLoad(EVT ResultVT, const SDLoc &DL, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad, SelectionDAG &DAG) const
Replace an extraction of a load with a narrowed load.
virtual SDValue BuildSREMPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created) const
Targets may override this function to provide custom SREM lowering for power-of-2 denominators.
bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain, SelectionDAG &DAG) const
Expand UINT(i64) to double(f64) conversion.
bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS, SDValue RHS, SmallVectorImpl< SDValue > &Result, EVT HiLoVT, SelectionDAG &DAG, MulExpansionKind Kind, SDValue LL=SDValue(), SDValue LH=SDValue(), SDValue RL=SDValue(), SDValue RH=SDValue()) const
Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes, respectively,...
SDValue expandAVG(SDNode *N, SelectionDAG &DAG) const
Expand vector/scalar AVGCEILS/AVGCEILU/AVGFLOORS/AVGFLOORU nodes.
SDValue expandCTLS(SDNode *N, SelectionDAG &DAG) const
Expand CTLS (count leading sign bits) nodes.
void setTypeIdForCallsiteInfo(const CallBase *CB, MachineFunction &MF, MachineFunction::CallSiteInfo &CSInfo) const
Primary interface to the complete machine description for the target machine.
bool isPositionIndependent() const
const Triple & getTargetTriple() const
TargetOptions Options
unsigned EmitCallSiteInfo
The flag enables call site info production.
unsigned EmitCallGraphSection
Emit section containing call graph metadata.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual StringRef getRegAsmName(MCRegister Reg) const
Return the assembly name for Reg.
bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const
Return true if the given TargetRegisterClass has the ValueType T.
TargetSubtargetInfo - Generic base class for all target subtargets.
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition Triple.h:873
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp:711
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
constexpr bool isKnownMultipleOf(ScalarTy RHS) const
This function tells the caller whether the element count is known at compile time to be a multiple of...
Definition TypeSize.h:181
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS*X will result in a value whose quantity matches our ...
Definition TypeSize.h:266
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
constexpr ScalarTy getKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns a value X where RHS*X will result in a value whose quantity matches our own.
Definition TypeSize.h:274
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:217
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3052
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ LOOP_DEPENDENCE_RAW_MASK
@ FGETSIGN
INT = FGETSIGN(FP) - Return the sign bit of the specified floating point value as an integer 0/1 valu...
Definition ISDOpcodes.h:543
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ AVGSUBFLOORS
AVGSUBFLOORS/AVGSUBFLOORU - Averaging subtract - Subtract two integers using an integer of type i[N+1...
Definition ISDOpcodes.h:739
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:397
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:296
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:403
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ CTTZ_ELTS
Returns the number of number of trailing (least significant) zero elements in a vector.
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ VECTOR_FIND_LAST_ACTIVE
Finds the index of the last active mask element Operands: Mask.
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ VECTOR_SHUFFLE_VAR
VECTOR_SHUFFLE_VAR(VEC, MASK) - Returns VEC permuted by MASK, an integer vector with the same number ...
Definition ISDOpcodes.h:665
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:942
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:533
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:802
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:410
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:820
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:731
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ PARTIAL_REDUCE_FMLA
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BRIND
BRIND - Indirect branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:640
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:688
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Same as FMINNUM/FMAXNUM, except that a signaling NaN operand deterministi...
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:669
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:931
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:416
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:807
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:181
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:726
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:673
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:306
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:819
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:953
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:977
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:629
@ CTTZ_ELTS_ZERO_POISON
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:746
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:775
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
LLVM_ABI NodeType getOppositeSignednessMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns the corresponding opcode with the opposi...
LLVM_ABI NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
bool isTrueWhenEqual(CondCode Cond)
Return true if the specified condition returns true if the two operands to the condition are equal.
unsigned getUnorderedFlavor(CondCode Cond)
This function returns 0 if the condition is always false if an operand is a NaN, 1 if the condition i...
LLVM_ABI bool matchBinaryPredicate(SDValue LHS, SDValue RHS, const APInt &DemandedElts, std::function< bool(ConstantSDNode *, ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTypeMismatch=false)
Attempt to match a binary predicate against a pair of scalar/splat constants or every element of a pa...
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI StringRef getCondCodeName(CondCode Operation)
Return the name of the given condition code, e.g. "setoeq".
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
LLVM_ABI bool isBuildVectorAllZeros(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are 0 or undef.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorOfConstantSDNodes(SDValue V)
Return true if the specified value is a BUILD_VECTOR node of all ConstantSDNode or undef.
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isUnsignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs an unsigned comparison when used with intege...
bool matchUnaryPredicate(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
LLVM_ABI Libcall getUREM(EVT VT)
Or< Preds... > m_AnyOf(const Preds &...preds)
TypeSize_match< ElementCount > m_ElementCount(ElementCount &V)
Match any integer constant or constant multiple of VSCALE that can be represented using ElementCount.
bool sd_match(SDValue N, Pattern &&P)
NUses_match< 1, Value_match > m_OneUse()
This is an optimization pass for GlobalISel generic memory operations.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:208
InstructionCost Cost
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
LLVM_ABI bool isAllOnesOrAllOnesSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
Definition Utils.cpp:1716
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI FPClassTest invertFPClassTestIfSimpler(FPClassTest Test, bool UseFCmp)
Evaluates if the specified FP class test is better performed as the inverse (i.e.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI bool isOneOrOneSplatFP(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant floating-point value, or a splatted vector of a constant float...
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
void * PointerTy
LLVM_ABI bool isNullOrNullSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Definition Utils.cpp:1700
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantFPSDNode * isConstOrConstSplatFP(SDValue N, bool AllowUndefs=false)
Returns the SDNode if it is a constant splat BuildVector or constant float.
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1793
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isOneOrOneSplat(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ Other
Any other memory.
Definition ModRef.h:68
To bit_cast(const From &from) noexcept
Definition bit.h:90
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
fltNonfiniteBehavior
Definition APFloat.h:966
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
@ TowardZero
roundTowardZero.
@ NearestTiesToEven
roundTiesToEven.
@ TowardPositive
roundTowardPositive.
@ NearestTiesToAway
roundTiesToAway.
@ TowardNegative
roundTowardNegative.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isZeroOrZeroSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
LLVM_ABI bool isNullFPConstant(SDValue V)
Returns true if V is an FP constant with a value of positive zero.
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition APFloat.h:1775
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
fltNanEncoding
Definition APFloat.h:990
@ Keep
No function return thunk.
Definition CodeGen.h:370
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Represent subnormal handling kind for floating point instruction inputs and outputs.
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ IEEE
IEEE-754 denormal numbers preserved.
constexpr bool inputsAreZero() const
Return true if input denormals must be implicitly treated as 0.
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:144
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
ElementCount getVectorElementCount() const
Definition ValueTypes.h:388
EVT getDoubleNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:509
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:281
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:397
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
EVT getHalfSizedIntegerVT(LLVMContext &Context) const
Finds the smallest simple value type that is greater than or equal to half the width of this EVT.
Definition ValueTypes.h:468
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:516
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
TypeSize getStoreSizeInBits() const
Return the number of bits overwritten by a store of the specified value type.
Definition ValueTypes.h:450
EVT changeVectorElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element type...
Definition ValueTypes.h:98
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
std::string getEVTString() const
This function returns value type as a string, e.g. "i32".
Definition ValueTypes.h:539
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
EVT widenIntegerVectorElementType(LLVMContext &Context) const
Return a VT for an integer vector type with the size of the elements doubled.
Definition ValueTypes.h:490
EVT changeVectorElementCount(LLVMContext &Context, ElementCount EC) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element coun...
Definition ValueTypes.h:109
bool isScalableVT() const
Return true if the type is a scalable type.
Definition ValueTypes.h:225
bool isFixedLengthVector() const
Definition ValueTypes.h:214
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:294
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT widenIntegerElementType(LLVMContext &Context) const
Return a VT for an integer element type with doubled bit width.
Definition ValueTypes.h:482
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:202
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
EVT changeElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a type whose attributes match ourselves with the exception of the element type that i...
Definition ValueTypes.h:136
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:346
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:499
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
KnownBits byteSwap() const
Definition KnownBits.h:562
static LLVM_ABI std::optional< bool > sge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGE result.
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
KnownBits reverseBits() const
Definition KnownBits.h:566
KnownBits concat(const KnownBits &Lo) const
Concatenate the bits from Lo onto the bottom of *this.
Definition KnownBits.h:247
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI std::optional< bool > ugt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGT result.
static LLVM_ABI std::optional< bool > slt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLT result.
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:62
static LLVM_ABI std::optional< bool > ult(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULT result.
static LLVM_ABI std::optional< bool > ule(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULE result.
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
static LLVM_ABI std::optional< bool > sle(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLE result.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:300
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
static bool hasVectorMaskArgument(RTLIB::LibcallImpl Impl)
Returns true if the function has a vector mask argument, which is assumed to be the last argument.
These are IR-level optimization flags that may be propagated to SDNodes.
bool hasNoUnsignedWrap() const
bool hasNoSignedWrap() const
void setNoSignedWrap(bool b)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
Magic data for optimising signed division by a constant.
static LLVM_ABI SignedDivisionByConstantInfo get(const APInt &D)
Calculate the magic numbers required to implement a signed integer division by a constant as a sequen...
This contains information for each constraint that we are lowering.
std::string ConstraintCode
This contains the actual string for the code, like "m".
LLVM_ABI unsigned getMatchedOperand() const
If this is an input matching constraint, this method returns the output operand it matches.
LLVM_ABI bool isMatchingInputConstraint() const
Return true of this is an input operand that is a matching constraint like "4".
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
CallLoweringInfo & setChain(SDValue InChain)
LLVM_ABI void AddToWorklist(SDNode *N)
LLVM_ABI void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO)
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setIsPostTypeLegalization(bool Value=true)
MakeLibCallOptions & setTypeListBeforeSoften(ArrayRef< EVT > OpsVT, EVT RetVT)
MakeLibCallOptions & setIsSigned(bool Value=true)
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...
Magic data for optimising unsigned division by a constant.
static LLVM_ABI UnsignedDivisionByConstantInfo get(const APInt &D, unsigned LeadingZeros=0, bool AllowEvenDivisorOptimization=true, bool AllowWidenOptimization=false)
Calculate the magic numbers required to implement an unsigned integer division by a constant as a seq...
fltNonfiniteBehavior nonFiniteBehavior
Definition APFloat.h:1064
fltNanEncoding nanEncoding
Definition APFloat.h:1066